1

My requirement is that I want to programmatically commit a file to a remote base repository (that resides in a central location like https//:myproject.git).

I would like to know if it is possible to commit a file to a remote base repository (master) without cloning the base repo into my local machine. I am a newbie to JGit. Please let me know.

Rüdiger Herrmann
  • 20,512
  • 11
  • 62
  • 79
gihan-maduranga
  • 4,381
  • 5
  • 41
  • 74
  • git only operates on local files. While it has facilities for synchronizing state between local and remote repositories, all repository updates happen locally. You will need to clone the repository, make your changes, and then push them back to the remote. – larsks Oct 18 '16 at 20:04

1 Answers1

1

As @larsks already pointed out, you need to first create a local clone of the remote base repository. Changes can only be committed to the local copy of the base repository. Finally, by pushing to the originating repository, the local changes are made available on the remote repository for others.

JGit has a Command API that is modeled after the Git command line and can be used to clone, commit, and push.

For example:

// clone base repository into a local directory
Git git Git.cloneRepository().setURI( "https://..." ).setDirectory( new File( "/path/to/local/copy/of/repo" ) ).call();
// create, modify, delete files in the repository's working directory,
// that is located at git.getRepository().getWorkTree()
// add and new and changed files to the staging area
git.add().addFilepattern( "." ).call();
// remove deleted files from the staging area
git.rm().addFilepattern( "" ).call();
// commit changes to the local repository
git.commit().setMessage( "..." ).call();
// push new commits to the base repository
git.push().setRemote( "http://..." ).setRefspec( new Refspec( "refs/heads/*:refs/remotes/origin/*" ) ).call();

The PushCommand in the above example explicitly states which remote to push to and which branches to update. In many cases, it may be sufficient to omit the setter and let the command read suitable defaults from the repository configuration with git.push().call().

For further information, you may want to have a look at some articles that go into more detail of cloning, making local changes, and other aspects like authentication and setting up the development environment

Community
  • 1
  • 1
Rüdiger Herrmann
  • 20,512
  • 11
  • 62
  • 79