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);
This tutorial will teach us to set up upstream branches in Git while doing a git push . Upstream branches are the branches on the remote repository that are tracked by a local remote branch in the local repository. These local remote branches are also called remote-tracking branches.
The easiest way to set the upstream branch is to use the “git push” command with the “-u” option for upstream branch. Alternatively, you can use the “–set-upstream” option that is equivalent to the “-u” option. As an example, let's say that you created a branch named “branch” using the checkout command.
--set-upstream is used to map a branch in your local to a branch on remote so that you can just do git push or git pull and it will know which branch to push/pull from. For adding a remote repo I use these commands. First, check your remote repositories with git remote -v.
Push a new Git branch to a remote repo Clone the remote Git repo locally. Create a new branch with the branch, switch or checkout commands. Perform a git push with the –set-upstream option to set the remote repo for the new branch. Continue to perform Git commits locally on the new branch.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With