簡體   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