首页 > 解决方案 > 使用 java 从 Azure devops 将 git 存储库克隆到本地

问题描述

使用以下代码从 ADO 克隆 repo。

        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();
        }

如果我们只尝试克隆一次 repo,它工作正常。在第二次它会抛出一个错误,如:

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)

请提出一个解决方案,其中:

  1. 如果存储库不在本地,请像上面一样克隆它。
  2. 如果它已经存在,则仅拉取最新的更改。

此外,如果在 Java 中有任何其他解决方案(任何其他 API 或其他东西),它会起作用。

谢谢

标签: javagitazure-devopsjgit

解决方案


如果你想试试git24j,你可以这样做:

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);
}

推荐阅读