gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 13:59:08 24 4
gpt4 key购买 nike

我正在使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com