public void FileDiff() { var diff = new FileDiff("original.txt", "new.txt"); var result = diff.Compute(); result.Print(); }
public FileDiff[] GetDiff(IGetDiffArgs args) { var ab = new ArgBuilder(); ab.Add("diff"); TempFile fileList = null; if (args.Files != null) { if (args.Files.Any()) { fileList = CreateFileList(args.Files); ab.Add($"--include listfile:\"{fileList}\""); } } try { if (args.Query != null) { ab.Add($"--rev \"{FormatQuery(args.Query)}\""); } var lines = RunCommand(ab, args); return(FileDiff.FromLines(lines)); } finally { fileList?.Dispose(); } }
FileDiff AddFileDiff(CommitDiff commitDiff, string name) { var result = new FileDiff(FileState.Added, FileType.None, name, null); commitDiff.AddFileDiff(result); return(result); }
Comment CommentLine(FileDiff fileDiff, LineDiff lineDiff, string user, string comment) { return(new Comment() { File = fileDiff.Name, LineId = lineDiff.Id, User = user, Text = comment }); }
public virtual Data.FileChange ConvertFile(FileDiff fileDiff) { Requires.NotNull(fileDiff, "fileDiff"); // Figure out the change type Data.FileChange chg; if (String.Equals(fileDiff.ModifiedFile, "/dev/null")) { // Deletion chg = new Data.FileDeletion() { FileName = fileDiff.OriginalFile }; } else if (String.Equals(fileDiff.OriginalFile, "/dev/null")) { // Addition chg = new Data.FileAddition() { FileName = fileDiff.ModifiedFile }; } else { // Modification chg = new Data.FileModification() { FileName = CleanPath(fileDiff.OriginalFile), NewFileName = CleanPath(fileDiff.ModifiedFile) }; } // Fill the lines chg.Diff = String.Join(Environment.NewLine, fileDiff.Hunks.Select(WriteHunk)); return chg; }
public static RevisionFile FromDiff(FileDiff file) { return(new RevisionFile { Id = GuidComb.Generate(), File = file.Path, IsNew = file.NewFile, IsDeleted = file.DeletedFile, IsRenamed = file.RenamedFile }); }
public TreeFile(string name, FileDiff fileDiff) { Name = name; Files = new List <ITreeFile>(); FileDiff = fileDiff; IsSelectable = true; IsAdded = fileDiff.Add; IsRemoved = fileDiff.Deleted; Added = fileDiff.Additions; Removed = fileDiff.Deletions; }
private static List <FileDiff> ParseFileDiffs(IRestResponse <EnterpriseDiffResponse> response) { var fileDiffs = new List <FileDiff>(); foreach (var diff in response.Data.Diffs) { var fileDiff = new FileDiff { From = diff.Source?.String, To = diff.Destination?.String, Chunks = new List <ChunkDiff>(), }; fileDiff.Type = fileDiff.From == null ? FileChangeType.Add : fileDiff.To == null ? FileChangeType.Delete : FileChangeType.Modified; fileDiffs.Add(fileDiff); foreach (var diffHunk in diff.Hunks ?? new List <Hunk>()) { var chunkDiff = new ChunkDiff() { Changes = new List <LineDiff>(), }; fileDiff.Chunks.Add(chunkDiff); foreach (var segment in diffHunk.Segments) { foreach (var line in segment.Lines) { var ld = new LineDiff() { Content = line.Text, OldIndex = segment.Type == "ADDED" ? null : (int?)line.Source, NewIndex = segment.Type == "REMOVED" ? null : (int?)line.Destination, Type = segment.Type == "ADDED" ? LineChangeType.Add : segment.Type == "REMOVED" ? LineChangeType.Delete : LineChangeType.Normal }; chunkDiff.Changes.Add(ld); } } } fileDiff.Additions = fileDiff.Chunks.Sum(y => y.Changes.Count(z => z.Add)); fileDiff.Deletions = fileDiff.Chunks.Sum(y => y.Changes.Count(z => z.Delete)); } return(fileDiffs); }
private void CreateDiffTab(FileDiff diff) { var item = new TabItem(); item.Header = diff.File + ": " + diff.NumberOfDiffs + " diffs"; var browser = new WebBrowser(); browser.NavigateToString(diff.Html); item.Content = browser; TabControl.Items.Add(item); }
public CommitDetails GetCommitDetails(string hash) { var details = new CommitDetails(); using (var repository = Open()) { var branch = _getBranch(repository, _branchName); var commit = branch.Commits .FirstOrDefault( x => x.Sha.Equals( hash, StringComparison.OrdinalIgnoreCase)); if (commit == null) { return(null); } details.Message = commit.ToCommitMessage(); var parentCommit = commit.Parents.FirstOrDefault(); var changes = repository.Diff.Compare( parentCommit != null ? parentCommit.Tree : null, commit.Tree); if (changes != null) { var result = new List <FileDiff>(); foreach (var change in changes) { var diff = new FileDiff { Path = change.Path, Patch = change.Patch, Additions = change.LinesAdded, Deletions = change.LinesDeleted }; result.Add(diff); } details.FileDiffs = result; } } return(details); }
private void ImlementInExistingFile(IEnumerable <string> stubs, string file, FileDiff response) { var content = File.ReadAllText(file); if (content == "") { ImplementInNewClass(response, file, stubs); } else { ImplementInExistingClass(response, file, stubs); } }
public void Create_One_FileDiff_No_Likes() { CommitDiff cd = CreateCommitDiff(0); FileDiff fd = AddFileDiff(cd, "file1"); AddLineDiff(fd, ChangeState.Added, "line0"); AddLineDiff(fd, ChangeState.Removed, "line1"); var result = RevisionDetailViewModel.Create(new Commit(), cd, new Comment[] { }); Assert.IsNotNull(result); Assert.AreEqual(1, result.RevisedFileDetails.Count()); Assert.AreEqual(2, result.RevisedFileDetails.First().LineDetails.Count()); }
// If previous block is add and next block is change, and both overlap, then merge. public FileDiff Apply(FileDiff previous, FileDiff next) { var newBlock = new FileDiff(); if (previous == null || next == null) { return(null); } if (previous.FileName != next.FileName) { return(null); } try { // Let's keep simple case for now, just one hunk, with an equal sized mod if (previous.Hunks.Count == next.Hunks.Count && previous.Hunks.Count == 1 && next.MyerDiffs[0].Left.Length == next.MyerDiffs[0].Right.Length ) { if (previous.MyerDiffs.All(m => m.DifferenceType == Models.Diff.DifferenceType.Add) && next.MyerDiffs.All(m => m.DifferenceType == Models.Diff.DifferenceType.Change) ) { //if (previous.MyerDiffs[0].Left.Inside(next.MyerDiffs[0].Left) && // next.MyerDiffs[0].Right.Inside(next.MyerDiffs[0].Right)) if (next.MyerDiffs[0].Left.TextLines.All(t => previous.MyerDiffs[0].Right.TextLines.Contains("+" + t.Remove(0, 1)))) { newBlock.Hunks = previous.Hunks; newBlock.MyerDiffs = previous.MyerDiffs; for (int i = 0; i < next.MyerDiffs[0].Right.TextLines.Count; i++) { var fixOnFixLine = next.MyerDiffs[0].Right.TextLines[i]; var prevLine = next.MyerDiffs[0].Left.Start - previous.Hunks[0].NewHunkRange.StartingLineNumber + i; newBlock.Hunks[0].DiffLines[prevLine] = fixOnFixLine; } return(newBlock); } } } } catch (Exception ex) { Trace.WriteLine(ex.Message); } return(null); }
/// <summary> /// Compute file size of the current file if the given snapshot is null; /// otherwise, get the file size from the given snapshot. /// </summary> public long ComputeFileSize(int snapshotId) { FileWithSnapshotFeature sf = this.GetFileWithSnapshotFeature(); if (snapshotId != Org.Apache.Hadoop.Hdfs.Server.Namenode.Snapshot.Snapshot.CurrentStateId && sf != null) { FileDiff d = sf.GetDiffs().GetDiffById(snapshotId); if (d != null) { return(d.GetFileSize()); } } return(ComputeFileSize(true, false)); }
public void ShouldPatchDataSet1709251127Diff() { string dataSetId = "D1709251127"; var diff = DataSetHelper.ReadFileContent(dataSetId, "Diff-b3a6303-781096c.diff"); FileDiff[] files = DiffParserHelper.Parse(diff, Environment.NewLine).ToArray(); FileDiff file = files[0]; string srcString = DataSetHelper.ReadFileContent(dataSetId, "Diff-b3a6303.txt"); string expectedString = DataSetHelper.ReadFileContent(dataSetId, "Diff-781096c.txt").Trim(); string patchedString = PatchHelper.Patch(srcString, file.Chunks, Environment.NewLine).Trim(); Assert.AreEqual(expectedString, patchedString); }
private void Start(string line) { file = new FileDiff(); files.Add(file); if (file.To == null && file.From == null) { var fileNames = ParseFileNames(line); if (fileNames != null) { file.From = fileNames[0]; file.To = fileNames[1]; } } }
private void ImplementInExistingClass(FileDiff response, string file, IEnumerable <string> stubs) { var root = CSharpSyntaxTree.ParseText(File.ReadAllText(file)).GetRoot(); var stepClass = root.DescendantNodes().OfType <ClassDeclarationSyntax>(); var diff = new TextDiff(); if (hasStepClass(stepClass)) { diff = getTextDiff(diff, stepClass, stubs); } else { diff = getTextDiff(diff, root, stubs, file); } response.FilePath = file; response.TextDiffs.Add(diff); }
public FileDiff Process(StubImplementationCodeRequest request) { var stubs = request.Codes; var file = request.ImplementationFilePath; var response = new FileDiff(); if (!File.Exists(file)) { var filepath = FileHelper.GetFileName("", 0); ImplementInNewClass(response, filepath, stubs); } else { ImlementInExistingFile(stubs, file, response); } return(response); }
private void ImplementInNewClass(FileDiff fileDiff, string filepath, IEnumerable <string> stubs) { var className = FileHelper.GetClassName(filepath); var content = GetNewClassContent(className, stubs); var diff = new TextDiff { Span = new Span { Start = 0, StartChar = 0, End = 0, EndChar = 0 }, Content = content }; fileDiff.TextDiffs.Add(diff); fileDiff.FilePath = filepath; }
private static void ImplementInExistingClass(FileDiff response, string file, IEnumerable <string> stubs) { var root = CSharpSyntaxTree.ParseText(File.ReadAllText(file)).GetRoot(); var stepMethods = root.DescendantNodes().OfType <MethodDeclarationSyntax>(); var lastMethodEndPosition = stepMethods.Last().GetLocation().GetLineSpan().EndLinePosition; var diff = new TextDiff { Span = new Span { Start = lastMethodEndPosition.Line, StartChar = lastMethodEndPosition.Character + 1, End = lastMethodEndPosition.Line, EndChar = lastMethodEndPosition.Character + 1 }, Content = $"{Environment.NewLine}{string.Join(Environment.NewLine, stubs)}" }; response.FilePath = file; response.TextDiffs.Add(diff); }
/// <returns>blocks of the file corresponding to the snapshot.</returns> public virtual BlockInfoContiguous[] GetBlocks(int snapshot) { if (snapshot == Org.Apache.Hadoop.Hdfs.Server.Namenode.Snapshot.Snapshot.CurrentStateId || GetDiffs() == null) { return(GetBlocks()); } FileDiff diff = GetDiffs().GetDiffById(snapshot); BlockInfoContiguous[] snapshotBlocks = diff == null?GetBlocks() : diff.GetBlocks (); if (snapshotBlocks != null) { return(snapshotBlocks); } // Blocks are not in the current snapshot // Find next snapshot with blocks present or return current file blocks snapshotBlocks = GetDiffs().FindLaterSnapshotBlocks(snapshot); return((snapshotBlocks == null) ? GetBlocks() : snapshotBlocks); }
public void CorrectlyConvertsDelete() { // Arrange var diff = new FileDiff("OldFile", "/dev/null", new DiffHunk(new SourceCoordinate(0, 0), new SourceCoordinate(10, 0), String.Empty, new LineDiff(LineDiffType.Removed, "Foo"), new LineDiff(LineDiffType.Removed, "Bar"), new LineDiff(LineDiffType.Removed, "Baz"))); // Act var actual = new DiffConverter().ConvertFile(diff); // Assert Assert.Equal(FileChangeType.Removed, actual.ChangeType); Assert.Equal("OldFile", actual.FileName); Assert.Equal(@"@@ -0,0 +10,0 @@ -Foo -Bar -Baz", actual.Diff); }
public void CorrectlyConvertsModification() { // Arrange var diff = new FileDiff("OldFile", "NewFile", new DiffHunk(new SourceCoordinate(0, 0), new SourceCoordinate(10, 0), String.Empty, new LineDiff(LineDiffType.Added, "Foo"), new LineDiff(LineDiffType.Removed, "Bar"), new LineDiff(LineDiffType.Same, "Baz"))); // Act var actual = new DiffConverter().ConvertFile(diff); // Assert Assert.Equal(FileChangeType.Modified, actual.ChangeType); Assert.Equal("OldFile", actual.FileName); Assert.Equal("NewFile", actual.NewFileName); Assert.Equal(@"@@ -0,0 +10,0 @@ +Foo -Bar Baz", actual.Diff); }
/// <summary>compute the quota usage change for a truncate op</summary> /// <param name="newLength">the length for truncation</param> /// <returns>the quota usage delta (not considering replication factor)</returns> internal virtual long ComputeQuotaDeltaForTruncate(long newLength) { BlockInfoContiguous[] blocks = GetBlocks(); if (blocks == null || blocks.Length == 0) { return(0); } int n = 0; long size = 0; for (; n < blocks.Length && newLength > size; n++) { size += blocks[n].GetNumBytes(); } bool onBoundary = size == newLength; long truncateSize = 0; for (int i = (onBoundary ? n : n - 1); i < blocks.Length; i++) { truncateSize += blocks[i].GetNumBytes(); } FileWithSnapshotFeature sf = GetFileWithSnapshotFeature(); if (sf != null) { FileDiff diff = sf.GetDiffs().GetLast(); BlockInfoContiguous[] sblocks = diff != null?diff.GetBlocks() : null; if (sblocks != null) { for (int i_1 = (onBoundary ? n : n - 1); i_1 < blocks.Length && i_1 < sblocks.Length && blocks[i_1].Equals(sblocks[i_1]); i_1++) { truncateSize -= blocks[i_1].GetNumBytes(); } } } return(onBoundary ? -truncateSize : (GetPreferredBlockSize() - truncateSize)); }
public void CorrectlyConvertsDelete() { // Arrange var diff = new FileDiff("OldFile", "/dev/null", new DiffHunk(new SourceCoordinate(0, 0), new SourceCoordinate(10, 0), String.Empty, new LineDiff(LineDiffType.Removed, "Foo"), new LineDiff(LineDiffType.Removed, "Bar"), new LineDiff(LineDiffType.Removed, "Baz"))); // Act var actual = new DiffConverter().ConvertFile(diff); // Assert Assert.Equal(new Data.FileDeletion() { FileName = "NewFile", Diff = @"@@ -0,0 +10,0 @@ -Foo -Bar -Baz" }, actual, new PropertyEqualityComparer()); }
private static FileDiff ParseDiffHeader(IStringReader reader, ChangeSetDetail merge) { string fileName = ParseFileName(reader.ReadLine()); bool binary = false; while (!reader.Done) { string line = reader.ReadLine(); if (line.StartsWith("@@", StringComparison.Ordinal)) { reader.PutBack(line.Length); break; } else if (line.StartsWith("GIT binary patch", StringComparison.Ordinal)) { binary = true; } } if (binary) { // Skip binary files reader.ReadToEnd(); } var diff = new FileDiff(fileName) { Binary = binary }; // Skip files from merged changesets if (merge != null && merge.Files.ContainsKey(fileName)) { return(null); } return(diff); }
private static string HighLightStyle(FileDiff fileDiff) { if (fileDiff == null) { return(HighlightMappings["xml"]); } var splitted = fileDiff.DisplayFileName.Split('.');//todo this wont work if path contains . if (splitted.Length < 2) { return(HighlightMappings["xml"]); } var ext = splitted.Last(); if (HighlightMappings.ContainsKey(ext)) { return(HighlightMappings[ext]); } return(HighlightMappings["xml"]); }
internal static IEnumerable <FileDiff> ParseDiff(IStringReader reader) { var builder = new StringBuilder(); // If this was a merge change set then we'll parse the details out of the // first diff ChangeSetDetail merge = null; do { string line = reader.ReadLine(); // If we see a new diff header then process the previous diff if any if ((reader.Done || IsDiffHeader(line)) && builder.Length > 0) { if (reader.Done) { builder.Append(line); } string diffChunk = builder.ToString(); FileDiff diff = ParseDiffChunk(diffChunk.AsReader(), ref merge); if (diff != null) { yield return(diff); } builder.Clear(); } if (!reader.Done) { builder.Append(line); } } while (!reader.Done); }
public FileDiffViewModel(FileDiff fileDiff) { this.fileDiff = fileDiff; }
public void RemovesPrefixesFromGitPaths() { // Arrange var diff = new FileDiff("a/Foo/Bar", "b/Biz/Baz", new DiffHunk(new SourceCoordinate(0, 0), new SourceCoordinate(10, 0), String.Empty, new LineDiff(LineDiffType.Added, "Foo"), new LineDiff(LineDiffType.Removed, "Bar"), new LineDiff(LineDiffType.Same, "Baz"))); // Act var actual = new DiffConverter().ConvertFile(diff); // Assert Assert.Equal(FileChangeType.Modified, actual.ChangeType); Assert.Equal("/Foo/Bar", actual.FileName); Assert.Equal("/Biz/Baz", actual.NewFileName); Assert.Equal(@"@@ -0,0 +10,0 @@ +Foo -Bar Baz", actual.Diff); }
private static FileDiff ParseDiffHeader(IStringReader reader, ChangeSetDetail merge) { string fileName = ParseFileName(reader.ReadLine()); bool binary = false; while (!reader.Done) { string line = reader.ReadLine(); if (line.StartsWith("@@", StringComparison.Ordinal)) { reader.PutBack(line.Length); break; } else if (line.StartsWith("GIT binary patch", StringComparison.Ordinal)) { binary = true; } } if (binary) { // Skip binary files reader.ReadToEnd(); } var diff = new FileDiff(fileName) { Binary = binary }; // Skip files from merged changesets if (merge != null && merge.Files.ContainsKey(fileName)) { return null; } return diff; }
static bool MatchesLine(IAnnotation annotation, FileDiff fileDiff, LineDiff lineDiff) { return(annotation.File == fileDiff.Name && annotation.LineId == lineDiff.Id); }
public static IEnumerable <FileDiff> Parse(string input, string lineEnding = "\n") { var lines = StringHelper.SplitLines(input, lineEnding); if (!lines.Any()) { return(Enumerable.Empty <FileDiff>()); } var files = new List <FileDiff>(); var in_del = 0; var in_add = 0; Chunk current = null; FileDiff file = null; int oldStart, newStart; int oldLines, newLines; ParserAction start = (line, m) => { file = new FileDiff(); files.Add(file); if (file.To == null && file.From == null) { var fileNames = parseFile(line); if (fileNames != null) { file.From = fileNames[0]; file.To = fileNames[1]; } } }; ParserAction restart = (line, m) => { if (file == null || file.Chunks.Count != 0) { start(null, null); } }; ParserAction new_file = (line, m) => { restart(null, null); file.Type = FileChangeType.Add; file.From = "/dev/null"; }; ParserAction deleted_file = (line, m) => { restart(null, null); file.Type = FileChangeType.Delete; file.To = "/dev/null"; }; ParserAction index = (line, m) => { restart(null, null); file.Index = line.Split(' ').Skip(1); }; ParserAction from_file = (line, m) => { restart(null, null); file.From = parseFileFallback(line); }; ParserAction to_file = (line, m) => { restart(null, null); file.To = parseFileFallback(line); }; ParserAction chunk = (line, match) => { in_del = oldStart = int.Parse(match.Groups[1].Value); oldLines = match.Groups[2].Success ? int.Parse(match.Groups[2].Value) : 0; in_add = newStart = int.Parse(match.Groups[3].Value); newLines = match.Groups[4].Success ? int.Parse(match.Groups[4].Value) : 0; ChunkRangeInfo rangeInfo = new ChunkRangeInfo( new ChunkRange(oldStart, oldLines), new ChunkRange(newStart, newLines) ); current = new Chunk(line, rangeInfo); file.Chunks.Add(current); }; ParserAction del = (line, match) => { string content = DiffLineHelper.GetContent(line); current.Changes.Add(new LineDiff(type: LineChangeType.Delete, index: in_del++, content: content)); file.Deletions++; }; ParserAction add = (line, m) => { string content = DiffLineHelper.GetContent(line); current.Changes.Add(new LineDiff(type: LineChangeType.Add, index: in_add++, content: content)); file.Additions++; }; const string noeol = "\\ No newline at end of file"; Action <string> normal = line => { if (file == null) { return; } string content = DiffLineHelper.GetContent(line); current.Changes.Add(new LineDiff( oldIndex: line == noeol ? 0 : in_del++, newIndex: line == noeol ? 0 : in_add++, content: content)); }; var schema = new Dictionary <Regex, ParserAction> { { new Regex(@"^diff\s"), start }, { new Regex(@"^new file mode \d+$"), new_file }, { new Regex(@"^deleted file mode \d+$"), deleted_file }, { new Regex(@"^index\s[\da-zA-Z]+\.\.[\da-zA-Z]+(\s(\d+))?$"), index }, { new Regex(@"^---\s"), from_file }, { new Regex(@"^\+\+\+\s"), to_file }, { new Regex(@"^@@\s+\-(\d+),?(\d+)?\s+\+(\d+),?(\d+)?\s@@"), chunk }, { new Regex(@"^-"), del }, { new Regex(@"^\+"), add } }; Func <string, bool> parse = line => { foreach (var p in schema) { var m = p.Key.Match(line); if (m.Success) { p.Value(line, m); return(true); } } return(false); }; foreach (var line in lines) { if (!parse(line)) { normal(line); } } return(files); }
LineDiff AddLineDiff(FileDiff fileDiff, ChangeState state, string text) { return(fileDiff.AddLine(state, text, lineNumber++, lineNumber++)); }
public static void SetFileDiff(DependencyObject obj, FileDiff value) { obj.SetValue(FileDiffProperty, value); }
public void RemovesPrefixesFromGitPaths() { // Arrange var diff = new FileDiff("a/Foo/Bar", "b/Biz/Baz", new DiffHunk(new SourceCoordinate(0, 0), new SourceCoordinate(10, 0), String.Empty, new LineDiff(LineDiffType.Added, "Foo"), new LineDiff(LineDiffType.Removed, "Bar"), new LineDiff(LineDiffType.Same, "Baz"))); // Act var actual = new DiffConverter().ConvertFile(diff); // Assert Assert.Equal(new Data.FileModification() { FileName = "/Foo/Bar", NewFileName = "/Biz/Baz", Diff = @"@@ -0,0 +10,0 @@ +Foo -Bar Baz" }, actual, new PropertyEqualityComparer()); }