### Clone Remote Repositories with LibGit2Sharp Source: https://context7.com/absolucy/libgit2sharp-md/llms.txt Shows how to clone a remote Git repository. Includes a simple clone and a more advanced example with options for branch name, bare repository, submodule recursion, checkout progress, credentials, and transfer progress. ```csharp using LibGit2Sharp; using LibGit2Sharp.Handlers; // Simple clone string clonedPath = Repository.Clone( "https://github.com/user/repo.git", @"C:\local\repo"); // Clone with options var cloneOptions = new CloneOptions { BranchName = "develop", IsBare = false, RecurseSubmodules = true, OnCheckoutProgress = (path, completedSteps, totalSteps) => { Console.WriteLine($"Checking out: {path} ({completedSteps}/{totalSteps})"); }, FetchOptions = { CredentialsProvider = (url, usernameFromUrl, types) => new UsernamePasswordCredentials { Username = "username", Password = "token_or_password" }, OnTransferProgress = progress => { Console.WriteLine($"Received: {progress.ReceivedObjects}/{progress.TotalObjects}"); return true; } } }; string path = Repository.Clone( "https://github.com/user/repo.git", @"C:\local\repo", cloneOptions); ``` -------------------------------- ### Manage Branches with LibGit2Sharp Source: https://context7.com/absolucy/libgit2sharp-md/llms.txt Illustrates common branch operations including getting the current branch (HEAD), listing all branches, retrieving specific branches, creating new branches from HEAD or a commit, renaming, deleting, and setting upstream tracking branches. ```csharp using LibGit2Sharp; using (var repo = new Repository(@"C:\path\to\repo")) { // Get current branch (HEAD) Branch head = repo.Head; Console.WriteLine($"Current branch: {head.FriendlyName}"); Console.WriteLine($"Is remote: {head.IsRemote}"); Console.WriteLine($"Tip commit: {head.Tip.Sha}"); // List all branches foreach (Branch branch in repo.Branches) { string trackingInfo = branch.IsTracking ? $ ``` ```csharp -> {branch.TrackedBranch.FriendlyName} ``` ```csharp : "" Console.WriteLine($"{branch.FriendlyName}{trackingInfo}"); } // Get a specific branch Branch main = repo.Branches["main"]; Branch remoteBranch = repo.Branches["origin/main"]; // Create a new branch from HEAD Branch newBranch = repo.Branches.Add("feature/new-feature", repo.Head.Tip); // Create branch from a specific commit Commit targetCommit = repo.Lookup("abc1234"); Branch featureBranch = repo.Branches.Add("feature/from-commit", targetCommit); // Rename a branch Branch renamedBranch = repo.Branches.Rename("old-name", "new-name"); // Delete a branch repo.Branches.Remove("feature/old-feature"); // Set upstream tracking branch repo.Branches.Update(newBranch, b => b.TrackedBranch = "refs/remotes/origin/feature/new-feature"); } ``` -------------------------------- ### Open and Initialize Repositories with LibGit2Sharp Source: https://context7.com/absolucy/libgit2sharp-md/llms.txt Demonstrates how to open an existing repository, initialize a new one (standard or bare), check for repository validity, and discover a repository from a subdirectory using the Repository class. ```csharp using LibGit2Sharp; // Open an existing repository using (var repo = new Repository(@"C:\path\to\repo")) { Console.WriteLine($"Repository path: {repo.Info.Path}"); Console.WriteLine($"Is bare: {repo.Info.IsBare}"); Console.WriteLine($"Working directory: {repo.Info.WorkingDirectory}"); } // Initialize a new repository string repoPath = Repository.Init(@"C:\path\to\new\repo"); Console.WriteLine($"Created repository at: {repoPath}"); // Initialize a bare repository string bareRepoPath = Repository.Init(@"C:\path\to\bare\repo", isBare: true); // Check if a path is a valid repository bool isValid = Repository.IsValid(@"C:\some\path"); // Discover repository from a subdirectory string discoveredPath = Repository.Discover(@"C:\repo\subdir\deep\folder"); ``` -------------------------------- ### Read, Set, and Unset Repository Configuration Source: https://context7.com/absolucy/libgit2sharp-md/llms.txt Demonstrates how to read, set, and unset configuration values at the repository level. Ensure a valid repository path is provided. Configuration changes are local to the repository. ```csharp using LibGit2Sharp; using (var repo = new Repository(@"C:\path\to\repo")) { Configuration config = repo.Config; // Read configuration values string userName = config.Get("user.name")?.Value; string userEmail = config.Get("user.email")?.Value; bool autoCrlf = config.Get("core.autocrlf")?.Value ?? false; Console.WriteLine($"User: {userName} <{userEmail}>"); // Set configuration values (repository level) config.Set("user.name", "New Name"); config.Set("user.email", "new@email.com"); config.Set("core.autocrlf", true); // Unset configuration config.Unset("custom.setting"); // Iterate through configuration entries foreach (ConfigurationEntry entry in config) { Console.WriteLine($"{entry.Key} = {entry.Value} ({entry.Level})"); } // Access specific configuration level ConfigurationEntry globalName = config.Get("user.name", ConfigurationLevel.Global); ConfigurationEntry localName = config.Get("user.name", ConfigurationLevel.Local); } ``` -------------------------------- ### Create and manage Git tags with LibGit2Sharp Source: https://context7.com/absolucy/libgit2sharp-md/llms.txt Demonstrates listing, creating, retrieving, and deleting lightweight and annotated tags. ```csharp using LibGit2Sharp; using (var repo = new Repository(@"C:\path\to\repo")) { // List all tags foreach (Tag tag in repo.Tags) { Console.WriteLine($"{tag.FriendlyName} -> {tag.Target.Sha}"); if (tag.IsAnnotated) { Console.WriteLine($" Tagger: {tag.Annotation.Tagger}"); Console.WriteLine($" Message: {tag.Annotation.Message}"); } } // Get a specific tag Tag v1 = repo.Tags["v1.0.0"]; // Create a lightweight tag Tag lightTag = repo.Tags.Add("v1.0.1", repo.Head.Tip); // Create an annotated tag var tagger = new Signature("Tagger", "tagger@email.com", DateTimeOffset.Now); Tag annotatedTag = repo.Tags.Add("v2.0.0", repo.Head.Tip, tagger, "Release version 2.0.0"); // Create tag on specific commit Commit targetCommit = repo.Lookup("abc1234"); repo.Tags.Add("release-point", targetCommit, tagger, "Release marker"); // Delete a tag repo.Tags.Remove("old-tag"); // Overwrite existing tag repo.Tags.Add("v1.0.0", repo.Head.Tip, tagger, "Updated release", allowOverwrite: true); } ``` -------------------------------- ### Reset Repository State with LibGit2Sharp Source: https://context7.com/absolucy/libgit2sharp-md/llms.txt Demonstrates soft, mixed, and hard resets, as well as index replacement and cleaning untracked files. ```csharp using LibGit2Sharp; using (var repo = new Repository(@"C:\path\to\repo")) { Commit targetCommit = repo.Lookup("abc1234"); // Soft reset - moves HEAD only, keeps staging and working directory repo.Reset(ResetMode.Soft, targetCommit); // Mixed reset (default) - moves HEAD and resets staging, keeps working directory repo.Reset(ResetMode.Mixed, targetCommit); // Hard reset - moves HEAD, resets staging and working directory repo.Reset(ResetMode.Hard, targetCommit); // Reset with checkout options var resetOptions = new CheckoutOptions { OnCheckoutProgress = (path, completed, total) => { Console.WriteLine($"Reset: {path}"); } }; repo.Reset(ResetMode.Hard, targetCommit, resetOptions); // Reset specific files in the index repo.Index.Replace(targetCommit, new[] { "file1.txt", "folder/file2.txt" }); repo.Index.Write(); // Clean untracked files repo.RemoveUntrackedFiles(); } ``` -------------------------------- ### Manage Git stashes with LibGit2Sharp Source: https://context7.com/absolucy/libgit2sharp-md/llms.txt Covers creating, listing, applying, popping, and removing stashes with various options. ```csharp using LibGit2Sharp; using (var repo = new Repository(@"C:\path\to\repo")) { var stasher = new Signature("User", "user@email.com", DateTimeOffset.Now); // Create a stash Stash stash = repo.Stashes.Add(stasher, "Work in progress"); if (stash != null) { Console.WriteLine($"Created stash: {stash.Message}"); } // Create stash with options Stash stashWithUntracked = repo.Stashes.Add(stasher, "Including untracked", StashModifiers.IncludeUntracked); // List all stashes foreach (Stash s in repo.Stashes) { Console.WriteLine($"stash@{{{s.Index}}}: {s.Message}"); } // Get a specific stash Stash firstStash = repo.Stashes[0]; // Most recent // Apply a stash (keeps it in the list) StashApplyStatus applyStatus = repo.Stashes.Apply(0); Console.WriteLine($"Apply result: {applyStatus}"); // Apply with options var applyOptions = new StashApplyOptions { CheckoutOptions = new CheckoutOptions { CheckoutModifiers = CheckoutModifiers.Force }, ApplyModifiers = StashApplyModifiers.ReinstateIndex }; repo.Stashes.Apply(0, applyOptions); // Pop a stash (apply and remove) StashApplyStatus popStatus = repo.Stashes.Pop(0); // Drop a stash without applying repo.Stashes.Remove(0); } ``` -------------------------------- ### Perform Checkout Operations in LibGit2Sharp Source: https://context7.com/absolucy/libgit2sharp-md/llms.txt Use Commands.Checkout to switch between branches, commits, or specific files. Supports options like force checkout and progress callbacks. ```csharp using LibGit2Sharp; using (var repo = new Repository(@"C:\path\to\repo")) { // Checkout a branch by name Branch branch = Commands.Checkout(repo, "feature/my-feature"); // Checkout with options var checkoutOptions = new CheckoutOptions { CheckoutModifiers = CheckoutModifiers.Force, OnCheckoutProgress = (path, completed, total) => { Console.WriteLine($"Checkout: {path}"); }, OnCheckoutNotify = (path, notifyFlags) => { Console.WriteLine($"Notify: {path} - {notifyFlags}"); return true; } }; Commands.Checkout(repo, "main", checkoutOptions); // Checkout a specific commit (detached HEAD) Commit commit = repo.Lookup("abc1234"); Commands.Checkout(repo, commit); // Checkout specific files from a commit repo.CheckoutPaths("main", new[] { "file1.txt", "folder/file2.txt" }, new CheckoutOptions()); } ``` -------------------------------- ### Create Commits with LibGit2Sharp Source: https://context7.com/absolucy/libgit2sharp-md/llms.txt Stage files using Commands.Stage and create new commits with author and committer information. Supports staging all changes and unstaging files. ```csharp using LibGit2Sharp; using (var repo = new Repository(@"C:\path\to\repo")) { // Stage files Commands.Stage(repo, "newfile.txt"); Commands.Stage(repo, new[] { "file1.txt", "file2.txt", "folder/*" }); // Stage all changes Commands.Stage(repo, "*"); // Unstage files Commands.Unstage(repo, "file.txt"); // Create a signature for commit var author = new Signature("Author Name", "author@email.com", DateTimeOffset.Now); var committer = new Signature("Committer Name", "committer@email.com", DateTimeOffset.Now); // Create commit Commit commit = repo.Commit("Add new feature", author, committer); Console.WriteLine($"Created commit: {commit.Sha}"); Console.WriteLine($"Message: {commit.MessageShort}"); Console.WriteLine($"Author: {commit.Author.Name} <{commit.Author.Email}>"); Console.WriteLine($"Date: {commit.Author.When}"); // Create commit with options var commitOptions = new CommitOptions { AllowEmptyCommit = false, AmendPreviousCommit = false, PrettifyMessage = true }; Commit newCommit = repo.Commit("Commit message", author, committer, commitOptions); // Amend the previous commit var amendOptions = new CommitOptions { AmendPreviousCommit = true }; Commit amendedCommit = repo.Commit("Updated message", author, committer, amendOptions); } ``` -------------------------------- ### Fetch and Pull Remote Changes in C# Source: https://context7.com/absolucy/libgit2sharp-md/llms.txt Download changes from remote repositories using fetch options for authentication and progress tracking, or perform a full pull operation. ```csharp using LibGit2Sharp; using (var repo = new Repository(@"C:\path\to\repo")) { // Fetch from a remote Remote remote = repo.Network.Remotes["origin"]; string[] refSpecs = remote.FetchRefSpecs.Select(rs => rs.Specification).ToArray(); var fetchOptions = new FetchOptions { CredentialsProvider = (url, user, types) => new UsernamePasswordCredentials { Username = "username", Password = "token" }, OnTransferProgress = progress => { Console.WriteLine($"Received {progress.ReceivedObjects}/{progress.TotalObjects}"); return true; }, TagFetchMode = TagFetchMode.Auto, Prune = true }; Commands.Fetch(repo, remote.Name, refSpecs, fetchOptions, "Fetching updates"); // Pull (fetch + merge) var signature = new Signature("User", "user@email.com", DateTimeOffset.Now); var pullOptions = new PullOptions { FetchOptions = fetchOptions, MergeOptions = new MergeOptions { FastForwardStrategy = FastForwardStrategy.Default } }; MergeResult result = Commands.Pull(repo, signature, pullOptions); Console.WriteLine($"Pull status: {result.Status}"); } ``` -------------------------------- ### Access Global Configuration Path Source: https://context7.com/absolucy/libgit2sharp-md/llms.txt Retrieves the search path for global Git configuration without needing an open repository. This is useful for accessing system-wide settings. ```csharp string globalConfigPath = GlobalSettings.GetConfigSearchPaths(ConfigurationLevel.Global).FirstOrDefault(); ``` -------------------------------- ### Push changes to remote repositories with LibGit2Sharp Source: https://context7.com/absolucy/libgit2sharp-md/llms.txt Configures push options including credentials and progress callbacks, then pushes branches or tags to a remote. ```csharp using LibGit2Sharp; using (var repo = new Repository(@"C:\path\to\repo")) { Remote remote = repo.Network.Remotes["origin"]; var pushOptions = new PushOptions { CredentialsProvider = (url, user, types) => new UsernamePasswordCredentials { Username = "username", Password = "token" }, OnPushStatusError = errors => { Console.WriteLine($"Push error: {errors.Message}"); }, OnPackBuilderProgress = (stage, current, total) => { Console.WriteLine($"Packing: {stage} {current}/{total}"); return true; } }; // Push current branch to its tracked remote repo.Network.Push(repo.Head, pushOptions); // Push specific refspec repo.Network.Push(remote, "refs/heads/main:refs/heads/main", pushOptions); // Push multiple branches repo.Network.Push(remote, new[] { "refs/heads/main:refs/heads/main", "refs/heads/develop:refs/heads/develop" }, pushOptions); // Push tags repo.Network.Push(remote, "refs/tags/v1.0.0:refs/tags/v1.0.0", pushOptions); } ``` -------------------------------- ### Manipulate Repository Index Source: https://context7.com/absolucy/libgit2sharp-md/llms.txt Provides methods for staging files, handling conflicts, and converting the index to tree objects. ```csharp using LibGit2Sharp; using (var repo = new Repository(@"C:\path\to\repo")) { Index index = repo.Index; // Check index state Console.WriteLine($"Index entry count: {index.Count}"); Console.WriteLine($"Is fully merged: {index.IsFullyMerged}"); // Get specific entry IndexEntry entry = index["path/to/file.txt"]; if (entry != null) { Console.WriteLine($"Path: {entry.Path}"); Console.WriteLine($"Mode: {entry.Mode}"); Console.WriteLine($"Blob SHA: {entry.Id}"); } // Add file to index index.Add("newfile.txt"); // Remove from index index.Remove("deletedfile.txt"); // Add blob directly to index Blob blob = repo.Lookup("abc1234"); index.Add(blob, "path/in/index.txt", Mode.NonExecutableFile); // Write index to disk index.Write(); // Write index to a tree object Tree tree = index.WriteToTree(); // Replace index with tree contents Tree sourceTree = repo.Head.Tip.Tree; index.Replace(sourceTree); index.Write(); // Handle conflicts if (!index.IsFullyMerged) { foreach (Conflict conflict in index.Conflicts) { Console.WriteLine($"Conflict: {conflict.Ours?.Path}"); Console.WriteLine($" Ours: {conflict.Ours?.Id}"); Console.WriteLine($" Theirs: {conflict.Theirs?.Id}"); Console.WriteLine($" Ancestor: {conflict.Ancestor?.Id}"); } } } ``` -------------------------------- ### Manage Remote Repositories in C# Source: https://context7.com/absolucy/libgit2sharp-md/llms.txt Perform CRUD operations on remote repository configurations and list remote references without cloning. ```csharp using LibGit2Sharp; using (var repo = new Repository(@"C:\path\to\repo")) { // List all remotes foreach (Remote remote in repo.Network.Remotes) { Console.WriteLine($"{remote.Name}: {remote.Url}"); Console.WriteLine($" Push URL: {remote.PushUrl}"); } // Get a specific remote Remote origin = repo.Network.Remotes["origin"]; // Add a new remote Remote upstream = repo.Network.Remotes.Add("upstream", "https://github.com/original/repo.git"); // Update remote properties repo.Network.Remotes.Update("origin", r => { r.Url = "https://github.com/new/url.git"; r.PushUrl = "git@github.com:new/url.git"; }); // Rename a remote repo.Network.Remotes.Rename("old-name", "new-name"); // Remove a remote repo.Network.Remotes.Remove("upstream"); // List remote references without cloning IEnumerable refs = Repository.ListRemoteReferences( "https://github.com/user/repo.git"); foreach (Reference reference in refs) { Console.WriteLine($"{reference.CanonicalName}"); } } ``` -------------------------------- ### Perform File Blame Analysis Source: https://context7.com/absolucy/libgit2sharp-md/llms.txt Retrieves commit and author information for file lines, including support for specific commit ranges and line-level lookups. ```csharp using LibGit2Sharp; using (var repo = new Repository(@"C:\path\to\repo")) { // Get blame for a file BlameHunkCollection blame = repo.Blame("path/to/file.cs"); foreach (BlameHunk hunk in blame) { Console.WriteLine($"Lines {hunk.FinalStartLineNumber}-{hunk.FinalStartLineNumber + hunk.LineCount - 1}"); Console.WriteLine($" Commit: {hunk.FinalCommit.Sha.Substring(0, 7)}"); Console.WriteLine($" Author: {hunk.FinalSignature.Name}"); Console.WriteLine($" Date: {hunk.FinalSignature.When}"); } // Blame with options var blameOptions = new BlameOptions { StartingAt = repo.Lookup("abc1234"), // Start from specific commit StoppingAt = repo.Lookup("def5678") // Stop at specific commit }; BlameHunkCollection historicBlame = repo.Blame("path/to/file.cs", blameOptions); // Get blame for specific line BlameHunk lineBlame = blame.HunkForLine(42); Console.WriteLine($"Line 42 last changed by {lineBlame.FinalSignature.Name}"); } ``` -------------------------------- ### Check Repository File Status Source: https://context7.com/absolucy/libgit2sharp-md/llms.txt Retrieve the status of files in the working directory and staging area. This includes checking individual files or the entire repository, with options to detect renames and include untracked files. ```csharp using LibGit2Sharp; using (var repo = new Repository(@"C:\path\to\repo")) { // Get status of a single file FileStatus status = repo.RetrieveStatus("file.txt"); Console.WriteLine($"File status: {status}"); // Get full repository status RepositoryStatus repoStatus = repo.RetrieveStatus(new StatusOptions { DetectRenamesInIndex = true, DetectRenamesInWorkDir = true, IncludeUntracked = true, RecurseUntrackedDirs = true }); Console.WriteLine($"Staged files: {repoStatus.Staged.Count()}"); Console.WriteLine($"Modified files: {repoStatus.Modified.Count()}"); Console.WriteLine($"Untracked files: {repoStatus.Untracked.Count()}"); // Iterate through changes foreach (StatusEntry entry in repoStatus) { Console.WriteLine($"{entry.State}: {entry.FilePath}"); } // Check specific states foreach (StatusEntry entry in repoStatus.Staged) { Console.WriteLine($"Staged: {entry.FilePath}"); } foreach (StatusEntry entry in repoStatus.Modified) { Console.WriteLine($"Modified: {entry.FilePath}"); } } ``` -------------------------------- ### Cherry-Pick and Revert Commits in C# Source: https://context7.com/absolucy/libgit2sharp-md/llms.txt Apply or undo specific commits using a signature. Options allow for staging without committing or specifying merge strategies. ```csharp using LibGit2Sharp; using (var repo = new Repository(@"C:\path\to\repo")) { var signature = new Signature("User", "user@email.com", DateTimeOffset.Now); // Cherry-pick a commit Commit commitToPick = repo.Lookup("abc1234"); CherryPickResult pickResult = repo.CherryPick(commitToPick, signature); if (pickResult.Status == CherryPickStatus.CherryPicked) { Console.WriteLine($"Cherry-picked successfully: {pickResult.Commit.Sha}"); } else if (pickResult.Status == CherryPickStatus.Conflicts) { Console.WriteLine("Cherry-pick resulted in conflicts"); } // Cherry-pick with options var cherryPickOptions = new CherryPickOptions { CommitOnSuccess = false, // Stage but don't commit MergeFileFavor = MergeFileFavor.Ours }; repo.CherryPick(commitToPick, signature, cherryPickOptions); // Revert a commit Commit commitToRevert = repo.Lookup("def5678"); RevertResult revertResult = repo.Revert(commitToRevert, signature); if (revertResult.Status == RevertStatus.Reverted) { Console.WriteLine($"Reverted successfully: {revertResult.Commit.Sha}"); } } ``` -------------------------------- ### Compare Changes in Git Repository Source: https://context7.com/absolucy/libgit2sharp-md/llms.txt Generate differences between various Git states, including the working directory, index, commits, and specific files. This allows for detailed analysis of changes. ```csharp using LibGit2Sharp; using (var repo = new Repository(@"C:\path\to\repo")) { // Compare working directory to index (unstaged changes) using (var changes = repo.Diff.Compare("file.txt")) { foreach (TreeEntryChanges change in changes) { Console.WriteLine($"{change.Status}: {change.Path}"); } } // Compare index to HEAD (staged changes) using (var changes = repo.Diff.Compare( repo.Head.Tip.Tree, DiffTargets.Index)) { foreach (TreeEntryChanges change in changes) { Console.WriteLine($"Staged {change.Status}: {change.Path}"); } } // Compare two commits Commit oldCommit = repo.Lookup("abc1234"); Commit newCommit = repo.Lookup("def5678"); using (var changes = repo.Diff.Compare(oldCommit.Tree, newCommit.Tree)) { Console.WriteLine($"Added: {changes.Added.Count()}"); Console.WriteLine($"Deleted: {changes.Deleted.Count()}"); Console.WriteLine($"Modified: {changes.Modified.Count()}"); Console.WriteLine($"Renamed: {changes.Renamed.Count()}"); } // Get patch content using (var patch = repo.Diff.Compare(oldCommit.Tree, newCommit.Tree)) { Console.WriteLine(patch.Content); // Full diff text foreach (PatchEntryChanges file in patch) { Console.WriteLine($"--- {file.Path} ---"); Console.WriteLine($"Added lines: {file.LinesAdded}"); Console.WriteLine($"Deleted lines: {file.LinesDeleted}"); Console.WriteLine(file.Patch); // File-specific diff } } // Compare specific files only using (var changes = repo.Diff.Compare( oldCommit.Tree, newCommit.Tree, new[] { "src/file1.cs", "src/file2.cs" })) { // Only changes in specified files } } ``` -------------------------------- ### Query Commit History in LibGit2Sharp Source: https://context7.com/absolucy/libgit2sharp-md/llms.txt Iterate through commit history, apply filters, and access detailed commit information including author, committer, and parent commits. ```csharp using LibGit2Sharp; using (var repo = new Repository(@"C:\path\to\repo")) { // Get all commits reachable from HEAD foreach (Commit commit in repo.Commits) { Console.WriteLine($"{commit.Sha.Substring(0, 7)} - {commit.MessageShort}"); } // Query commits with filters var filter = new CommitFilter { IncludeReachableFrom = repo.Branches["main"], ExcludeReachableFrom = repo.Branches["develop"], SortBy = CommitSortStrategies.Topological | CommitSortStrategies.Time }; foreach (Commit commit in repo.Commits.QueryBy(filter)) { Console.WriteLine($"{commit.Sha} by {commit.Author.Name}"); } // Access commit details Commit head = repo.Head.Tip; Console.WriteLine($"SHA: {head.Sha}"); Console.WriteLine($"Message: {head.Message}"); Console.WriteLine($"Author: {head.Author}"); Console.WriteLine($"Committer: {head.Committer}"); Console.WriteLine($"Parents: {string.Join(", ", head.Parents.Select(p => p.Sha.Substring(0, 7)))}"); // Access files in a commit foreach (TreeEntry entry in head.Tree) { Console.WriteLine($"{entry.Mode} {entry.TargetType} {entry.Path}"); } // Get a specific file from a commit TreeEntry file = head["path/to/file.txt"]; if (file != null) { var blob = (Blob)file.Target; string content = blob.GetContentText(); } } ``` -------------------------------- ### Merge Branches in Git Repository Source: https://context7.com/absolucy/libgit2sharp-md/llms.txt Perform merge operations between branches, handling different merge strategies and potential conflicts. This includes merging branches, specific commits, and configuring merge options. ```csharp using LibGit2Sharp; using (var repo = new Repository(@"C:\path\to\repo")) { var signature = new Signature("User", "user@email.com", DateTimeOffset.Now); // Merge a branch into HEAD Branch branchToMerge = repo.Branches["feature/new-feature"]; MergeResult result = repo.Merge(branchToMerge, signature); switch (result.Status) { case MergeStatus.UpToDate: Console.WriteLine("Already up to date"); break; case MergeStatus.FastForward: Console.WriteLine($"Fast-forwarded to {result.Commit.Sha}"); break; case MergeStatus.NonFastForward: Console.WriteLine($"Merged with commit {result.Commit.Sha}"); break; case MergeStatus.Conflicts: Console.WriteLine("Merge resulted in conflicts"); // Handle conflicts foreach (Conflict conflict in repo.Index.Conflicts) { Console.WriteLine($"Conflict: {conflict.Ours?.Path ?? conflict.Theirs?.Path}"); } break; } // Merge with options var mergeOptions = new MergeOptions { FastForwardStrategy = FastForwardStrategy.NoFastForward, MergeFileFavor = MergeFileFavor.Theirs, CommitOnSuccess = true }; MergeResult mergeResult = repo.Merge(branchToMerge, signature, mergeOptions); // Merge a specific commit Commit commitToMerge = repo.Lookup("abc1234"); repo.Merge(commitToMerge, signature); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.