切换分支
要在类似于git checkout的分支之间切换,实际上需要将头部符号引用指向新分支,并将索引和工作副本重置为匹配。一个简单的手动方法是# 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 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()方法