Skip to content
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.

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(
        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);
}
Clone this wiki locally
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy