Amir Ashfaq
Amir Ashfaq

Reputation: 335

Make an existing Git branch track a remote branch with JGit?

I am using JGit for creating a new git repository, and everything already present in the folder, I save as new branch.

I am using

Git.init().setDirectory(workingDir).call();

(by-default master branch is created after above statement, so i rename it to "backupBranch"). because master I clone from a remote master later.

Problem is when I push the backupbranch, its pushed but no remote tracking I am able to establish.

from terminal: if I use git branch -vv result is

master       5f1994c [origin/master] commitmsg
backupbranch 7a4d671 taking backup of file already in MyTests Folder..

According to link Make an existing Git branch track a remote branch? I can use git branch -u upstream/foo from terminal to specify any time after pushing backupbranch.

How to achieve it using JGit.

Following is code I am using

to create the backupbranch

git.branchRename().setNewName(backUpName).call();
git.add().addFilepattern(".").call();
RevCommit commit = git.commit().setMessage("taking backup of file already in MyTests Folder..").call();

then push it first time.

Iterable<PushResult> pushResult = git.push().call();

Please suggest the way I can specify remote tracking for existing branch.

Upvotes: 6

Views: 903

Answers (1)

R&#252;diger Herrmann
R&#252;diger Herrmann

Reputation: 20985

You can use the CreateBranchCommand as decribed in this post

CreateBranchCommand create = git.branchCreate();
create.setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM);
create.setName("develop");
create.setStartPoint("origin/develop");
create.setForce(true)
create.call();

Note the setForce(true) call. Because your local branch already exists you will need to override it. It will point to the remote tracking branch (origin/develop) afterwards - which it did before anyway.

Alternatively you can directly modify the config file. For example:

StoredConfig config = git.getRepository().getConfig();
String branchName = "develop"
String remoteName = "origin";
config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName,  ConfigConstants.CONFIG_KEY_REMOTE, remoteName);
config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName, ConfigConstants.CONFIG_KEY_MERGE, Constants.R_HEADS + branchName);
config.save();

This will result in a configuration section like this:

[branch "develop"]
remote = origin
merge = refs/heads/develop

Upvotes: 7

Related Questions