how to commit and push in libgit2sharp

user3900196 picture user3900196 · Aug 1, 2014 · Viewed 7.8k times · Source

I just downloaded the nugget package for libgit2sharp. I am finding it difficult to do even basic operations.

I have an existing git repo (both remote and local). I just need to commit new changes when it occurs and push it to the remote.

I have the code below to explain what I did.

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...");

Where should I specify remote url's ? also is this the right way of doing these operations(commit & push)?

Thanks

Answer

user3900196 picture user3900196 · Aug 4, 2014
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);
    }
}