使用 JGit 将更改推送到特定提交到远程存储库

Push changes till particular commit to remote repository with JGit

我可以使用 JGit 将所有本地提交推送到远程(裸存储库)。

RefSpec spec = new RefSpec("master:master");
Iterable<PushResult> resultIterable = git.push().setRemote("origin").setRefSpecs(spec).call();

现在我想将更改推送到特定提交。下面是 git shell 命令,我需要等效的 JGit 实现。

git push <remotename> <commit SHA>:<remotebranchname>

这是一个示例。我在git-bash.

做了一些准备
#init foo as the local repository
cd /e/
git init foo
#init bar as the remote repository
git init bar
#create two commits in the local repository
cd foo
> a
git add .
git commit -m 'root'
#the first sha1 is b8d35be23d9f4574c9da81cf2fddb4212daf92a1
> b
git add .
git commit -m 'ab'
#create a remote pointing to /e/bar
git remote add bar /e/bar

现在尝试代码,模拟 git push bar b8d35be23d9f4574c9da81cf2fddb4212daf92a1:refs/heads/newbranch:

try {
        Git git = Git.open(new File("E:/foo/.git"));
        RefSpec spec = new RefSpec("b8d35be23d9f4574c9da81cf2fddb4212daf92a1:refs/heads/newbranch");
        git.push().setRemote("bar").setRefSpecs(spec).call();            
} catch (Exception e) {
        System.out.println(e);
}