public Lookup ( ObjectId id, GitObjectType type = GitObjectType.Any ) : GitObject | ||
id | ObjectId | The id to lookup. |
type | GitObjectType | The kind of GitObject being looked up |
리턴 | GitObject |
static void Main(string[] args) { Setup(); using (var repo = new Repository(Environment.CurrentDirectory)) { if (repo.Index.Conflicts.Any()) Console.WriteLine("Found UASSET conflicts. Building folder for diff"); foreach (var conflict in repo.Index.Conflicts.Where(x => x.Ours.Path.EndsWith(".uasset"))) { Console.WriteLine("Setting up diff files for " + conflict.Ours.Path); var a = repo.Lookup<Blob>(conflict.Ours.Id); var b = repo.Lookup<Blob>(conflict.Theirs.Id); using (FileStream fileStream = File.Create(Path.Combine(tempDir, Path.GetFileNameWithoutExtension(conflict.Ours.Path) + "_a" + Path.GetExtension(conflict.Ours.Path)))) { a.GetContentStream().CopyTo(fileStream); } using (FileStream fileStream = File.Create(Path.Combine(tempDir, Path.GetFileNameWithoutExtension(conflict.Theirs.Path) + "_b" + Path.GetExtension(conflict.Theirs.Path)))) { b.GetContentStream().CopyTo(fileStream); } } } Console.WriteLine(); Console.WriteLine(File.ReadAllText(Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location), "helpfiles", "diffsetupcomplete.txt"))); }
/// <summary> /// Calculates the version number of a specific commit in the git repository /// </summary> public SemanticVersion GetVersion(string sha) { Commit commit = repo.Lookup <Commit>(sha); if (commit == null) { throw new ArgumentException($"The commit with reference {sha} does not exist in the repository."); } return(GetVersion(commit)); }
public void GetCommitChangesAddedRemoved() { var commit = "9ed729ee"; var com = repo.Lookup <Commit> (commit); var changes = GitUtil.CompareCommits(repo, com.Parents.First(), com).ToArray(); var add = changes.First(c => c.Path.EndsWith("DocumentLine.cs", StringComparison.Ordinal)); var remove = changes.First(c => c.OldPath.EndsWith("LineSegment.cs", StringComparison.Ordinal)); Assert.AreEqual(ChangeKind.Renamed, add.Status, "#1"); Assert.AreEqual("main/src/core/Mono.Texteditor/Mono.TextEditor/Document/LineSegment.cs".Replace('/', Path.DirectorySeparatorChar), add.OldPath, "#2"); Assert.AreEqual(ChangeKind.Renamed, remove.Status, "#3"); Assert.AreEqual("main/src/core/Mono.Texteditor/Mono.TextEditor/Document/DocumentLine.cs".Replace('/', Path.DirectorySeparatorChar), remove.Path, "#4"); }
public void sha1_of_trees_rocks() { var first = TestHelper.TestGitRepository.Commits.First( sc => sc.Message.StartsWith( "First in parallel world." ) ); var modified = TestHelper.TestGitRepository.Commits.First( sc => sc.Message.StartsWith( "Change in parallel-world.txt content (1)." ) ); var reset = TestHelper.TestGitRepository.Commits.First( sc => sc.Message.StartsWith( "Reset change in parallel-world.txt content (2)." ) ); using( var r = new Repository( TestHelper.TestGitRepositoryFolder ) ) { var cFirst = r.Lookup<Commit>( first.Sha ); var cModified = r.Lookup<Commit>( modified.Sha ); var cReset = r.Lookup<Commit>( reset.Sha ); Assert.That( cFirst.Tree.Sha, Is.Not.EqualTo( cModified.Tree.Sha ) ); Assert.That( cReset.Tree.Sha, Is.Not.EqualTo( cModified.Tree.Sha ) ); Assert.That( cFirst.Tree.Sha, Is.EqualTo( cReset.Tree.Sha ) ); } }
public BranchWrapper(Repository repo, Branch branch) { this.repo = repo; this.branch = branch; IsRemote = branch.IsRemote; if (branch.TrackedBranch != null) { TrackedBranch = new BranchWrapper(repo, branch.TrackedBranch); } IsTracking = branch.IsTracking; TrackingDetails = (Func<object, Task<object>>)(async (j) => { return branch.TrackingDetails; }); IsCurrentRepositoryHead = (Func<object, Task<object>>)(async (j) => { return branch.IsCurrentRepositoryHead; }); Tip = async (j) => { return new CommitWrapper(branch.Tip); }; UpstreamBranchCanonicalName = (Func<object, Task<object>>)(async (j) => { return branch.UpstreamBranchCanonicalName; }); Remote = branch.Remote; CanonicalName = branch.CanonicalName; Commits = (Func<object, Task<object>>)(async (j) => { if (j != null) { Commit after = repo.Lookup<Commit>((string)j); Commit until = branch.Tip; Commit ancestor = repo.Commits.FindMergeBase(after, until) ?? after; return CommitsAfter(after, until, ancestor).Distinct().Select(c => new CommitWrapper(c)); } else { return branch.Commits.Select(c => new CommitWrapper(c)); } }); Name = branch.Name; }
internal Commit(ObjectId id, ObjectId treeId, Repository repo) : base(id) { this.tree = new Lazy<Tree>(() => repo.Lookup<Tree>(treeId)); this.parents = new Lazy<IEnumerable<Commit>>(() => RetrieveParentsOfCommit(id.Oid)); this.repo = repo; }
internal Commit(ObjectId id, ObjectId treeId, Repository repo) : base(id) { tree = new Lazy<Tree>(() => repo.Lookup<Tree>(treeId)); parents = new Lazy<IEnumerable<Commit>>(() => RetrieveParentsOfCommit(id)); shortMessage = new Lazy<string>(ExtractShortMessage); this.repo = repo; }
public override bool Execute() { try { //if (LocalPath == ".") //{ // // User didn't define a Path, find the Git path by expecting this Task to be contained in a Git repo // LocalPath = //} using (var repo = new Repository(LocalPath)) { LastCommitHash = LastCommitShortHash = LastCommitMessage = LastTagName = LastTagMessage = LastTagCommitHash = String.Empty; RevisionCount = 0; Commit commit = null; CommitCollection commits = repo.Commits; if (!String.IsNullOrEmpty(CommitHash)) { // We're looking for a from a particular Commit on back commit = repo.Lookup<Commit>(CommitHash); commits = commits.StartingAt(CommitHash); } else { // We're looking from the most recent Commit commit = repo.Commits.First(); } if (null == commit) { Log.LogError("Can't find a Git Commit with that hash."); return false; } LastCommitShortHash = GetCommitShortHash(commit); LastCommitHash = commit.Sha; LastCommitMessage = commit.Message; Tag tag = GetMostRecentTagByEnumeration(commits, repo.Tags); if (null != tag) { LastTagName = tag.Annotation.Name; LastTagMessage = tag.Annotation.Message; LastTagCommitHash = tag.Annotation.TargetId.Sha; } } } catch (Exception exception) { Log.LogMessage("StackTrace: " + exception.StackTrace); Log.LogErrorFromException(exception); return false; } return true; }
public ChangeSet GetChangeSet(string id) { using (var repo = new LibGit2Sharp.Repository(RepositoryPath)) { LibGit2Sharp.Commit commit = repo.Lookup <LibGit2Sharp.Commit>(id); return(commit == null ? null : new ChangeSet(commit.Sha, commit.Author.Name, commit.Author.Email, commit.Message, commit.Author.When)); } }
public IEnumerable<HunkRangeInfo> GetGitDiffFor(ITextDocument textDocument, ITextSnapshot snapshot) { var content = GetCompleteContent(textDocument, snapshot); if (content == null) yield break; var filename = textDocument.FilePath; var discoveredPath = Repository.Discover(Path.GetFullPath(filename)); if (!Repository.IsValid(discoveredPath)) yield break; using (var repo = new Repository(discoveredPath)) { var retrieveStatus = repo.Index.RetrieveStatus(filename); if (retrieveStatus == FileStatus.Untracked || retrieveStatus == FileStatus.Added) yield break; content = AdaptCrlf(repo, content, textDocument); using (var currentContent = new MemoryStream(content)) { var newBlob = repo.ObjectDatabase.CreateBlob(currentContent); var directoryInfo = new DirectoryInfo(discoveredPath).Parent; if (directoryInfo == null) yield break; var relativeFilepath = filename.Replace(directoryInfo.FullName + "\\", string.Empty); // Determine 'from' and 'to' trees. var currentBranch = repo.Head.Name; var baseCommitEntry = repo.Config.Get<string>(string.Format("branch.{0}.diffmarginbase", currentBranch)); Tree tree = null; if (baseCommitEntry != null) { var baseCommit = repo.Lookup<Commit>(baseCommitEntry.Value); if (baseCommit != null) { // Found a merge base to diff from. tree = baseCommit.Tree; } } tree = tree ?? repo.Head.Tip.Tree; var from = TreeDefinition.From(tree); var treeDefinition = from.Add(relativeFilepath, newBlob, Mode.NonExecutableFile); var to = repo.ObjectDatabase.CreateTree(treeDefinition); var treeChanges = repo.Diff.Compare(tree, to, compareOptions: new CompareOptions { ContextLines = ContextLines, InterhunkLines = 0 }); var gitDiffParser = new GitDiffParser(treeChanges.Patch, ContextLines); var hunkRangeInfos = gitDiffParser.Parse(); foreach (var hunkRangeInfo in hunkRangeInfos) { yield return hunkRangeInfo; } } } }
private string UniqueAbbreviation(Repository repo, string full) { for (int len = 7; len < 40; ++len) { try { repo.Lookup(full.Substring(0, len)); return full.Substring(0, len); } catch (AmbiguousSpecificationException) { continue; } } return full; }
internal static TagAnnotation BuildFromPtr(GitObjectSafeHandle obj, ObjectId id, Repository repo) { ObjectId targetOid = NativeMethods.git_tag_target_oid(obj).MarshalAsObjectId(); return new TagAnnotation(id) { Message = NativeMethods.git_tag_message(obj), Name = NativeMethods.git_tag_name(obj), Tagger = new Signature(NativeMethods.git_tag_tagger(obj)), targetBuilder = new Lazy<GitObject>(() => repo.Lookup<GitObject>(targetOid)) }; }
public void Reset() { // Undo potential impact from earlier tests using (var repository = new LibGit2Sharp.Repository(Module.WorkingDir)) { var options = new LibGit2Sharp.CheckoutOptions(); repository.Reset(LibGit2Sharp.ResetMode.Hard, (LibGit2Sharp.Commit)repository.Lookup(CommitHash, LibGit2Sharp.ObjectType.Commit), options); repository.RemoveUntrackedFiles(); } CommitHelper.SetCommitMessage(Module, commitMessageText: null, amendCommit: false); }
public void Reset() { // Undo potential impact from earlier tests using (var repository = new LibGit2Sharp.Repository(Module.WorkingDir)) { var options = new LibGit2Sharp.CheckoutOptions(); repository.Reset(LibGit2Sharp.ResetMode.Hard, (LibGit2Sharp.Commit)repository.Lookup(CommitHash, LibGit2Sharp.ObjectType.Commit), options); repository.RemoveUntrackedFiles(); } new CommitMessageManager(Module.WorkingDirGitDir, Module.CommitEncoding).ResetCommitMessage(); }
internal static TagAnnotation BuildFromPtr(IntPtr obj, ObjectId id, Repository repo) { IntPtr oidPtr = NativeMethods.git_tag_target_oid(obj); var oid = (GitOid)Marshal.PtrToStructure(oidPtr, typeof(GitOid)); return new TagAnnotation(id) { Message = NativeMethods.git_tag_message(obj).MarshallAsString(), Name = NativeMethods.git_tag_name(obj).MarshallAsString(), Tagger = new Signature(NativeMethods.git_tag_tagger(obj)), targetBuilder = new Lazy<GitObject>(() => repo.Lookup<GitObject>(new ObjectId(oid))) }; }
private string CreateBranchForNewChanges(NewChanges newChanges, string prBranch) { string OriginalSha; var targetRepo = newChanges.TargetRepository; var branchName = $"mirror-merge-{(long)DateTime.Now.Subtract(new DateTime(2000, 1, 1, 0, 0, 0)).TotalMinutes}"; s_logger.Info($"Creating branch {prBranch} in {targetRepo} to merge changes into {prBranch}"); using (var repo = new Repository(targetRepo.Path)) { var branch = repo.CreateBranch(branchName); s_logger.Info("Checking out PR branch"); Commands.Checkout(repo, branch); OriginalSha = branch.Tip.ToString(); } foreach (var source in newChanges.changes.Keys) { var sourceRepository = targetRepo.Configuration.Repos.Where(t => t.Name == source).First(); using (var repo = new Repository(sourceRepository.Path)) { foreach (var change in newChanges.changes[sourceRepository.Name]) { var commit = repo.Lookup <Commit>(change); if (!IsMirrorCommit(commit.Message, targetRepo.Configuration.MirrorSignatureUser) && commit.Parents.Count() == 1 ) { s_logger.Info($"Applying {change}"); var patch = FormatPatch(sourceRepository, change); if (string.IsNullOrWhiteSpace(patch)) { continue; } s_logger.Debug($"Patch:\n{patch}"); ApplyPatch(sourceRepository, newChanges.TargetRepository, patch, commit); } } } } using (var repo = new Repository(targetRepo.Path)) { if (repo.Head.Tip.ToString() == OriginalSha) { s_logger.Info($"No new commits To add into this branch"); return(null); } } return(branchName); }
public bool DoesBranchContainCommit(string branchName, string commitOrBranchName) { using (var repo = new LibGit2Sharp.Repository(RepositoryPath)) { var branch = repo.Branches[branchName]; if (branch == null) { return(false); } return(repo.Refs.ReachableFrom( new[] { repo.Refs[branch.CanonicalName] }, new[] { repo.Lookup <Commit>(commitOrBranchName) }).Any()); } }
public List <Changes> GetChanges(GitCommit commit, string repositoryPath) { List <Changes> changes = new List <Changes>(); using (GitRepository gitRepositoryInfo = new GitRepository(repositoryPath)) { bool isInitial = false; var firstCommit = commit.Parents.FirstOrDefault(); if (firstCommit == null) { isInitial = true; } Tree rootCommitTree = gitRepositoryInfo.Lookup <GitCommit>(commit.Id.ToString()).Tree; Patch patch; if (!isInitial) { Tree commitTreeWithUpdatedFile = gitRepositoryInfo.Lookup <GitCommit>(commit.Parents.FirstOrDefault().Sha).Tree; patch = gitRepositoryInfo.Diff.Compare <Patch>(commitTreeWithUpdatedFile, rootCommitTree); } else { patch = gitRepositoryInfo.Diff.Compare <Patch>(null, rootCommitTree); } foreach (var change in patch) { changes.Add(new Changes() { Type = ConvertChangeKindToChangeType(change.Status), Path = change.Path, ChangeContent = change.Patch }); } } return(changes); }
public IActionResult GetRawBlob(string userName, string repoName, string id, string path) { return(TryGetResult(repoName, () => { if (path == null) { return Redirect(Url.UnencodedRouteLink("GetTreeView", new { repoName = repoName, id = id, path = path })); } repoName = Path.Combine(userName, repoName); LibGit2Sharp.Repository repo = RepositoryService.GetRepository(repoName); Commit commit = repo.Branches[id]?.Tip ?? repo.Lookup <Commit>(id); if (commit == null) { return NotFound(); } TreeEntry entry = commit[path.Replace('/', Path.DirectorySeparatorChar)]; if (entry == null) { return NotFound(); } switch (entry.TargetType) { case TreeEntryTargetType.Blob: { Blob blob = (Blob)entry.Target; if (blob.IsBinary) { return File(blob.GetContentStream(), "application/octet-stream", entry.Name); } else { return File(blob.GetContentStream(), "text/plain"); } } case TreeEntryTargetType.Tree: return Redirect(Url.UnencodedRouteLink("GetTreeView", new { repoName = repoName, id = id, path = path })); default: return BadRequest(); } })); }
public RepositoryWrapper(Repository repo) { this.repo = repo; Head = async (i) => { return new BranchWrapper(repo, repo.Head); }; Config = async (i) => { return repo.Config; }; Index = async (i) => { return repo.Index; }; Ignore = async (i) => { return repo.Ignore; }; Network = async (i) => { return new NetworkWrapper(repo.Network); }; ObjectDatabase = async (i) => { return repo.ObjectDatabase; }; Refs = async (i) => { return repo.Refs; }; Commits = async (i) => { return repo.Commits.Select(c => new CommitWrapper(c)); }; Tags = async (i) => { return repo.Tags; }; Stashes = async (i) => { return repo.Stashes; }; Info = async (i) => { return repo.Info; }; Diff = async (i) => { return repo.Diff; }; Notes = async (i) => { return repo.Notes; }; Submodules = async (i) => { return repo.Submodules; }; Dispose = async (i) => { repo.Dispose(); return null; }; Lookup = async (id) => { var found = repo.Lookup(id.ToString()); if (found.GetType() == typeof(Commit)) { return new CommitWrapper((Commit)found); } else { return found; } }; Branches = async (i) => repo.Branches.Select(b => new BranchWrapper(repo, b)).ToDictionary(b => b.Name); Reset = async (dynamic i) => { var modeName = ((string)i.mode).ToLower(); ResetMode mode; if (modeName == "soft") { mode = ResetMode.Soft; } else if (modeName == "mixed") { mode = ResetMode.Mixed; } else { mode = ResetMode.Hard; } var committish = (string)i.committish; repo.Reset(mode, committish, null, null); return null; }; Checkout = async (i) => { var branch = repo.Branches.First(b => b.Name == i.ToString()); repo.Checkout(branch); return branch; }; }
public VotedPost GetPost(string id) { using (var repo = new Repository(_directory.FullName)) { Commit commit = repo.Lookup<Commit>(id); var post = JsonConvert.DeserializeObject<VotedPost>(commit.Message); post.Id = commit.Sha; // Get the votes for the post Commit postTip = repo.Branches[post.Id].Tip; Tree postTree = postTip.Tree; Tree votesDir = (Tree)postTree[VOTES_DIR].Target; post.Votes = votesDir.Where(f => f.Mode == Mode.NonExecutableFile).Select(DecodeVote).ToList(); return post; } }
private void SanityCheck(RepositoryInfo repository, string branch) { using (var repo = new Repository(repository.Path)) { s_logger.Info($"Running sanity check for {repository.Name}/{branch}"); var lastLookedAtCommit = repo.Lookup <Commit>(repository.LastSynchronizedCommits[branch]); var remoteBranch = repo.Refs[$"refs/heads/{branch}"]; var commitFilter = new CommitFilter { IncludeReachableFrom = remoteBranch, ExcludeReachableFrom = lastLookedAtCommit, SortBy = CommitSortStrategies.Topological | CommitSortStrategies.Time | CommitSortStrategies.Reverse, }; var commitList = repo.Commits.QueryBy(commitFilter).ToList(); if (commitList.Count == 0) { return; } foreach (var commit in commitList) { if (IsMirrorCommit(commit.Message, repository.Configuration.MirrorSignatureUser)) { continue; } var changedFiles = GetChangedFiles(repo, commit); var sharedDirectory = repository.SharedPath; foreach (var changedFile in changedFiles) { if (changedFile.Contains(sharedDirectory)) { foreach (string targetRepo in s_repos[repository.Name]) { RetrieveOrInsert(repository.Name, branch, commit.Sha, targetRepo); } break; } } } UpdateLastSynchronizedCommit(repository, commitList.Last().Sha, branch); s_logger.Info($"sanity check Completed for {repository.Name}/{branch}"); } }
public IEnumerable<HunkRangeInfo> GetGitDiffFor(ITextDocument textDocument, ITextSnapshot snapshot) { var filename = textDocument.FilePath; var discoveredPath = Repository.Discover(Path.GetFullPath(filename)); if (!Repository.IsValid(discoveredPath)) yield break; using (var repo = new Repository(discoveredPath)) { var retrieveStatus = repo.Index.RetrieveStatus(filename); if (retrieveStatus == FileStatus.Untracked || retrieveStatus == FileStatus.Added) yield break; var content = GetCompleteContent(textDocument, snapshot); if (content == null) yield break; content = AdaptCrlf(repo, content, textDocument); using (var currentContent = new MemoryStream(content)) { var newBlob = repo.ObjectDatabase.CreateBlob(currentContent); var directoryInfo = new DirectoryInfo(discoveredPath).Parent; if (directoryInfo == null) yield break; var relativeFilepath = filename.Replace(directoryInfo.FullName + "\\", string.Empty); var from = TreeDefinition.From(repo.Head.Tip.Tree); if (!repo.ObjectDatabase.Contains(@from[relativeFilepath].TargetId)) yield break; var blob = repo.Lookup<Blob>(@from[relativeFilepath].TargetId); var treeChanges = repo.Diff.Compare(blob, newBlob, new CompareOptions { ContextLines = ContextLines, InterhunkLines = 0 }); var gitDiffParser = new GitDiffParser(treeChanges.Patch, ContextLines); var hunkRangeInfos = gitDiffParser.Parse(); foreach (var hunkRangeInfo in hunkRangeInfos) { yield return hunkRangeInfo; } } } }
public static CommitDetails GetCheckinDetails(string checkinId) { Repository repo = new Repository(ConfigurationManager.AppSettings["RepoRoot"]); //Commit commit = repo.Lookup<Commit>(checkinId); //return commit.Message; string patchDirectory = Path.Combine(repo.Info.Path, "patches"); CommitDetails commitDetails = new CommitDetails(); IEnumerable<string> files = Directory.EnumerateFiles(patchDirectory, checkinId + "*", SearchOption.TopDirectoryOnly); if (files != null && files.Any()) { string patchFileName = files.First(); string commitId = Path.GetFileNameWithoutExtension(patchFileName); commitDetails.Commit = repo.Lookup<Commit>(commitId); commitDetails.FileChanges = Serializer.Deserialize<List<FileChanges>>(File.OpenRead(patchFileName)); } return commitDetails; }
private static void ObtenerComits(Repository repo) { /*Obtener dos commits, el comit1 sera el ultimo comit realizado y el comit2 sera el elemento padre (el anterior) del comit actual La cola esta de forma inversa, es decir, cuando accedemos a First() estamos accediendo al ultimo commit guardado */ try { comit1 = repo.Lookup<Commit>(repo.Commits.First().Id.Sha); comit2 = comit1.Parents.First(); Console.WriteLine("\r\nCommit: \r\n\tpadre " + comit1.Id + " \r\n\thijo " + comit2.Id + "; "); } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Error: " + ex.Message); } }
public void Reset() { // Undo potential impact from earlier tests using (var repository = new LibGit2Sharp.Repository(Module.WorkingDir)) { var options = new LibGit2Sharp.CheckoutOptions(); repository.Reset(LibGit2Sharp.ResetMode.Hard, (LibGit2Sharp.Commit)repository.Lookup(CommitHash, LibGit2Sharp.ObjectType.Commit), options); repository.RemoveUntrackedFiles(); var remoteNames = repository.Network.Remotes.Select(remote => remote.Name).ToArray(); foreach (var remoteName in remoteNames) { repository.Network.Remotes.Remove(remoteName); } repository.Config.Set(SettingKeyString.UserName, "author"); repository.Config.Set(SettingKeyString.UserEmail, "*****@*****.**"); } new CommitMessageManager(Module.WorkingDirGitDir, Module.CommitEncoding).ResetCommitMessage(); }
public void CreateOrResetBranch(string branchName, string startPoint) { using (var repo = new LibGit2Sharp.Repository(RepositoryPath)) { if (string.IsNullOrWhiteSpace(startPoint)) { var branch = repo.GetOrCreateBranch(branchName); repo.Checkout(branch); } else { var commit = repo.Lookup <Commit>(startPoint); if (commit == null) { throw new LibGit2Sharp.NotFoundException(string.Format("Start point \"{0}\" for reset was not found.", startPoint)); } var branch = repo.GetOrCreateBranch(branchName); repo.Checkout(branch); repo.Reset(ResetMode.Hard, commit); } } }
public static string GetConflictContent( string rootFolder, StageLevel stage, string conflict ) { using ( var repository = new Repository( rootFolder ) ) { var conflictEntry = repository.Index.Conflicts.FirstOrDefault( c => c.GetPath() == conflict ); if ( conflictEntry == null ) { throw new InvalidDataException( "Could not find the matching conflict entry for " + conflict ); } IndexEntry entry = conflictEntry.GetEntry( stage ); if ( entry == null ) { return null; } Blob stageBlob = repository.Lookup<Blob>( entry.Id ); using ( var reader = new StreamReader( stageBlob.GetContentStream() ) ) { return reader.ReadToEnd(); } } }
public IActionResult GetTreeView(string userName, string repoName, string id, string path) { return(TryGetResult(repoName, () => { repoName = Path.Combine(userName, repoName); LibGit2Sharp.Repository repo = RepositoryService.GetRepository(repoName); Commit commit = repo.Branches[id]?.Tip ?? repo.Lookup <Commit>(id); if (commit == null) { return View("Init"); } if (path == null) { return View("Tree", new TreeModel(repo, "/", repoName, commit.Tree)); } TreeEntry entry = commit[path]; if (entry == null) { return NotFound(); } string parent = Path.GetDirectoryName(entry.Path).Replace(Path.DirectorySeparatorChar, '/'); switch (entry.TargetType) { case TreeEntryTargetType.Tree: return View("Tree", new TreeModel(repo, entry.Path, entry.Name, (Tree)entry.Target, parent)); case TreeEntryTargetType.Blob: return Redirect(Url.UnencodedRouteLink("GetBlobView", new { repoName = repoName, id = id, path = path })); default: return BadRequest(); } })); }
public ActionResult DownloadVersion(Guid id, string sha) { using (var db = ApplicationDbContext.Create()) { ManagedFile file = db.Files.Where(x => x.Id == id) .Include(x => x.CatalogRecord) .Include(x => x.CatalogRecord.Organization).FirstOrDefault(); if (file == null) { //TODO error page? return(RedirectToAction("Index")); } EnsureUserIsAllowed(file.CatalogRecord, db); EnsureUserCanDownload(file.CatalogRecord.Organization); string processingDirectory = SettingsHelper.GetProcessingDirectory(file.CatalogRecord.Organization, db); string path = Path.Combine(processingDirectory, file.CatalogRecord.Id.ToString()); using (var repo = new LibGit2Sharp.Repository(path)) { var blob = repo.Lookup <Blob>(sha); var cd = new System.Net.Mime.ContentDisposition { FileName = file.Name,//always uses the current file name right now... Inline = false, Size = blob.Size }; var contentStream = blob.GetContentStream(); Response.AppendHeader("Content-Disposition", cd.ToString()); return(new FileStreamResult(contentStream, "application/octet-stream")); } } }
/// <summary> /// Run the current rebase step. This will handle reporting that we are about to run a rebase step, /// identifying and running the operation for the current step, and reporting the current step is completed. /// </summary> /// <param name="rebaseOperationHandle"></param> /// <param name="repository"></param> /// <param name="committer"></param> /// <param name="options"></param> /// <param name="stepToApplyIndex"></param> /// <param name="totalStepCount"/> /// <returns></returns> private static unsafe RebaseResult RunRebaseStep(RebaseHandle rebaseOperationHandle, Repository repository, Identity committer, RebaseOptions options, long stepToApplyIndex, long totalStepCount) { RebaseStepResult rebaseStepResult = null; RebaseResult rebaseSequenceResult = null; git_rebase_operation *rebaseOp = Proxy.git_rebase_operation_byindex(rebaseOperationHandle, stepToApplyIndex); ObjectId idOfCommitBeingRebased = ObjectId.BuildFromPtr(&rebaseOp->id); RebaseStepInfo stepToApplyInfo = new RebaseStepInfo(rebaseOp->type, repository.Lookup <Commit>(idOfCommitBeingRebased), LaxUtf8NoCleanupMarshaler.FromNative(rebaseOp->exec)); // Report the rebase step we are about to perform. if (options.RebaseStepStarting != null) { options.RebaseStepStarting(new BeforeRebaseStepInfo(stepToApplyInfo, stepToApplyIndex, totalStepCount)); } // Perform the rebase step git_rebase_operation *rebaseOpReport = Proxy.git_rebase_next(rebaseOperationHandle); // Verify that the information from the native library is consistent. VerifyRebaseOp(rebaseOpReport, stepToApplyInfo); // Handle the result switch (stepToApplyInfo.Type) { case RebaseStepOperation.Pick: rebaseStepResult = ApplyPickStep(rebaseOperationHandle, repository, committer, options, stepToApplyInfo); break; case RebaseStepOperation.Squash: case RebaseStepOperation.Edit: // case RebaseStepOperation.Exec: case RebaseStepOperation.Fixup: case RebaseStepOperation.Reword: // These operations are not yet supported by lg2. throw new LibGit2SharpException("Rebase Operation Type ({0}) is not currently supported in LibGit2Sharp.", stepToApplyInfo.Type); default: throw new ArgumentException(string.Format( "Unexpected Rebase Operation Type: {0}", stepToApplyInfo.Type)); } // Report that we just completed the step if (options.RebaseStepCompleted != null && (rebaseStepResult.Status == RebaseStepStatus.Committed || rebaseStepResult.Status == RebaseStepStatus.ChangesAlreadyApplied)) { if (rebaseStepResult.ChangesAlreadyApplied) { options.RebaseStepCompleted(new AfterRebaseStepInfo(stepToApplyInfo, stepToApplyIndex, totalStepCount)); } else { options.RebaseStepCompleted(new AfterRebaseStepInfo(stepToApplyInfo, repository.Lookup <Commit>(new ObjectId(rebaseStepResult.CommitId)), stepToApplyIndex, totalStepCount)); } } // If the result of the rebase step is something that requires us to stop // running the rebase sequence operations, then report the result. if (rebaseStepResult.Status == RebaseStepStatus.Conflicts) { rebaseSequenceResult = new RebaseResult(RebaseStatus.Conflicts, stepToApplyIndex, totalStepCount, null); } return(rebaseSequenceResult); }
public void RepoManager() { using (var repo = new Repository(dir)) { // CREATE a new file const string oldName = "polite.txt"; string oldPath = Path.Combine(repo.Info.WorkingDirectory, oldName); File.WriteAllText(oldPath, "hello test file\n", Encoding.ASCII); repo.Index.Stage(oldName); Signature who = new Signature("James Davis", "*****@*****.**", new DateTimeOffset(System.DateTime.Now)); //This is a test helper that returns a dummy signature repo.Commit("Initial Commit", who, who, false); // RENAME a file const string newName = "being.frakking.polite.txt"; string newPath = Path.Combine(repo.Info.WorkingDirectory, newName); repo.Index.Unstage(oldName); File.Move(oldPath, newPath); repo.Index.Stage(newName); //who = who.TimeShift(TimeSpan.FromMinutes(1)); //Also a test helper extension method Commit commit = repo.Commit("Fix file name", who, who); ObjectId blobId = commit.Tree[newName].Target.Id; //For future usage below // UPDATE a file File.AppendAllText(newPath, "Hey! I said 'hello'. Why don't you answer me\n", Encoding.ASCII); repo.Index.Stage(newName); //who = who.TimeShift(TimeSpan.FromMinutes(1)); repo.Commit("Update the content", who, who); // DELETE a file repo.Index.Unstage(newName); //who = who.TimeShift(TimeSpan.FromMinutes(2)); repo.Commit("Remove the file as it's not that polite", who, who); // RETRIEVE a specific version of a file Blob file = repo.Lookup<Blob>(blobId); } }
private static HashSet<Commit> GitMergeBaseAll(Repository repo, Commit source, Commit destination) { var startInfo = new ProcessStartInfo(GitReviewApplication.GitPath, string.Format("merge-base --all {0} {1}", source.Sha, destination.Sha)) { WorkingDirectory = GitReviewApplication.RepositoryPath, RedirectStandardOutput = true, UseShellExecute = false, }; using (var git = Process.Start(startInfo)) { var lines = git.StandardOutput.ReadToEnd().TrimEnd('\n').Split('\n'); return new HashSet<Commit>(lines.Select(s => (Commit)repo.Lookup(s))); } }
public void StartExternalDiff(ITextDocument textDocument) { if (textDocument == null || string.IsNullOrEmpty(textDocument.FilePath)) return; var filename = textDocument.FilePath; var repositoryPath = GetGitRepository(Path.GetFullPath(filename)); if (repositoryPath == null) return; using (var repo = new Repository(repositoryPath)) { string workingDirectory = repo.Info.WorkingDirectory; string relativePath = Path.GetFullPath(filename); if (relativePath.StartsWith(workingDirectory, StringComparison.OrdinalIgnoreCase)) relativePath = relativePath.Substring(workingDirectory.Length); // the name of the object in the database string objectName = Path.GetFileName(filename); Blob oldBlob = null; var indexEntry = repo.Index[relativePath]; if (indexEntry != null) { objectName = Path.GetFileName(indexEntry.Path); oldBlob = repo.Lookup<Blob>(indexEntry.Id); } var tempFileName = Path.GetTempFileName(); if (oldBlob != null) File.WriteAllText(tempFileName, oldBlob.GetContentText(new FilteringOptions(relativePath))); IVsDifferenceService differenceService = _serviceProvider.GetService(typeof(SVsDifferenceService)) as IVsDifferenceService; if (differenceService != null) { string leftFileMoniker = tempFileName; // The difference service will automatically load the text from the file open in the editor, even if // it has changed. string rightFileMoniker = filename; string actualFilename = objectName; string tempPrefix = Path.GetRandomFileName().Substring(0, 5); string caption = string.Format("{0}_{1} vs. {1}", tempPrefix, actualFilename); string tooltip = null; string leftLabel; if (indexEntry != null) { // determine if the file has been staged string revision; FileStatus stagedMask = FileStatus.Added | FileStatus.Staged; if ((repo.Index.RetrieveStatus(relativePath) & stagedMask) != 0) revision = "index"; else revision = repo.Head.Tip.Sha.Substring(0, 7); leftLabel = string.Format("{0}@{1}", objectName, revision); } else if (oldBlob != null) { // file was added leftLabel = null; } else { // we just compared to head leftLabel = string.Format("{0}@{1}", objectName, repo.Head.Tip.Sha.Substring(0, 7)); } string rightLabel = filename; string inlineLabel = null; string roles = null; __VSDIFFSERVICEOPTIONS grfDiffOptions = __VSDIFFSERVICEOPTIONS.VSDIFFOPT_LeftFileIsTemporary; differenceService.OpenComparisonWindow2(leftFileMoniker, rightFileMoniker, caption, tooltip, leftLabel, rightLabel, inlineLabel, roles, (uint)grfDiffOptions); // Since the file is marked as temporary, we can delete it now File.Delete(tempFileName); } else { // Can't use __VSDIFFSERVICEOPTIONS, so mark the temporary file(s) read only on disk File.SetAttributes(tempFileName, File.GetAttributes(tempFileName) | FileAttributes.ReadOnly); string remoteFile; if (textDocument.IsDirty) { remoteFile = Path.GetTempFileName(); File.WriteAllBytes(remoteFile, GetCompleteContent(textDocument, textDocument.TextBuffer.CurrentSnapshot)); File.SetAttributes(remoteFile, File.GetAttributes(remoteFile) | FileAttributes.ReadOnly); } else { remoteFile = filename; } var diffGuiTool = repo.Config.Get<string>("diff.guitool"); if (diffGuiTool == null) { diffGuiTool = repo.Config.Get<string>("diff.tool"); if (diffGuiTool == null) return; } var diffCmd = repo.Config.Get<string>("difftool." + diffGuiTool.Value + ".cmd"); if (diffCmd == null || diffCmd.Value == null) return; var cmd = diffCmd.Value.Replace("$LOCAL", tempFileName).Replace("$REMOTE", remoteFile); string fileName = Regex.Match(cmd, ParameterPattern).Value; string arguments = cmd.Substring(fileName.Length); ProcessStartInfo startInfo = new ProcessStartInfo(fileName, arguments); Process.Start(startInfo); } } }
string TryFindCommit( RepositoryInfoOptions options, Repository r, out Commit commit, out CIBranchVersionMode ciVersionMode, out string branchNameForCIVersion ) { ciVersionMode = CIBranchVersionMode.None; commit = null; branchNameForCIVersion = null; string commitSha = options.StartingCommitSha; // Find current commit (the head) if none is provided. if( string.IsNullOrWhiteSpace( commitSha ) ) { IEnumerable<string> branchNames; if( string.IsNullOrWhiteSpace( options.StartingBranchName ) ) { // locCommit is here because one cannot use an out parameter inside a lambda. var locCommit = commit = r.Head.Tip; if( locCommit == null ) return "Unitialized Git repository."; // Save the branches! // By doing this, when we are in 'Detached Head' state (the head of the repository is on a commit and not on a branch: git checkout <sha>), // we can detect that it is the head of a branch and hence apply possible options (mainly CI) for it. // We take into account only the branches from options.RemoteName remote here. string branchName = r.Head.FriendlyName; if( branchName == "(no branch)" ) { string remotePrefix = options.RemoteName + '/'; branchNames = r.Branches .Where( b => b.Tip == locCommit && (!b.IsRemote || b.FriendlyName.StartsWith( remotePrefix )) ) .Select( b => b.IsRemote ? b.FriendlyName.Substring( remotePrefix.Length ) : b.FriendlyName ); } else branchNames = new[] { branchName }; } else { Branch br = r.Branches[options.StartingBranchName] ?? r.Branches[ options.RemoteName + '/' + options.StartingBranchName]; if( br == null ) return string.Format( "Unknown StartingBranchName: '{0}' (also tested on remote '{1}/{0}').", options.StartingBranchName, options.RemoteName ); commit = br.Tip; branchNames = new[] { options.StartingBranchName }; } RepositoryInfoOptionsBranch bOpt; if( options.Branches != null && (bOpt = options.Branches.FirstOrDefault( b => branchNames.Contains( b.Name ) )) != null && bOpt.CIVersionMode != CIBranchVersionMode.None ) { ciVersionMode = bOpt.CIVersionMode; branchNameForCIVersion = string.IsNullOrWhiteSpace( bOpt.VersionName ) ? bOpt.Name : bOpt.VersionName; } } else { commit = r.Lookup<Commit>( commitSha ); if( commit == null ) return string.Format( "Commit '{0}' not found.", commitSha ); } return null; }
/// <summary> /// Initializes a new instance of the <see cref = "Branch" /> class. /// </summary> /// <param name = "targetId">The id of the commit which is pointed at by this Branch</param> /// <param name = "repo">The repo.</param> /// <param name = "canonicalName">The full name of the reference</param> internal Branch(string canonicalName, ObjectId targetId, Repository repo) : this(canonicalName, new Lazy <Commit>(() => repo.Lookup <Commit>(targetId)), repo) { }
public override bool Execute() { using (var context = CollectorRepository.CreateContext(this.ConnectionString)) { db = new CollectorRepository(); db.Context = context; using (repo = new Repository(System.IO.Path.Combine(this.Directory, ".git"))) { foreach (var tag in repo.Tags) { ObjectId commitID = tag.IsAnnotated ? tag.Annotation.TargetId : tag.Target.Id; ImportTag(tag.Name, (LibGit2Sharp.Commit)repo.Lookup(commitID, GitObjectType.Commit), true); } foreach (var branch in repo.Branches) { if (branch.IsRemote && branch.Name.StartsWith(this.Remote + "/", StringComparison.Ordinal)) { string branchName = branch.Name.Substring(this.Remote.Length + 1); if (branchName != "HEAD") { ImportTag(branchName, branch.Tip, false); } } } } if (EnableGitSvnImport && svnRevisionToCommitIdMapping.Count > 0) { var map = svnRevisionToCommitIdMapping.OrderBy(p => p.Key).ToList(); for (int i = 0; i < map.Count - 1; i++) { int minRev = map[i].Key; int maxRev = map[i + 1].Key - 1; foreach (var session in db.Context.Sessions.Where(s => s.AppVersionRevision >= minRev && s.AppVersionRevision <= maxRev)) { session.CommitId = map[i].Value; } } int lastRev = map.Last().Key; foreach (var session in db.Context.Sessions.Where(s => s.AppVersionRevision == lastRev)) { session.CommitId = map.Last().Value; } db.Context.SaveChanges(); } db = null; } return true; }
/// <summary> /// Change the screen to a new commit /// </summary> /// <param name="sha">sha hash of requested commit</param> private void changeCommit(string sha) { currentRepo = new Repository(mLocalRepositories[0].LocalPath); //Commit currentCommit = (Commit)currentRepo.Commits.Where(Commit => Commit.Id.Sha == sha).First(); Commit currentCommit = (Commit)currentRepo.Lookup(new ObjectId(sha), GitObjectType.Commit); //update file list fillFileList(currentCommit.Tree); //update labels lblUser.Text = currentCommit.Committer.Name; lblChangeset.Text = "(" + currentCommit.Id.ToString().Substring(0,6) + ") " + currentCommit.MessageShort; //lblBranch.Text = currentCommit. }
private static string GetFileContent(Repository repo, Dictionary<string, Commit> commits, string commitId, string fileName) { // look up commit in repo var gitCommit = repo.Lookup<LibGit2Sharp.Commit>(commitId); // save the commit message Commit commit; if (commits.TryGetValue(commitId, out commit)) commit.SetMessage(gitCommit.Message); return GetFileContent(gitCommit, fileName); }
public IActionResult RetrieveQuoteGit(string quoteNumber) { var watch = Stopwatch.StartNew(); using (var repo = new Repository("C:\\temp\\rooted\\path")) { var commit = repo.Lookup<Commit>(quoteNumber); var treeEntry = commit["output.json"]; var blob = (Blob)treeEntry.Target; var contentStream = blob.GetContentStream(); using (var tr = new StreamReader(contentStream, Encoding.UTF8)) { string content = tr.ReadToEnd(); Quote jsondata = new JavaScriptSerializer().Deserialize<Quote>(content); QuoteViewModel viewModel = new QuoteViewModel() { FirstName = jsondata.FirstName, LastName = jsondata.LastName, Email = jsondata.Email }; watch.Stop(); var elapsedMs = watch.ElapsedMilliseconds; ViewBag.Message = "Time taken: " + elapsedMs + " ms"; return View("DisplayQuoteSql", viewModel); } } }
public void CreateOrResetBranch(string branchName, string startPoint) { using (var repo = new LibGit2Sharp.Repository(RepositoryPath)) { if (string.IsNullOrWhiteSpace(startPoint)) { var branch = repo.GetOrCreateBranch(branchName); repo.Checkout(branch); } else { var commit = repo.Lookup<Commit>(startPoint); if (commit == null) { throw new LibGit2Sharp.NotFoundException(string.Format("Start point \"{0}\" for reset was not found.", startPoint)); } var branch = repo.GetOrCreateBranch(branchName); repo.Checkout(branch); repo.Reset(ResetMode.Hard, commit); } } }
//TODO: Cries for refactoring... really! internal static T BuildFromPtr <T>(IntPtr ptr, Repository repo) where T : class { if (ptr == IntPtr.Zero) { return(default(T)); } string name = NativeMethods.git_reference_name(ptr).MarshallAsString(); GitReferenceType type = NativeMethods.git_reference_type(ptr); Reference reference; string targetIdentifier; switch (type) { case GitReferenceType.Symbolic: IntPtr resolveRef; targetIdentifier = NativeMethods.git_reference_target(ptr).MarshallAsString(); int res = NativeMethods.git_reference_resolve(out resolveRef, ptr); if (res == (int)GitErrorCode.GIT_ENOTFOUND) { reference = new SymbolicReference { CanonicalName = name, Target = null, TargetIdentifier = targetIdentifier }; break; } Ensure.Success(res); var targetRef = BuildFromPtr <Reference>(resolveRef, repo); reference = new SymbolicReference { CanonicalName = name, Target = targetRef, TargetIdentifier = targetIdentifier }; break; case GitReferenceType.Oid: IntPtr oidPtr = NativeMethods.git_reference_oid(ptr); var oid = (GitOid)Marshal.PtrToStructure(oidPtr, typeof(GitOid)); var targetId = new ObjectId(oid); targetIdentifier = targetId.Sha; var targetBuilder = new Lazy <GitObject>(() => repo.Lookup(targetId)); reference = new DirectReference(targetBuilder) { CanonicalName = name, TargetIdentifier = targetIdentifier }; break; default: throw new LibGit2Exception(String.Format(CultureInfo.InvariantCulture, "Unable to build a new reference from a type '{0}'.", Enum.GetName(typeof(GitReferenceType), type))); } if (typeof(Reference).IsAssignableFrom(typeof(T))) { return(reference as T); } var targetOid = new ObjectId(targetIdentifier); if (Equals(typeof(T), typeof(Tag))) { return(new Tag(reference.CanonicalName, targetOid, repo) as T); } if (Equals(typeof(T), typeof(Branch))) { return(new Branch(reference.CanonicalName, targetOid, repo) as T); } throw new LibGit2Exception( string.Format(CultureInfo.InvariantCulture, "Unable to build a new instance of '{0}' from a reference of type '{1}'.", typeof(T), Enum.GetName(typeof(GitReferenceType), type))); }
internal Tree Build(Repository repository) { WrapAllTreeDefinitions(repository); using (var builder = new TreeBuilder()) { var builtTreeEntryDefinitions = new List<Tuple<string, TreeEntryDefinition>>(entries.Count); foreach (KeyValuePair<string, TreeEntryDefinition> kvp in entries) { string name = kvp.Key; TreeEntryDefinition ted = kvp.Value; var transient = ted as TransientBlobTreeEntryDefinition; if (transient == null) { builder.Insert(name, ted); continue; } Blob blob = transient.Builder(repository.ObjectDatabase); TreeEntryDefinition ted2 = TreeEntryDefinition.From(blob, ted.Mode); builtTreeEntryDefinitions.Add(new Tuple<string, TreeEntryDefinition>(name, ted2)); builder.Insert(name, ted2); } builtTreeEntryDefinitions.ForEach(t => entries[t.Item1] = t.Item2); ObjectId treeId = builder.Write(repository); return repository.Lookup<Tree>(treeId); } }
private static string GetFileContent(string repositoryPath, string commitId, string fileName) { using (var repo = new Repository(repositoryPath)) { var gitCommit = repo.Lookup<LibGit2Sharp.Commit>(commitId); return GetFileContent(gitCommit, fileName); } }
public static TreeChanges GetChangedFiles(LibGit2Sharp.Repository repo, string refRev) { return(GitUtil.CompareCommits(repo, repo.Lookup <Commit> (refRev), repo.Head.Tip)); }
private int DoPrintLog(CancellationToken cancellationToken) { ConsoleColor defaultColor = Console.ForegroundColor; ConsoleColor graphColor = ConsoleColor.DarkYellow; ConsoleColor versionColor = ConsoleColor.DarkRed; using (GitVersionCalulator versionCalculater = new GitVersionCalulator(RepoPath)) using (LibGit2Sharp.Repository repo = new LibGit2Sharp.Repository(RepoPath)) { Commit tip = repo.Head.Tip; if (!string.IsNullOrEmpty(Sha)) { tip = repo.Lookup <Commit>(Sha); if (tip == null) { log.Error($"The commit with reference {Sha} does not exist in the repository."); return(1); } } IEnumerable <Commit> History = repo.Commits.QueryBy(new CommitFilter() { IncludeReachableFrom = tip, SortBy = CommitSortStrategies.Topological }); // Run through to determine max Position (number of concurrent branches) to be able to indent correctly later int maxLines = int.Parse(PrintLog); int lineCount = 0; Dictionary <Commit, int> commitPosition = new Dictionary <Commit, int>(); commitPosition.Add(History.First(), 0); int maxPosition = 0; foreach (Commit c in History) { cancellationToken.ThrowIfCancellationRequested(); if (maxPosition < commitPosition[c]) { maxPosition = commitPosition[c]; } if (!c.Parents.Any()) { // this is the very first commit in the repo. Stop here. maxLines = ++lineCount; break; } Commit p1 = c.Parents.First(); if (c.Parents.Count() > 1) { Commit p2 = c.Parents.Last(); if (commitPosition.ContainsKey(p1)) { if (commitPosition[p1] != commitPosition[c]) { int startPos = Math.Min(commitPosition[p1], commitPosition[c]); int endPos = Math.Max(commitPosition[p1], commitPosition[c]); commitPosition[c] = startPos; foreach (var kvp in commitPosition.Where((KeyValuePair <Commit, int> kvp) => kvp.Value == endPos).ToList()) { commitPosition.Remove(kvp.Key); } } } if (!commitPosition.ContainsKey(p2)) { // move out to an position out for the new branch int newPosition = commitPosition[c] + 1; while (commitPosition.ContainsValue(newPosition) && (newPosition <= commitPosition.Values.Max())) { newPosition++; } commitPosition[p2] = newPosition; commitPosition[p1] = commitPosition[c]; } else if (!commitPosition.ContainsKey(p1)) { commitPosition[p1] = commitPosition[c]; } } else { if (!commitPosition.ContainsKey(p1)) { commitPosition[p1] = commitPosition[c]; } if (commitPosition[p1] != commitPosition[c]) { int startPos = Math.Min(commitPosition[p1], commitPosition[c]); int endPos = Math.Max(commitPosition[p1], commitPosition[c]); // c is now merged back, no need to keep track of it (or any other commit on this branch) // this way we can reuse the position for another branch foreach (var kvp in commitPosition.Where((KeyValuePair <Commit, int> kvp) => kvp.Value == endPos).ToList()) { commitPosition.Remove(kvp.Key); } commitPosition[p1] = startPos; foreach (var kvp in commitPosition.Where((KeyValuePair <Commit, int> kvp) => kvp.Value == startPos).ToList()) { if (kvp.Key != p1) { commitPosition.Remove(kvp.Key); } } } } if (++lineCount >= maxLines) { break; } } { maxPosition++; } { // Run through again to print lineCount = 0; commitPosition = new Dictionary <Commit, int>(); commitPosition.Add(History.First(), 0); HashSet <Commit> taggedCommits = repo.Tags.Select(t => t.Target.Peel <Commit>()).ToHashSet(); foreach (Commit c in History) { cancellationToken.ThrowIfCancellationRequested(); void DrawPositionSpacer(int fromPos, int toPos) { for (int i = fromPos; i < toPos; i++) { if (commitPosition.ContainsValue(i)) { Console.Write("\u2502 "); } else { Console.Write(" "); } } } void DrawMergePositionSpacer(int fromPos, int toPos) { for (int i = fromPos; i < toPos; i++) { if (commitPosition.ContainsValue(i)) { Console.Write("\u2502\u2500"); } else { Console.Write("\u2500\u2500"); } } } Console.ForegroundColor = graphColor; DrawPositionSpacer(0, commitPosition[c]); Console.ForegroundColor = defaultColor; if (taggedCommits.Contains(c)) { Console.Write("v "); } else { Console.Write("* "); } Console.ForegroundColor = graphColor; DrawPositionSpacer(commitPosition[c] + 1, maxPosition); Console.ForegroundColor = versionColor; Console.Write(versionCalculater.GetVersion(c).ToString(FieldCount)); Console.ForegroundColor = defaultColor; Console.Write(" - "); Console.Write(c.MessageShort.Trim()); if (++lineCount >= maxLines) { Console.WriteLine(); break; } if (c.Parents.Any()) { Commit p1 = c.Parents.First(); //Console.Write("Parent1: " + p1.Sha.Substring(0,8)); Console.WriteLine(); Console.ForegroundColor = graphColor; if (c.Parents.Count() > 1) { Commit p2 = c.Parents.Last(); int startPos; int endPos; if (commitPosition.ContainsKey(p1)) { if (commitPosition[p1] != commitPosition[c]) { startPos = Math.Min(commitPosition[p1], commitPosition[c]); // something we already printed has the current commit as its parent, draw the line to that commit now DrawPositionSpacer(0, startPos); // Draw ├─┘ Console.Write("\u251C\u2500"); endPos = Math.Max(commitPosition[p1], commitPosition[c]); DrawMergePositionSpacer(startPos + 1, endPos); Console.Write("\u2518 "); DrawPositionSpacer(endPos + 1, maxPosition); Console.WriteLine(); commitPosition[c] = startPos; foreach (var kvp in commitPosition.Where((KeyValuePair <Commit, int> kvp) => kvp.Value == endPos).ToList()) { commitPosition.Remove(kvp.Key); } } } if (!commitPosition.ContainsKey(p2)) { DrawPositionSpacer(0, commitPosition[c]); // move out to an position out for the new branch int newPosition = commitPosition[c] + 1; while (commitPosition.ContainsValue(newPosition) && (newPosition <= commitPosition.Values.Max())) { newPosition++; } commitPosition[p2] = newPosition; commitPosition[p1] = commitPosition[c]; // Draw ├─┐ Console.Write("\u251C\u2500"); DrawMergePositionSpacer(commitPosition[c] + 1, commitPosition[p2]); Console.Write("\u2510 "); DrawPositionSpacer(commitPosition[p2] + 1, maxPosition); Console.WriteLine(); } else if (!commitPosition.ContainsKey(p1)) { commitPosition[p1] = commitPosition[c]; // this branch is merged several times startPos = Math.Min(commitPosition[p2], commitPosition[c]); DrawPositionSpacer(0, startPos); // draws something like: ├─┤ Console.Write("\u251C\u2500"); endPos = Math.Max(commitPosition[p2], commitPosition[c]); DrawMergePositionSpacer(startPos + 1, endPos); Console.Write("\u2524 "); DrawPositionSpacer(endPos + 1, maxPosition); Console.WriteLine(); } //else //{ // DrawPositionSpacer(0, commitPosition[p2]); // Console.Write("\u251C\u2500"); // DrawMergePositionSpacer(commitPosition[p2] + 1, commitPosition[c]); // Console.WriteLine("\u2524"); //} } else { if (!commitPosition.ContainsKey(p1)) { commitPosition[p1] = commitPosition[c]; } if (commitPosition[p1] != commitPosition[c]) { int startPos = Math.Min(commitPosition[p1], commitPosition[c]); DrawPositionSpacer(0, startPos); // Draw ├─┘ Console.Write("\u251C\u2500"); int endPos = Math.Max(commitPosition[p1], commitPosition[c]); DrawMergePositionSpacer(startPos + 1, endPos); Console.Write("\u2518 "); DrawPositionSpacer(endPos + 1, maxPosition); Console.WriteLine(); // c is now merged back, no need to keep track of it (or any other commit on this branch) // this way we can reuse the position for another branch foreach (var kvp in commitPosition.Where((KeyValuePair <Commit, int> kvp) => kvp.Value == endPos).ToList()) { commitPosition.Remove(kvp.Key); } commitPosition[p1] = startPos; foreach (var kvp in commitPosition.Where((KeyValuePair <Commit, int> kvp) => kvp.Value == startPos).ToList()) { if (kvp.Key != p1) { commitPosition.Remove(kvp.Key); } } } } } } } } return(0); }
public ChangeSet GetChangeSet(string id) { using (var repo = new LibGit2Sharp.Repository(RepositoryPath)) { LibGit2Sharp.Commit commit = repo.Lookup<LibGit2Sharp.Commit>(id); if (commit == null) { return null; } return new ChangeSet(commit.Sha, commit.Author.Name, commit.Author.Email, commit.Message, commit.Author.When); } }
public void StartExternalDiff(ITextDocument textDocument) { if (textDocument == null || string.IsNullOrEmpty(textDocument.FilePath)) return; var filename = textDocument.FilePath; if (textDocument.IsDirty) { var docu = _dte.Documents.AllDocuments().FirstOrDefault(doc => doc.FullName == filename); if (docu != null) { docu.Save(); } }; var discoveredPath = Repository.Discover(Path.GetFullPath(filename)); using (var repo = new Repository(discoveredPath)) { var diffGuiTool = repo.Config.Get<string>("diff.guitool"); if (diffGuiTool == null) return; var diffCmd = repo.Config.Get<string>("difftool." + diffGuiTool.Value + ".path"); var indexEntry = repo.Index[filename.Replace(repo.Info.WorkingDirectory, "")]; var blob = repo.Lookup<Blob>(indexEntry.Id); var tempFileName = Path.GetTempFileName(); File.WriteAllText(tempFileName, blob.GetContentText()); var process = new Process { StartInfo = { FileName = diffCmd.Value, Arguments = String.Format("{0} {1}", tempFileName, filename) } }; process.Start(); } }
public bool DoesBranchContainCommit(string branchName, string commitOrBranchName) { using (var repo = new LibGit2Sharp.Repository(RepositoryPath)) { var branch = repo.Branches[branchName]; if (branch == null) return false; return repo.Refs.ReachableFrom( new[] { repo.Refs[branch.CanonicalName] }, new[] { repo.Lookup<Commit>(commitOrBranchName) }).Any(); } }
public List <TaskTimeItem> GetRepositoryLog(Settings settings, string currentRepository, DateTime?date = null, CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(currentRepository) || !Directory.Exists(currentRepository)) { _log.Error("Папка с репо не сушествует."); return(new List <TaskTimeItem>()); } date = date.GetValueOrDefault(DateTime.Now.Date); var workTasks = new List <TaskTimeItem>(); foreach (var repoDirectory in Directory.GetDirectories(currentRepository, ".git", SearchOption.AllDirectories)) { if (cancellationToken.IsCancellationRequested) { return(new List <TaskTimeItem>()); } //var project = new DirectoryInfo(repoDirectory).Name; var repoRootDirectory = repoDirectory.Replace(".git", ""); var directoryInfo = new DirectoryInfo(repoRootDirectory); if (!directoryInfo.Exists) { continue; } var repo = new LibGit2Sharp.Repository(repoRootDirectory); if (settings.PullBeforeProcess) { try { // Credential information to fetch LibGit2Sharp.PullOptions options = new LibGit2Sharp.PullOptions(); options.FetchOptions = new FetchOptions(); // 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); } catch (Exception ex) { _log?.Trace($" - Не получается сделать pull для репозитория: {directoryInfo.Name} - {ex.Message}"); } } var allCommits = new List <Commit>(); var reflog = repo.Refs.Log(repo.Refs.Head); foreach (var reflogItem in reflog) { var dateMatch = date.Value.Date == reflogItem.Committer.When.Date; var committerEmail = reflogItem.Committer.Email; var userMatch = committerEmail.Equals(settings.MercurialAuthorEmail, StringComparison.CurrentCultureIgnoreCase) || committerEmail.Equals(settings.AlternativeEmail, StringComparison.CurrentCultureIgnoreCase); if (!dateMatch || !userMatch) { continue; } var commit = repo.Lookup <LibGit2Sharp.Commit>(reflogItem.To.Sha); if (commit != null && allCommits.All(f => f.Sha != commit.Sha)) { allCommits.Add(commit); } } foreach (Commit commit in allCommits) { if (cancellationToken.IsCancellationRequested) { return(new List <TaskTimeItem>()); } var userMatch = commit.Author.Email.Equals(settings.MercurialAuthorEmail, StringComparison.CurrentCultureIgnoreCase) || commit.Author.Email.Equals(settings.AlternativeEmail, StringComparison.CurrentCultureIgnoreCase); if (commit.Author.When.DateTime.Date != date.Value.Date || !userMatch) { continue; } var regex = new Regex("[a-zA-Z0-9]{1,5}-[0-9]{1,6}"); var branch = ListBranchesContainsCommit(repo, commit.Sha) .Select(f => f.FriendlyName) .FirstOrDefault(f => regex.IsMatch(f)); //.Where(f => f.Contains("-") && !f.Contains("/")).Distinct().FirstOrDefault(); if (branch == null) { continue; } branch = regex.Match(branch).Value; var commitMessage = commit.MessageShort; commitMessage = _technicalInfoSkipper.StripBranchPrefix(branch, commitMessage); if (_commitSkipper.IsNeedToSkip(branch, commitMessage)) { continue; } commitMessage = _technicalInfoSkipper.StripTechnicalInfo(commitMessage); var files = FilesToMerge(commit, repo); var task = new TaskTimeItem(branch, commitMessage, directoryInfo.Name, commit.Committer.When.DateTime, TimeSpan.Zero, 1, files.Length, //changeset.PathActions.Count, "", GetCommitType(branch)); workTasks.Add(task); _log?.Trace($" - Найден commit: {commit.Committer.When.DateTime} - {branch} - {commit.Author.Email} - {commitMessage}"); } } if (!workTasks.Any()) { return(new List <TaskTimeItem>()); } return(workTasks); }