JGit - 无法跟踪新创建的分支

JGit - Can't track newly created branch

我想在现有存储库中创建一个分支,然后跟踪该分支。创建分支成功,新创建的分支还在跟踪master。我尝试了几种不同的解决方案,但结果相同 - 创建了分支,但跟踪了 master。

首先我克隆存储库:

Git.cloneRepository()./*set creds*/.setURI(..).setDirectory(...).call

到目前为止一切顺利。

接下来,从克隆生成的 git 文件构建存储库。

FileRepositoryBuilder builder = new FileRepositoryBuilder();
Repository repo = builder.setGitDir(gitFile).readEnvironment().findGitDir()
    .build();

在这一点上,我已经尝试过将 createBranch 设置为 true 的分支检出,并分两步进行 - 创建,然后检出。这是两步法:

git.branchCreate()
        .setForce(true)
        .setName(branchName)
        .setStartPoint("origin/master")
        .call();
git.checkout()
        .setName(branchName)
        .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
        .setStartPoint("origin/"+branchName)
        .call();

我尝试过的其他事情:

结果始终是 .git/config 文件,如下所示:

[remote "origin"]
    url = ssh://..
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master
    rebase = true
[branch "newbranch1"]
    remote = origin
    merge = refs/heads/master << TRACKING master, not newbranch1

在我使用常规 git(不是 jgit)创建的分支上,配置文件如下所示:

[remote "origin"]
    url = ssh:...
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master
    rebase = true
[branch "newbranch2"]
    remote = origin
    merge = refs/heads/newbranch2 << WANT THIS

关于如何让我的新分支跟踪分支而不是主分支有什么想法吗?

使用 jgit-4.6.0.201612231935

我认为您无法使用 JGit 的 CreateBranchCommand 跟踪不存在的分支。 setStartPoint() 仅用于指定新分支最初应指向的位置。

但是,您可以使用

直接操作存储库配置
StoredConfig config = repository.getConfig();
config.setString( "branch", "newbranch", "remote", "origin" );
config.setString( "branch", "newbranch", "merge", "refs/heads/newbranch" );
config.save();

这是否解决了您的问题?

这是最终的工作代码:(谢谢 Rüdiger Herrmann)

Git git = Git.cloneRepository...

git.checkout().setCreateBranch(true).setName(branchName).call();

pushCmd.setRemote( "origin" )
  .setRefSpecs( new RefSpec( branchName+":"+branchName )).call();

StoredConfig config = git.getRepository().getConfig();
config.setString( "branch", branchName, "remote", "origin" );
config.setString( "branch", branchName, "merge", "refs/heads/" + branchName );
config.save();