[英]Clone repository into existing directory using NGit / JGit
I'm trying to clone a GitHub repository into a existing, non-empty directory. 我正在尝试将GitHub存储库克隆到现有的非空目录中。 I tried mimicking the way it's done using the git command line:
我试图模仿使用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();
In this particular case I got a "Nothing to fetch" error. 在这种特殊情况下,我收到“什么也无法提取”错误。 I've tried a number of different things, including cloning into a temporary dictionary, using BranchCreate, ... but I've always ran into an issue somewhere .
我已经尝试了许多不同的方法,包括使用BranchCreate克隆到临时字典中,但是...我总是在某个地方遇到问题。
So how would you go about properly cloning a repository and set it up to fetch updates in the future? 那么您将如何正确克隆存储库并将其设置为将来获取更新?
While cloning is easier than git init .
虽然克隆比
git init .
容易git init .
+ git remote add origin ...
+ git fetch
+ git reset --hard origin/master
., that sequence is needed for a non-empty folder indeed. +
git remote add origin ...
+ git fetch
+ git reset --hard origin/master
。,确实需要一个非空文件夹的序列。
In that case, you need to tell Git what to fetch, as commented by the OP: 在这种情况下,您需要告诉Git要获取什么,如OP所述:
git.Fetch().SetRefSpecs(new RefSpec("+refs/heads/*:refs/remotes/origin/*")).Call();
That will allow the git.Fetch().Call();
这将允许
git.Fetch().Call();
to actually fetch something. 实际获取东西。
(That is what the NGit.Test/NGit.Api/FetchCommandTest.cs
L61-L82 is doing) (这就是
NGit.Test/NGit.Api/FetchCommandTest.cs
L61-L82所做的事情)
After extensive discussion in the chat , here is the code the OP is using: 在聊天中进行了广泛讨论之后, 这是 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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.