Reputation: 491
I am trying to create a remote branch with jgit, which executes exactly the following git commands:
After these executions, I can change and push the files of the branch without merge request.
jGit:
Unfortunately jgit does not know the command "push -u" (Upstream). So I found some maybe solution. But all solutions does not work really.
First in StackOverflow:
// git clone done, than:
git.branchCreate()
.setName("superBranch")
.setForce(true)
.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
.setStartPoint("origin/superBranch").call(); // <-- Ref not found
RefSpec refSpec = new RefSpec().setSourceDestination("superBranch", "superBranch");
git.push()
.setRefSpecs(refSpec)
.setCredentialsProvider(provider).call();
git.checkout().setName("superBranch").call();
Exception:
org.eclipse.jgit.api.errors.RefNotFoundException: Ref origin/superBranch cannot be resolved
Another solution I found here Eclipse Forum:
git.branchCreate().setName("superBranch").call();
git.push()
.setRemote("origin")
.setRefSpecs(new RefSpec("superBranch" + ":" + "superBranch")) //<-- Ref not found
.setCredentialsProvider(provider).call();
git.branchCreate()
.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.SET_UPSTREAM)
.setStartPoint("origin/" + "superBranch")
.setForce(true).call();
git.checkout().setName("superBranch").call();
Exception:
org.eclipse.jgit.api.errors.InvalidRefNameException: Branch name <null> is not allowed
Does anyone know how can I create a remote and local branch, without call an api or make a merge request like my git example on the top?
Upvotes: 2
Views: 2075
Reputation: 784
Finally, I tried this, that works for me.
git.branchCreate().setName(localBranchName).call();
git.push().setRemote("origin")
.setCredentialsProvider(createCredential(name, password))
.setRefSpecs(new RefSpec(localBranchName + ":" + localBranchName)).call();
//delete is necessary
git.branchDelete().setBranchNames(localBranchName).call();
git.checkout().setCreateBranch(true).setName(localBranchName)
.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
.setStartPoint("origin/" + localBranchName)
.call();
Upvotes: 0
Reputation: 491
Following code works for me:
Git git = Git.cloneRepository()
.setURI("https://gitlab.com/my-project/test.git")
.setDirectory(new File("scratch/test"))
.setCloneAllBranches(true)
.setCredentialsProvider(provider).call();
git.checkout()
.setCreateBranch(true)
.setName(BRANCH).call();
git.push()
.setRemote("origin")
.setRefSpecs(new RefSpec(BRANCH + ":" + BRANCH))
.setCredentialsProvider(provider).call();
So I clone the repository, checkout the branch or create the branch if not exits, then I push the new branch to the remote repository.
Upvotes: 1