4

I need a piece of code which can pull from origin and merge with local repo. I tried with local repo which can get the last commit and revision. however not able to pull the changes from origin.

File gitWorkDir = new File(gitDir);
Git git = Git.open(gitWorkDir);
Repository repo = git.getRepository();
UsernamePasswordCredentialsProvider user = new 
UsernamePasswordCredentialsProvider("username", "password");
PullCommand pullCmd = git.pull();
pullCmd.setCredentialsProvider(user);
pullCmd.call();
ObjectId lastCommitId = repo.resolve(Constants.HEAD);
log.info(lastCommitId);

where gitDir is my local Repository Dir.

Mincong Huang
  • 5,284
  • 8
  • 39
  • 62
Deepak sethi
  • 45
  • 1
  • 5

1 Answers1

7

You need to provide the remote repository name, and the remote branche name. For example origin and master:

PullResult result = git.pull()
    .setCredentialsProvider(user)
    .setRemote("origin")
    .setRemoteBranchName("master")
    .call();

if (result.isSuccessful()) {
  ...
} else {
  ...
}

Please also note that the result returned by the pull command is PullRequestβ€”its method isSuccessful() indicates whether the pull was successful. You might want to add this logic in your code too.

References:

Mincong Huang
  • 5,284
  • 8
  • 39
  • 62