使用GitPython检出一个分支,进行提交,然后切换回之前的分支。

9
我正在使用GitPython库进行一些简单的Git操作,我想切换分支、提交代码,然后再切换回之前的分支。但文件资料对如何实现有点令人困惑。目前,我的代码是这样的:
import git
repo = git.Repo()
previous_branch = repo.active_branch
new_branch_name = "foo"
new_branch = repo.create_head(new_branch_name)
new_branch.checkout()
repo.index.commit("my commit message")  # this seems wrong
## ?????

通过 git 命令的验证,我可以确认这个方法成功了,但是我感觉我操作有误。我不知道如何安全地返回到之前的分支,只是用原始的 git 命令(直接在库中)。

1个回答

4

来自http://gitpython.readthedocs.io/en/stable/tutorial.html

分支切换

要像git checkout一样在分支之间切换,您需要将HEAD符号引用指向新分支,并重置索引和工作副本以匹配。一个简单的手动方法是以下方法

    # Reset our working tree 10 commits into the past
    past_branch = repo.create_head('past_branch', 'HEAD~10')
    repo.head.reference = past_branch
    assert not repo.head.is_detached
    # reset the index and working tree to match the pointed-to commit
    repo.head.reset(index=True, working_tree=True)

    # To detach your head, you have to point to a commit directy
    repo.head.reference = repo.commit('HEAD~5')
    assert repo.head.is_detached
    # now our head points 15 commits into the past, whereas the working tree
    # and index are 10 commits in the past

以前的方法会粗暴地覆盖用户在工作副本和索引中所做的更改,比git-checkout不够复杂。后者通常会防止您破坏您的工作。请使用以下更安全的方法。
    # checkout the branch using git-checkout. It will fail as the working tree appears dirty
    self.failUnlessRaises(git.GitCommandError, repo.heads.master.checkout)
    repo.heads.past_branch.checkout()

或者,在此之下: 直接使用Git 如果您缺少某些功能,因为它们没有被包装,您可以方便地直接使用Git命令。它是每个存储库实例拥有的。

    git = repo.git
    git.checkout('HEAD', b="my_new_branch")         # create a new branch
    git.branch('another-new-one')
    git.branch('-D', 'another-new-one')             # pass strings for full control over argument order
    git.for_each_ref()                              # '-' becomes '_' when calling it

只需使用 git.checkout() 方法即可


1
“repo.head.reference = repo.commit(someSHA)”和“git checkout someSHA”有什么区别?我发现在使用Python时,引用指向HEAD和master,但在使用git cli时只有HEAD。这意味着通过Python使用它时,工作目录是脏的。如何使用Python工具进入分离状态并保持干净? - DanCat

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接