/// <summary> /// Apply the specified changes to the TFS workspace. This won't commit the changes. /// </summary> private bool ApplyGitChangeToWorkspace(TreeChanges treeChanges) { Debug.Assert(treeChanges.Any()); Debug.Assert(!HasPendingChangesBesidesLock()); return(_commitPortUtil.ApplyGitChangeToWorkspace(treeChanges)); }
public VisorDiff(logicaGIT.CommitShortInfo _commit) { InitializeComponent(); logica = new logicaGIT(_commit.RepoPath); Commit cNuevo = logica.getCommitByID(_commit.ID); Commit cPadre = null; if (cNuevo.Parents.Count() > 0) { cPadre = cNuevo.Parents.First(); } else { cPadre = cNuevo; } cambios = logica.VerCambios(cPadre.Id.Sha, cNuevo.Id.Sha); foreach (TreeEntryChanges cambio in cambios) { if (logic.logicaGIT.extensionesProhibidas(cambio.Path)) { cmbFicheros.Items.Add(cambio.Path); } } }
private bool ApplyCommitInternal(Commit commit, TreeChanges changes, Repository repo) { this.CommitCountSinceVersionChange++; // return false if this is a version number root var projectFileChange = changes.Where(x => x.Path?.Equals(this.ProjectFilePath, StringComparison.OrdinalIgnoreCase) == true).FirstOrDefault(); if (projectFileChange != null) { if (projectFileChange.Status == ChangeKind.Added) { // the version must have been set here return(false); } else { var blob = repo.Lookup <Blob>(projectFileChange.Oid); using (var s = blob.GetContentStream()) { var project = new ProjectReader().ReadProject(s, this.Name, this.FullProjectFilePath, null); if (project.Version != this.Version) { // version changed return(false); } } } // version must have been the same lets carry on return(true); } return(true); }
private bool ApplyCommit(Commit commit, Repository repo) { foreach (Commit parent in commit.Parents) { TreeChanges changes = repo.Diff.Compare <TreeChanges>(parent.Tree, commit.Tree); foreach (TreeEntryChanges change in changes) { if (!string.IsNullOrWhiteSpace(change.OldPath)) { if (this.MatchPath(change.OldPath)) { return(this.ApplyCommitInternal(commit, changes, repo)); } } if (!string.IsNullOrWhiteSpace(change.Path)) { if (this.MatchPath(change.Path)) { return(this.ApplyCommitInternal(commit, changes, repo)); } } } } return(true); }
public void ExactModeDetectsExactCopies() { SelfCleaningDirectory scd = BuildSelfCleaningDirectory(); var path = Repository.Init(scd.DirectoryPath); using (var repo = new Repository(path)) { const string originalPath = "original.txt"; const string copiedPath = "copied.txt"; var originalFullPath = Path.Combine(repo.Info.WorkingDirectory, originalPath); var copiedFullPath = Path.Combine(repo.Info.WorkingDirectory, copiedPath); Touch(repo.Info.WorkingDirectory, originalPath, "a\nb\nc\nd\n"); repo.Index.Stage(originalPath); Commit old = repo.Commit("Initial", Constants.Signature, Constants.Signature); File.Copy(originalFullPath, copiedFullPath); repo.Index.Stage(copiedPath); Commit @new = repo.Commit("Updated", Constants.Signature, Constants.Signature); TreeChanges changes = repo.Diff.Compare <TreeChanges>(old.Tree, @new.Tree, compareOptions: new CompareOptions { Similarity = SimilarityOptions.Exact, }); Assert.Equal(1, changes.Count()); Assert.Equal(1, changes.Copied.Count()); } }
private void createFileDatas(TreeChanges changes, List <FileData> fDatas, Patch patch) { //Creation des objets FileData en initialisant le path et le status foreach (TreeEntryChanges treeEntryChanges in changes) { String[] split = treeEntryChanges.Path.Split('\\'); //fileNames.Add(split[split.Length - 1]); fDatas.Add(new FileData() { Path = split[split.Length - 1], status = treeEntryChanges.Status.ToString(), linesAdded = 0, linesDeleted = 0 }); } //Puis init des lignes ajoutées et supprimées pour chaque fichier for (int i = 0; i < fDatas.Count; i++) { FileData f = fDatas[i]; var pt = patch.Where(x => x.Path == f.Path); if (pt.Count <PatchEntryChanges>() > 0) { f.linesAdded = pt.ElementAt <PatchEntryChanges>(0).LinesAdded; f.linesDeleted = pt.ElementAt <PatchEntryChanges>(0).LinesDeleted; } } }
public void CanCompareTwoVersionsOfAFileWithADiffOfTwoHunks(int contextLines, int interhunkLines) { var compareOptions = new CompareOptions { ContextLines = contextLines, InterhunkLines = interhunkLines, }; using (var repo = new Repository(StandardTestRepoPath)) { Tree rootCommitTree = repo.Lookup <Commit>("f8d44d7").Tree; Tree mergedCommitTree = repo.Lookup <Commit>("7252fe2").Tree; TreeChanges changes = repo.Diff.Compare(rootCommitTree, mergedCommitTree, compareOptions: compareOptions); Assert.Equal(3, changes.Count()); Assert.Equal(1, changes.Modified.Count()); Assert.Equal(1, changes.Deleted.Count()); Assert.Equal(1, changes.Added.Count()); TreeEntryChanges treeEntryChanges = changes["numbers.txt"]; Assert.Equal(3, treeEntryChanges.LinesAdded); Assert.Equal(1, treeEntryChanges.LinesDeleted); Assert.Equal(Mode.Nonexistent, changes["my-name-does-not-feel-right.txt"].Mode); Assert.Equal(Expected("f8d44d7...7252fe2/numbers.txt-{0}-{1}.diff", contextLines, interhunkLines), treeEntryChanges.Patch); Assert.Equal(Expected("f8d44d7...7252fe2/full-{0}-{1}.diff", contextLines, interhunkLines), changes.Patch); } }
T getBranchChanged <T>(TreeChanges changes, BranchInfo branchInfo) where T : BranchModification, new() => new T { Branch = branchInfo, Added = changes.Added.Select(a => new ItemAdded { Key = a.Path, GetValue = () => getBlobValue(a.Oid) }).ToList(), Modified = changes.Modified.Select(m => new ItemModified { Key = m.Path, GetValue = () => getBlobValue(m.Oid), GetOldValue = () => getBlobValue(m.OldOid) }).ToList(), Renamed = changes.Renamed.Select(r => new ItemRenamed { Key = r.Path, GetValue = () => getBlobValue(r.Oid), GetOldValue = () => getBlobValue(r.OldOid), OldKey = r.OldPath }).ToList(), Deleted = changes.Deleted.Select(d => new ItemDeleted { Key = d.Path, GetValue = () => getBlobValue(d.OldOid) }).ToList() };
string GetStatusDisplay(IPullRequestFileModel file, TreeChanges changes) { switch (file.Status) { case PullRequestFileStatus.Added: return(Resources.AddedFileStatus); case PullRequestFileStatus.Renamed: var fileName = file.FileName.Replace("/", "\\"); var change = changes?.Renamed.FirstOrDefault(x => x.Path == fileName); if (change != null) { return(Path.GetDirectoryName(change.OldPath) == Path.GetDirectoryName(change.Path) ? Path.GetFileName(change.OldPath) : change.OldPath); } else { return(Resources.RenamedFileStatus); } default: return(null); } }
public void CanIncludeUnmodifiedEntriesWhenEnabled() { SelfCleaningDirectory scd = BuildSelfCleaningDirectory(); var path = Repository.Init(scd.DirectoryPath); using (var repo = new Repository(path)) { Touch(repo.Info.WorkingDirectory, "a.txt", "abc\ndef\n"); Touch(repo.Info.WorkingDirectory, "b.txt", "abc\ndef\n"); repo.Index.Stage(new[] { "a.txt", "b.txt" }); Commit old = repo.Commit("Initial", Constants.Signature, Constants.Signature); File.AppendAllText(Path.Combine(repo.Info.WorkingDirectory, "b.txt"), "ghi\njkl\n"); repo.Index.Stage("b.txt"); Commit @new = repo.Commit("Updated", Constants.Signature, Constants.Signature); TreeChanges changes = repo.Diff.Compare <TreeChanges>(old.Tree, @new.Tree, compareOptions: new CompareOptions { IncludeUnmodified = true }); Assert.Equal(2, changes.Count()); Assert.Equal(1, changes.Unmodified.Count()); Assert.Equal(1, changes.Modified.Count()); } }
public void ExactModeDoesntDetectRenamesWithEdits() { SelfCleaningDirectory scd = BuildSelfCleaningDirectory(); var path = Repository.Init(scd.DirectoryPath); using (var repo = new Repository(path)) { const string originalPath = "original.txt"; const string renamedPath = "renamed.txt"; Touch(repo.Info.WorkingDirectory, originalPath, "a\nb\nc\nd\n"); repo.Index.Stage(originalPath); Commit old = repo.Commit("Initial", Constants.Signature, Constants.Signature); repo.Index.Move(originalPath, renamedPath); File.AppendAllText(Path.Combine(repo.Info.WorkingDirectory, renamedPath), "e\nf\n"); repo.Index.Stage(renamedPath); Commit @new = repo.Commit("Updated", Constants.Signature, Constants.Signature); TreeChanges changes = repo.Diff.Compare <TreeChanges>(old.Tree, @new.Tree, compareOptions: new CompareOptions { Similarity = SimilarityOptions.Exact, }); Assert.Equal(2, changes.Count()); Assert.Equal(0, changes.Renamed.Count()); Assert.Equal(1, changes.Added.Count()); Assert.Equal(1, changes.Deleted.Count()); } }
public void CanNotDetectTheExactRenamingFilesWhenNotEnabled() { SelfCleaningDirectory scd = BuildSelfCleaningDirectory(); var path = Repository.Init(scd.DirectoryPath); using (var repo = new Repository(path)) { const string originalPath = "original.txt"; const string renamedPath = "renamed.txt"; Touch(repo.Info.WorkingDirectory, originalPath, "a\nb\nc\nd\n"); repo.Index.Stage(originalPath); Commit old = repo.Commit("Initial", Constants.Signature, Constants.Signature); repo.Index.Move(originalPath, renamedPath); Commit @new = repo.Commit("Updated", Constants.Signature, Constants.Signature); TreeChanges changes = repo.Diff.Compare <TreeChanges>(old.Tree, @new.Tree, compareOptions: new CompareOptions { Similarity = SimilarityOptions.None, }); Assert.Equal(2, changes.Count()); Assert.Equal(0, changes.Renamed.Count()); } }
public void DetectsTheExactRenamingOfFilesByDefault() { SelfCleaningDirectory scd = BuildSelfCleaningDirectory(); var path = Repository.Init(scd.DirectoryPath); using (var repo = new Repository(path)) { const string originalPath = "original.txt"; const string renamedPath = "renamed.txt"; Touch(repo.Info.WorkingDirectory, originalPath, "a\nb\nc\nd\n"); repo.Index.Stage(originalPath); Commit old = repo.Commit("Initial", Constants.Signature, Constants.Signature); repo.Index.Move(originalPath, renamedPath); Commit @new = repo.Commit("Updated", Constants.Signature, Constants.Signature); TreeChanges changes = repo.Diff.Compare <TreeChanges>(old.Tree, @new.Tree); Assert.Equal(1, changes.Count()); Assert.Equal(1, changes.Renamed.Count()); Assert.Equal("original.txt", changes.Renamed.Single().OldPath); Assert.Equal("renamed.txt", changes.Renamed.Single().Path); } }
public IEnumerable <Change> GetTreeChanges(string branch) { var gitBranch = _repository.Branches[branch]; var gitCurrentCommit = TryAndGetCurrentCommit(gitBranch); var gitPreviousCommit = TryAndGetPreviousCommit(gitBranch); List <Change> changes = new List <Change>(); if (gitCurrentCommit != null && gitPreviousCommit != null) { TreeChanges tc = _repository.Diff.Compare <TreeChanges>(gitPreviousCommit.Tree, gitCurrentCommit.Tree); changes.AddRange(tc.Select(c => new Change { Path = c.Path, Mode = (GitMode)c.Mode, Status = (GitChangeKind)c.Status })); } else { throw new Exception("Either the current or previous commits specified could not be found!"); } return(changes); }
private RepositoryCommitModel ToModel(Commit commit, bool withDiff = false) { var model = new RepositoryCommitModel { Author = commit.Author.Name, AuthorEmail = commit.Author.Email, Date = commit.Author.When.LocalDateTime, ID = commit.Sha, Message = commit.Message, TreeID = commit.Tree.Sha, Parents = commit.Parents.Select(i => i.Sha).ToArray(), }; if (!withDiff) { return(model); } TreeChanges changes = !commit.Parents.Any() ? _repository.Diff.Compare(null, commit.Tree) : _repository.Diff.Compare(commit.Parents.First().Tree, commit.Tree); model.Changes = changes.OrderBy(s => s.Path).Select(i => new RepositoryCommitChangeModel { Path = i.Path.Replace('\\', '/'), Status = i.Status, }); return(model); }
/// <summary> /// Generates the commit tree. /// </summary> /// <returns>The list of elements.</returns> public static List <CommitTreeElement> GenerateCommitTree() { IDCounter = 0; TreeChanges changes = RepositoryManager.GetChanges(); Folder rootFolder = new Folder(); foreach (TreeEntryChanges c in changes) { #region ////// Build a tree using File and Folder models string[] pathSplit = c.Path.Split(new[] { "\\", "/" }, StringSplitOptions.None); if (pathSplit.Length == 1) { File endFile = new File() { name = pathSplit[0], fullPath = pathSplit[0] }; rootFolder.filesChildren.Add(endFile); continue; } Folder parent = rootFolder; for (int i = 0; i < pathSplit.Length; ++i) { if (i == pathSplit.Length - 1) { File endFile = new File() { name = pathSplit[i], fullPath = c.Path }; parent.filesChildren.Add(endFile); break; } else { Folder currentFolder = parent.folderChildren.Find(x => x.name == pathSplit[i]); if (currentFolder == null) { currentFolder = new Folder() { name = pathSplit[i] }; parent.folderChildren.Add(currentFolder); } parent = currentFolder; } } #endregion } // Use the File and Folder tree to create the CommitTree var root = new CommitTreeElement("Root", -1, IDCounter); var treeElements = new List <CommitTreeElement>(); treeElements.Add(root); AddChildren(ref treeElements, 0, rootFolder); return(treeElements); }
public CommitDetail GetCommitDetails(string sha) { if (string.IsNullOrEmpty(sha)) { throw new ArgumentNullException(); } var commit = _repository.Lookup <LibGit2Sharp.Commit>(sha); if (commit == null) { throw new CommitNotFoundException(sha); } var commitParent = commit.Parents.Last(); TreeChanges treeChanges = _repository.Diff.Compare <TreeChanges>(commitParent.Tree, commit.Tree); CommitDetail commitDetail = new CommitDetail(sha, commit.Message, commit.Author.Name, commit.Author.When.Date); commitDetail.Files.AddRange(treeChanges.Select(s => new CommitFile((int)s.Status, s.Path, Path.GetFileName(s.Path)))); //commitDetail.Files.AddRange(treeChanges.Modified.Select(s => new CommitFile((int)s.Status, s.Path, Path.GetFileName(s.Path)))); //commitDetail.Files.AddRange(treeChanges.Deleted.Select(s => new CommitFile((int)s.Status, s.Path, Path.GetFileName(s.Path)))); return(commitDetail); }
/* * $ git init . * $ echo -ne 'a' > file.txt * $ git add . * $ git commit -m "No line ending" * $ echo -ne '\n' >> file.txt * $ git add . * $ git diff --cached * diff --git a/file.txt b/file.txt * index 2e65efe..7898192 100644 * --- a/file.txt * +++ b/file.txt * @@ -1 +1 @@ * -a * \ No newline at end of file * +a */ public void CanCopeWithEndOfFileNewlineChanges() { string repoPath = InitNewRepository(); using (var repo = new Repository(repoPath)) { var fullpath = Touch(repo.Info.WorkingDirectory, "file.txt", "a"); repo.Index.Stage("file.txt"); repo.Commit("Add file without line ending", Constants.Signature, Constants.Signature); File.AppendAllText(fullpath, "\n"); repo.Index.Stage("file.txt"); TreeChanges changes = repo.Diff.Compare(repo.Head.Tip.Tree, DiffTargets.Index); Assert.Equal(1, changes.Modified.Count()); Assert.Equal(1, changes.LinesAdded); Assert.Equal(1, changes.LinesDeleted); var expected = new StringBuilder() .Append("diff --git a/file.txt b/file.txt\n") .Append("index 2e65efe..7898192 100644\n") .Append("--- a/file.txt\n") .Append("+++ b/file.txt\n") .Append("@@ -1 +1 @@\n") .Append("-a\n") .Append("\\ No newline at end of file\n") .Append("+a\n"); Assert.Equal(expected.ToString(), changes.Patch); } }
public void CanNotDetectTheExactCopyingOfModifiedFilesWhenNotEnabled() { SelfCleaningDirectory scd = BuildSelfCleaningDirectory(); var path = Repository.Init(scd.DirectoryPath); using (var repo = new Repository(path)) { const string originalPath = "original.txt"; const string copiedPath = "copied.txt"; string originalFullPath = Path.Combine(repo.Info.WorkingDirectory, originalPath); string copiedFullPath = Path.Combine(repo.Info.WorkingDirectory, copiedPath); Touch(repo.Info.WorkingDirectory, originalPath, "a\nb\nc\nd\n"); repo.Index.Stage(originalPath); Commit old = repo.Commit("Initial", Constants.Signature, Constants.Signature); File.Copy(originalFullPath, copiedFullPath); File.AppendAllText(originalFullPath, "e\n"); repo.Index.Stage(originalPath); repo.Index.Stage(copiedPath); Commit @new = repo.Commit("Updated", Constants.Signature, Constants.Signature); TreeChanges changes = repo.Diff.Compare <TreeChanges>(old.Tree, @new.Tree); Assert.Equal(2, changes.Count()); Assert.Equal(0, changes.Copied.Count()); } }
public IEnumerable <TreeEntryChanges> FilterForProject(TreeChanges changes) { return(changes .Where(c => c.Status.HasSemanticMeaning()) .Where(c => c.Path.StartsWith(Directory) || c.OldPath.StartsWith(Directory))); }
public void CanDetectTheExactRenamingExactCopyingOfNonModifiedAndModifiedFilesWhenEnabled() { SelfCleaningDirectory scd = BuildSelfCleaningDirectory(); var path = Repository.Init(scd.DirectoryPath); using (var repo = new Repository(path)) { const string originalPath = "original.txt"; const string renamedPath = "renamed.txt"; const string originalPath2 = "original2.txt"; const string copiedPath1 = "copied.txt"; const string originalPath3 = "original3.txt"; const string copiedPath2 = "copied2.txt"; Touch(repo.Info.WorkingDirectory, originalPath, "a\nb\nc\nd\n"); Touch(repo.Info.WorkingDirectory, originalPath2, "1\n2\n3\n4\n"); Touch(repo.Info.WorkingDirectory, originalPath3, "5\n6\n7\n8\n"); repo.Index.Stage(originalPath); repo.Index.Stage(originalPath2); repo.Index.Stage(originalPath3); Commit old = repo.Commit("Initial", Constants.Signature, Constants.Signature); var originalFullPath2 = Path.Combine(repo.Info.WorkingDirectory, originalPath2); var originalFullPath3 = Path.Combine(repo.Info.WorkingDirectory, originalPath3); var copiedFullPath1 = Path.Combine(repo.Info.WorkingDirectory, copiedPath1); var copiedFullPath2 = Path.Combine(repo.Info.WorkingDirectory, copiedPath2); File.Copy(originalFullPath2, copiedFullPath1); File.Copy(originalFullPath3, copiedFullPath2); File.AppendAllText(originalFullPath3, "9\n"); repo.Index.Stage(originalPath3); repo.Index.Stage(copiedPath1); repo.Index.Stage(copiedPath2); repo.Index.Move(originalPath, renamedPath); Commit @new = repo.Commit("Updated", Constants.Signature, Constants.Signature); TreeChanges changes = repo.Diff.Compare <TreeChanges>(old.Tree, @new.Tree, compareOptions: new CompareOptions { Similarity = SimilarityOptions.CopiesHarder, }); Assert.Equal(4, changes.Count()); Assert.Equal(1, changes.Modified.Count()); Assert.Equal(1, changes.Renamed.Count()); Assert.Equal("original.txt", changes.Renamed.Single().OldPath); Assert.Equal("renamed.txt", changes.Renamed.Single().Path); Assert.Equal(2, changes.Copied.Count()); Assert.Equal("original2.txt", changes.Copied.ElementAt(0).OldPath); Assert.Equal("copied.txt", changes.Copied.ElementAt(0).Path); Assert.Equal("original3.txt", changes.Copied.ElementAt(1).OldPath); Assert.Equal("copied2.txt", changes.Copied.ElementAt(1).Path); } }
private static void LogChanges(TreeChanges changeLog) { Console.WriteLine("File Added: " + Extensions.JoinWithPlaceholder(", ", "0", changeLog.Added.Select(x => x.Path))); Console.WriteLine("File Copied: " + Extensions.JoinWithPlaceholder(", ", "0", changeLog.Copied.Select(x => x.Path))); Console.WriteLine("File Deleted: " + Extensions.JoinWithPlaceholder(", ", "0", changeLog.Deleted.Select(x => x.Path))); Console.WriteLine("File Modified: " + Extensions.JoinWithPlaceholder(", ", "0", changeLog.Modified.Select(x => x.Path))); Console.WriteLine("File Renamed: " + Extensions.JoinWithPlaceholder(", ", "0", changeLog.Renamed.Select(x => x.Path))); Console.WriteLine("File Unmodified: " + Extensions.JoinWithPlaceholder(", ", "0", changeLog.Unmodified.Select(x => x.Path))); }
public void ComparingTwoNullTreesReturnsAnEmptyTreeChanges() { using (var repo = new Repository(StandardTestRepoPath)) { TreeChanges changes = repo.Diff.Compare(null, null, null); Assert.Equal(0, changes.Count()); } }
static string GetOldFileName(PullRequestFileModel file, TreeChanges changes) { if (file.Status == PullRequestFileStatus.Renamed) { var gitPath = Paths.ToGitPath(file.FileName); return(changes?.Renamed.FirstOrDefault(x => x.Path == gitPath)?.OldPath); } return(null); }
string GetOldFileName(IPullRequestFileModel file, TreeChanges changes) { if (file.Status == PullRequestFileStatus.Renamed) { var fileName = file.FileName.Replace("/", "\\"); return(changes?.Renamed.FirstOrDefault(x => x.Path == fileName)?.OldPath); } return(null); }
public TreeChanges VerCambios(string commitID1, string commitID2) { feed.Logs.WriteText("Ver cambios", "Se desea ver los cambios del proyecto " + NombreProyecto); Tree t1 = Repositorio.Lookup <Commit>(commitID1).Tree; Tree t2 = Repositorio.Lookup <Commit>(commitID2).Tree; TreeChanges changes = Repositorio.Diff.Compare(t1, t2); return(changes); }
private void AddCurrentChanges(GitVersionIdentification versionIdentification, FilesProgramModel model, Repository repo) { var lastCommit = repo.Head.Tip; TreeChanges diff = repo.Diff.Compare <TreeChanges>(default(Tree), lastCommit.Tree); foreach (var entry in diff) { var filePath = entry.Path; var fullPath = Path.Combine(versionIdentification.RepositoryPath, filePath); var relativePathToSolution = RelativePathHelper.GetRelativePath(model, fullPath); if (model.Files.All(x => !x.Id.Equals(relativePathToSolution, StringComparison.Ordinal))) { model.Files.Add(new FileElement(relativePathToSolution, () => GetContent(versionIdentification.RepositoryPath, lastCommit.Id.Sha, filePath))); } } var status = repo.RetrieveStatus(); status.Added.Union(status.Untracked).ForEach(addedFile => { var fullPath = Path.Combine(versionIdentification.RepositoryPath, addedFile.FilePath); var relativePathToSolution = RelativePathHelper.GetRelativePath(model, fullPath); if (model.Files.All(x => !x.Id.Equals(relativePathToSolution, StringComparison.Ordinal))) { model.Files.Add(new FileElement(relativePathToSolution, () => File.ReadAllText(fullPath))); } }); status.Modified.Union(status.Staged).ForEach(changedFile => { var fullPath = Path.Combine(versionIdentification.RepositoryPath, changedFile.FilePath); var relativePathToSolution = RelativePathHelper.GetRelativePath(model, fullPath); var file = model.Files.SingleOrDefault(x => x.Id.Equals(relativePathToSolution, StringComparison.Ordinal)); if (file != null) { model.Files.Remove(file); model.Files.Add(new FileElement(relativePathToSolution, () => File.ReadAllText(fullPath))); } }); status.Missing.Union(status.Removed).ForEach(changedFile => { var fullPath = Path.Combine(versionIdentification.RepositoryPath, changedFile.FilePath); var relativePathToSolution = RelativePathHelper.GetRelativePath(model, fullPath); if (model.Files.Any(x => x.Id.Equals(relativePathToSolution, StringComparison.Ordinal))) { model.Files.RemoveAll(x => x.Id.Equals(relativePathToSolution, StringComparison.Ordinal)); } }); }
private RepositoryCommitModel ToModel(Commit commit, bool withDiff = false) { string tagsString = string.Empty; var tags = _repository.Tags.Where(o => o.Target.Sha == commit.Sha).Select(o => o.Name).ToList(); var shortMessageDetails = RepositoryCommitModelHelpers.MakeCommitMessage(commit.Message, 50); IEnumerable <string> links = null; if (UserConfiguration.Current.HasLinks) { links = Regex.Matches(commit.Message, UserConfiguration.Current.LinksRegex).OfType <Match>().Select(m => m.Value); } var model = new RepositoryCommitModel { Author = commit.Author.Name, AuthorEmail = commit.Author.Email, AuthorAvatar = commit.Author.GetAvatar(), Date = commit.Author.When.LocalDateTime, ID = commit.Sha, Message = shortMessageDetails.ShortTitle, MessageShort = shortMessageDetails.ExtraTitle, TreeID = commit.Tree.Sha, Parents = commit.Parents.Select(i => i.Sha).ToArray(), Tags = tags, Notes = (from n in commit.Notes select new RepositoryCommitNoteModel(n.Message, n.Namespace)).ToList(), Links = links }; if (!withDiff) { return(model); } TreeChanges changes = !commit.Parents.Any() ? _repository.Diff.Compare <TreeChanges>(null, commit.Tree) : _repository.Diff.Compare <TreeChanges>(commit.Parents.First().Tree, commit.Tree); Patch patches = !commit.Parents.Any() ? _repository.Diff.Compare <Patch>(null, commit.Tree) : _repository.Diff.Compare <Patch>(commit.Parents.First().Tree, commit.Tree); model.Changes = changes.OrderBy(s => s.Path).Select(i => { var patch = patches[i.Path]; return(new RepositoryCommitChangeModel { ChangeId = i.Oid.Sha, Path = i.Path.Replace('\\', '/'), Status = i.Status, LinesAdded = patch.LinesAdded, LinesDeleted = patch.LinesDeleted, Patch = patch.Patch, }); }); return(model); }
public void CanCompareTheWorkDirAgainstTheIndex() { using (var repo = new Repository(StandardTestRepoPath)) { TreeChanges changes = repo.Diff.Compare(); Assert.Equal(2, changes.Count()); Assert.Equal("deleted_unstaged_file.txt", changes.Deleted.Single().Path); Assert.Equal("modified_unstaged_file.txt", changes.Modified.Single().Path); } }
public void RetrievingANonExistentFileChangeReturnsNull() { using (var repo = new Repository(StandardTestRepoPath)) { Tree tree = repo.Head.Tip.Tree; TreeChanges changes = repo.Diff.Compare(tree, tree); Assert.Null(changes["batman"]); } }
public void ComparingATreeAgainstItselfReturnsNoDifference() { using (var repo = new Repository(StandardTestRepoPath)) { Tree tree = repo.Head.Tip.Tree; TreeChanges changes = repo.Diff.Compare(tree, tree); Assert.Empty(changes); Assert.Equal(string.Empty, changes.Patch); } }
private static void PrintChanges(TreeChanges changes) { Printf("All:"); changes.ToList().ForEach(x => Printf(x.Path)); Printf("\nModified:"); changes.Modified.ToList().ForEach(x => Printf(x.Path)); Printf("\nDeleted:"); changes.Deleted.ToList().ForEach(x => Printf(x.Path)); Printf("\nAdded:"); changes.Added.ToList().ForEach(x => Printf(x.Path)); Printf("\nRenamed:"); changes.Renamed.ToList().ForEach(x => Printf(string.Format("{0} -> {1}", x.OldPath, x.Path))); Printf(); }
private static void LogChanges(TreeChanges changes) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(string.Format("All: ({0}){1}", changes.ToList().Count, Environment.NewLine)); changes.ToList().ForEach(x => { stringBuilder.Append(x.Path); stringBuilder.Append(Environment.NewLine);}); stringBuilder.Append(string.Format("\nModified: ({0}){1}", changes.Modified.ToList().Count, Environment.NewLine)); changes.Modified.ToList().ForEach(x => { stringBuilder.Append(x.Path); stringBuilder.Append(Environment.NewLine); }); stringBuilder.Append(string.Format("\nDeleted: ({0}){1}", changes.Deleted.ToList().Count, Environment.NewLine)); changes.Deleted.ToList().ForEach(x => { stringBuilder.Append(x.Path); stringBuilder.Append(Environment.NewLine); }); stringBuilder.Append(string.Format("\nAdded: ({0}){1}", changes.Added.ToList().Count, Environment.NewLine)); changes.Added.ToList().ForEach(x => { stringBuilder.Append(x.Path); stringBuilder.Append(Environment.NewLine); }); stringBuilder.Append(string.Format("\nRenamed: ({0}){1}", changes.Renamed.ToList().Count, Environment.NewLine)); changes.Renamed.ToList().ForEach(x => { stringBuilder.Append(string.Format("{0} -> {1}",x.OldPath, x.Path)); stringBuilder.Append(Environment.NewLine); }); Logger.Instance.Log(stringBuilder.ToString()); }
public void reset( TreeChanges newChanges, Console console ) { changes = newChanges; treeView = new TreeView(); }
void NotifyFileChanges (ProgressMonitor monitor, TreeChanges statusList) { // Files added to source branch not present to target branch. var removed = statusList.Where (c => c.Status == ChangeKind.Added).Select (c => GetRepository (c.Path).FromGitPath (c.Path)).ToList (); var modified = statusList.Where (c => c.Status != ChangeKind.Added).Select (c => GetRepository (c.Path).FromGitPath (c.Path)).ToList (); monitor.BeginTask (GettextCatalog.GetString ("Updating solution"), removed.Count + modified.Count); FileService.NotifyFilesChanged (modified, true); monitor.Step (modified.Count); FileService.NotifyFilesRemoved (removed); monitor.Step (removed.Count); monitor.EndTask (); }
private bool CheckForRename(TreeChanges treeChanges, TreeEntryChanges fileChange, out TreeEntryChanges renameSourceChange) { if (fileChange == null || fileChange.Status != ChangeKind.Added) { renameSourceChange = (TreeEntryChanges)null; return false; } List<TreeEntryChanges> list = Enumerable.ToList<TreeEntryChanges>(Enumerable.Where<TreeEntryChanges>(treeChanges.Deleted, (Func<TreeEntryChanges, bool>)(d => d.OldOid == fileChange.Oid))); if (list.Count == 1) { renameSourceChange = list[0]; //trace "GitRepository.CheckForRename rename detected relTarget={0} relSource={1}", (object)fileChange.Path, (object)renameSourceChange.Path); return true; } if (list.Count > 1) { //trace "GitRepository.CheckForRename rename detected but there are {0} possible sources", (object)list.Count); } renameSourceChange = (TreeEntryChanges)null; return false; }
private static void AssertCanCompareASubsetOfTheTreeAgainstTheIndex(TreeChanges changes) { Assert.NotNull(changes); Assert.Equal(1, changes.Count()); Assert.Equal("deleted_staged_file.txt", changes.Deleted.Single().Path); }
IEnumerable<IPullRequestFileNode> CreateChangedFilesList(IPullRequestModel pullRequest, TreeChanges changes) { return pullRequest.ChangedFiles .Select(x => new PullRequestFileNode(repository.LocalPath, x.FileName, x.Sha, x.Status, GetStatusDisplay(x, changes))); }
public BundleCreationResult RollBack(string sourceBasePath, string destinationBasePath, TreeChanges changes) { Logger.Instance.Log("----- STARTING ROLLBACK -----"); BundleCreationResult result = BundleCreationResult.Succes; List<TreeEntryChanges> filesToBeCopied = new List<TreeEntryChanges>(); filesToBeCopied.AddRange(changes.Modified); filesToBeCopied.AddRange(changes.Deleted); filesToBeCopied.AddRange(changes.Renamed); foreach (TreeEntryChanges file in filesToBeCopied) { string sourceFilePath = string.Format("{0}{1}", sourceBasePath, file.OldPath); string destinationFilePath = string.Format("{0}{1}", destinationBasePath, file.OldPath); string destinationDirectory = Path.GetDirectoryName(destinationFilePath); if (destinationDirectory != null && !Directory.Exists(destinationDirectory)) { Directory.CreateDirectory(destinationDirectory); } try { File.Copy(sourceFilePath, destinationFilePath, true); Logger.Instance.Log(string.Format("File '{0}' rolled back (copy)", file.OldPath)); } catch (Exception exception) { string exeptionMessage = string.Format("Failed to roll back file '{0}' (copy){1}", file.OldPath, Environment.NewLine); Logger.Instance.Log(string.Format("{0}EXCEPTION: {1}{2}{3}", exeptionMessage, exception.Message, Environment.NewLine, exception.StackTrace)); result = BundleCreationResult.Fail; } } List<TreeEntryChanges> filesToBeDeleted = new List<TreeEntryChanges>(); filesToBeDeleted.AddRange(changes.Added); filesToBeDeleted.AddRange(changes.Renamed); foreach (TreeEntryChanges file in filesToBeDeleted) { string destinationFilePath = string.Format("{0}{1}", destinationBasePath, file.Path); try { File.Delete(destinationFilePath); Logger.Instance.Log(string.Format("File '{0}' rolled back (delete)", file.Path)); DeleteDirectoryIfNeeded(sourceBasePath, destinationFilePath, file.Path); } catch (Exception exception) { string exeptionMessage = string.Format("Failed to roll back file '{0}' (delete){1}", file.Path, Environment.NewLine); Logger.Instance.Log(string.Format("{0}EXCEPTION: {1}{2}{3}", exeptionMessage, exception.Message, Environment.NewLine, exception.StackTrace)); result = BundleCreationResult.Fail; } } Logger.Instance.Log("----- FINISHED ROLLBACK -----"); return result; }
public void draw( Console console, int i ) { scroll = GUILayout.BeginScrollView( scroll ); try { pathNodes.Clear(); treeView.nodes.Clear(); changes = changes ?? console.repo.Diff.Compare(); foreach ( TreeEntryChanges change in changes ) { buildTreeView( change ); } foreach ( string untrackedFile in untracked ) { buildTreeView( untrackedFile ); } drawTreeView( console ); } catch {} GUILayout.EndScrollView(); GUILayout.Label( "Commit message:" ); commitText = GUILayout.TextArea( commitText ); if ( GUILayout.Button( "Commit Changes" ) ) { Signature signature = new Signature( "Jerome Doby", "*****@*****.**", System.DateTimeOffset.Now ); //# Stage everything string[] stage = new string[ checkboxValues.Count ]; i = 0; foreach ( KeyValuePair<string, bool> pair in checkboxValues ) { if ( pair.Value ) { stage[ i ] = pair.Key; i++; } } stage = stage.Where( x => !string.IsNullOrEmpty( x ) ).ToArray(); if ( stage.Length == 0 ) { console.currentError = "You cannot commit without staged items."; console.currentErrorLocation = rect; } else if ( commitText.Equals( string.Empty ) ) { console.currentError = "Please enter a commit message."; console.currentErrorLocation = rect; } else { console.repo.Index.Stage( stage ); console.repo.Commit( commitText, signature ); checkboxValues.Clear(); foldoutValues.Clear(); console.fetch(); } commitText = string.Empty; } }
IEnumerable<IChange> GetChanges(TreeChanges treeChanges, GitBasedFileSystemSnapshot fromSnapshot, GitBasedFileSystemSnapshot toSnapshot) { foreach (var treeChange in treeChanges.Where(c => !IgnoreTreeChange(c))) { switch (treeChange.Status) { case ChangeKind.Unmodified: throw new InvalidOperationException("Unmodified changes should have been filtered out"); case ChangeKind.Modified: var fromFile = fromSnapshot.GetFileForGitPath(treeChange.Path); var toFile = toSnapshot.GetFileForGitPath(treeChange.Path); yield return new Change(ChangeType.Modified, fromFile.ToReference(), toFile.ToReference()); break; case ChangeKind.Added: yield return new Change(ChangeType.Added, null, toSnapshot.GetFileForGitPath(treeChange.Path).ToReference()); break; case ChangeKind.Deleted: yield return new Change(ChangeType.Deleted, fromSnapshot.GetFileForGitPath(treeChange.Path).ToReference(), null); break; default: throw new NotImplementedException(); } } }
public BundleCreationResult DeployFiles(string sourceBasePath, string destinationBasePath, TreeChanges changes, string repositoryBasePath) { Logger.Instance.Log("----- STARTING DEPLOYMENT -----"); BundleCreationResult result = BundleCreationResult.Succes; List<TreeEntryChanges> filesToBeCopied = new List<TreeEntryChanges>(); filesToBeCopied.AddRange(changes.Modified); filesToBeCopied.AddRange(changes.Added); filesToBeCopied.AddRange(changes.Renamed); foreach (TreeEntryChanges file in filesToBeCopied) { string sourcePath = string.Format("{0}{1}", sourceBasePath, file.Path); string destinationPath = string.Format("{0}{1}", destinationBasePath, file.Path); try { Directory.CreateDirectory(Path.GetDirectoryName(destinationPath)); File.Copy(sourcePath, destinationPath, true); File.SetLastWriteTime(destinationPath, DateTime.Now); Logger.Instance.Log(string.Format("File {0} deployed",file.Path)); } catch (Exception exception) { string exeptionMessage = string.Format("Failed to copy file '{0}' from '{1}' to '{2}'{3}", file.Path, sourcePath, destinationPath, Environment.NewLine); Logger.Instance.Log(string.Format("{0}EXCEPTION: {1}{2}{3}", exeptionMessage, exception.Message, Environment.NewLine ,exception.StackTrace)); result = BundleCreationResult.Fail; } } List<TreeEntryChanges> filesToBeDeleted = new List<TreeEntryChanges>(); filesToBeDeleted.AddRange(changes.Deleted); filesToBeDeleted.AddRange(changes.Renamed); foreach (TreeEntryChanges file in filesToBeDeleted) { string filePath = file.OldPath; string destinationPath = string.Format("{0}{1}", destinationBasePath, filePath); try { File.Delete(destinationPath); Logger.Instance.Log(string.Format("File {0} deleted", filePath)); DeleteDirectoryIfNeeded(repositoryBasePath, destinationPath, filePath); } catch (Exception exception) { string exeptionMessage = string.Format("Failed to delete file '{0}' in '{1}'{2}", filePath, destinationPath, Environment.NewLine); Logger.Instance.Log(string.Format("{0}EXCEPTION: {1}{2}{3}", exeptionMessage, exception.Message, Environment.NewLine, exception.StackTrace)); result = BundleCreationResult.Fail; } } Logger.Instance.Log("----- FINISHED DEPLOYMENT -----"); return result; }
string GetStatusDisplay(IPullRequestFileModel file, TreeChanges changes) { switch (file.Status) { case PullRequestFileStatus.Added: return "add"; case PullRequestFileStatus.Renamed: var fileName = file.FileName.Replace("/", "\\"); var change = changes?.Renamed.FirstOrDefault(x => x.Path == fileName); if (change != null) { return Path.GetDirectoryName(change.OldPath) == Path.GetDirectoryName(change.Path) ? Path.GetFileName(change.OldPath) : change.OldPath; } else { return "rename"; } default: return null; } }
public void reset( TreeChanges newChanges, Console console ) { changes = newChanges; untracked = console.repo.Index.RetrieveStatus().Untracked; treeView = new TreeView(); }
IEnumerable<string> GetChangedPaths(TreeChanges treeChanges) { // for every change, get the path of the changed file this change maps to // without loading the entire snapshot foreach (var treeChange in treeChanges.Where(c => !IgnoreTreeChange(c))) { switch (treeChange.Status) { case ChangeKind.Unmodified: throw new InvalidOperationException("Unmodified changes should have been filtered out"); case ChangeKind.Modified: case ChangeKind.Added: case ChangeKind.Deleted: yield return GitBasedFileSystemSnapshot.GetPathForGitPath(treeChange.Path); break; default: throw new NotImplementedException(); } } }