如何使用JGit删除远程分支

6

我不知道如何删除远程分支。

我试图模仿以下GIT命令:     git push origin :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

感谢您提供的想法和解决方案。


从您的错误信息来看,似乎您的refSpec存在问题。您确定它是正确的吗? - S.P.
4个回答

16

这应该可以帮助你:

//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 进行了测试。


3
按照常规的git语法,你的RefSpec()应该是::branchToDelete,对吗?

是的,可以使用new RefSpec(":branchToDelete")new RefSpec().setSource("").setDestination("branchToDelete") - robinst
@Vince 不,如果源为空,则意味着应该在远程上删除目标分支。(这就是问题所在。) - robinst

2

我从未这样做过,但你是否尝试过通过指定 origin/branchToDelete 来使用 DeleteBranchCommand 进行删除?

编辑:我特别指的是 Git/JGit 通过结构 <remote name>/<branch name> 引用远程分支(并使用 ListBranchCommand 将帮助您确保拼写正确)。

要知道分支名称的确切拼写,可以使用 ListBranchCommand(不要忘记调用 setListMode(REMOTE))。

注意:Git 允许更多奇怪的行为,而 JGit 不允许,因此除非有明确说明,否则不要期望它们的行为相同。

编辑:我的意思是 refspec 应该具有以下语法:<remote branch>:<local branch>(或者可能反过来),但是如果您缺少一端,则不要期望在 JGit 中有效,即使在 Git 中有效。


OP不仅想在本地删除远程跟踪分支,而是希望推送分支删除操作。 - robinst
是的,我明白了。我的意思是你可以显示远程分支(与本地跟踪分支不同),然后删除远程分支。顺便说一下,refspec 用于指定本地跟踪分支和远程分支之间的链接。我编辑了我的答案以便更好地理解。 - Vince
太棒了!将 origin/branchToDelete(或者更准确地说是 refs/remotes/origin/branchToDelete)传递给 DeleteBranchCommand 就可以工作了。使用 JGit 的关键是:不要试图模仿 GIT 命令。 - ivan.verhun
你可以在删除分支后尝试运行 git push。我的意思是,Git 是一个两步工具,首先你要在本地记录更改,然后再提交到远程存储库。因此,我认为你应该先删除跟踪分支或远程分支,然后再进行推送。 - Vince
什么也不会发生,你只是在本地存储库中删除了远程跟踪分支。 - Vampire
显示剩余2条评论

0

我可以用这个让它工作:

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

希望能有所帮助。


他想要删除远程分支,而不是从本地配置中删除远程。 - Vampire

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接