虽然克隆比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();