Клонировать репозиторий в существующий каталог с помощью NGit / JGit

Я пытаюсь клонировать GitHub-репозиторий в существующий непустой каталог. Я попытался подражать, как это делается с помощью командной строки git:

git init
git remote add origin https://github.com/[...].git
git fetch
git reset --hard origin/branch

var git = Git.Init().SetDirectory(Location).Call();
Repository = git.GetRepository();

var config = Repository.GetConfig();
config.SetString("remote", "origin", "url", "https://github.com/[...].git");
config.Save();

git.Fetch().Call();

git.Reset().SetRef("origin/branch")
    .SetMode(ResetCommand.ResetType.HARD).Call();

В этом конкретном случае я получил ошибку "Ничего не получить". Я пробовал разные вещи, в том числе клонирование во временный словарь, использование BranchCreate,... но я всегда где-то сталкивался с проблемой.

Итак, как бы вы правильно клонировали репозиторий и настроили его для получения обновлений в будущем?

1 ответ

Решение

Хотя клонирование проще, чем git init . + git remote add origin ... + git fetch + git reset --hard origin/master., эта последовательность необходима для непустой папки действительно.

В этом случае вам нужно указать Git, что нужно получить, как прокомментировал OP:

git.Fetch().SetRefSpecs(new RefSpec("+refs/heads/*:refs/remotes/origin/*")).Call();

Это позволит git.Fetch().Call(); на самом деле получить что-то.

(Это то, что NGit.Test/NGit.Api/FetchCommandTest.cs Делает L61-L82)

После обширного обсуждения в чате вот код, который использует OP:

var cloneUrl = ...;
var branchName = ...;

var git = Git.Init().SetDirectory(Location).Call();
Repository = git.GetRepository();

// Original code in question works, is shorter,
// but this is most likely the "proper" way to do it.
var config = Repository.GetConfig();
RemoteConfig remoteConfig = new RemoteConfig(config, "origin");
remoteConfig.AddURI(new URIish(cloneUrl));
// May use * instead of branch name to fetch all branches.
// Same as config.SetString("remote", "origin", "fetch", ...);
remoteConfig.AddFetchRefSpec(new RefSpec(
    "+refs/heads/" + Settings.Branch +
    ":refs/remotes/origin/" + Settings.Branch));
remoteConfig.Update(config);
config.Save();

git.Fetch().Call();
git.BranchCreate().SetName(branchName).SetStartPoint("origin/" + branchName)
    .SetUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).Call();
git.Checkout().SetName(branchName).Call();

// To update the branch:

git.Fetch().Call();
git.Reset().SetRef("origin/" + branchName).Call();
Другие вопросы по тегам