-
Notifications
You must be signed in to change notification settings - Fork 892
git commit
Radium Zheng edited this page Dec 7, 2023
·
8 revisions
The following examples assume you already have a repository in place to work with. If not, see git-init.
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);
}
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(
author,
committer,
"i'm a commit message :)",
tree,
repo.Commits,
prettifyMessage: false);
// Update the HEAD reference to point to the latest commit
repo.Refs.UpdateTarget(repo.Refs.Head, commit.Id);
}