python - 使用 GitPython 检查一个分支。进行提交,然后切换回上一个分支

标签 python git

我正在使用 GitPython库来做一些简单的 Git 操作,我想 check out 一个分支,进行提交,然后 check out 前一个分支。文档对如何执行此操作有点困惑。到目前为止,我有这个:

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 命令(直接从库中直接)安全地切换回前一个分支。

最佳答案

来自 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() 方法

关于python - 使用 GitPython 检查一个分支。进行提交,然后切换回上一个分支,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38060456/

相关文章:

python - 谷歌 Foobar : How to find edge cases and identify test cases. Python

git - git 是否将无法访问的对象推送到远程

git - 整个计算机处于 Git 状态未跟踪文件

git - 如何链接到 GitHub 上的特定行号

python - 逻辑向量作为 Python 中的索引?

python - 跟踪自上次击键以来的时间?

python - Twitter API - 如何获取 OAUTH_FILE?

关于花费时间的Python问题

git 状态在 virtualbox 上的共享文件夹上花费的时间太长

git - 如何删除 git-lfs 跟踪的文件并释放存储配额?