Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/git/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
GitPython:从远程拉/签出,放弃本地更改_Python_Git_Gitpython - Fatal编程技术网

GitPython:从远程拉/签出,放弃本地更改

GitPython:从远程拉/签出,放弃本地更改,python,git,gitpython,Python,Git,Gitpython,为了将文件部署到某些目标(Windows)计算机上,我想创建一个Python模块,该模块可以提供必要的参数。 然后,模块应检查outputpath中是否存在指定的repo a) 如果不存在:从远程克隆最新提交 b) 如果存在:放弃所有本地更改,从远程获取最新提交 一种方法(至少对我来说是有效的)是删除本地目标文件夹,重新创建它,然后再次克隆所有内容 我的代码,仅适用于空目录: stderr:“致命:远程源已存在。” import git, os, shutil #outputfolder the

为了将文件部署到某些目标(Windows)计算机上,我想创建一个Python模块,该模块可以提供必要的参数。 然后,模块应检查outputpath中是否存在指定的repo

a) 如果不存在:从远程克隆最新提交

b) 如果存在:放弃所有本地更改,从远程获取最新提交

一种方法(至少对我来说是有效的)是删除本地目标文件夹,重新创建它,然后再次克隆所有内容

我的代码,仅适用于空目录:

stderr:“致命:远程源已存在。”

import git, os, shutil
#outputfolder there?
if not os.path.exists(MY_outputfolder):
    os.makedirs(MY_outputfolder)
repowrk = git.Repo.init(MY_outputfolder)
wrkr = repowrk.create_remote('origin',MY_REMOTE_URL)
wrkr.fetch()
wrkr.pull(wrkr.refs[0].remote_head)
print("---- DONE ----")

如果repo存在,并且您希望放弃所有本地更改,并从远程获取最新提交,则可以使用以下命令:

# discard any current changes
repo.git.reset('--hard')

# if you need to reset to a specific branch:    
repo.git.reset('--hard','origin/master')

# pull in the changes from from the remote
repo.remotes.origin.pull()
使用这些命令,您不必再次删除repo和克隆


您可以查看文档以了解更多信息。

这是解决我问题的代码

a、 )输出目录包含一个.git文件夹:假设这是一个本地repo。还原所有本地更改,清除未版本的文件

b、 )输出目录不包含.git文件夹(或文件树不存在):假设目标目录为脏目录或不是本地存储库。删除目标树并将远程目录克隆到指定的目标

outdir_checker = outdir+'\.git'

if os.path.exists(outdir_checker):
    repo_worker = git.Repo.init(outdir)
    repo_worker.git.fetch(remote_url)
    repo_worker.git.reset('--hard')
    repo_worker.git.clean('-fdx')
    print('git dir not created; already existed')
if not os.path.exists(outdir_checker):
    shutil.rmtree(outdir, ignore_errors=True)
    os.makedirs(outdir)
    git.Repo.clone_from(remote_url, outdir)
    print('git dir created')

repo.remotes.origin.pull()?