### LibGit2Sharp: Full Example - Compare Commit and Working File Content Source: https://github.com/libgit2/libgit2sharp/wiki/git-cat-file A complete C# example demonstrating how to iterate through modified files in a repository, retrieve their content from the HEAD commit, and compare it with the content in the working directory. Requires specifying the repository path. ```csharp using System; using System.IO; using System.Text; using System.Collections.Generic; using LibGit2Sharp; namespace libgitblob { class MainClass { public static void Main (string[] args) { var repo = new Repository ("/your/repo/path"); foreach (var item in repo.RetrieveStatus()) { if (item.State == FileStatus.Modified) { var blob = repo.Head.Tip[item.FilePath].Target as Blob; string commitContent; using (var content = new StreamReader(blob.GetContentStream(), Encoding.UTF8)) { commitContent = content.ReadToEnd(); } string workingContent; using (var content = new StreamReader(repo.Info.WorkingDirectory + Path.DirectorySeparatorChar + item.FilePath, Encoding.UTF8)) { workingContent = content.ReadToEnd(); } Console.WriteLine ("\n\n~~~~ Original file ~~~~ "); Console.WriteLine(commitContent); Console.WriteLine ("\n\n~~~~ Current file ~~~~ "); Console.WriteLine(workingContent); } } } } } ``` -------------------------------- ### Complete C# Example: Generate Patches for All Modified Files Source: https://github.com/libgit2/libgit2sharp/wiki/git-diff-{filename}---local.patch A full C# program demonstrating how to iterate through modified files in a repository using LibGit2Sharp and generate a patch for each. ```csharp using System; using System.Collections.Generic; using LibGit2Sharp; namespace libgitdiff { class MainClass { public static void Main (string[] args) { var repo = new Repository ("/your/repo/path"); foreach (var item in repo.RetrieveStatus()) { if (item.State == FileStatus.Modified) { var patch = repo.Diff.Compare (new List() { item.FilePath }); Console.WriteLine ("~~~~ Patch file ~~~~"); Console.WriteLine (patch.Content); } } } } } ``` -------------------------------- ### Git Command-Line: Cat-File Example Source: https://github.com/libgit2/libgit2sharp/wiki/git-cat-file Demonstrates the basic syntax for using the git cat-file command to retrieve the content of a specific file (identified by SHA and filename) from a Git repository. ```bash $git cat-file {sha}:{filename} ``` -------------------------------- ### Remove File and Commit using LibGit2Sharp Source: https://github.com/libgit2/libgit2sharp/wiki/git-rm This example demonstrates removing a file and then committing the change to the repository using LibGit2Sharp. It includes creating the necessary author and committer signatures. ```csharp using (var repo = new Repository("")) { // Create the committer's signature and commit Signature author = new Signature("Author", "@Author", DateTime.Now); Signature committer = author; // Remove the file. Path must be in Posix format (using '/' as path separator) repo.Index.Remove(""); // Commit to the repository Commit commit = repo.Commit(message, author, committer); } ``` -------------------------------- ### LibGit2Sharp API Usage Example Source: https://github.com/libgit2/libgit2sharp/wiki/Home This snippet demonstrates common operations such as object lookup, rev walking, reference manipulation, branch management, and tag creation using the LibGit2Sharp API. Ensure a valid repository path is provided. ```csharp using (var repo = new Repository("path\to\repo.git")) { // Object lookup var obj = repo.Lookup("sha"); var commit = repo.Lookup("sha"); var tree = repo.Lookup("sha"); var tag = repo.Lookup("sha"); // Rev walking foreach (var c in repo.Commits.Walk("sha")) { } var commits = repo.Commits.StartingAt("sha").Where(c => c).ToList(); var sortedCommits = repo.Commits.StartingAt("sha").SortBy(SortMode.Topo).ToList(); // Refs var reference = repo.Refs["refs/heads/master"]; var allRefs = repo.Refs.ToList(); foreach (var c in repo.Refs["HEAD"].Commits) { } foreach (var c in repo.Head.Commits) { } var headCommit = repo.Head.Commits.First(); var allCommits = repo.Refs["HEAD"].Commits.ToList(); var newRef = repo.Refs.CreateFrom(reference); var anotherNewRef = repo.Refs.CreateFrom("sha"); // Branches // special kind of reference var allBranches = repo.Branches.ToList(); var branch = repo.Branches["master"]; var remoteBranch = repo.Branches["origin/master"]; var localBranches = repo.Branches.Where(p => p.Type == BranchType.Local).ToList(); var remoteBranches = repo.Branches.Where(p => p.Type == BranchType.Remote).ToList(); var newBranch = repo.Branches.CreateFrom("sha"); var anotherNewBranch = repo.Branches.CreateFrom(newBranch); repo.Branches.Delete(anotherNewBranch); // Tags // really another special kind of reference var aTag = repo.Tags["refs/tags/v1.0"]; var allTags = repo.Tags.ToList(); var newTag = repo.Tags.CreateFrom("sha"); var newTag2 = repo.Tags.CreateFrom(commit); var newTag3 = repo.Tags.CreateFrom(reference); } ``` -------------------------------- ### Get Repository Status with LibGit2Sharp Source: https://github.com/libgit2/libgit2sharp/wiki/git-status This snippet shows how to initialize a LibGit2Sharp repository object and iterate through its status items to display file paths. Ensure you have the correct path to your repository. ```csharp using (var repo = new Repository("path/to/your/repo")) { foreach (var item in repo.RetrieveStatus(new LibGit2Sharp.StatusOptions())) { Console.WriteLine(item.FilePath); } } ``` -------------------------------- ### List All Git Tags Source: https://github.com/libgit2/libgit2sharp/wiki/git-tag Lists all tags in the repository. This is useful for getting an overview of all tagged versions. ```git $ git tag ``` -------------------------------- ### Clone libgit2 Repository Source: https://github.com/libgit2/libgit2sharp/wiki/How-to-build-x64-libgit2-and-LibGit2Sharp Fetches the libgit2 source code from its GitHub repository. Ensure you have git installed and accessible in your PATH. ```bash > git clone git://github.com/libgit2/libgit2.git ``` -------------------------------- ### Create New Working Branch Source: https://github.com/libgit2/libgit2sharp/wiki/How-to-upgrade-libgit2-binaries Create a new branch for your work, starting from the upstream/vNext branch. This is useful for isolating your changes. ```bash git checkout --no-track -b topic/upgrade-binaries upstream/vNext ``` -------------------------------- ### Get Repository Status with Git CLI Source: https://github.com/libgit2/libgit2sharp/wiki/git-status This is the standard command-line interface command to check the status of a Git repository. ```bash $ git status ``` -------------------------------- ### Initialize Standard Repository from Rooted Path (LibGit2Sharp) Source: https://github.com/libgit2/libgit2sharp/wiki/git-init Use this method to create a new, standard Git repository at a specified absolute path using LibGit2Sharp. ```csharp string rootedPath = Repository.Init(@"D:\temp\rooted\path"); Console.WriteLine(rootedPath); // "D:\temp\rooted\path\.git\" ``` -------------------------------- ### Initialize Bare Repository from Rooted Path (LibGit2Sharp) Source: https://github.com/libgit2/libgit2sharp/wiki/git-init Use this method to create a new, bare Git repository at a specified absolute path using LibGit2Sharp. Bare repositories are typically used on servers. ```csharp string rootedPath = Repository.Init(@"D:\temp\rooted\path", true); Console.WriteLine(rootedPath); // "D:\temp\rooted\path\" ``` -------------------------------- ### Initialize Standard Repository from Rooted Path (Git) Source: https://github.com/libgit2/libgit2sharp/wiki/git-init Use this command to create a new, standard Git repository at a specified absolute path. ```bash $ git init /d/temp/rooted/path Initialized empty Git repository in d:/temp/rooted/path/.git/ ``` -------------------------------- ### Initialize Standard Repository from Relative Path (LibGit2Sharp) Source: https://github.com/libgit2/libgit2sharp/wiki/git-init Use this method to create a new, standard Git repository using a path relative to the current working directory with LibGit2Sharp. ```csharp string rootedPath = Repository.Init(@"relative\path"); Console.WriteLine(rootedPath); // "D:\temp\relative\path\.git\" ``` -------------------------------- ### Read the HEAD Symbolic Reference with LibGit2Sharp Source: https://github.com/libgit2/libgit2sharp/wiki/git-symbolic-ref Access the `Head` property in LibGit2Sharp to get the canonical name of the HEAD reference. ```csharp using (var repo = new Repository("path/to/your/repo")) { Console.WriteLine(repo.Head.CanonicalName)); } ``` -------------------------------- ### Initialize Bare Repository from Relative Path (LibGit2Sharp) Source: https://github.com/libgit2/libgit2sharp/wiki/git-init Use this method to create a new, bare Git repository using a path relative to the current working directory with LibGit2Sharp. ```csharp string rootedPath = Repository.Init(@"relative\path", true); Console.WriteLine(rootedPath); // "D:\temp\relative\path\" ``` -------------------------------- ### Initialize Bare Repository from Rooted Path (Git) Source: https://github.com/libgit2/libgit2sharp/wiki/git-init Use this command to create a new, bare Git repository at a specified absolute path. Bare repositories are typically used on servers. ```bash $ git init --bare /d/temp/rooted/path Initialized empty Git repository in d:/temp/rooted/path/ ``` -------------------------------- ### Get Submodule Index Commit using LibGit2Sharp Source: https://github.com/libgit2/libgit2sharp/wiki/git-submodule Retrieves the commit ID of the submodule as recorded in the index. This is useful for understanding what commit is staged for the next commit. ```csharp using (var repo = new Repository("path/to/your/repo")) { var submodule = repo.Submodules["submodule"]; Console.WriteLine(submodule.IndexCommitId.Sha); } ``` -------------------------------- ### Initialize Standard Repository from Relative Path (Git) Source: https://github.com/libgit2/libgit2sharp/wiki/git-init Use this command to create a new, standard Git repository using a path relative to the current working directory. ```bash $ git init relative/path Initialized empty Git repository in d:/temp/relative/path/.git/ ``` -------------------------------- ### Initialize Bare Repository from Relative Path (Git) Source: https://github.com/libgit2/libgit2sharp/wiki/git-init Use this command to create a new, bare Git repository using a path relative to the current working directory. ```bash $ git init --bare relative/path Initialized empty Git repository in d:/temp/relative/path/ ``` -------------------------------- ### Get Submodule Head Commit using LibGit2Sharp Source: https://github.com/libgit2/libgit2sharp/wiki/git-submodule Retrieves the commit ID of the submodule's head commit. Use this when you need to know the latest commit the submodule is pointing to. ```csharp using (var repo = new Repository("path/to/your/repo")) { var submodule = repo.Submodules["submodule"]; Console.WriteLine(submodule.HeadCommitId.Sha); } ``` -------------------------------- ### Get Patch for a Specific File Between Commits (LibGit2Sharp) Source: https://github.com/libgit2/libgit2sharp/wiki/git-diff This snippet retrieves the patch content for a specific file between two commits in a repository using LibGit2Sharp. It handles cases where the file might have been renamed. ```csharp string result; using (var repo = new Repository("path/to/your/repo")) { List CommitList = new List(); foreach (LogEntry entry in repo.Commits.QueryBy("relative/path/to/your/file").ToList()) CommitList.Add(entry.Commit); CommitList.Add(null); // Added to show correct initial add int ChangeDesired = 0; // Change difference desired var repoDifferences = repo.Diff.Compare((Equals(CommitList[ChangeDesired + 1], null)) ? null : CommitList[ChangeDesired + 1].Tree, (Equals(CommitList[ChangeDesired], null)) ? null : CommitList[ChangeDesired].Tree); PatchEntryChanges file = null; try { file = repoDifferences.First(e => e.Path == "relative/path/to/your/file");} catch {} // If the file has been renamed in the past- this search will fail if (!Equals(file, null)) { result = file.Patch; } } ``` -------------------------------- ### Build libgit2 Source: https://github.com/libgit2/libgit2sharp/wiki/How-to-build-x64-libgit2-and-LibGit2Sharp Initiates the build process for libgit2 using the generated Visual Studio project files. This command compiles the library, and warnings C4244 and C4267 will be ignored due to previous configuration. ```bash > cmake --build . ``` -------------------------------- ### Fetch all remotes with authentication using LibGit2Sharp (Commands) Source: https://github.com/libgit2/libgit2sharp/wiki/git-fetch Fetches updates from all remotes using the Commands.Fetch method with a UsernamePasswordCredentials provider. Ensure to replace 'USERNAME' and 'PASSWORD' with actual credentials. ```csharp string logMessage = ""; using (var repo = new Repository("path/to/your/repo")) { FetchOptions options = new FetchOptions(); options.CredentialsProvider = new CredentialsHandler((url, usernameFromUrl, types) => new UsernamePasswordCredentials() { Username = "USERNAME", Password = "PASSWORD" }); foreach (Remote remote in repo.Network.Remotes) { IEnumerable refSpecs = remote.FetchRefSpecs.Select(x => x.Specification); Commands.Fetch(repo, remote.Name, refSpecs, options, logMessage); } } Console.WriteLine(logMessage); ``` -------------------------------- ### Fetch updates from 'origin' remote using LibGit2Sharp (Commands) Source: https://github.com/libgit2/libgit2sharp/wiki/git-fetch Fetches updates from the 'origin' remote using the Commands.Fetch method in LibGit2Sharp. Requires specifying refspecs. ```csharp string logMessage = ""; using (var repo = new Repository("path/to/your/repo")) { var remote = repo.Network.Remotes["origin"]; var refSpecs = remote.FetchRefSpecs.Select(x => x.Specification); Commands.Fetch(repo, remote.Name, refSpecs, null, logMessage); } Console.WriteLine(logMessage); ``` -------------------------------- ### Create Lightweight Tag (LibGit2Sharp) Source: https://github.com/libgit2/libgit2sharp/wiki/git-tag Applies a lightweight tag with the specified name to the current HEAD. The repository path must be valid. ```csharp using (var repo = new Repository("path/to/your/repo")) { Tag t = repo.ApplyTag("a-nice-tag-name"); } ``` -------------------------------- ### Stage All Working Directory Changes in LibGit2Sharp Source: https://github.com/libgit2/libgit2sharp/wiki/git-add Use this snippet to stage all changes (modified, added, deleted files) in the entire working directory using LibGit2Sharp. This is the programmatic equivalent of `git add --all .`. ```csharp using (var repo = new Repository(@"path/to/your/repo")) { Commands.Stage(repo, "*"); } ``` -------------------------------- ### Create a Symbolic Reference with LibGit2Sharp Source: https://github.com/libgit2/libgit2sharp/wiki/git-symbolic-ref Use LibGit2Sharp's `Refs.Create` method to programmatically create a symbolic reference. ```csharp using (var repo = new Repository("path/to/your/repo")) { var symRef = repo.Refs.Create("i-track-for-a-living", "refs/heads/master"); } ``` -------------------------------- ### Show Changes in Working Directory (LibGit2Sharp) Source: https://github.com/libgit2/libgit2sharp/wiki/git-diff Use LibGit2Sharp to compare the repository's index with the working directory to find changes. ```csharp using (var repo = new Repository("path/to/your/repo")) { foreach (TreeEntryChanges c in repo.Diff.Compare()) { Console.WriteLine(c); } } ``` -------------------------------- ### Pull Updates with Authentication using LibGit2Sharp Source: https://github.com/libgit2/libgit2sharp/wiki/git-pull Demonstrates how to pull updates from a remote repository using LibGit2Sharp, including setting up credentials for authentication and providing user information for the merge commit. ```csharp using (var repo = new Repository("path/to/your/repo")) { // Credential information to fetch LibGit2Sharp.PullOptions options = new LibGit2Sharp.PullOptions(); options.FetchOptions = new FetchOptions(); options.FetchOptions.CredentialsProvider = new CredentialsHandler( (url, usernameFromUrl, types) => new UsernamePasswordCredentials() { Username = USERNAME, Password = PASSWORD }); // User information to create a merge commit var signature = new LibGit2Sharp.Signature( new Identity("MERGE_USER_NAME", "MERGE_USER_EMAIL"), DateTimeOffset.Now); // Pull Commands.Pull(repo, signature, options); } ``` -------------------------------- ### Generate Visual Studio Project Files Source: https://github.com/libgit2/libgit2sharp/wiki/How-to-build-x64-libgit2-and-LibGit2Sharp Navigates to the libgit2 source directory, creates a build directory, and then uses CMake to generate Visual Studio 10 Win64 project files. This command configures the build for a 64-bit architecture. ```bash > cd libgit2 > mkdir buildx64 > cd buildx64 > cmake -G "Visual Studio 10 Win64" .. -- Check for working C compiler using: Visual Studio 10 Win64 -- Check for working C compiler using: Visual Studio 10 Win64 -- works -- Detecting C compiler ABI info -- Detecting C compiler ABI info - done -- Configuring done -- Generating done -- Build files have been written to: path/to/your/libgit2/buildx64 ``` -------------------------------- ### Show Changes in Index and Working Directory (LibGit2Sharp) Source: https://github.com/libgit2/libgit2sharp/wiki/git-diff Use LibGit2Sharp to compare the repository's HEAD commit against both the index and the working directory. ```csharp using (var repo = new Repository("path/to/your/repo")) { foreach (TreeEntryChanges c in repo.Diff.Compare(repo.Head.Tip.Tree, DiffTargets.Index | DiffTargets.WorkingDirectory)) { Console.WriteLine(c); } } ``` -------------------------------- ### Make a Commit to a Bare Repository Source: https://github.com/libgit2/libgit2sharp/wiki/git-commit This snippet demonstrates how to commit to a bare Git repository. It requires creating a blob from content, adding it to a tree, and then creating the commit object. ```csharp 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); } ``` -------------------------------- ### List All Tags with LibGit2Sharp Source: https://github.com/libgit2/libgit2sharp/wiki/git-tag Iterates through all tags in a LibGit2Sharp repository and prints their friendly names. Ensure the repository path is correct. ```csharp using (var repo = new Repository("path/to/your/repo")) { foreach (Tag t in repo.Tags) { Console.WriteLine(t.FriendlyName); } } ``` -------------------------------- ### Fetch all remotes with authentication using LibGit2Sharp (Old Version) Source: https://github.com/libgit2/libgit2sharp/wiki/git-fetch Fetches updates from all remotes using the older repo.Network.Fetch method with a UsernamePasswordCredentials provider. Ensure to replace 'USERNAME' and 'PASSWORD' with actual credentials. ```csharp using (var repo = new Repository("path/to/your/repo")) { foreach(Remote remote in repo.Network.Remotes) { FetchOptions options = new FetchOptions(); options.CredentialsProvider = new CredentialsHandler( (url, usernameFromUrl, types) => new UsernamePasswordCredentials() { Username = "USERNAME", Password = "PASSWORD" }); repo.Network.Fetch(remote, options); } } ``` -------------------------------- ### Fetch all remotes using Git Source: https://github.com/libgit2/libgit2sharp/wiki/git-fetch Standard Git command to fetch updates from all configured remotes. ```bash $ git fetch --all ``` -------------------------------- ### List Local Branches and Highlight Current Source: https://github.com/libgit2/libgit2sharp/wiki/git-branch Displays all local branches in the repository, marking the current HEAD with an asterisk. Ensure you have a valid repository path. ```git $ git branch ``` ```csharp using (var repo = new Repository("path/to/your/repo")) { foreach(Branch b in repo.Branches.Where(b => !b.IsRemote)) { Console.WriteLine(string.Format("{0}{1}", b.IsCurrentRepositoryHead ? "*" : " ", b.FriendlyName)); } } ``` -------------------------------- ### Create Lightweight Tag on Specific Target (LibGit2Sharp) Source: https://github.com/libgit2/libgit2sharp/wiki/git-tag Applies a lightweight tag with a given name to a specified branch or commit SHA. Ensure the target reference is valid. ```csharp using (var repo = new Repository("path/to/your/repo")) { Tag t = repo.ApplyTag("a-better-tag-name", "refs/heads/cool-branch"); Tag t2 = repo.ApplyTag("the-best-tag-name", "5df3e2b3ca5ebe8123927a81d682993ad597a584"); } ``` -------------------------------- ### Clone a Repository with Authentication Source: https://github.com/libgit2/libgit2sharp/wiki/git-clone Clone a Git repository using LibGit2Sharp with provided username and password credentials. This is useful for private repositories. ```csharp var co = new CloneOptions(); co.FetchOptions.CredentialsProvider = (_url, _user, _cred) => new UsernamePasswordCredentials { Username = "Username", Password = "Password" }; Repository.Clone("https://github.com/libgit2/libgit2sharp.git", "path/to/repo", co); ``` -------------------------------- ### Fetch updates from 'origin' remote using LibGit2Sharp (Old Version) Source: https://github.com/libgit2/libgit2sharp/wiki/git-fetch Fetches updates from the 'origin' remote using the older repo.Network.Fetch method in LibGit2Sharp. ```csharp using (var repo = new Repository("path/to/your/repo")) { Remote remote = repo.Network.Remotes["origin"]; repo.Network.Fetch(remote); } ``` -------------------------------- ### Checkout branch by name using libgit2sharp Source: https://github.com/libgit2/libgit2sharp/wiki/git-checkout This C# code snippet demonstrates how to checkout an existing branch by its name using the libgit2sharp library. It handles cases where the branch might not exist. ```csharp using (var repo = new Repository("path/to/your/repo")) { var branch = repo.Branches[branchName]; if (branch == null) { // repository return null object when branch not exists return null; } Branch currentBranch = Commands.Checkout(repo, branch); } ``` -------------------------------- ### Move a file using LibGit2Sharp Source: https://github.com/libgit2/libgit2sharp/wiki/git-mv Use LibGit2Sharp to move a file within a repository. Ensure paths are in Posix format. ```csharp using (var repo = new Repository("")) { // Moves the file. Path must be in Posix format (using '/' as path separator) Commands.Move(repo, "", "") } ``` -------------------------------- ### Fetch and Checkout libgit2 Revision Source: https://github.com/libgit2/libgit2sharp/wiki/How-to-upgrade-libgit2-binaries Navigate into the libgit2 submodule directory, fetch the latest changes, and checkout a specific revision. ```bash cd libgit2 git fetch git checkout 99a9c86 cd .. ``` -------------------------------- ### Fetch updates from 'origin' remote using Git Source: https://github.com/libgit2/libgit2sharp/wiki/git-fetch Standard Git command to fetch updates from the 'origin' remote. ```bash $ git fetch origin ``` -------------------------------- ### Pushing to a Remote with LibGit2Sharp (Branch) Source: https://github.com/libgit2/libgit2sharp/wiki/git-push Pushes updates for a specified branch to a remote repository using LibGit2Sharp. Requires setting up a CredentialsProvider for authentication. ```csharp using (var repo = new Repository("path/to/your/repo")) { LibGit2Sharp.PushOptions options = new LibGit2Sharp.PushOptions(); options.CredentialsProvider = new CredentialsHandler( (url, usernameFromUrl, types) => new UsernamePasswordCredentials() { Username = USERNAME, Password = PASSWORD }); repo.Network.Push(repo.Branches[BRANCHNAME], options); } ``` -------------------------------- ### Create a Symbolic Reference with Git Source: https://github.com/libgit2/libgit2sharp/wiki/git-symbolic-ref Use the `git symbolic-ref` command to create a new symbolic reference pointing to another reference. ```git $ git symbolic-ref i-track-for-a-living refs/heads/master ``` -------------------------------- ### Update libgit2 Binaries with PowerShell Script Source: https://github.com/libgit2/libgit2sharp/wiki/How-to-upgrade-libgit2-binaries Execute the UpdateLibGit2ToSha.ps1 script to build libgit2. Specify the Visual Studio version if necessary. ```powershell .\UpdateLibGit2ToSha.ps1 99a9c86 ``` ```powershell .\UpdateLibGit2ToSha.ps1 -vs 11 99a9c86 ``` -------------------------------- ### Show Changes in Index (LibGit2Sharp) Source: https://github.com/libgit2/libgit2sharp/wiki/git-diff Use LibGit2Sharp to compare the repository's HEAD commit with the index to find staged changes. ```csharp using (var repo = new Repository("path/to/your/repo")) { foreach (TreeEntryChanges c in repo.Diff.Compare(repo.Head.Tip?.Tree, DiffTargets.Index)) { Console.WriteLine(c); } } ``` -------------------------------- ### Change Target Platform to AnyCPU Source: https://github.com/libgit2/libgit2sharp/wiki/How-to-build-x64-libgit2-and-LibGit2Sharp Modifies the TargetPlatform setting in the .csproj files for both LibGit2Sharp.Tests and LibGit2Sharp. This change is necessary to ensure compatibility when building the LibGit2Sharp project, switching from x86 to AnyCPU. ```diff $ git diff LibGit2Sharp.Tests/LibGit2Sharp.Tests.csproj diff --git a/LibGit2Sharp.Tests/LibGit2Sharp.Tests.csproj b/LibGit2Sharp.Tests/LibGit2Sharp.Tests.csproj index ddf10df..8ed5884 100644 --- a/LibGit2Sharp.Tests/LibGit2Sharp.Tests.csproj +++ b/LibGit2Sharp.Tests/LibGit2Sharp.Tests.csproj @@ -21,7 +21,7 @@ TRACE;DEBUG;NET35 prompt 4 - x86 + AnyCPU $ git diff LibGit2Sharp/LibGit2Sharp.csproj diff --git a/LibGit2Sharp/LibGit2Sharp.csproj b/LibGit2Sharp/LibGit2Sharp.csproj index e38804e..060bd99 100644 --- a/LibGit2Sharp/LibGit2Sharp.csproj +++ b/LibGit2Sharp/LibGit2Sharp.csproj @@ -24,7 +24,7 @@ 4 false true - x86 + AnyCPU AllRules.ruleset ``` -------------------------------- ### Create Annotated Tag (LibGit2Sharp) Source: https://github.com/libgit2/libgit2sharp/wiki/git-tag Applies an annotated tag with a name, target commit SHA, tagger signature, and message. Requires a valid repository and commit SHA. ```csharp using (var repo = new Repository("path/to/your/repo")) { Signature tagger = new Signature("James", "@jugglingnutcase", DateTime.Now); repo.ApplyTag("a-good-tag-name", "5df3e2b", tagger, "Create a tag pointing at 5df3e2b"); } ``` -------------------------------- ### Stage All Working Directory Changes with Git Source: https://github.com/libgit2/libgit2sharp/wiki/git-add This is the command-line equivalent for staging all changes in the Git repository. It stages all modified, added, and deleted files in the current directory and its subdirectories. ```bash $ git add --all . ``` -------------------------------- ### Basic Git Push Command Source: https://github.com/libgit2/libgit2sharp/wiki/git-push The standard git command-line instruction to push local changes to a remote repository. ```git $ git push ``` -------------------------------- ### LibGit2Sharp to Compare Commits and List File Changes Source: https://github.com/libgit2/libgit2sharp/wiki/git-log-name-status Iterate through commits and their parents using LibGit2Sharp to compare trees and identify file status changes (Modified, Added, Deleted) between them. Requires a valid repository path. ```csharp var repo = new LibGit2Sharp.Repository ("/your/repo/path"); foreach (Commit commit in repo.Commits) { foreach (var parent in commit.Parents) { Console.WriteLine ("{0} | {1}", commit.Sha, commit.MessageShort); foreach (TreeEntryChanges change in repo.Diff.Compare(parent.Tree, commit.Tree)) { Console.WriteLine ("{0} : {1}", change.Status, change.Path); } } } ``` -------------------------------- ### Create Lightweight Tag (Git) Source: https://github.com/libgit2/libgit2sharp/wiki/git-tag Creates a lightweight tag pointing to the current HEAD commit. This is the simplest form of tagging. ```git $ git tag a-nice-tag-name ``` -------------------------------- ### List Unmerged Files with LibGit2Sharp Source: https://github.com/libgit2/libgit2sharp/wiki/git-ls-files Iterate through the repository's index using LibGit2Sharp to find and display unmerged files. This C# code checks the `StageLevel` property of each `IndexEntry`. ```csharp using (var repo = new Repository("path/to/your/repo")) { foreach(IndexEntry e in repo.Index) { if (e.StageLevel == 0) { continue; } Console.WriteLine("{0} {1} {2} {3}", Convert.ToString((int)e.Mode, 8), e.Id.ToString(), (int)e.StageLevel, e.Path); } } ``` -------------------------------- ### Checkout branch by name using Git Source: https://github.com/libgit2/libgit2sharp/wiki/git-checkout Use this command to switch your working directory to an existing branch. ```git git checkout ``` -------------------------------- ### Create Lightweight Tag on Specific Target (Git) Source: https://github.com/libgit2/libgit2sharp/wiki/git-tag Creates a lightweight tag pointing to a specific branch or commit SHA. This allows tagging historical points. ```git $ git tag a-better-tag-name refs/heads/cool-branch $ git tag the-best-tag-name 5df3e2b3ca5ebe8123927a81d682993ad597a584 ``` -------------------------------- ### Rename a file using LibGit2Sharp Source: https://github.com/libgit2/libgit2sharp/wiki/git-mv Use LibGit2Sharp to rename a file. Ensure paths are in Posix format. ```csharp using (var repo = new Repository("")) { // Renames the file. Path must be in Posix format (using '/' as path separator) Commands.Move(repo, "", "/") } ``` -------------------------------- ### Remove File using LibGit2Sharp Source: https://github.com/libgit2/libgit2sharp/wiki/git-rm Use the `repo.Index.Remove()` method in LibGit2Sharp to stage a file for removal. Ensure the file path is in Posix format (using '/' as the separator). ```csharp using (var repo = new Repository("")) { // Removes the file. Path must be in Posix format (using '/' as path separator) repo.Index.Remove(""); } ``` -------------------------------- ### Show Changes in Index and Working Directory (Git) Source: https://github.com/libgit2/libgit2sharp/wiki/git-diff Use `git diff HEAD` to compare the index and working directory against the last commit. ```git $ git diff HEAD ``` -------------------------------- ### Configure Git Line Endings on Linux Source: https://github.com/libgit2/libgit2sharp/wiki/Home Sets the global Git configuration for line endings to input on Linux. ```git $ git config --global core.autocrlf input ``` -------------------------------- ### List Tree Items using LibGit2Sharp Source: https://github.com/libgit2/libgit2sharp/wiki/git-ls-tree Iterate through the items of a tree object in a Git repository using LibGit2Sharp. Ensure you have a valid repository path and tree ID. ```csharp using (var repo = new Repository("path/to/your/repo")) { var tree = repo.Lookup(id); foreach(var item in tree) Console.WriteLine(item.Name); } ``` -------------------------------- ### Stage a File with Changes in LibGit2Sharp Source: https://github.com/libgit2/libgit2sharp/wiki/git-add Use this snippet to stage a specific file that has been modified in your repository. Ensure the repository path is correct and the file exists. ```csharp using (var repo = new Repository(@"path/to/your/repo")) { // Stage the file repo.Index.Add("file/with/changes.txt"); repo.Index.Write(); } ``` -------------------------------- ### Clone a Repository Source: https://github.com/libgit2/libgit2sharp/wiki/git-clone Use this snippet to clone a Git repository to a specified local path. Ensure the target path does not already exist. ```csharp Repository.Clone("https://github.com/libgit2/libgit2sharp.git", "path/to/repo"); ``` -------------------------------- ### Configure Git Line Endings on Windows Source: https://github.com/libgit2/libgit2sharp/wiki/Home Sets the global Git configuration for line endings to true on Windows. ```git $ git config --global core.autocrlf true ``` -------------------------------- ### Find common ancestor using LibGit2Sharp Source: https://github.com/libgit2/libgit2sharp/wiki/git-merge-base Implement a C# method to find the merge base of two commits using LibGit2Sharp. Ensure the repository path and commit SHAs are valid. ```csharp public string GetMergeBase(string a, string b) { using (var repo = new Repository("path/to/your/repo")) { var aCommit = repo.Lookup(a); var bCommit = repo.Lookup(b); if (aCommit == null || bCommit == null) return null; var baseCommit = repo.ObjectDatabase.FindMergeBase(aCommit, bCommit); return baseCommit != null ? baseCommit.Sha : null; } } ``` -------------------------------- ### Show Changes in Working Directory (Git) Source: https://github.com/libgit2/libgit2sharp/wiki/git-diff Use `git diff` to see modifications in your working directory that have not been staged. ```git $ git diff ``` -------------------------------- ### LibGit2Sharp: Retrieve Blob Content Source: https://github.com/libgit2/libgit2sharp/wiki/git-cat-file Shows how to access the content of a file (Blob) from the HEAD commit using LibGit2Sharp and read it as a UTF-8 encoded string. ```csharp repo.Head.Tip[{FilePathToContentFrom}].Target as Blob; using (var content = new StreamReader(blob.GetContentStream(), Encoding.UTF8)) { commitContent = content.ReadToEnd(); } ``` -------------------------------- ### Move a file using Git Source: https://github.com/libgit2/libgit2sharp/wiki/git-mv Use this command to move a file to a new location in your Git repository. ```git $ git mv ``` -------------------------------- ### Pushing to a Remote with LibGit2Sharp (Remote and Ref) Source: https://github.com/libgit2/libgit2sharp/wiki/git-push Pushes updates for a specific ref (e.g., master branch) to a named remote (e.g., origin) using LibGit2Sharp. This variant explicitly uses the Remote object and refspec. ```csharp using (var repo = new Repository("path/to/your/repo")) { Remote remote = repo.Network.Remotes["origin"]; var options = new PushOptions(); options.CredentialsProvider = (_url, _user, _cred) => new UsernamePasswordCredentials { Username = "USERNAME", Password = "PASSWORD" }; repo.Network.Push(remote, @"refs/heads/master", options); } ``` -------------------------------- ### Basic Git Pull Command Source: https://github.com/libgit2/libgit2sharp/wiki/git-pull The standard command-line interface for pulling updates from a remote repository. ```shell $ git pull ``` -------------------------------- ### Read Any Symbolic Reference Target with LibGit2Sharp Source: https://github.com/libgit2/libgit2sharp/wiki/git-symbolic-ref Access a specific reference by its name using `repo.Refs[]` and retrieve its `TargetIdentifier`. ```csharp using (var repo = new Repository("path/to/your/repo")) { Console.WriteLine(repo.Refs["i-track-for-a-living"].TargetIdentifier); } ``` -------------------------------- ### Create a New Branch from HEAD Source: https://github.com/libgit2/libgit2sharp/wiki/git-branch Creates a new local branch named 'develop' that points to the current commit (HEAD). Alternatively, use `repo.Branches.Add`. ```git $ git branch develop ``` ```csharp using (var repo = new Repository("path/to/your/repo")) { repo.CreateBranch("develop"); // Or repo.Branches.Add("develop", "HEAD"); } ``` -------------------------------- ### Make a Commit to a Non-Bare Repository Source: https://github.com/libgit2/libgit2sharp/wiki/git-commit Use this snippet to commit changes to a checked-out Git repository. It involves updating a file on the file system, staging it, and then creating the commit. ```csharp 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); } ``` -------------------------------- ### List Tree Items using Git CLI Source: https://github.com/libgit2/libgit2sharp/wiki/git-ls-tree Use the `git ls-tree` command to display the contents of a Git tree object. ```git $ git ls-tree commit ``` -------------------------------- ### Generate Patch for a Specific File using LibGit2Sharp Source: https://github.com/libgit2/libgit2sharp/wiki/git-diff-{filename}---local.patch Use the LibGit2Sharp `Diff.Compare` method to generate a patch for a specified file path. ```csharp var patch = repo.Diff.Compare (new List() { "myChangedFile.as" }); ``` -------------------------------- ### Display Tag Message (LibGit2Sharp) Source: https://github.com/libgit2/libgit2sharp/wiki/git-tag Retrieves a specific tag by name and prints its annotation message if it's an annotated tag, otherwise prints the short commit message. Requires the tag name to exist. ```csharp using (var repo = new Repository("path/to/your/repo")) { Tag t = repo.Tags["your-tag-name"]; Console.WriteLine(t.IsAnnotated ? t.Annotation.Message : ((Commit) t.Target).MessageShort); } ``` -------------------------------- ### List Unmerged Files with Git Source: https://github.com/libgit2/libgit2sharp/wiki/git-ls-files Use the `git ls-files --unmerged` command to display files that have unmerged paths in the index. ```git $ git ls-files --unmerged ``` -------------------------------- ### Read Any Symbolic Reference Target with Git Source: https://github.com/libgit2/libgit2sharp/wiki/git-symbolic-ref Use `git symbolic-ref ` to retrieve the target of a specific symbolic reference. ```git $ git symbolic-ref i-track-for-a-living ``` -------------------------------- ### Add CMake to PATH Source: https://github.com/libgit2/libgit2sharp/wiki/How-to-build-x64-libgit2-and-LibGit2Sharp Appends the directory containing CMake binaries to the system's PATH environment variable. This allows you to run CMake commands from any directory. ```bash > set PATH=c:\path\to\your\cmake2.8\bin;%PATH% ``` -------------------------------- ### Modify CMakeLists.txt for Compiler Warnings Source: https://github.com/libgit2/libgit2sharp/wiki/How-to-build-x64-libgit2-and-LibGit2Sharp Applies a patch to the CMakeLists.txt file to change the C compiler flags. This change instructs the linker to ignore specific warnings (C4244, C4267) instead of treating them as errors, preventing build failures. ```diff diff --git a/CMakeLists.txt b/CMakeLists.txt index 7655e0b..e2cf729 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -55,7 +55,7 @@ IF (MSVC) # Not using __stdcall with the CRT causes problems OPTION (STDCALL "Buildl libgit2 with the __stdcall convention" ON) - SET(CMAKE_C_FLAGS "/W4 /nologo /Zi ${CMAKE_C_FLAGS}") + SET(CMAKE_C_FLAGS "/W4 /wd4244 /wd4267 /nologo /Zi ${CMAKE_C_FLAGS}") IF (STDCALL) SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /Gz") ENDIF () ```