SharpGit2 1.0.0-alpha.1
dotnet add package SharpGit2 --version 1.0.0-alpha.1
NuGet\Install-Package SharpGit2 -Version 1.0.0-alpha.1
<PackageReference Include="SharpGit2" Version="1.0.0-alpha.1" />
<PackageVersion Include="SharpGit2" Version="1.0.0-alpha.1" />
<PackageReference Include="SharpGit2" />
paket add SharpGit2 --version 1.0.0-alpha.1
#r "nuget: SharpGit2, 1.0.0-alpha.1"
#:package SharpGit2@1.0.0-alpha.1
#addin nuget:?package=SharpGit2&version=1.0.0-alpha.1&prerelease
#tool nuget:?package=SharpGit2&version=1.0.0-alpha.1&prerelease
SharpGit2
A managed implementation of Git for .NET, written entirely in C#. It reads and writes Git repositories directly, with
no native Git library or git executable required.
Warning: SharpGit2 is in early alpha. It is not ready for production use and may damage repositories it works on; keep backups. Public APIs may change at any future alpha version without notice.
What it covers
- Repositories: open, init, clone, worktrees, submodules, bare and in-memory object databases, SHA-1 and SHA-256
- Objects: commits, trees, blobs, tags, packfiles, commit-graph files, mailmap
- References: loose and packed refs, reftable, reflogs, branches, tags, notes, rev-parse and revision walking
- Working with changes: index, status, diff, apply, blame, describe, checkout, reset, stash
- Combining history: merge, rebase, cherry-pick, revert
- Filters and attributes:
.gitattributes,.gitignore, line-ending conversion - Remotes: fetch and push over HTTP(S),
git://and local paths; reading bundles
Not there yet
- SSH transport
- SHA-1 collision detection (git rejects objects crafted for known SHA-1 collision attacks; SharpGit2 does not yet)
- Writing bundles
- Loose objects of 2 GiB or more
Requirements
.NET 11+
Installing
dotnet add package SharpGit2 --prerelease
Getting started
GitRepository is the entry point. Its collections (Branches, Commits, Objects, References, Remotes,
Tags and others) group the operations on the repository. A few types live in sub-namespaces, such as
SharpGit2.Diff and SharpGit2.Remote. Dispose of repositories and remotes when you're done with them; commits,
trees and blobs need no disposal.
Opening, creating and cloning
using SharpGit2;
// Open an existing repository (the working directory or the .git directory)
using var repository = GitRepository.Open("path/to/repository");
// Create a new one
using var created = GitRepository.InitRepository("path/to/new-repository", isBare: false);
// Clone one
using var cloned = await GitRepository.CloneAsync("https://example.com/project.git", "path/to/clone");
Branches and commits
// Look up a local branch by name
var main = repository.Branches.Lookup("main");
// List the local branches
foreach (var branch in repository.Branches.EnumerateLocal())
{
Console.WriteLine(branch.Name);
}
// The commit a branch points to
var commit = (GitCommit)main.Peel(GitObjectType.Commit);
Console.WriteLine($"{commit.ObjectID} {commit.Author.Name}: {commit.Summary}");
// Faster, when the branch is known to point directly at a commit
var tip = repository.Objects.LookupCommit(in main.DirectTarget);
// Any revision git understands
var previous = (GitCommit)repository.RevParseSingle("HEAD~1")!;
Walking history
var walk = new GitRevWalk(repository);
walk.Sorting(GitRevWalk.SortType.Time);
walk.PushHead();
while (walk.Next(out var id))
{
var c = repository.Objects.LookupCommit(in id);
Console.WriteLine($"{id.ToString()[..7]} {c.Summary}");
}
PushRange("main..feature"), Hide and SetPathspec narrow the walk, like the arguments of git log.
Reading files
var tree = commit.GetTree();
// A file by path
var entry = tree.GetEntryByPath("src/Program.cs");
var blob = repository.Objects.LookupBlob(in entry.ObjectId);
using (var reader = new StreamReader(blob.GetContentStream()))
{
Console.WriteLine(reader.ReadToEnd());
}
// The entries of a directory
for (int i = 0; i < tree.EntryCount; i++)
{
var e = tree[i];
Console.WriteLine($"{(e.IsTree ? "dir " : "file")} {e.FileName}");
}
Status
foreach (var item in repository.GetStatus())
{
Console.WriteLine($"{item.Status}: {item.Path}"); // e.g. "WorkTreeModified: README.md"
}
Staging and committing
var index = repository.Index;
index.AddByPath("README.md");
index.AddByPath("notes.txt");
index.Write();
// The author and committer default to user.name and user.email from the configuration
var me = new GitSignature("Ada", "ada@example.com", DateTimeOffset.Now);
var newId = repository.Commits.CreateFromStage("Add notes", new GitCommitOptions { Author = me, Committer = me });
Diffs
using SharpGit2.Diff;
var newCommit = repository.Objects.LookupCommit(in newId);
var diff = GitDiff.TreeToTree(repository, newCommit.GetParent(0).GetTree(), newCommit.GetTree());
foreach (var delta in diff)
{
Console.WriteLine($"{delta.Status} {delta.NewFile.Path}");
}
Console.WriteLine(diff.ToText()); // the patch, as git diff prints it
Console.WriteLine(diff.GetStats()); // " 2 files changed, 2 insertions(+)"
TreeToIndex, IndexToWorkDir and TreeToWorkDirWithIndex compare against the index and the working directory.
Branches, tags and checkout
var feature = repository.Branches.Create("feature", newCommit, force: false);
repository.Tags.CreateLightweight("v1.0", newCommit, allowReferenceOverwrite: false);
repository.Tags.Create("v1.0-annotated", newCommit, me, "First release", allowReferenceOverwrite: false);
// Switch to the branch, like git switch
repository.CheckoutTree(newCommit);
repository.SetHead(feature.ReferenceName);
Fetching and pushing
using SharpGit2.Remote;
using var origin = repository.Remotes.Lookup("origin");
await origin.FetchAsync();
await origin.PushAsync(["refs/heads/feature:refs/heads/feature"]);
Credentials, progress reporting and certificate checks go through an IGitRemoteCallbacks implementation, passed in
GitFetchOptions, GitPushOptions or GitCloneOptions.FetchOptions:
using SharpGit2.ObjectDB;
using SharpGit2.Remote;
var options = new GitFetchOptions { Callbacks = new TokenCallbacks("user", "token") };
await origin.FetchAsync(options: options);
sealed class TokenCallbacks(string username, string password) : IGitRemoteCallbacks
{
public ValueTask<GitCredential?> GetCredentialsAsync(GitCredentialRequest request, CancellationToken cancellationToken)
// Once these credentials are rejected, returning null gives up: the operation throws GitNetAuthException
=> ValueTask.FromResult<GitCredential?>(request.Rejected == null ? new GitUserPassCredential(username, password) : null);
public void SideBandProgress(ReadOnlySpan<char> message) { }
public void Completion(GitRemoteCompletionType type) { }
public void TransferProgress(GitIndexerProgress stats) { }
public void PushTransferProgress(uint current, uint total, long bytes) { }
public void PackProgress(int stage, uint current, uint total) { }
public void RemoteReady(GitRemote remote, GitDirection direction) { }
}
Source code
Each package published to NuGet is built from a tagged commit of this repository. The tag is named after the package version, and the package metadata also records the exact commit it was built from. The complete source for any release is available from that tag at https://gitlab.com/Sunkin351/SharpGit2.
License
SharpGit2 is licensed under the GNU General Public License, version 2, with a linking exception. In short: you may use the library in programs under any license, including proprietary ones, without those programs becoming subject to the GPL. If you distribute a modified version of SharpGit2 itself, that version must be released under the same terms. The full text is in LICENSE.
SharpGit2 contains code derived from libgit2, and some components come from other projects under their own licenses. See THIRD-PARTY-NOTICES.md.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net11.0 is compatible. |
-
net11.0
- BitFaster.Caching (>= 2.5.4)
- CommunityToolkit.HighPerformance (>= 8.4.0)
- Microsoft.IO.RecyclableMemoryStream (>= 3.0.1)
- Mono.Posix.NETStandard (>= 1.0.0)
- System.IO.Hashing (>= 10.0.9)
- TerraFX.Interop.Windows (>= 10.0.26100.5)
- ValueCollections (>= 6.3.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 1.0.0-alpha.1 | 50 | 11/24/2026 |
Early preview. See the README for what's implemented and known gaps.