如何提交和推送libgit2sharp

时间:2014-08-01 16:38:25

标签: libgit2 libgit2sharp

我刚刚下载了libgit2sharp的nugget包。 我发现即使是基本的操作也很困难。

我有一个现有的git repo(远程和本地)。我只需要在发生更改时提交新的更改并将其推送到远程。

我有以下代码来解释我的所作所为。

string path = @"working direcory path(local)";
Repository repo = new Repository(path);
repo.Commit("commit done for ...");

Remote remote = repo.Network.Remotes["origin"];          
var credentials = new UsernamePasswordCredentials {Username = "*******", Password = "******"};
var options = new PushOptions();
options.Credentials = credentials;
var pushRefSpec = @"refs/heads/master";                      
repo.Network.Push(remote, pushRefSpec, options, null, "push done...");

我应该在哪里指定远程网址?这也是做这些操作的正确方法(commit& push)?

由于

2 个答案:

答案 0 :(得分:9)

public void StageChanges() {
    try {
        RepositoryStatus status = repo.Index.RetrieveStatus();
        List<string> filePaths = status.Modified.Select(mods => mods.FilePath).ToList();
        repo.Index.Stage(filePaths);
    }
    catch (Exception ex) {
        Console.WriteLine("Exception:RepoActions:StageChanges " + ex.Message);
    }
}

public void CommitChanges() {
    try {

        repo.Commit("updating files..", new Signature(username, email, DateTimeOffset.Now),
            new Signature(username, email, DateTimeOffset.Now));
    }
    catch (Exception e) {
        Console.WriteLine("Exception:RepoActions:CommitChanges " + e.Message);
    }
}

public void PushChanges() {
    try {
        var remote = repo.Network.Remotes["origin"];
        var options = new PushOptions();
        var credentials = new UsernamePasswordCredentials { Username = username, Password = password };
        options.Credentials = credentials;
        var pushRefSpec = @"refs/heads/master";
        repo.Network.Push(remote, pushRefSpec, options, new Signature(username, email, DateTimeOffset.Now),
            "pushed changes");
    }
    catch (Exception e) {
        Console.WriteLine("Exception:RepoActions:PushChanges " + e.Message);
    }
}

答案 1 :(得分:3)

遥控器已有网址。

如果您想更改与名为“origin”的远程关联的网址,则需要:

  • 删除该遥控器:

    repo.Network.Remotes.Remove("origin");
    
    # you can check it with:
    Assert.Null(repo.Network.Remotes["origin"]);
    Assert.Empty(repo.Refs.FromGlob("refs/remotes/origin/*"));
    
  • 创建一个新的(默认refspec)

    const string name = "origin";
    const string url = "https://github.com/libgit2/libgit2sharp.git";
    repo.Network.Remotes.Add(name, url);
    
    # check it with:
    Remote remote = repo.Network.Remotes[name];
    Assert.NotNull(remote);
    

LibGit2Sharp.Tests/RemoteFixture.cs

了解详情

in the comments nulltoken contributor to libgit2更新了PR 803

  

{{3}}已合并。
  这应该允许一些代码,如

Remote updatedremote = 
   repo.Network.Remotes.Update(remote, r => r.Url = "http://yoururl");