how to commit and push in libgit2sharp

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);
    }
}

The remote already has an url.

If you wanted to change the url associated with remote named 'origin', you would need to:

  • remove that remote:

    repo.Network.Remotes.Remove("origin");
    
    # you can check it with:
    Assert.Null(repo.Network.Remotes["origin"]);
    Assert.Empty(repo.Refs.FromGlob("refs/remotes/origin/*"));
    
  • create a new one (default 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);
    

See more at LibGit2Sharp.Tests/RemoteFixture.cs


As updated in the comments by nulltoken, contributor to libgit2:

PR 803 has been merged.
This should allow some code such as

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