Exemplo n.º 1
0
        // https://github.com/mmanela/diffplex#sample-code
        public static void ToConsole(string before, string after)
        {
            var diff = InlineDiffBuilder.Diff(before, after);

            var savedColor = Console.ForegroundColor;

            foreach (var line in diff.Lines)
            {
                switch (line.Type)
                {
                case ChangeType.Inserted:
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.Write("+ ");
                    break;

                case ChangeType.Deleted:
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.Write("- ");
                    break;

                default:
                    Console.ForegroundColor = ConsoleColor.Gray; // compromise for dark or light background
                    Console.Write("  ");
                    break;
                }

                Console.WriteLine(line.Text);
            }
            Console.ForegroundColor = savedColor;
        }
Exemplo n.º 2
0
        // Copied from https://github.com/VerifyTests/Verify.DiffPlex/blob/master/src/Verify.DiffPlex/VerifyDiffPlex.cs
        public static Task <CompareResult> OnlyIncludeChanges(string received, string verified, IReadOnlyDictionary <string, object> _)
        {
            var diff = InlineDiffBuilder.Diff(verified, received);

            var builder = new StringBuilder();

            foreach (var line in diff.Lines)
            {
                switch (line.Type)
                {
                case ChangeType.Inserted:
                    builder.Append("+ ");
                    break;

                case ChangeType.Deleted:
                    builder.Append("- ");
                    break;

                default:
                    // omit unchanged files
                    continue;
                }
                builder.AppendLine(line.Text);
            }

            var compareResult = CompareResult.NotEqual(builder.ToString());

            return(Task.FromResult(compareResult));
        }
Exemplo n.º 3
0
        public static void Initialize()
        {
            VerifierSettings.SetDefaultStringComparer((received, verified, _) =>
            {
                var diff = InlineDiffBuilder.Diff(verified, received);

                var builder = new StringBuilder();
                foreach (var line in diff.Lines)
                {
                    switch (line.Type)
                    {
                    case ChangeType.Inserted:
                        builder.Append("+ ");
                        break;

                    case ChangeType.Deleted:
                        builder.Append("- ");
                        break;

                    default:
                        builder.Append("  ");
                        break;
                    }
                    builder.AppendLine(line.Text);
                }

                var compareResult = CompareResult.NotEqual(builder.ToString());
                return(Task.FromResult(compareResult));
            });
        }
Exemplo n.º 4
0
        static void Main(string[] args)
        {
            var compilerinvocations1 = CompilerInvocationsReader.ReadInvocations(args[0])
                                       .ToDictionary(x => x.ProjectFilePath);

            var compilerinvocations2 = CompilerInvocationsReader.ReadInvocations(args[1])
                                       .ToDictionary(x => x.ProjectFilePath);

            var projectsInSecondButNotFirst = new List <string>();

            foreach (var(projectPath, compilerInvocation2) in compilerinvocations2)
            {
                if (!compilerinvocations1.TryGetValue(projectPath, out var compilerInvocation1))
                {
                    projectsInSecondButNotFirst.Add(projectPath);
                    continue;
                }

                var before = string.Join('\n', compilerInvocation1.CommandLineArguments.Split(' ').OrderByDescending(x => x));
                var after  = string.Join('\n', compilerInvocation2.CommandLineArguments.Split(' ').OrderByDescending(x => x));;
                var diff   = InlineDiffBuilder.Diff(before, after);
                PrintDiff(diff);
            }

            if (projectsInSecondButNotFirst.Any())
            {
                Console.WriteLine("Projects in second build but not in the first: ");
                Console.WriteLine(string.Join('\n', projectsInSecondButNotFirst));
            }
        }
Exemplo n.º 5
0
    public static void EqualJson <T>(T expected, T actual, string?description = null)
    {
        var options = new JsonSerializerOptions()
        {
            Encoder       = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
            WriteIndented = true,
        };

        options.Converters.Add(BytesReadOnlyMemoryConverter.Default);

        var expectedJsonString = JsonSerializer.Serialize(expected, options);
        var actualJsonString   = JsonSerializer.Serialize(actual, options);

        if (expectedJsonString == actualJsonString)
        {
            return;
        }

        var diff = InlineDiffBuilder.Diff(expectedJsonString, actualJsonString);

        var savedColor = Console.ForegroundColor;

        try
        {
            foreach (var line in diff.Lines)
            {
                switch (line.Type)
                {
                case ChangeType.Inserted:
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.Write("+ ");
                    break;

                case ChangeType.Deleted:
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.Write("- ");
                    break;

                default:
                    Console.ForegroundColor = ConsoleColor.Gray;     // compromise for dark or light background
                    Console.Write("  ");
                    break;
                }

                Console.WriteLine(line.Text);
            }
        }
        finally
        {
            Console.ForegroundColor = savedColor;
        }

        throw new AssertException($"EqualJson Error: {description}");
    }
Exemplo n.º 6
0
 public string CreateDiff()
 {
     var diffResult = InlineDiffBuilder.Diff(Before, After, false);
     var diff       = diffResult.Lines.Select(o =>
     {
         return(o.Type switch
         {
             ChangeType.Inserted => $"+ {o.Text}",
             ChangeType.Deleted => $"- {o.Text}",
             _ => null,
         });
     }).Where(o => o != null);
Exemplo n.º 7
0
        private void ComparisonSchema(MySqlConnection connection, string db1, string db2)
        {
            TestContext.Progress.WriteLine($"Сравниваем схемы базы {db1} и {db2}.");
            string schema1 = GetSchema(connection, db1);
            string schema2 = GetSchema(connection, db2);

            if (schema1 != schema2)
            {
                var diff = InlineDiffBuilder.Diff(schema1, schema2);

                for (int i = 0; i < diff.Lines.Count; i++)
                {
                    bool showLine = false;
                    for (int x = Math.Max(0, i - showDiffLinesAfter); x < Math.Min(diff.Lines.Count, i + showDiffLinesBefore); x++)
                    {
                        if (diff.Lines[x].Type == ChangeType.Inserted || diff.Lines[x].Type == ChangeType.Deleted)
                        {
                            showLine = true;
                            break;
                        }
                    }

                    if (!showLine)
                    {
                        continue;
                    }

                    var line = diff.Lines[i];
                    switch (line.Type)
                    {
                    case ChangeType.Inserted:
                        Console.Write("+ ");
                        break;

                    case ChangeType.Deleted:
                        Console.Write("- ");
                        break;

                    default:
                        Console.Write("  ");
                        break;
                    }
                    Console.WriteLine(line.Text);
                }
            }

            Assert.That(schema1, Is.EqualTo(schema2));
        }
Exemplo n.º 8
0
        public static void Run()
        {
            var txt1 = Resources.oldState;

            var txt2 = Resources.newState;

            var diff       = InlineDiffBuilder.Diff(txt1, txt2);
            var diff2      = SideBySideDiffBuilder.Diff(txt1, txt2);
            var savedColor = Console.ForegroundColor;

            _printLines(diff2.OldText.Lines);
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("-------------------------------------------");
            _printLines(diff2.NewText.Lines);

            Console.ForegroundColor = savedColor;
        }
Exemplo n.º 9
0
        /// <summary>
        /// Populate the top rich text box with an inline compare.
        /// </summary>
        private void PerformInlineDiff()
        {
            var builder = InlineDiffBuilder.Diff(OldText, NewText);

            if (builder.HasDifferences)
            {
                foreach (var line in builder.Lines)
                {
                    if (!string.IsNullOrWhiteSpace(richTextBoxInline.Text))
                    {
                        richTextBoxInline.AppendText(Environment.NewLine);
                    }
                    switch (line.Type)
                    {
                    case ChangeType.Unchanged:
                        richTextBoxInline.AppendText(line.Text);
                        break;

                    case ChangeType.Deleted:
                        richTextBoxInline.AppendText(line.Text, Color.Red);
                        break;

                    case ChangeType.Inserted:
                        richTextBoxInline.AppendText(line.Text, Color.Blue);
                        break;

                    case ChangeType.Imaginary:
                        richTextBoxInline.AppendText(String.Empty);
                        break;

                    case ChangeType.Modified:
                        richTextBoxInline.AppendText(line.Text, Color.Green);
                        break;

                    default:
                        richTextBoxInline.AppendText(line.Text, Color.Purple);
                        break;
                    }
                }
            }
            else
            {
                richTextBoxInline.AppendText(NewText);
            }
        }
Exemplo n.º 10
0
        public static void AssertBencodexEqual(IValue expected, IValue actual)
        {
            bool equal = (expected is null && actual is null) ||
                         (expected is Null && actual is Null) ||
                         (expected is Bencodex.Types.Boolean && actual is Bencodex.Types.Boolean &&
                          expected.Equals(actual)) ||
                         (expected is Integer && actual is Integer && expected.Equals(actual)) ||
                         (expected is Binary && actual is Binary && expected.Equals(actual)) ||
                         (expected is Text && actual is Text && expected.Equals(actual)) ||
                         (expected is List && actual is List && expected.Equals(actual)) ||
                         (expected is Dictionary && actual is Dictionary && expected.Equals(actual));

            if (equal)
            {
                return;
            }

            string        expectedInspection = expected?.ToString() ?? "(null)";
            string        actualInspection   = actual?.ToString() ?? "(null)";
            DiffPaneModel diffModel          = InlineDiffBuilder.Diff(expectedInspection, actualInspection);
            var           prefixes           = new Dictionary <ChangeType, string>
            {
                [ChangeType.Deleted]   = "-",
                [ChangeType.Inserted]  = "+",
                [ChangeType.Unchanged] = " ",
            };

            string diff = string.Join(
                Environment.NewLine,
                diffModel.Lines.Select(line =>
                                       (prefixes.TryGetValue(line.Type, out string prefix) ? prefix : " ") + line.Text
                                       )
                );

            throw new XunitException(
                      "Two Bencodex values are not equal.\n--- Expected\n+++ Actual\n\n" + diff
                      );
        }
        public static string GenerateDiff(string before, string after)
        {
            var diff   = InlineDiffBuilder.Diff(before, after);
            var result = new StringBuilder();

            foreach (var line in diff.Lines)
            {
                switch (line.Type)
                {
                case ChangeType.Inserted:
                    result.AppendLine($"<span style=\"color: green\">+ {line.Text}</span><br>");
                    break;

                case ChangeType.Deleted:
                    result.AppendLine($"<span style=\"color: red\">- {line.Text}</span><br>");
                    break;

                default:
                    break;
                }
            }
            return(result.ToString());
        }
        string GetDiff(string before, string after)
        {
            var diff   = InlineDiffBuilder.Diff(before, after);
            var result = new StringBuilder();

            foreach (var line in diff.Lines)
            {
                switch (line.Type)
                {
                case ChangeType.Inserted:
                    result.Append("+ ");
                    result.AppendLine(line.Text);
                    break;

                case ChangeType.Deleted:
                    result.Append("- ");
                    result.AppendLine(line.Text);
                    break;
                }
            }

            return(result.ToString());
        }
Exemplo n.º 13
0
        /// <summary>
        /// Check difference between two files line by line with DiffPlex
        /// https://www.nuget.org/packages/DiffPlex
        /// </summary>
        /// <param name="arg"></param>
        /// <param name="currentDirectory"></param>
        private void DiffFiles(string arg, string currentDirectory)
        {
            try
            {
                arg = arg.Replace("diff ", string.Empty);
                string files      = arg.SplitByText(" -f ", 0);
                var    filesSplit = files.Split(';');
                int    countSplit = filesSplit.Count();
                if (countSplit == 2)
                {
                    string firstFile = FileSystem.SanitizePath(filesSplit[0], currentDirectory);
                    string secondFile;
                    if (arg.Contains(" -verbose") && !arg.Contains(" -f "))
                    {
                        secondFile = FileSystem.SanitizePath(filesSplit[1].Replace(" -verbose", string.Empty), currentDirectory);
                    }
                    else
                    {
                        secondFile = FileSystem.SanitizePath(filesSplit[1], currentDirectory);
                    }

                    var linesFirst  = File.ReadAllText(firstFile);
                    var linesSecond = File.ReadAllText(secondFile);
                    var diff        = InlineDiffBuilder.Diff(linesFirst, linesSecond);
                    var savedColor  = Console.ForegroundColor;
                    if (!arg.Contains(" -f "))
                    {
                        if (!arg.Contains(" -verbose"))
                        {
                            if (!diff.HasDifferences)
                            {
                                FileSystem.ColorConsoleTextLine(ConsoleColor.Yellow, "There is no difference between files!");
                                return;
                            }
                            foreach (var line in diff.Lines)
                            {
                                switch (line.Type)
                                {
                                case ChangeType.Inserted:
                                    Console.ForegroundColor = ConsoleColor.Green;
                                    Console.WriteLine($"Ins Line:{line.Position} {line.Text}");
                                    Console.ForegroundColor = savedColor;
                                    break;

                                case ChangeType.Deleted:
                                    Console.ForegroundColor = ConsoleColor.Red;
                                    Console.WriteLine($"Del Line:{line.Position} {line.Text}");
                                    Console.ForegroundColor = savedColor;
                                    break;
                                }
                            }
                            return;
                        }
                        var diffVerbose = InlineDiffBuilder.Diff(linesFirst, linesSecond);
                        foreach (var line in diffVerbose.Lines)
                        {
                            switch (line.Type)
                            {
                            case ChangeType.Inserted:
                                Console.ForegroundColor = ConsoleColor.Green;
                                Console.Write("+ ");
                                break;

                            case ChangeType.Deleted:
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.Write("- ");
                                break;

                            default:
                                Console.ForegroundColor = ConsoleColor.Gray;     // compromise for dark or light background
                                Console.Write("  ");
                                break;
                            }
                            Console.WriteLine(line.Text);
                        }
                        Console.ForegroundColor = savedColor;
                        return;
                    }
                    if (!arg.Contains(" -verbose"))
                    {
                        string outFile = FileSystem.SanitizePath(arg.SplitByText(" -f ", 1), currentDirectory);
                        string outData = string.Empty;
                        foreach (var line in diff.Lines)
                        {
                            switch (line.Type)
                            {
                            case ChangeType.Inserted:
                                outData += $"Ins Line:{line.Position} {line.Text}\n";
                                break;

                            case ChangeType.Deleted:
                                outData += $"Del Line:{line.Position} {line.Text}\n";
                                break;
                            }
                        }
                        if (outData.Length > 0)
                        {
                            FileSystem.ColorConsoleTextLine(ConsoleColor.Green, FileSystem.SaveFileOutput(outFile, currentDirectory, outData));
                        }
                        else
                        {
                            FileSystem.ColorConsoleTextLine(ConsoleColor.Yellow, "There is no difference between files!");
                        }
                    }
                    else
                    {
                        string outFile = FileSystem.SanitizePath(arg.MiddleString("-f", "-verbose"), currentDirectory);
                        string outData = string.Empty;
                        foreach (var line in diff.Lines)
                        {
                            switch (line.Type)
                            {
                            case ChangeType.Inserted:
                                outData += $"Ins Line:{line.Position} {line.Text}\n";
                                break;

                            case ChangeType.Deleted:
                                outData += $"Del Line:{line.Position} {line.Text}\n";
                                break;

                            default:
                                outData += $"{line.Text}\n";
                                break;
                            }
                        }
                        if (outData.Length > 0)
                        {
                            FileSystem.ColorConsoleTextLine(ConsoleColor.Green, FileSystem.SaveFileOutput(outFile, currentDirectory, outData));
                        }
                        else
                        {
                            FileSystem.ColorConsoleTextLine(ConsoleColor.Yellow, "There is no difference between files!");
                        }
                    }
                    return;
                }
                FileSystem.ColorConsoleTextLine(ConsoleColor.Yellow, "Only 2 files can be compared!");
            }
            catch (Exception e)
            {
                FileSystem.ErrorWriteLine(e.Message);
            }
        }
Exemplo n.º 14
0
        private static async Task <int> CompareFiles(ConsulClient client, bool includeIdenticalResults)
        {
            var nonFolderPairs = await Common.GetNonFolderPairsAsync(client);

            if (nonFolderPairs == null)
            {
                return(1);
            }

            var localFiles = Common.GetLocalFiles();

            localFiles = localFiles.Select(f => Path.GetRelativePath(Common.BaseDirectoryFullPath, f).ToUnixPath()).ToList();

            var table = new Table();

            table.HorizontalBorder();
            table.BorderColor(Color.Grey74);
            table.AddColumn(new TableColumn("Files".ToSilver(isBold: true)));
            table.AddColumn(new TableColumn("Consul - Local".ToSilver(isBold: true)).Centered());

            var commonPairs              = nonFolderPairs.Where(p => localFiles.Contains(p.Key));
            var consulFiles              = nonFolderPairs.Select(p => p.Key);
            var missingFilesOnConsul     = localFiles.Where(f => !consulFiles.Contains(f)).ToList();
            var missingFilesOnFileSystem = consulFiles.Where(k => !localFiles.Contains(k)).ToList();
            var exitCode = 0;

            if (missingFilesOnConsul.Any() || missingFilesOnFileSystem.Any())
            {
                exitCode = 2;
            }

            foreach (var pair in commonPairs)
            {
                var filePath    = Path.Combine(Common.BaseDirectoryFullPath, pair.Key);
                var fileContent = await File.ReadAllTextAsync(filePath, Encoding.UTF8);

                var consulContent = Encoding.UTF8.GetString(pair.Value ?? new byte[] { });
                var diffModel     = InlineDiffBuilder.Diff(consulContent, fileContent);

                if (diffModel.HasDifferences)
                {
                    exitCode = 2;
                    table.AddRow(pair.Key.ToRed(), FileContentsAreDifferentSign.ToRed());
                }
                else if (includeIdenticalResults)
                {
                    table.AddRow(pair.Key.ToSilver(), FileContentsAreEqualSign.ToSilver());
                }
            }

            foreach (var file in missingFilesOnConsul)
            {
                table.AddRow(file.ToYellow(), OnlyInFileSystemSign.ToYellow());
            }

            foreach (var file in missingFilesOnFileSystem)
            {
                table.AddRow(file.ToYellow(), OnlyInConsulSign.ToYellow());
            }

            AnsiConsole.Render(table);
            return(exitCode);
        }