2012-08-09 27 views
1

我無法弄清楚如何刪除遠程分支。如何使用JGit刪除遠程分支

我試圖模仿下面的GIT命令: 混帳推產地:branchToDelete

下面的代碼,並將其與空的源變化:

RefSpec refSpec = new RefSpec(); 
refSpec = refSpec.setSource(""); 
// remove branch from origin: 
git.push().setRefSpecs(refSpec).add(branchToDelete).call(); 

拋出和異常,如:

org.eclipse.jgit.api.errors.JGitInternalException: Exception caught during execution of push command 
    at org.eclipse.jgit.api.PushCommand.call(PushCommand.java:175) 
    at org.gitscripts.DeleteBranchOperation.execute(DeleteBranchOperation.java:27) 
    at org.gitscripts.Main.main(Main.java:27) 
Caused by: java.io.IOException: Source ref doesnt resolve to any object. 
    at org.eclipse.jgit.transport.RemoteRefUpdate.<init>(RemoteRefUpdate.java:285) 
    at org.eclipse.jgit.transport.RemoteRefUpdate.<init>(RemoteRefUpdate.java:189) 
    at org.eclipse.jgit.transport.Transport.findRemoteRefUpdatesFor(Transport.java:612) 
    at org.eclipse.jgit.transport.Transport.findRemoteRefUpdatesFor(Transport.java:1150) 
    at org.eclipse.jgit.api.PushCommand.call(PushCommand.java:149) 
    ... 2 more 

在此先感謝您的想法和解決方案。

+0

從你的錯誤看來你的refSpec有問題。你確定它是正確的? – 2012-08-09 22:18:43

回答

2

根據定期的git語法,你的RefSpec()不應該是::branchToDelete

+0

是的,使用'new RefSpec(「:branchToDelete」)或'new RefSpec()。setSource(「」)。setDestination(「branchToDelete」)'。 – robinst 2012-08-10 08:09:09

+0

@Vince不,如果源爲空,則意味着應該在遠程刪除目標分支。 (這就是問題所在。) – robinst 2012-08-10 10:55:57

+0

好吧,我寧願刪除註釋以避免錯誤,然後 – Vince 2012-08-10 11:24:29

1

我從來沒有這樣做過,但是您是否簡單地通過指定origin/branchToDelete來嘗試一個DeleteBranchCommand?編輯:我特別指Git/JGit通過結構<remote name>/<branch name>引用遠程分支(並且使用ListBranchCommand將幫助您確保您得到正確的拼寫)。

要知道分支名稱的確切拼寫,您可以使用ListBranchCommand(不要忘記撥打setListMode(REMOTE))。

注意:Git允許比JGit更奇怪的行爲,所以除非寫入某處,否則不要期待它們。編輯:我的意思是一個refspec應該有以下語法:<remote branch>:<local branch>(或可能相反),但不要指望它在JGit中的作品,如果你錯過了一端,即使它在Git中工作。

+0

OP不想只在本地刪除遠程跟蹤分支,而是推送分支刪除。 – robinst 2012-08-10 08:06:30

+0

是的,我明白了。我的意思是你可以顯示遠程分支(不同於本地分支跟蹤它),然後刪除遠程分支。順便說一下,refspec會指定本地跟蹤分支和遠程分支之間的鏈接。我編輯了我的答案,以便更好地理解 – Vince 2012-08-10 08:23:02

+0

輝煌!將'origin/branchToDelete'(或者確切地說,'refs/remotes/origin/branchToDelete')傳遞給'DeleteBranchCommand'工作。 與JGit一起工作的關鍵是:不要試圖模仿GIT命令 – 2012-08-13 14:11:24

6

這應該做您排憂解難:

//delete branch 'branchToDelete' locally 
git.branchDelete().setBranchNames('refs/heads/branchToDelete').call(); 

//delete branch 'branchToDelete' on remote 'origin' 
RefSpec refSpec = new RefSpec() 
     .setSource(null) 
     .setDestination("refs/heads/branchToDelete"); 
git.push().setRefSpecs(refSpec).setRemote('origin').call(); 

與jgit 2.0.0.201206130900-R測試

0

我可以使它與這方面的工作:

StoredConfig config = git.getRepository().getConfig(); 
config.unsetSection("remote", "origin"); 
try { 
    config.save(); 
} catch (IOException e) { 
    logger.error(e.getMessage()); 
} 

希望它可以幫助。