繁体   English   中英

使用 java 从 Azure devops 将 git 存储库克隆到本地

[英]Clone a git repository to local from Azure devops using java

使用以下代码从 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();
        }

如果我们只尝试克隆 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 或其他东西)中有任何其他解决方案,它会起作用。

谢谢

请检查您的文件夹是否存在,然后使用pull命令

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

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

pullCommand.call();

根据git clone命令,只有当目录为时才允许克隆到现有目录,因此您不能第二次克隆 repo。

关于您的 2# 请求“如果它已经存在,则仅提取最新的更改。”,您应该使用git pull而不是git clone

如果你想尝试一下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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM