public static void Diff(this string expected, string actual, string message = null)
		{
			var d = new Differ();
			var inlineBuilder = new InlineDiffBuilder(d);
			var result = inlineBuilder.BuildDiffModel(expected, actual);
			var hasChanges = result.Lines.Any(l => l.Type != ChangeType.Unchanged);
			if (!hasChanges) return;

			var diff = result.Lines.Aggregate(new StringBuilder().AppendLine(message), (sb, line) =>
			{
				if (line.Type == ChangeType.Inserted)
					sb.Append("+ ");
				else if (line.Type == ChangeType.Deleted)
					sb.Append("- ");
				else
					sb.Append("  ");
				sb.AppendLine(line.Text);
				return sb;
			}, sb => sb.ToString());

			diff += "\r\n C# approximation of actual: \r\n new ";
			var approx = Regex.Replace(actual, @"^(?=.*:.*)[^:]+:", (s) => s
				.Value.Replace("\"", "")
				.Replace(":", " =")
			, RegexOptions.Multiline)
				.Replace(" = {", " = new {")
				.Replace(" = [", " = new [] {")
				;
			approx = Regex.Replace(approx, @"^\s*\],?.*$", s => s.Value.Replace("]", "}"), RegexOptions.Multiline);
			diff += approx + ";";

			throw new Exception(diff);
		}
            public void Will_throw_is_NewText_is_null()
            {
                var differ = new Mock<IDiffer>();
                var builder = new InlineDiffBuilder(differ.Object);

                var ex = Record.Exception(() => builder.BuildDiffModel("asa", null));

                Assert.IsType<ArgumentNullException>(ex);
                var an = (ArgumentNullException)ex;
                Assert.Equal("newText", an.ParamName);
            }
Example #3
0
        private static void Main(string[] args)
        {
            var d = new Differ();
            var inlineBuilder = new InlineDiffBuilder(d);
            var result = inlineBuilder.BuildDiffModel(OldText, NewText);
            foreach (var line in result.Lines)
            {
                if(line.Type == ChangeType.Inserted)
                    Console.Write("+ ");
                else if(line.Type == ChangeType.Deleted)
                    Console.Write("- ");
                else
                    Console.Write("  ");

                Console.WriteLine(line.Text);
            }
        }
            public void Will_build_diffModel_for_middle_is_different_documents()
            {
                string textOld = "1\n2\na\nb\nc\nd\ne\f\n";
                string textNew = "1\n2\nz\ny\nx\nw\ne\f\n";
                string[] textLinesOld = new[] { "1", "2", "a", "b", "c", "d", "e", "f" };
                string[] textLinesNew = new[] { "1", "2", "z", "y", "x", "w", "e", "f" };
                var differ = new Mock<IDiffer>();
                differ.Setup(x => x.CreateLineDiffs(textOld, textNew, true))
                    .Returns(new DiffResult(textLinesOld, textLinesNew, new List<DiffBlock> { new DiffBlock(2, 4, 2, 4) }));
                var builder = new InlineDiffBuilder(differ.Object);

                var bidiff = builder.BuildDiffModel(textOld, textNew);

                Assert.NotNull(bidiff);
                Assert.Equal(12, bidiff.Lines.Count);

                Assert.Equal("1", bidiff.Lines[0].Text);
                Assert.Equal(ChangeType.Unchanged, bidiff.Lines[0].Type);
                Assert.Equal(1, bidiff.Lines[0].Position);
                Assert.Equal("2", bidiff.Lines[1].Text);
                Assert.Equal(ChangeType.Unchanged, bidiff.Lines[1].Type);
                Assert.Equal(2, bidiff.Lines[1].Position);

                for (int i = 2; i <= 5; i++)
                {
                    Assert.Equal(textLinesOld[i], bidiff.Lines[i].Text);
                    Assert.Equal(ChangeType.Deleted, bidiff.Lines[i].Type);
                    Assert.Null(bidiff.Lines[i].Position);
                }

                for (int i = 6; i <= 9; i++)
                {
                    Assert.Equal(textLinesNew[i - 4], bidiff.Lines[i].Text);
                    Assert.Equal(ChangeType.Inserted, bidiff.Lines[i].Type);
                    Assert.Equal(i - 3, bidiff.Lines[i].Position);
                }

                Assert.Equal("e", bidiff.Lines[10].Text);
                Assert.Equal(ChangeType.Unchanged, bidiff.Lines[10].Type);
                Assert.Equal(7, bidiff.Lines[10].Position);
                Assert.Equal("f", bidiff.Lines[11].Text);
                Assert.Equal(ChangeType.Unchanged, bidiff.Lines[11].Type);
                Assert.Equal(8, bidiff.Lines[11].Position);
            }
            public void Will_build_diffModel_for_duplicate_strings()
            {
                string text = "a\nb\nc\nd\n\n";
                string[] textLines = new[] { "a", "b", "c", "d", "" };
                var differ = new Mock<IDiffer>();
                differ.Setup(x => x.CreateLineDiffs(text, text, true))
                    .Returns(new DiffResult(textLines, textLines, new List<DiffBlock>() { new DiffBlock(0, 0, 5, 0) }));
                var builder = new InlineDiffBuilder(differ.Object);

                var bidiff = builder.BuildDiffModel(text, text);

                Assert.NotNull(bidiff);
                Assert.Equal(textLines.Length, bidiff.Lines.Count);
                for (int i = 0; i < textLines.Length; i++)
                {
                    Assert.Equal(textLines[i], bidiff.Lines[i].Text);
                    Assert.Equal(ChangeType.Unchanged, bidiff.Lines[i].Type);
                    Assert.Equal(i + 1, bidiff.Lines[i].Position);
                }
            }
Example #6
0
        public static string GetDiffHtml(string oldText, string newText)
        {
            var html = new StringBuilder();
            var diff = new InlineDiffBuilder(new Differ()).BuildDiffModel(oldText ?? String.Empty, newText ?? String.Empty);

            if (diff.Lines.Count > 0)
            {
                html.Append("<div class=\"diff-panel\">");

                foreach (var piece in diff.Lines)
                {
                    html.Append("<span class=\"diff-line\">");
                    WritePiece(html, piece);
                    html.Append("</span>");
                }

                html.Append("</div>");
            }

            return html.ToString();
        }
Example #7
0
 private static DiffPaneModel GetDiff(IDiffer differ, string oldText, string newText)
 {
     var inlineBuilder = new InlineDiffBuilder(differ);
       return inlineBuilder.BuildDiffModel(oldText, newText);
 }
        //сравнение
        private void Differ()
        {
            StringBuilder sb = new StringBuilder();

            List<string> inserted = new List<string>();
            List<string> deleted = new List<string>();
            List<string> modified = new List<string>();
            List<string> imaginary = new List<string>();

            var d = new DiffPlex.Differ();
            var builder = new InlineDiffBuilder(d);
            var result = builder.BuildDiffModel(oldText, newText);

            foreach (var line in result.Lines)
            {
                if (line.Type == ChangeType.Inserted)
                {
                    //Color Green
                    inserted.Add(line.Text);
                    // sb.Append("+ ");
                }
                else if (line.Type == ChangeType.Deleted)
                {
                    //Color Red
                    deleted.Add(line.Text);
                    // sb.Append("- ");
                }
                else if (line.Type == ChangeType.Modified)
                {
                    //Color Blue
                    modified.Add(line.Text);
                    // sb.Append("* ");
                }
                else if (line.Type == ChangeType.Imaginary)
                {                   
                    //Color.Orange
                    imaginary.Add(line.Text);
                    //  sb.Append("? ");
                }
                else if (line.Type == ChangeType.Unchanged)
                {
                    // sb.Append("  ");
                }

                sb.Append(line.Text + "\r\n");
            }


            string res = sb.ToString();

            richTextBoxDiff.Text = res;
           
            //проблема с подцветкой реализовать другой алгоритм
            //обработка цветом

            foreach (string str in inserted)
            {
                HighlightText(richTextBoxDiff, str, Color.GreenYellow);
            }
            foreach (string str in deleted)
            {
                HighlightText(richTextBoxDiff, str, Color.IndianRed);
            }

            foreach (string str in modified)
            {
                HighlightText(richTextBoxDiff, str, Color.Blue);
            }
            foreach (string str in imaginary)
            {
                HighlightText(richTextBoxDiff, str, Color.Orange);
            }
        }
        //сравнение вариант производительнее
        private void DifferTable(object sender, EventArgs e)
        {
            //DateTime start = DateTime.Now;
            StringBuilder sb = new StringBuilder();
            Hashtable insertedTable = new Hashtable();
            Hashtable deletedTable = new Hashtable();
            Hashtable modifiedTable = new Hashtable();
            Hashtable imaginaryTable = new Hashtable();

            var d = new DiffPlex.Differ();
            var builder = new InlineDiffBuilder(d);
            var result = builder.BuildDiffModel(oldText, newText);

            foreach (var line in result.Lines)
            {
                if (line.Type == ChangeType.Inserted)
                {
                    //Color Green
                    //inserted.Add(line.Text);
                    if (!insertedTable.ContainsKey(line.Text))
                    {
                        insertedTable.Add(line.Text, "INSERTED");
                    }
                    // sb.Append("+ ");
                }
                else if (line.Type == ChangeType.Deleted)
                {
                    //Color Red
                    // deleted.Add(line.Text);
                    if (!deletedTable.ContainsKey(line.Text))
                    {
                        deletedTable.Add(line.Text, "DELETED");
                    }
                    // sb.Append("- ");
                }
                else if (line.Type == ChangeType.Modified)
                {
                    //Color Blue
                    // modified.Add(line.Text);
                    if (!modifiedTable.ContainsKey(line.Text))
                    {
                        modifiedTable.Add(line.Text, "MODIFIED");
                    }

                    // sb.Append("* ");
                }
                else if (line.Type == ChangeType.Imaginary)
                {
                    //Color.Orange
                    //imaginary.Add(line.Text);
                    if (!imaginaryTable.ContainsKey(line.Text))
                    {
                        imaginaryTable.Add(line.Text, "MODIFIED");
                    }

                    //  sb.Append("? ");
                }
                else if (line.Type == ChangeType.Unchanged)
                {
                    // sb.Append("  ");
                }

                sb.Append(line.Text + "\r\n");
            }


            string res = sb.ToString();

            richTextBoxDiff.Text = res;

            //проблема с подцветкой реализовать другой алгоритм
            //обработка цветом


            foreach (string str in insertedTable.Keys)
            {
                HighlightText(richTextBoxDiff, str, Color.GreenYellow);
            }
            foreach (string str in deletedTable.Keys)
            {
                HighlightText(richTextBoxDiff, str, Color.IndianRed);
            }
            foreach (string str in modifiedTable.Keys)
            {
                HighlightText(richTextBoxDiff, str, Color.Blue);
            }
            foreach (string str in imaginaryTable.Keys)
            {
                HighlightText(richTextBoxDiff, str, Color.Blue);
            }
            //TimeSpan time = DateTime.Now - start;
            //MessageBox.Show(time.ToString());
        }
            public void Will_build_diffModel_for_multiple_diff_blocks()
            {
                string textOld = "1\n2\na\nb\nc\nd\ne\f\n";
                string textNew = "1\n2\nz\ny\nc\nw\ne\f\n";
                string[] textLinesOld = new[] { "1", "2", "a", "b", "c", "d", "e", "f" };
                string[] textLinesNew = new[] { "1", "2", "z", "y", "c", "w", "e", "f" };
                var differ = new Mock<IDiffer>();
                differ.Setup(x => x.CreateLineDiffs(textOld, textNew, true))
                    .Returns(new DiffResult(textLinesOld, textLinesNew, new List<DiffBlock> { new DiffBlock(2, 2, 2, 2), new DiffBlock(5, 1, 5, 1) }));
                var builder = new InlineDiffBuilder(differ.Object);

                var bidiff = builder.BuildDiffModel(textOld, textNew);

                Assert.NotNull(bidiff);
                Assert.Equal(11, bidiff.Lines.Count);

                Assert.Equal("1", bidiff.Lines[0].Text);
                Assert.Equal(ChangeType.Unchanged, bidiff.Lines[0].Type);
                Assert.Equal(1, bidiff.Lines[0].Position);
                Assert.Equal("2", bidiff.Lines[1].Text);
                Assert.Equal(ChangeType.Unchanged, bidiff.Lines[1].Type);
                Assert.Equal(2, bidiff.Lines[1].Position);
                Assert.Equal("a", bidiff.Lines[2].Text);
                Assert.Equal(ChangeType.Deleted, bidiff.Lines[2].Type);
                Assert.Null(bidiff.Lines[2].Position);
                Assert.Equal("b", bidiff.Lines[3].Text);
                Assert.Equal(ChangeType.Deleted, bidiff.Lines[3].Type);
                Assert.Null(bidiff.Lines[3].Position);
                Assert.Equal("z", bidiff.Lines[4].Text);
                Assert.Equal(ChangeType.Inserted, bidiff.Lines[4].Type);
                Assert.Equal(3, bidiff.Lines[4].Position);
                Assert.Equal("y", bidiff.Lines[5].Text);
                Assert.Equal(ChangeType.Inserted, bidiff.Lines[5].Type);
                Assert.Equal(4, bidiff.Lines[5].Position);
                Assert.Equal("c", bidiff.Lines[6].Text);
                Assert.Equal(ChangeType.Unchanged, bidiff.Lines[6].Type);
                Assert.Equal(5, bidiff.Lines[6].Position);
                Assert.Equal("d", bidiff.Lines[7].Text);
                Assert.Equal(ChangeType.Deleted, bidiff.Lines[7].Type);
                Assert.Null(bidiff.Lines[7].Position);
                Assert.Equal("w", bidiff.Lines[8].Text);
                Assert.Equal(ChangeType.Inserted, bidiff.Lines[8].Type);
                Assert.Equal(6, bidiff.Lines[8].Position);
                Assert.Equal("e", bidiff.Lines[9].Text);
                Assert.Equal(ChangeType.Unchanged, bidiff.Lines[9].Type);
                Assert.Equal(7, bidiff.Lines[9].Position);
                Assert.Equal("f", bidiff.Lines[10].Text);
                Assert.Equal(ChangeType.Unchanged, bidiff.Lines[10].Type);
                Assert.Equal(8, bidiff.Lines[10].Position);
            }
            public void Will_build_diffModel_when_oldText_is_empty()
            {
                string textOld = "";
                string textNew = "z\ny\nx\nw\n";
                string[] textLinesOld = new string[] { };
                string[] textLinesNew = new[] { "z", "y" };
                var differ = new Mock<IDiffer>();
                differ.Setup(x => x.CreateLineDiffs(textOld, textNew, true))
                    .Returns(new DiffResult(textLinesOld, textLinesNew, new List<DiffBlock> { new DiffBlock(0, 0, 0, 2) }));
                var builder = new InlineDiffBuilder(differ.Object);

                var bidiff = builder.BuildDiffModel(textOld, textNew);

                Assert.NotNull(bidiff);
                Assert.Equal(2, bidiff.Lines.Count);

                for (int j = 0; j < textLinesNew.Length; j++)
                {
                    Assert.Equal(textLinesNew[j], bidiff.Lines[j].Text);
                    Assert.Equal(ChangeType.Inserted, bidiff.Lines[j].Type);
                    Assert.Equal(j + 1, bidiff.Lines[j].Position);
                }
            }
            public void Will_build_diffModel_for_unique_strings()
            {
                string textOld = "a\nb\nc\nd\n\n";
                string textNew = "z\ny\nx\nw\n";
                string[] textLinesOld = new[] { "a", "b", "c", "d", "" };
                string[] textLinesNew = new[] { "z", "y", "x", "w" };
                var differ = new Mock<IDiffer>();
                differ.Setup(x => x.CreateLineDiffs(textOld, textNew, true))
                    .Returns(new DiffResult(textLinesOld, textLinesNew, new List<DiffBlock> { new DiffBlock(0, 5, 0, 4) }));
                var builder = new InlineDiffBuilder(differ.Object);

                var bidiff = builder.BuildDiffModel(textOld, textNew);

                Assert.NotNull(bidiff);
                Assert.Equal(9, bidiff.Lines.Count);
                int i = 0;

                for (; i < textLinesOld.Length - 1; i++)
                {
                    Assert.Equal(textLinesOld[i], bidiff.Lines[i].Text);
                    Assert.Equal(ChangeType.Deleted, bidiff.Lines[i].Type);
                    Assert.Null(bidiff.Lines[i].Position);
                }

                for (var j = 0; j < textLinesNew.Length; j++)
                {
                    Assert.Equal(textLinesNew[j], bidiff.Lines[i].Text);
                    Assert.Equal(ChangeType.Inserted, bidiff.Lines[i].Type);
                    Assert.Equal(j + 1, bidiff.Lines[i].Position);
                    i++;
                }

                Assert.Equal("", bidiff.Lines[8].Text);
                Assert.Equal(ChangeType.Deleted, bidiff.Lines[8].Type);
                Assert.Null(bidiff.Lines[8].Position);
            }
Example #13
0
        /// <summary>
        /// Lê o csv e retorna uma lista com as rodadas
        /// </summary>
        /// <param name="instanceFile"></param>
        /// <param name="biblioteca"></param>
        /// <param name="dirGa"></param>
        private static List<RodadaMapper> RecuperarRodadasDoGaNoCsv(FileInfo instanceFile, DirectoryInfo biblioteca, DirectoryInfo dirGa)
        {
            if (!File.Exists(biblioteca.GetFiles().First().FullName))
            {
                Console.WriteLine("Deveria existir o arquivo original da biblioteca aqui. | {0}", dirGa.FullName);
                Environment.Exit(-1);
            }

            //Ler as rodadas
            var rodadas = new List<RodadaMapper>();

            using (var csv = new TextFieldParser(instanceFile.FullName))
            {
                csv.ReadLine();
                csv.ReadLine();

                csv.TextFieldType = FieldType.Delimited;
                csv.SetDelimiters(",");
                csv.HasFieldsEnclosedInQuotes = true;

                //Conta das linhas do original
                var totalLinhas = ContarLinhas(biblioteca.GetFiles().First().FullName);
                //Conta Tokens do Original
                var totalchars = GetNumOfCharsInFile(biblioteca.GetFiles().First().FullName);
                //Texto do Original
                var textoOriginal = File.ReadAllText(biblioteca.GetFiles().First().FullName);

                while (!csv.EndOfData)
                {
                    string[] currentRow = csv.ReadFields();
                    string bestFile = Path.GetFileName(currentRow[1]);
                    int totalLinhasBest = 0;
                    int totalcharsBest = 0;
                    string tempoOriginal = "00:00:00,000";
                    string fitOrignal = "00000";
                    string tempoFinalComUnload = "";
                    string fitFinal = "";
                    DiffPaneModel resultadoComparacao = null;

                    //Tempo e fit originais
                    tempoOriginal = RecuperarTempoMedioeFitOriginal(biblioteca, dirGa, currentRow[0], out fitOrignal);

                    var fileList = dirGa.GetFiles(bestFile, SearchOption.AllDirectories);
                    //Se o arquivo melhorado existe, conta as linhas e os caracteres do mesmo

                    if (fileList.Any())
                    {
                        totalLinhasBest = ContarLinhas(fileList.First().FullName);
                        totalcharsBest = GetNumOfCharsInFile(fileList.First().FullName);
                        tempoFinalComUnload = currentRow[4];
                        fitFinal = currentRow[3];

                        var textoMelhor = File.ReadAllText(fileList.First().FullName);

                        var d = new Differ();
                        var builder = new InlineDiffBuilder(d);
                        resultadoComparacao = builder.BuildDiffModel(textoOriginal, textoMelhor);
                    }
                    else
                    {
                        //Não houve melhor
                        totalLinhasBest = totalLinhas;
                        totalcharsBest = totalchars;
                        tempoFinalComUnload = tempoOriginal;
                        fitFinal = fitOrignal;
                    }

                    rodadas.Add(new RodadaMapper()
                        {
                            Algoritmo = dirGa.Name,
                            Biblioteca = biblioteca.Name,
                            Rodada = currentRow[0],
                            Individuo = currentRow[1],
                            Operacao = currentRow[2],
                            Fitness = fitOrignal,
                            FitnessFinal = fitFinal,
                            TempoOriginalComUnload = tempoOriginal,
                            TempoFinalComUnload = tempoFinalComUnload,
                            Testes = currentRow[5],
                            LocOriginal = totalLinhas,
                            LocFinal = totalLinhasBest,
                            CaracteresOriginal = totalchars,
                            CaracteresFinal = totalcharsBest,
                            Diferencas = resultadoComparacao
                        });
                }
            }

            return rodadas;
        }