我使用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命令验证它的工作原理,但我觉得我做错了。我不是如何使用raw git命令(直接从库中)安全地切换回上一个分支。
答案 0 :(得分: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()方法