Sanket Singh
Sanket Singh

Reputation: 1366

Clone a git repository to local from Azure devops using java

Used the following piece of code to clone the repo from ADO.

        File file = new File("local_folder_location");
        CredentialsProvider cp = new UsernamePasswordCredentialsProvider("user_id", "password");
        try {
            Git.cloneRepository()
                      .setURI("repo_path")
                      .setCredentialsProvider(cp)
                      .setDirectory(file)
                      .call();
        } catch (GitAPIException e) {
            e.printStackTrace();
        }

It is working fine if we try to clone the repo only once. On the second time it will throw an error like:

Exception in thread "main" org.eclipse.jgit.api.errors.JGitInternalException: Destination path "path" already exists and is not an empty directory
    at org.eclipse.jgit.api.CloneCommand.verifyDirectories(CloneCommand.java:253)
    at org.eclipse.jgit.api.CloneCommand.call(CloneCommand.java:189)

Please suggest a solution in which:

  1. If the repository is not there in local, Clone it like above.
  2. If it is already existing, pull the latest changes only.

Also if there's any other solution to this in Java (any other API or something), it would work.

Thanks

Upvotes: 0

Views: 1167

Answers (3)

Shijing Lv
Shijing Lv

Reputation: 6736

If you would like to give git24j a try, you can do this:

String urlThatNeedsAuth = "https://github.com/a-private-repo.git";
File localDir = new File("/tmp/localPath");
// libgit2 sets credential through callbacks
Clone.Options opts = Clone.Options.defaultOpts();
opts.getFetchOpts()
    .getCallbacks()
    .setCredAcquireCb(
        (url, usernameFromUrl, allowedTypes) ->
            Credential.userpassPlaintextNew("fake-user", "fake-passwd"));

// pull if local clone exits, clone otherwise
if (localDir.exists()) {
    Repository repo = Repository.open(localDir.getPath());
    Remote.lookup(repo, "origin").fetch(null, opts.getFetchOpts(), null);
} else {
    Clone.cloneRepo(aUrlThatNeedsAuth, localDir.getPath(), opts);
}

Upvotes: 1

Cece Dong - MSFT
Cece Dong - MSFT

Reputation: 31083

According to git clone command, cloning into an existing directory is only allowed if the directory is empty, so you can not clone the repo second time.

Regarding your 2# request "If it is already existing, pull the latest changes only.", you should use git pull instead of git clone.

Upvotes: 1

Krzysztof Madej
Krzysztof Madej

Reputation: 40729

Please check if your folder exists and if then use pull command

Git git = Git.open(new File("/path/to/repo/.git"));

PullCommand pullCommand = git.pull();
    pullCommand.setCredentialsProvider(
      new UsernamePasswordCredentialsProvider("user_id", "password" )
    );

pullCommand.call();

Upvotes: 1

Related Questions