} // Diff /// <summary> /// This function converts all textlines of the text into unique numbers for every unique textline /// so further work can work only with simple numbers. /// </summary> /// <param name="aText">the input text</param> /// <param name="h">This extern initialized hashtable is used for storing all ever used textlines.</param> /// <param name="trimSpace">ignore leading and trailing space characters</param> /// <returns>a array of integers.</returns> private static int[] DiffCodes(LineCollection lines, Hashtable h, DiffOptions options) { // get all codes of the text int lastUsedCode = h.Count; int []codes = new int[lines.Count]; for (int i = 0; i < lines.Count; ++i) { string s = lines[i].Text; if (options != null && options.IgnoreWhitespace) { s = Regex.Replace(s, "\\s+", " "); // TODO: optimization: faster blank removal. } if (options != null && options.IgnoreCase) s = s.ToLower(); object aCode = h[s]; if (aCode == null) { lastUsedCode++; h[s] = lastUsedCode; codes[i] = lastUsedCode; } else { codes[i] = (int)aCode; } // if } // for return codes; } // DiffCodes
public static void Main(string[] args) { try { DiffOptions.Get(); Configuration.Get(); XMLDiff diff; if (args == null || args.Length == 0) { diff = new XMLDiff(null); } else if (args.Length == 1) { diff = new XMLDiff(args[0]); } else if (args.Length == 3) { diff = new XMLDiff(args[0], args[1], args[2], null); } else { diff = new XMLDiff(args[0], args[1], args[2], args[3]); } diff.Compare(); } catch (Exception ex) { throw ex; } }
/// <summary> /// Find the difference in 2 text documents, comparing by textlines. /// The algorithm itself is comparing 2 arrays of numbers so when comparing 2 text documents /// each line is converted into a (hash) number. This hash-value is computed by storing all /// textlines into a common hashtable so i can find dublicates in there, and generating a /// new number each time a new textline is inserted. /// </summary> /// <param name="TextA">A-version of the text (usualy the old one)</param> /// <param name="TextB">B-version of the text (usualy the new one)</param> /// <param name="trimSpace">When set to true, all leading and trailing whitespace characters are stripped out before the comparation is done.</param> /// <param name="ignoreSpace">When set to true, all whitespace characters are converted to a single space character before the comparation is done.</param> /// <param name="ignoreCase">When set to true, all characters are converted to their lowercase equivivalence before the comparation is done.</param> /// <returns>Returns a array of Items that describe the differences.</returns> static Item[] DiffText(LineCollection a, LineCollection b, DiffOptions options) { // prepare the input-text and convert to comparable numbers. Hashtable h = new Hashtable(a.Count + b.Count); // The A-Version of the data (original data) to be compared. DiffData DataA = new DiffData(DiffCodes(a, h, options)); // The B-Version of the data (modified data) to be compared. DiffData DataB = new DiffData(DiffCodes(b, h, options)); h = null; // free up hashtable memory (maybe) int MAX = DataA.Length + DataB.Length + 1; /// vector for the (0,0) to (x,y) search int[] DownVector = new int[2 * MAX + 2]; /// vector for the (u,v) to (N,M) search int[] UpVector = new int[2 * MAX + 2]; LCS(DataA, 0, DataA.Length, DataB, 0, DataB.Length, DownVector, UpVector); Optimize(DataA); Optimize(DataB); return CreateDiffs(DataA, DataB); } // DiffText
public ResolveContext(ResolverMap resolversMap, Type type, DiffOptions options) { Options = options; Resolvers = resolversMap; _path = new Stack <string>(); Type = type; }
// NOTE: Overlay two PDF files and give the visual color diff between them // Used to review two document revisions or drawing blueprints that are overlayed with updated data private async void ProcessVisualDiff() { var docA = mPDFViewCtrlA.GetDoc(); var docB = mPDFViewCtrlB.GetDoc(); DiffOptions diffOptions = new DiffOptions(); diffOptions.SetColorA(new ColorPt(1, 0, 0)); diffOptions.SetColorB(new ColorPt(0, 0, 0)); diffOptions.SetBlendMode(GStateBlendMode.e_bl_normal); pdftron.PDF.Page docAPage = docA.GetPage(1); pdftron.PDF.Page docBPage = docB.GetPage(1); try { PDFDoc outputDocument = new PDFDoc(); outputDocument.AppendVisualDiff(docAPage, docBPage, diffOptions); Controls.PDFResultDialog contentDialog = new Controls.PDFResultDialog(); var pdfCompare = new PDFCompareResult(outputDocument); pdfCompare.CloseButtonClicked += delegate { contentDialog.Hide(); }; contentDialog.Content = pdfCompare; await contentDialog.ShowAsync(); } catch (Exception ex) { } }
private static DiffOptions CreateDefault() { var options = new DiffOptions(); options.Freeze(); return(options); }
void MyShowChangesetEventHandler(object sender, ShowChangesetEventArgs args) { int changesetId = args.ChangesetId; VersionControlServer vcs = args.VersionControlServer; ChangesetVersionSpec versionSpec = new ChangesetVersionSpec(changesetId); string tname = System.IO.Path.GetTempFileName(); using (StreamWriter sw = new StreamWriter(tname)) { DiffOptions options = new DiffOptions(); options.UseThirdPartyTool = false; options.Flags = DiffOptionFlags.EnablePreambleHandling; options.OutputType = DiffOutputType.Unified; options.TargetEncoding = Encoding.UTF8; options.SourceEncoding = Encoding.UTF8; options.StreamWriter = sw; options.StreamWriter.AutoFlush = true; DiffHelper.ShowChangeset(vcs, versionSpec, false, options); } Document d = MonoDevelop.Ide.Gui.IdeApp.Workbench.OpenDocument(tname, true); d.FileName = "Changeset " + changesetId.ToString(); File.Delete(tname); }
public static void DiffFiles(VersionControlServer versionControl, IDiffItem source, IDiffItem target, DiffOptions diffOpts, string fileNameForHeader, bool wait) { DiffItemUtil aItem = new DiffItemUtil('a', fileNameForHeader, source.GetFile()); DiffItemUtil bItem = new DiffItemUtil('b', fileNameForHeader, target.GetFile()); StreamWriter stream = diffOpts.StreamWriter; // short circuit for binary file comparisions if (source.GetEncoding() == RepositoryConstants.EncodingBinary && target.GetEncoding() == RepositoryConstants.EncodingBinary) { stream.WriteLine("Binary files {0} and {1} differ", aItem.Name, bItem.Name); return; } WriteHeader(aItem, bItem, diffOpts); // short circuit new files if (aItem.Length == 0) { WriteNewFile(stream, bItem.Lines); return; } Hashtable hashtable = new Hashtable(aItem.Length + bItem.Length); bool ignoreWhiteSpace = (diffOpts.Flags & DiffOptionFlags.IgnoreWhiteSpace) == DiffOptionFlags.IgnoreWhiteSpace; DiffItem[] items = DiffUtil.DiffText(hashtable, aItem.Lines, bItem.Lines, ignoreWhiteSpace, ignoreWhiteSpace, false); WriteUnified(stream, aItem.Lines, bItem.Lines, items); }
public bool TryParseArgs(string[] args, out DiffOptions result) { result = _diffOptions; try { _optionSet.Parse(args); if (_showHelp) { var helpText = File.ReadAllLines(@".\Resources\HelpText.txt"); Console.WriteLine(string.Join(Environment.NewLine, helpText)); return(false); } Debug.WriteLine(_diffOptions); bool areArgumentsValid = _argumentValidator.AreValid(args); if (areArgumentsValid) { _diffOptions.SourceFile = args[0]; _diffOptions.TargetFile = args[1]; } return(areArgumentsValid); } catch (OptionException e) { Console.Write("diffTool : "); Console.WriteLine(e.Message); Console.WriteLine("diffTool --help for more information."); return(false); } }
public DiffUsingTFS(string[] args) { Debug.Assert(args.Count() >= 2, "Usage: SyntaxDiff.exe file1 file2"); string file1 = args[0], file2 = args[1]; DiffOptions diffOptions = new DiffOptions(); diffOptions.UseThirdPartyTool = false; diffOptions.OutputType = DiffOutputType.Unified; // Wherever we want to send our text-based diff output diffOptions.StreamWriter = new System.IO.StreamWriter(Console.OpenStandardOutput()); Console.WriteLine("Difference.DiffFiles - output to console"); DiffSegment diffs = Microsoft.TeamFoundation.VersionControl.Client.Difference.DiffFiles( file1, FileType.Detect(file1, null), file2, FileType.Detect(file2, null), diffOptions); var diff = diffs; while (diff != null) { Console.WriteLine("Diff ==> {0} {1}:{2}:{3} {4}:{5}:{6}", diff.Type, diff.OriginalStart, diff.OriginalLength, diff.OriginalStartOffset, diff.ModifiedStart, diff.ModifiedLength, diff.ModifiedStartOffset); diff = diff.Next; } }
public void SetDifficulty(DifficultyOptions difficulty) { DiffOptions diff = new DiffOptions(difficulty); maxTime = diff.maxTime; numRounds = diff.numRounds; }
public IChangeInfo DiffFiles(Item item1, Item item2) { if (item1.ItemType != ItemType.File) return null; DiffItemVersionedFile diffItem1 = new DiffItemVersionedFile(item1, new ChangesetVersionSpec(item1.ChangesetId)); DiffItemVersionedFile diffItem2 = new DiffItemVersionedFile(item2, new ChangesetVersionSpec(item2.ChangesetId)); DiffOptions options = new DiffOptions(); options.UseThirdPartyTool = false; options.Flags = DiffOptionFlags.EnablePreambleHandling | DiffOptionFlags.IgnoreWhiteSpace; options.OutputType = DiffOutputType.Unified; options.TargetEncoding = Console.OutputEncoding; options.SourceEncoding = Console.OutputEncoding; using (var statistics = new DiffStatisticsReader()) { options.StreamWriter = statistics.CreateWriter(); options.StreamWriter.AutoFlush = true; Difference.DiffFiles(item1.VersionControlServer, diffItem1, diffItem2, options, item1.ServerItem, true); return statistics.GetStatistics(null); } }
public ResolveContext(ResolveContext context, string memberPath, Type type) { Resolvers = context.Resolvers; Options = context.Options; _path = new Stack <string>(context._path.Reverse()); _path.Push(memberPath); Type = type; }
public void Should_IgnoreByCustomAttributeName() { var object1 = new CustomAttributeObject(1, "A string"); var object2 = new CustomAttributeObject(1, "A different string"); var diffOptions = new DiffOptions(new List <object> { "DescriptionAttribute" }); var diff = object1.Diff(object2, ComparisonOptions.All, diffOptions); Assert.AreEqual(0, diff.Count); }
protected DiffOptions GetDiffOptions(StreamWriter writer) { DiffOptions options = new DiffOptions(); options.UseThirdPartyTool = false; options.Flags = DiffOptionFlags.EnablePreambleHandling; options.OutputType = DiffOutputType.Unified; options.TargetEncoding = Encoding.UTF8; options.SourceEncoding = Encoding.UTF8; options.StreamWriter = writer; options.StreamWriter.AutoFlush = true; return options; }
private void DiffOptionsForm_Load(object sender, EventArgs e) { DiffOptions.Get(); ChildOrder_CheckBox.Checked = DiffOptions.IgnoreChildOrder; Comments_CheckBox.Checked = DiffOptions.IgnoreComments; Dtd_CheckBox.Checked = DiffOptions.IgnoreDtd; Namespaces_CheckBox.Checked = DiffOptions.IgnoreNamespaces; Pi_CheckBox.Checked = DiffOptions.IgnorePI; Prefixes_CheckBox.Checked = DiffOptions.IgnorePrefixes; Whitespace_CheckBox.Checked = DiffOptions.IgnoreWhitespace; XmlDecleration_CheckBox.Checked = DiffOptions.IgnoreXmlDecl; None_CheckBox.Checked = DiffOptions.None; }
public DiffBinding(IDiffSource diffSource, DiffViewer diffViewer, DiffOptions diffOptions) { Verify.Argument.IsNotNull(diffSource, "diffSource"); Verify.Argument.IsNotNull(diffViewer, "diffViewer"); Verify.Argument.IsNotNull(diffOptions, "diffOptions"); _diffSource = diffSource; _diffViewer = diffViewer; _diffOptions = diffOptions; _allDiffPanels = new List <FileDiffPanel>(); _progressPanel = new FlowProgressPanel(); Progress = _progressPanel.ProgressMonitor; }
protected DiffOptions GetDiffOptions(StreamWriter writer) { DiffOptions options = new DiffOptions(); options.UseThirdPartyTool = false; options.Flags = DiffOptionFlags.EnablePreambleHandling; options.OutputType = DiffOutputType.Unified; options.TargetEncoding = Encoding.UTF8; options.SourceEncoding = Encoding.UTF8; options.StreamWriter = writer; options.StreamWriter.AutoFlush = true; return(options); }
/// <summary> /// returns a list of line numbers in s and t that differ /// </summary> /// <param name="s"></param> /// <param name="t"></param> /// <returns></returns> public Tuple <List <int>, List <int> > DiffStrings(List <string> s, List <string> t) { if (s.Count == t.Count && s.Zip(t).Where(x => x.Item1 != x.Item2).Count() == 0) { Console.WriteLine("No diffs"); return(Tuple.Create(new List <int>(), new List <int>())); } //dump to a file and call DiffFiles var sFileName = "___tmp_diff_str_1"; var tFileName = "___tmp_diff_str_2"; var sFile = new StreamWriter(sFileName); var tFile = new StreamWriter(tFileName); s.Iter(l => sFile.WriteLine(l)); sFile.Close(); t.Iter(l => tFile.WriteLine(l)); tFile.Close(); DiffOptions diffOptions = new DiffOptions(); diffOptions.UseThirdPartyTool = false; diffOptions.OutputType = DiffOutputType.Unified; // Wherever we want to send our text-based diff output diffOptions.StreamWriter = new System.IO.StreamWriter(Console.OpenStandardOutput()); DiffSegment diffs = Microsoft.TeamFoundation.VersionControl.Client.Difference.DiffFiles( sFileName, FileType.Detect(sFileName, null), tFileName, FileType.Detect(tFileName, null), diffOptions); var diff = diffs; var sDiffLines = new List <int>(); var tDiffLines = new List <int>(); if (diff.Next != null) //some diff { int sLast = int.MaxValue; int tLast = int.MaxValue; while (diff != null) { /*Console.WriteLine("Diff ==> {0} {1}:{2}:{3} {4}:{5}:{6}", * diff.Type, diff.OriginalStart, diff.OriginalLength, diff.OriginalStartOffset, diff.ModifiedStart, diff.ModifiedLength, diff.ModifiedStartOffset);*/ sDiffLines.AddRange(ComputeRange(sLast, diff.OriginalStart)); sLast = diff.OriginalStart + diff.OriginalLength; tDiffLines.AddRange(ComputeRange(tLast, diff.ModifiedStart)); tLast = diff.ModifiedStart + diff.ModifiedLength; diff = diff.Next; } } return(Tuple.Create(sDiffLines, tDiffLines)); }
private void DiffOptionsOk_Button_Click(object sender, EventArgs e) { DiffOptions.IgnoreChildOrder = ChildOrder_CheckBox.Checked; DiffOptions.IgnoreComments = Comments_CheckBox.Checked; DiffOptions.IgnoreDtd = Dtd_CheckBox.Checked; DiffOptions.IgnoreNamespaces = Namespaces_CheckBox.Checked; DiffOptions.IgnorePI = Pi_CheckBox.Checked; DiffOptions.IgnorePrefixes = Prefixes_CheckBox.Checked; DiffOptions.IgnoreWhitespace = Whitespace_CheckBox.Checked; DiffOptions.IgnoreXmlDecl = XmlDecleration_CheckBox.Checked; DiffOptions.None = None_CheckBox.Checked; DiffOptions.Write(); Console.WriteLine("XML Diff options have been modified"); this.Close(); }
/// <summary> /// Show changes between a <see cref = "Tree"/> and the Index, the Working Directory, or both. /// </summary> /// <param name = "oldTree">The <see cref = "Tree"/> to compare from.</param> /// <param name = "diffTargets">The targets to compare to.</param> /// <param name = "paths">The list of paths (either files or directories) that should be compared.</param> /// <returns>A <see cref = "TreeChanges"/> containing the changes between the <see cref="Tree"/> and the selected target.</returns> public virtual TreeChanges Compare(Tree oldTree, DiffTargets diffTargets, IEnumerable <string> paths = null) { var comparer = handleRetrieverDispatcher[diffTargets](repo); DiffOptions diffOptions = diffTargets.HasFlag(DiffTargets.WorkingDirectory) ? DiffOptions.IncludeUntracked : DiffOptions.None; using (GitDiffOptions options = BuildOptions(diffOptions, paths)) using (DiffListSafeHandle dl = BuildDiffListFromTreeAndComparer( oldTree != null ? oldTree.Id : null, comparer, options)) { return(new TreeChanges(dl)); } }
public SplitDiffBinding(IDiffSource diffSource, DiffViewer diffViewerHeaders, DiffViewer diffViewerFiles, DiffOptions diffOptions) { Verify.Argument.IsNotNull(diffSource, nameof(diffSource)); Verify.Argument.IsNotNull(diffViewerHeaders, nameof(diffViewerHeaders)); Verify.Argument.IsNotNull(diffViewerFiles, nameof(diffViewerFiles)); Verify.Argument.IsNotNull(diffOptions, nameof(diffOptions)); _diffSource = diffSource; _diffViewerHeaders = diffViewerHeaders; _diffViewerFiles = diffViewerFiles; _diffOptions = diffOptions; _allDiffPanels = new List <FileDiffPanel>(); _progressPanel = new FlowProgressPanel(); Progress = _progressPanel.ProgressMonitor; }
private void FormSave_LoadSettings(object sender, SettingsEventArgs e) { Options.Load(e.SettingsNode.GetSubNode(nameof(Options), true)); DiffOptions.Load(e.SettingsNode.GetSubNode("DiffOptions", true)); this.ApplyOptions(); // Handle command-line options string[] names = CommandLineProcessor.Names; if (names != null) { // Post a message to ourselves to process the command-line // arguments after the form finishes displaying. this.PostFiles(names, true); } }
protected override void AttachViewModel(object viewModel) { base.AttachViewModel(viewModel); var vm = viewModel as DiffViewModel; if (vm != null) { _options = vm.DiffOptions; if (_options == null) { _options = new DiffOptions(); } DiffSource = vm.DiffSource; UpdateText(); } }
private static GitDiffOptions BuildOptions(DiffOptions diffOptions, FilePath[] filePaths = null, MatchedPathsAggregator matchedPathsAggregator = null, CompareOptions compareOptions = null) { var options = new GitDiffOptions(); options.Flags |= GitDiffOptionFlags.GIT_DIFF_INCLUDE_TYPECHANGE; compareOptions = compareOptions ?? new CompareOptions(); options.ContextLines = (ushort)compareOptions.ContextLines; options.InterhunkLines = (ushort)compareOptions.InterhunkLines; if (diffOptions.HasFlag(DiffOptions.IncludeUntracked)) { options.Flags |= GitDiffOptionFlags.GIT_DIFF_INCLUDE_UNTRACKED | GitDiffOptionFlags.GIT_DIFF_RECURSE_UNTRACKED_DIRS | GitDiffOptionFlags.GIT_DIFF_INCLUDE_UNTRACKED_CONTENT; } if (diffOptions.HasFlag(DiffOptions.IncludeIgnored)) { options.Flags |= GitDiffOptionFlags.GIT_DIFF_INCLUDE_IGNORED; } if (diffOptions.HasFlag(DiffOptions.IncludeUnmodified)) { options.Flags |= GitDiffOptionFlags.GIT_DIFF_INCLUDE_UNMODIFIED; } if (diffOptions.HasFlag(DiffOptions.DisablePathspecMatch)) { options.Flags |= GitDiffOptionFlags.GIT_DIFF_DISABLE_PATHSPEC_MATCH; } if (matchedPathsAggregator != null) { options.NotifyCallback = matchedPathsAggregator.OnGitDiffNotify; } if (filePaths == null) { return(options); } options.PathSpec = GitStrArrayIn.BuildFrom(filePaths); return(options); }
protected override void AttachViewModel(object viewModel) { base.AttachViewModel(viewModel); if (viewModel is DiffViewModel vm) { if (vm.DiffOptions != null) { _options = vm.DiffOptions; } else if (_options == null) { _options = new DiffOptions(); } DiffSource = vm.DiffSource; UpdateText(); } }
private TreeChanges BuildTreeChangesFromComparer( ObjectId oldTreeId, ObjectId newTreeId, TreeComparisonHandleRetriever comparisonHandleRetriever, DiffOptions diffOptions, IEnumerable <string> paths = null, ExplicitPathsOptions explicitPathsOptions = null, CompareOptions compareOptions = null) { var matchedPaths = new MatchedPathsAggregator(); var filePaths = ToFilePaths(repo, paths); using (GitDiffOptions options = BuildOptions(diffOptions, filePaths, matchedPaths, compareOptions)) using (DiffListSafeHandle diffList = comparisonHandleRetriever(oldTreeId, newTreeId, options)) { if (explicitPathsOptions != null) { DispatchUnmatchedPaths(explicitPathsOptions, filePaths, matchedPaths); } return(new TreeChanges(diffList)); } }
internal virtual TreeChanges Compare(DiffOptions diffOptions, IEnumerable <string> paths = null, ExplicitPathsOptions explicitPathsOptions = null, CompareOptions compareOptions = null) { var comparer = WorkdirToIndex(repo); if (explicitPathsOptions != null) { diffOptions |= DiffOptions.DisablePathspecMatch; if (explicitPathsOptions.ShouldFailOnUnmatchedPath || explicitPathsOptions.OnUnmatchedPath != null) { diffOptions |= DiffOptions.IncludeUnmodified; } } return(BuildTreeChangesFromComparer(null, null, comparer, diffOptions, paths, explicitPathsOptions, compareOptions)); }
public static bool HasReallyChange(this PendingChange pendingChange) { if (pendingChange.IsAdd || string.IsNullOrEmpty(Path.GetExtension(pendingChange.LocalItem)) || !File.Exists(pendingChange.LocalItem)) { return(true); } string tempFileName = Path.GetTempFileName(); pendingChange.DownloadBaseFile(tempFileName); var diffOptions = new DiffOptions { Flags = DiffOptionFlags.IgnoreWhiteSpace }; var summary = Common.DiffSummary.DiffFiles(tempFileName, FileType.Detect(tempFileName, FileType.TextFileType), pendingChange.LocalItem, FileType.Detect(pendingChange.LocalItem, FileType.TextFileType), diffOptions); var res = summary.TotalLinesAdded != 0 || summary.TotalLinesDeleted != 0 || summary.TotalLinesModified != 0; return(res); }
public IDiffResultOption <IDiffResult> Create(DiffOptions diffOptions) { if (diffOptions.ShouldShowAll) { if (diffOptions.ShouldShowPerLine) { return(new ShowAllInPerLineStyleResultOption()); } return(new ShowAllInLineRangeStyleResultOption()); } //else { if (diffOptions.ShouldShowPerLine) { return(new ShowOnlyDifferencesInPerLineStyleResultOption()); } } //Default return(new DefaultDiffResultOption()); }
/// <summary> /// Show changes between a <see cref = "Tree"/> and the Index, the Working Directory, or both. /// </summary> /// <param name = "oldTree">The <see cref = "Tree"/> to compare from.</param> /// <param name = "diffTargets">The targets to compare to.</param> /// <param name = "paths">The list of paths (either files or directories) that should be compared.</param> /// <param name = "explicitPathsOptions"> /// If set, the passed <paramref name="paths"/> will be treated as explicit paths. /// Use these options to determine how unmatched explicit paths should be handled. /// </param> /// <param name = "compareOptions">Additional options to define comparison behavior.</param> /// <returns>A <see cref = "TreeChanges"/> containing the changes between the <see cref="Tree"/> and the selected target.</returns> public virtual TreeChanges Compare(Tree oldTree, DiffTargets diffTargets, IEnumerable <string> paths = null, ExplicitPathsOptions explicitPathsOptions = null, CompareOptions compareOptions = null) { var comparer = handleRetrieverDispatcher[diffTargets](repo); ObjectId oldTreeId = oldTree != null ? oldTree.Id : null; DiffOptions diffOptions = diffTargets.HasFlag(DiffTargets.WorkingDirectory) ? DiffOptions.IncludeUntracked : DiffOptions.None; if (explicitPathsOptions != null) { diffOptions |= DiffOptions.DisablePathspecMatch; if (explicitPathsOptions.ShouldFailOnUnmatchedPath || explicitPathsOptions.OnUnmatchedPath != null) { diffOptions |= DiffOptions.IncludeUnmodified; } } return(BuildTreeChangesFromComparer(oldTreeId, null, comparer, diffOptions, paths, explicitPathsOptions, compareOptions)); }
protected DiffOptions GetDiffOptions() { DiffOptions options = new DiffOptions(); options.UseThirdPartyTool = false; options.Flags = DiffOptionFlags.EnablePreambleHandling; if (OptionIgnoreWhiteSpace) { options.Flags |= DiffOptionFlags.IgnoreWhiteSpace; } options.OutputType = DiffOutputType.Unified; options.TargetEncoding = Console.OutputEncoding; options.SourceEncoding = Console.OutputEncoding; options.StreamWriter = new StreamWriter(Console.OpenStandardOutput(), Console.OutputEncoding); options.StreamWriter.AutoFlush = true; return(options); }
private GitDiffOptions BuildOptions(DiffOptions diffOptions, IEnumerable <string> paths = null) { var options = new GitDiffOptions(); options.Flags |= GitDiffOptionFlags.GIT_DIFF_INCLUDE_TYPECHANGE; options.ContextLines = 3; if (diffOptions.HasFlag(DiffOptions.IncludeUntracked)) { options.Flags |= GitDiffOptionFlags.GIT_DIFF_INCLUDE_UNTRACKED | GitDiffOptionFlags.GIT_DIFF_RECURSE_UNTRACKED_DIRS | GitDiffOptionFlags.GIT_DIFF_INCLUDE_UNTRACKED_CONTENT; } if (paths == null) { return(options); } options.PathSpec = GitStrArrayIn.BuildFrom(ToFilePaths(repo, paths)); return(options); }
private static GitDiffOptions BuildOptions(DiffOptions diffOptions, FilePath[] filePaths = null, MatchedPathsAggregator matchedPathsAggregator = null, CompareOptions compareOptions = null) { var options = new GitDiffOptions(); options.Flags |= GitDiffOptionFlags.GIT_DIFF_INCLUDE_TYPECHANGE; compareOptions = compareOptions ?? new CompareOptions(); options.ContextLines = (ushort)compareOptions.ContextLines; options.InterhunkLines = (ushort)compareOptions.InterhunkLines; if (diffOptions.HasFlag(DiffOptions.IncludeUntracked)) { options.Flags |= GitDiffOptionFlags.GIT_DIFF_INCLUDE_UNTRACKED | GitDiffOptionFlags.GIT_DIFF_RECURSE_UNTRACKED_DIRS | GitDiffOptionFlags.GIT_DIFF_INCLUDE_UNTRACKED_CONTENT; } if (diffOptions.HasFlag(DiffOptions.IncludeIgnored)) { options.Flags |= GitDiffOptionFlags.GIT_DIFF_INCLUDE_IGNORED; } if (diffOptions.HasFlag(DiffOptions.IncludeUnmodified)) { options.Flags |= GitDiffOptionFlags.GIT_DIFF_INCLUDE_UNMODIFIED; } if (diffOptions.HasFlag(DiffOptions.DisablePathspecMatch)) { options.Flags |= GitDiffOptionFlags.GIT_DIFF_DISABLE_PATHSPEC_MATCH; } if (matchedPathsAggregator != null) { options.NotifyCallback = matchedPathsAggregator.OnGitDiffNotify; } if (filePaths == null) { return options; } options.PathSpec = GitStrArrayIn.BuildFrom(filePaths); return options; }
public IAnnotatedFile Annotate(string path, VersionSpec version) { var options = new DiffOptions { Flags = DiffOptionFlags.EnablePreambleHandling | DiffOptionFlags.IgnoreLeadingAndTrailingWhiteSpace | DiffOptionFlags.IgnoreEndOfLineDifference }; PendingChange[] pendingChanges = server.GetWorkspace(path).GetPendingChanges(path); if (pendingChanges.Length >= 2) { throw new InvalidOperationException("Expected at most 1 pending change, but got " + pendingChanges.Length); } Changeset currentChangeset = null; AnnotatedFile annotatedFile; string currentPath; int currentEncoding; if (pendingChanges.Length == 1 && (pendingChanges[0].ChangeType & ChangeType.Edit) != 0) { annotatedFile = new AnnotatedFile(path, pendingChanges[0].Encoding); if (annotatedFile.IsBinary()) { return annotatedFile; } currentPath = path; currentEncoding = pendingChanges[0].Encoding; } else { annotatedFile = null; currentPath = null; currentEncoding = 0; } using (var historyProvider = new HistoryProvider(server, path, version)) { bool done = false; while (!done && historyProvider.Next()) { Changeset previousChangeset = historyProvider.Changeset(); string previousPath = historyProvider.Filename(); int previousEncoding = previousChangeset.Changes[0].Item.Encoding; if (annotatedFile == null) { annotatedFile = new AnnotatedFile(previousPath, previousEncoding); if (annotatedFile.IsBinary()) { return annotatedFile; } } else if (previousEncoding == -1) { annotatedFile.Apply(currentChangeset); done = true; } else { var diff = Diff(Difference.DiffFiles(currentPath, currentEncoding, previousPath, previousEncoding, options)); done = annotatedFile.ApplyDiff(currentChangeset, diff); } currentChangeset = previousChangeset; currentEncoding = previousEncoding; currentPath = previousPath; } if (annotatedFile != null) { annotatedFile.Apply(currentChangeset); } } return annotatedFile; }
public static void ShowChangeset(VersionControlServer vcs, ChangesetVersionSpec versionSpec, bool brief, DiffOptions diffOpts) { int changesetId = versionSpec.ChangesetId; Changeset changeset = vcs.GetChangeset(changesetId, true, true); // fetch all items in one fell swoop List<int> ids = new List<int>(); foreach (Change change in changeset.Changes) ids.Add(change.Item.ItemId); // find items in prior changeset Item[] items = vcs.GetItems(ids.ToArray(), changesetId-1, true); SortedList<int, Item> itemList = new SortedList<int, Item>(); foreach (Item item in items) { // itemId of 0 means a null item, IOW file was added in this changeset // and missing in prior changeset if (item.ItemId == 0) continue; itemList.Add(item.ItemId, item); } foreach (Change change in changeset.Changes) { // skip folders if (change.Item.ItemType == ItemType.Folder) continue; string p = change.Item.ServerItem.Substring(2); if (brief) { Console.WriteLine(p); continue; } IDiffItem a = new DiffItemNull(); IDiffItem b = new DiffItemNull(); string tnameA = null; string tnameB = null; if (((change.ChangeType & ChangeType.Add) != ChangeType.Add) && (itemList.ContainsKey(change.Item.ItemId))) { Item itemA = itemList[change.Item.ItemId]; tnameA = Path.GetTempFileName(); itemA.DownloadFile(tnameA); a = new DiffItemLocalFile(tnameA, itemA.Encoding, changeset.CreationDate, true); } if ((change.ChangeType & ChangeType.Delete) != ChangeType.Delete) { tnameB = Path.GetTempFileName(); change.Item.DownloadFile(tnameB); b = new DiffItemLocalFile(tnameB, change.Item.Encoding, changeset.CreationDate, true); } diffOpts.TargetLabel = versionSpec.DisplayString; Difference.DiffFiles(vcs, a, b, diffOpts, p, true); if (!String.IsNullOrEmpty(tnameA)) File.Delete(tnameA); if (!String.IsNullOrEmpty(tnameB)) File.Delete(tnameB); } }
private GitDiffOptions BuildOptions(DiffOptions diffOptions, IEnumerable<string> paths = null) { var options = new GitDiffOptions(); options.Flags |= GitDiffOptionFlags.GIT_DIFF_INCLUDE_TYPECHANGE; options.ContextLines = 3; if (diffOptions.HasFlag(DiffOptions.IncludeUntracked)) { options.Flags |= GitDiffOptionFlags.GIT_DIFF_INCLUDE_UNTRACKED | GitDiffOptionFlags.GIT_DIFF_RECURSE_UNTRACKED_DIRS | GitDiffOptionFlags.GIT_DIFF_INCLUDE_UNTRACKED_CONTENT; } if (paths == null) { return options; } options.PathSpec = GitStrArrayIn.BuildFrom(ToFilePaths(repo, paths)); return options; }
private void WriteDiffsToStream(Item file, IDiffItem sourceItem, IDiffItem targetItem, StreamWriter outputStream) { var diffOptions = new DiffOptions { SourceEncoding = Encoding.GetEncoding(file.Encoding), TargetEncoding = Encoding.GetEncoding(file.Encoding), OutputType = DiffOutputType.Unified, StreamWriter = outputStream, }; Difference.DiffFiles(this.versionControlServer, sourceItem, targetItem, diffOptions, "AllYourBaseAreBelongToUs", true); }
internal static void WriteHeader(DiffItemUtil aItem, DiffItemUtil bItem, DiffOptions diffOpts) { StreamWriter stream = diffOpts.StreamWriter; stream.Write("diff --tfs " + aItem.Name + " "); if (!String.IsNullOrEmpty(diffOpts.SourceLabel)) stream.Write(diffOpts.SourceLabel + " "); stream.Write(bItem.Name); if (!String.IsNullOrEmpty(diffOpts.TargetLabel)) stream.Write("@" + diffOpts.TargetLabel); stream.WriteLine(); // the trailing tabs below help diffutils grok filenames with spaces stream.WriteLine("--- " + aItem.Name + "\t"); stream.WriteLine("+++ " + bItem.Name + "\t"); }
protected override void AttachViewModel(object viewModel) { base.AttachViewModel(viewModel); var vm = viewModel as DiffViewModel; if(vm != null) { _options = vm.DiffOptions; if(_options == null) { _options = new DiffOptions(); } DiffSource = vm.DiffSource; UpdateText(); } }
private static DiffOptions CreateDefault() { var options = new DiffOptions(); options.Freeze(); return options; }
public string DiffItemWithPrevVersion(Item item) { string diffStr = ""; // Get previous version item // Item prevItem = Server.GetItem(item.ItemId, item.ChangesetId - 1); if (prevItem != null) { DiffItemVersionedFile curFile = new DiffItemVersionedFile(Server, item.ItemId, item.ChangesetId, null); DiffItemVersionedFile prevFile = new DiffItemVersionedFile(Server, prevItem.ItemId, prevItem.ChangesetId, null); // Create memory stream for buffering diff output in memory // MemoryStream memStream = new MemoryStream(); // Here we set up the options to show the diffs in the console with the unified diff // format. DiffOptions options = new DiffOptions(); options.UseThirdPartyTool = false; // These settings are just for the text diff (not needed for an external tool). options.Flags = DiffOptionFlags.EnablePreambleHandling | DiffOptionFlags.IgnoreWhiteSpace; options.OutputType = DiffOutputType.Unified; options.TargetEncoding = Console.OutputEncoding; options.SourceEncoding = Console.OutputEncoding; options.StreamWriter = new StreamWriter(memStream); options.StreamWriter.AutoFlush = true; Difference.DiffFiles(Server, prevFile, curFile, options, prevItem.ServerItem, true); // Move to the beginning of the stream for reading. memStream.Seek(0, SeekOrigin.Begin); StreamReader sr = new StreamReader(memStream); diffStr = sr.ReadToEnd(); } return diffStr; }
/// <summary> /// Get differences between an original stream and a modified stream. /// </summary> /// <param name="originalStream">Original stream.</param> /// <param name="originalEncoding">Encoding of original stream.</param> /// <param name="modifiedStream">Modified stream.</param> /// <param name="modifiedEncoding">Encoding of modified stream.</param> /// <returns>A summary of the differences between two streams.</returns> private DiffSummary GetDifference(Stream originalStream, Encoding originalEncoding, Stream modifiedStream, Encoding modifiedEncoding) { var diffOptions = new DiffOptions { UseThirdPartyTool = false }; if (_marginSettings.IgnoreLeadingAndTrailingWhiteSpace) diffOptions.Flags |= DiffOptionFlags.IgnoreLeadingAndTrailingWhiteSpace; originalStream.Position = 0; modifiedStream.Position = 0; DiffSummary diffSummary = DiffUtil.Diff( originalStream, originalEncoding, modifiedStream, modifiedEncoding, diffOptions, true); return diffSummary; }
internal virtual TreeChanges Compare(DiffOptions diffOptions, IEnumerable<string> paths = null, ExplicitPathsOptions explicitPathsOptions = null, CompareOptions compareOptions = null) { var comparer = WorkdirToIndex(repo); if (explicitPathsOptions != null) { diffOptions |= DiffOptions.DisablePathspecMatch; if (explicitPathsOptions.ShouldFailOnUnmatchedPath || explicitPathsOptions.OnUnmatchedPath != null) { diffOptions |= DiffOptions.IncludeUnmodified; } } return BuildTreeChangesFromComparer(null, null, comparer, diffOptions, paths, explicitPathsOptions, compareOptions); }
/// <summary> /// Gets the change from the shelveset. /// Returns null if any error occurs, or the change is not pending. /// </summary> /// <param name="changeId"> shelveset identifier. </param> /// <param name="includeBranchedFiles"> Include full text for branched and integrated files. </param> /// <returns> The change. </returns> Change ISourceControl.GetChange(string changeId, bool includeBranchedFiles) { bool getFilesFromShelveSet = Tfs.GetFilesFromShelveSet; Debug.Assert(Tfs.GetFilesFromShelveSet || Workspace != null); string shelvesetName = changeId; string shelvesetOwner = TfsServer.AuthenticatedUserName; Shelveset shelveset = null; PendingSet[] sets = null; { var nameAndOwner = changeId.Split(new char[] { ';' }); if (nameAndOwner.Length == 2) { shelvesetName = nameAndOwner[0]; shelvesetOwner = nameAndOwner[1]; } Shelveset[] shelvesets = VcsServer.QueryShelvesets(shelvesetName, shelvesetOwner); if (shelvesets.Length != 1) { if (shelvesets.Count() == 0) Console.WriteLine("Change not found."); else Console.WriteLine("Ambiguous change name."); return null; } shelveset = shelvesets.First(); if (getFilesFromShelveSet) sets = VcsServer.QueryShelvedChanges(shelvesetName, shelvesetOwner, null, true); else sets = VcsServer.QueryShelvedChanges(shelveset); } List<ChangeFile> files = new List<ChangeFile>(); foreach (PendingSet set in sets) { PendingChange[] changes = set.PendingChanges; foreach (PendingChange change in changes) { ChangeFile.SourceControlAction action; string originalFileName = null; if (change.ChangeTypeName.Equals("edit")) { action = ChangeFile.SourceControlAction.EDIT; } else if (change.ChangeTypeName.Equals("add")) { action = ChangeFile.SourceControlAction.ADD; } else if (change.ChangeTypeName.Equals("delete") || change.ChangeTypeName.Equals("merge, delete")) { action = ChangeFile.SourceControlAction.DELETE; } else if (change.ChangeTypeName.Equals("branch") || change.ChangeTypeName.Equals("merge, branch")) { action = ChangeFile.SourceControlAction.BRANCH; } else if (change.ChangeTypeName.Equals("merge, edit")) { action = ChangeFile.SourceControlAction.INTEGRATE; } else if (change.ChangeTypeName.Equals("rename")) { action = ChangeFile.SourceControlAction.RENAME; } else if (change.ChangeTypeName.Equals("rename, edit")) { action = ChangeFile.SourceControlAction.EDIT; originalFileName = change.SourceServerItem; } else { Console.WriteLine("Unsupported action for file " + change.LocalItem + " : " + change.ChangeTypeName); return null; } ChangeFile file = new ChangeFile(change.ServerItem, action, change.Version, (change.ItemType == ItemType.File) && IsTextEncoding(change.Encoding)); files.Add(file); file.LocalFileName = Workspace.GetLocalItemForServerItem(change.ServerItem); file.OriginalServerFileName = originalFileName; if (getFilesFromShelveSet) { if (action != ChangeFile.SourceControlAction.DELETE) { file.LastModifiedTime = shelveset.CreationDate.ToUniversalTime(); } } else if (File.Exists(file.LocalFileName)) { file.LastModifiedTime = File.GetLastWriteTimeUtc(file.LocalFileName); } if (!file.IsText) continue; // Store the entire file. if (action == ChangeFile.SourceControlAction.ADD || (action == ChangeFile.SourceControlAction.BRANCH && includeBranchedFiles)) { if (getFilesFromShelveSet) { using (Malevich.Util.TempFile tempFile = new Malevich.Util.TempFile()) { change.DownloadShelvedFile(tempFile.FullName); file.Data = File.ReadAllText(tempFile.FullName); } } else { file.Data = File.ReadAllText(file.LocalFileName); } } // Store the diff. else if (action == ChangeFile.SourceControlAction.EDIT || (action == ChangeFile.SourceControlAction.INTEGRATE && includeBranchedFiles)) { #if USE_DIFF_TOOL using (var baseFile = new TempFile()) using (var changedFile = new TempFile()) { change.DownloadBaseFile(baseFile.FullName); change.DownloadShelvedFile(changedFile.FullName); string args = baseFile.FullName + " " + changedFile.FullName; using (Process diff = new Process()) { diff.StartInfo.UseShellExecute = false; diff.StartInfo.RedirectStandardError = true; diff.StartInfo.RedirectStandardOutput = true; diff.StartInfo.CreateNoWindow = true; diff.StartInfo.FileName = @"bin\diff.exe"; diff.StartInfo.Arguments = args; diff.Start(); string stderr; file.Data = Malevich.Util.CommonUtils.ReadProcessOutput(diff, false, out stderr); } } #else IDiffItem changedFile = getFilesFromShelveSet ? (IDiffItem)new DiffItemShelvedChange(shelveset.Name, change) : (IDiffItem)new DiffItemLocalFile(file.LocalFileName, change.Encoding, file.LastModifiedTime.Value, false); DiffItemPendingChangeBase baseFile = new DiffItemPendingChangeBase(change); // Generate the diffs DiffOptions options = new DiffOptions(); options.OutputType = DiffOutputType.UnixNormal; options.UseThirdPartyTool = false; using (var memStream = new MemoryStream()) { options.StreamWriter = new StreamWriter(memStream); { // DiffFiles closes options.StreamWriter. Difference.DiffFiles(VcsServer, baseFile, changedFile, options, null, true); memStream.Seek(0, SeekOrigin.Begin); // Remove TFS-specific delimiters. using (StreamReader reader = new StreamReader(memStream)) { StringBuilder sb = new StringBuilder(); for (string line = reader.ReadLine(); line != null; line = reader.ReadLine()) { if (line.Equals("")) continue; if (line.StartsWith("=")) continue; sb.Append(line); sb.Append('\n'); } file.Data = sb.ToString(); } } } #endif } } } if (files.Count() == 0) { Console.WriteLine("The shelveset does not contain any files!"); return null; } // Iterate the workitems associated with the bug and store the IDs. var bugIds = new List<string>(); foreach (WorkItemCheckinInfo workItemInfo in shelveset.WorkItemInfo) { var workItem = workItemInfo.WorkItem; bugIds.Add(workItem.Id.ToString()); } return new Change( Tfs, Tfs.Workspace, shelveset.Name, shelveset.OwnerName, shelveset.CreationDate.ToUniversalTime(), shelveset.Comment, bugIds, files) { ChangeListFriendlyName = shelveset.DisplayName.Split(new char[] { ';' })[0] }; }
void MyShowChangesetEventHandler(object sender, ShowChangesetEventArgs args) { int changesetId = args.ChangesetId; VersionControlServer vcs = args.VersionControlServer; ChangesetVersionSpec versionSpec = new ChangesetVersionSpec(changesetId); string tname = System.IO.Path.GetTempFileName(); using (StreamWriter sw = new StreamWriter(tname)) { DiffOptions options = new DiffOptions(); options.UseThirdPartyTool = false; options.Flags = DiffOptionFlags.EnablePreambleHandling; options.OutputType = DiffOutputType.Unified; options.TargetEncoding = Encoding.UTF8; options.SourceEncoding = Encoding.UTF8; options.StreamWriter = sw; options.StreamWriter.AutoFlush = true; DiffHelper.ShowChangeset(vcs, versionSpec, false, options); } Document d = MonoDevelop.Ide.Gui.IdeApp.Workbench.OpenDocument (tname, true); d.FileName = "Changeset " + changesetId.ToString(); File.Delete(tname); }
private TreeChanges BuildTreeChangesFromComparer( ObjectId oldTreeId, ObjectId newTreeId, TreeComparisonHandleRetriever comparisonHandleRetriever, DiffOptions diffOptions, IEnumerable<string> paths = null, ExplicitPathsOptions explicitPathsOptions = null, CompareOptions compareOptions = null) { var matchedPaths = new MatchedPathsAggregator(); var filePaths = ToFilePaths(repo, paths); using (GitDiffOptions options = BuildOptions(diffOptions, filePaths, matchedPaths, compareOptions)) using (DiffListSafeHandle diffList = comparisonHandleRetriever(oldTreeId, newTreeId, options)) { if (explicitPathsOptions != null) { DispatchUnmatchedPaths(explicitPathsOptions, filePaths, matchedPaths); } return new TreeChanges(diffList); } }