2012-06-12 36 views
8

我试图用GitPython编写一些Python脚本,我可以用它来简化我的日常任务,因为我管理很多分支。使用GitPython模块获取远程HEAD分支

当谈到编写复杂的脚本时,我对Python也很新颖。

这是我所使用的API:GitPython API doc

我想它写在GitPython,简单地执行以下操作并解析出这说明我的远程分支指向的HEAD部分。在另一个词,我想基本上得到了remotes/origin/HEAD

$ git branch -a 
    master 
* branch_to_remove 
    remotes/origin/HEAD -> origin/master 
    remotes/origin/master 
    remotes/origin/testing 

我浏览API文档很多次,起初我无法理解这些API文档的Python的格式,我找不到任何东西有用的除了remote_headremote_head

但我甚至不知道如何调用/初始化它。

这里是我到目前为止,你可以告诉我想要做的,简单地重置为“无分支”状态并删除当前分支我在:

import git 
from git import * 
repo = git.Repo("/some/path/testing") 
repo.git.branch() 
[some code to get the remotes/origin/HEAD, set it to remoteHeadBranch ] 
repo.git.checkout(remoteHeadBranch) # this should reset the Git back to 'no branch' state 
repo.git.checkout(D="branch_to_remove") 

任何帮助深表感谢!

谢谢。

回答

3

我刚才看到你的问题我在想这个gitPython,看起来像非常好的工具,我在GitPython文档中寻找这个具体的问题,没有幸运,但如果你在github上搜索,你会看到很多测试那里有一个测试。

你会看到这样的事情,当你搜索 “删除新的分支”:

# remove new branch 
Head.delete(new_remote_branch.repo, new_remote_branch) 

GitPython Reference

+0

感谢您的评论!我会试试这个! 在阅读这些Python API文档时,有人能帮助我吗?我的意思是这个文档非常不同,很难让我读一个像我这样的Java人:-( 谢谢! – xbeta

+0

这将* NOT *工作,因为你不能删除你当前的分支,所以第一步总是返回到'no branch'状态,我试图去做什么 '错误切换到'no'分支状态 'git branch -d newMaster'返回退出状态1:错误:无法删除分支'你当前在'newMaster'。“ – xbeta

3

要打印当前分支:

print(repo.head.ref) 

要列出分支机构

print [str(b) for b in repo.heads] 

检出一个分支

repo.heads[branch].checkout() 

repo.git.checkout(branch)

如果你想删除一个分支,你需要在不同的本地分支,您可以通过多种方式

repo.heads['master'].checkout() 

repo.git.checkout('master')repo.git.checkout('remotes/origin/master')

希望这有助于