Join GitHub today
GitHub is home to over 31 million developers working together to host and review code, manage projects, and build software together.
Sign upgit commit
The following examples assume you already have a repository in place to work with. If not, see git-init.
Make a commit to a non-bare repository
If you want to commit to a repository that is checked out to the file system, you can update the file on the file system and use the repository's Commit method.
using (var repo = new Repository("path/to/your/repo"))
{
// Write content to file system
var content = "Commit this!";
File.WriteAllText(Path.Combine(repo.Info.WorkingDirectory, "fileToCommit.txt"), content);
// Stage the file
repo.Index.Add("fileToCommit.txt");
repo.Index.Write();
// Create the committer's signature and commit
Signature author = new Signature("James", "@jugglingnutcase", DateTime.Now);
Signature committer = author;
// Commit to the repository
Commit commit = repo.Commit("Here's a commit i made!", author, committer);
}Make a commit to a bare repository
using (Repository repo = new Repository("path-to-bare-repo"))
{
string content = "Hello commit!";
// Create a blob from the content stream
byte[] contentBytes = System.Text.Encoding.UTF8.GetBytes(content);
MemoryStream ms = new MemoryStream(contentBytes);
Blob newBlob = repo.ObjectDatabase.CreateBlob(ms);
// Put the blob in a tree
TreeDefinition td = new TreeDefinition();
td.Add("filePath.txt", newBlob, Mode.NonExecutableFile);
Tree tree = repo.ObjectDatabase.CreateTree(td);
// Committer and author
Signature committer = new Signature("James", "@jugglingnutcase", DateTime.Now);
Signature author = committer;
// Create binary stream from the text
Commit commit = repo.ObjectDatabase.CreateCommit(
"i'm a commit message :)",
author,
committer,
tree,
repo.Commits);
// Update the HEAD reference to point to the latest commit
repo.Refs.UpdateTarget(repo.Refs.Head, commit.Id);
}
