使用 NGit / JGit 将存储库克隆到现有目录

Clone repository into existing directory using 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();

在这种特殊情况下,我遇到了 "Nothing to fetch" 错误。我尝试了很多不同的方法,包括克隆到临时字典中,使用 B运行chCreate,...但我总是 运行 遇到问题 某处.

那么您将如何正确克隆存储库并将其设置为将来获取更新?

虽然克隆比 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 所做的)

extensive discussion in the chat, here is the code 之后,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();