12

In JGit, I search a way to push a branch and add the upstream reference (tracking).

It is the option -u or --set-upstream into the push command.

I don't see a method in the class PushCommand which permits to do this.

Please, could you tell me how I can do this ?

PushCommand pushCommand = git.push()
                    .setRemote(remoteAlias)
                    .setRefSpecs(spec);

1 Answer 1

12

The JGit PushCommand does not offer this functionality (yet), but you can modify the repository configuration like --set-upstream would.

If you pass a remote alias to setRemote() (like the snippet from the question suggests), you need to set the upstream like so:

StoredConfig config = git.getRepository().getConfig();
config.setString(CONFIG_BRANCH_SECTION, "local-branch", "remote", "remote-alias-name");
config.setString(CONFIG_BRANCH_SECTION, "local-branch", "merge", "refs/heads/name-of-branch-on-remote");
config.save();

This will result in this configuration section

[branch "local-branch"] 
remote = remote-alias-name 
merge = refs/heads/name-of-branch-on-remote

If the remote hasn't been configured yet (i.e. there is no section [remote "remote-alias-name"], you will also have to create such a section. For example, like this:

config.setString(CONFIG_REMOTE_SECTION, "remote-alias-name", "url", "url-of-remote");
config.setString(CONFIG_REMOTE_SECTION, "remote-alias-name", "fetch", "ref-spec");

Constants are defined in class ConfigConstants.

3
  • It works fine, thanks. I can now do a fetch without specified the remote branch. But I don't understand why I doesn't have the information of the tracked branch when I do a git branch -vv. Do you know why ? Maybe it is because the tracked information is stored into the gitconfig file.
    – ascott
    Jan 8, 2015 at 9:42
  • If you create a branch with the CreateBranchCommand and the start point dentes a branch you can specify whether the new branch should track the start point through setUpstreamMode(). Does that answer your question? Jan 8, 2015 at 13:36
  • It is finally OK, it was my fault ! When I have configured my remote I forgot to called remoteConfig.addFetchRefSpec, that's why when I called git branch -vv, it didin't show me the tracked branch... Thanks for your answer that was perfect.
    – ascott
    Jan 9, 2015 at 10:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.