使用 GitPython 签出一个分支。进行提交,然后切换回上一个分支

tho*_*rca 8 python git

我正在使用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
## ?????
Run Code Online (Sandbox Code Playgroud)

我可以通过 git 命令验证它来判断它是否有效,但我觉得我这样做不正确。我不知道如何使用原始 git 命令(直接从库中)安全地切换回前一个分支。

Dav*_*idN 5

来自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
Run Code Online (Sandbox Code Playgroud)

以前的方法会残酷地覆盖用户在工作副本和索引中的更改,并且不如 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()
Run Code Online (Sandbox Code Playgroud)

或者,就在下面:直接使用 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
Run Code Online (Sandbox Code Playgroud)

只需执行 git.checkout() 方法