1

我正在尝试将 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”错误。我尝试了许多不同的事情,包括克隆到临时字典,使用 BranchCreate,......但我总是在某个地方遇到问题。

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

4

1 回答 1

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.csL61-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();
于 2015-06-27T05:56:51.057 回答