private string DiffToHtml(string s1, string s2) { var dmp = new diff_match_patch(); var diffs = dmp.diff_main(s1 ?? string.Empty, s2 ?? string.Empty); dmp.diff_cleanupSemantic(diffs); return dmp.diff_prettyHtml(diffs); }
static IEnumerable<Span> DiffInline(ILine originalLine, ILine modifiedLine) { var dmp = new diff_match_patch(); var diffs = dmp.diff_main(originalLine.Value, modifiedLine.Value); dmp.diff_cleanupSemantic(diffs); return diffs .Select(x => new Span(x.text, OperationToKind(x.operation))) .ToArray(); }
private static BlameResult GetBlameOutput(string repositoryPath, string fileName, string blameCommitId, string[] currentLines) { BlameResult blameResult; using (var repo = new Repository(repositoryPath)) { // try to determine if the remote URL is plausibly a github.com or GitHub Enterprise URL Uri webRootUrl = repo.Network.Remotes .OrderBy(x => x.Name == "origin" ? 0 : 1) .ThenBy(x => x.Name) .Select(x => { Match m = Regex.Match(x.Url, @"^(git@(?'host'[^:]+):(?'user'[^/]+)/(?'repo'[^/]+)\.git|(git|https?)://(?'host'[^/]+)/(?'user'[^/]+)/(?'repo'[^/]+)\.git)$", RegexOptions.ExplicitCapture); if (m.Success) { string host = m.Groups["host"].Value; return new Uri(string.Format("http{0}://{1}/{2}/{3}/", host == "github.com" ? "s" : "", host, m.Groups["user"].Value, m.Groups["repo"].Value)); } else { return null; } }).FirstOrDefault(x => x != null); var loadingPerson = new Person("Loading…", "loading"); var commit = new Commit(UncommittedChangesCommitId, loadingPerson, DateTimeOffset.Now, loadingPerson, DateTimeOffset.Now, "", null, null); // create a fake blame result that assigns all the code to the HEAD revision blameResult = new BlameResult(webRootUrl, new[] { new Block(1, currentLines.Length, commit, fileName, 1) }.AsReadOnly(), currentLines.Select((l, n) => new Line(n + 1, l, true)).ToList(), new Dictionary<string, Commit> { { commit.Id, commit } }); } Task.Run(() => { // run "git blame" ExternalProcess git = new ExternalProcess(GetGitPath(), Path.GetDirectoryName(repositoryPath)); List<string> arguments = new List<string> { "blame", "--incremental", "--encoding=utf-8" }; if (blameCommitId != null) arguments.Add(blameCommitId); arguments.AddRange(new[] { "--", fileName }); var results = git.Run(new ProcessRunSettings(arguments.ToArray())); if (results.ExitCode != 0) return; // parse output List<Block> blocks = new List<Block>(); Dictionary<string, Commit> commits = new Dictionary<string, Commit>(); ParseBlameOutput(results.Output, blocks, commits); // allocate a (1-based) array for all lines in the file int lineCount = blocks.Sum(b => b.LineCount); Invariant.Assert(lineCount == currentLines.Length, "Unexpected number of lines in file."); // initialize all lines from current version Line[] lines = currentLines .Select((l, n) => new Line(n + 1, l, false)) .ToArray(); blameResult.SetData(blocks, lines, commits); Dictionary<string, Task<string>> getFileContentTasks = CreateGetFileContentTasks(repositoryPath, blocks, commits, currentLines); // process the blocks for each unique commit foreach (var groupLoopVariable in blocks.OrderBy(b => b.StartLine).GroupBy(b => b.Commit)) { // check if this commit modifies a previous one var group = groupLoopVariable; Commit commit = group.Key; string commitId = commit.Id; string previousCommitId = commit.PreviousCommitId; if (previousCommitId != null) { // diff the old and new file contents when they become available Task<string> getOldFileContentTask = getFileContentTasks[previousCommitId]; Task<string> getNewFileContentTask = getFileContentTasks[commitId]; Task.Factory.ContinueWhenAll(new[] { getOldFileContentTask, getNewFileContentTask }, tasks => { // diff the two versions var oldFileContents = tasks[0].Result; var newFileContents = tasks[1].Result; // diff_match_patch can generate incorrect output if there are more than 65536 lines being diffed var checkLines = GetLineCount(oldFileContents) < 65000 && GetLineCount(newFileContents) < 65000; var diff = new diff_match_patch { Diff_Timeout = 10 }; var diffs = diff.diff_main(oldFileContents, newFileContents, checkLines); diff.diff_cleanupSemantic(diffs); // process all the lines in the diff output, matching them to blocks using (IEnumerator<Line> lineEnumerator = ParseDiffOutput(diffs).GetEnumerator()) { // move to first line (which is expected to always be present) Invariant.Assert(lineEnumerator.MoveNext(), "Expected at least one line from diff output."); Line line = lineEnumerator.Current; // process all the blocks, finding the corresponding lines from the diff for each one foreach (Block block in group) { // skip all lines that occurred before the start of this block while (line.LineNumber < block.OriginalStartLine) { Invariant.Assert(lineEnumerator.MoveNext(), "diff does not contain the expected number of lines."); line = lineEnumerator.Current; } // process all lines in the current block while (line.LineNumber >= block.OriginalStartLine && line.LineNumber < block.OriginalStartLine + block.LineCount) { // assign this line to the correct index in the blamed version of the file blameResult.SetLine(line.LineNumber - block.OriginalStartLine + block.StartLine, line); // move to the next line (if available) if (lineEnumerator.MoveNext()) line = lineEnumerator.Current; else break; } } } }); } else { // this is the initial commit (but has not been modified since); grab its lines from the current version of the file foreach (Block block in group) for (int lineNumber = block.StartLine; lineNumber < block.StartLine + block.LineCount; lineNumber++) blameResult.SetLine(lineNumber, new Line(lineNumber, currentLines[lineNumber - 1], true)); } } }); return blameResult; }
private static void MakeContentDiffs(Dictionary<int, DiffLine[]> addDeletePairs) { addDeletePairs.Values .Where(x => x.All(y => y != null)) .ForEach(p => { var deleteLine = p[0]; var addLine = p[1]; var deleteContent = deleteLine.Content; var addContent = addLine.Content; var dmp = new diff_match_patch(); var diffs = dmp.diff_main(deleteContent, addContent); dmp.diff_cleanupSemantic(diffs); var deleteIndex = 0; var addIndex = 0; var deleteContentDiffs = new List<DiffLine.ContentDiff>(); var addContentDiffs = new List<DiffLine.ContentDiff>(); diffs.ForEach(d => { var diffTextLength = d.text.Length; switch (d.operation) { case Operation.DELETE: deleteContentDiffs.Add(new DiffLine.ContentDiff { StartIndex = deleteIndex, EndIndex = deleteIndex + diffTextLength }); deleteIndex += diffTextLength; break; case Operation.INSERT: addContentDiffs.Add(new DiffLine.ContentDiff { StartIndex = addIndex, EndIndex = addIndex + diffTextLength }); addIndex += diffTextLength; break; case Operation.EQUAL: deleteIndex += diffTextLength; addIndex += diffTextLength; break; } }); if (deleteContentDiffs.Any()) deleteLine.ContentDiffs = deleteContentDiffs.ToArray(); if (addContentDiffs.Any()) addLine.ContentDiffs = addContentDiffs.ToArray(); }); }