Beispiel #1
1
        static void Main(string[] args)
        {
            string pathfileA = @"C:\xcmpdata\trunk\lineTypeCodeListing.txt";
            string pathfileB = @"C:\xcmpdata\branch\lineTypeCodeListing.txt";

            FileInfo a = new FileInfo(pathfileA);
            FileInfo b = new FileInfo(pathfileB);

            //string s1 = "hello, world - parag,";
            //string s2 = "hello, WXld - parag.";
            StreamReader sra = null;
            StreamReader srb = null;

            try
            {
                //Open Text files for Reading
                sra = a.OpenText();
                string sa = sra.ReadToEnd();
                srb = b.OpenText();
                string sb = srb.ReadToEnd();

                //Pass the strings to be matched for Diff
                DiffMatchPatch.diff_match_patch xdiff = new diff_match_patch();
                List<DiffMatchPatch.Diff> diffs = xdiff.diff_main(sa, sb, true);

                //Print the Diff with content
                string html = xdiff.diff_prettyHtml(diffs);

                string diffFileURI = @"C:\xcmpdata\results\diff.html";
                StreamWriter diffFile = null;
                try
                {
                    diffFile = new StreamWriter(diffFileURI);
                    diffFile.Write(html);
                }
                catch (Exception e)
                {
                    Console.Write("Exception occurred: " + e.InnerException);
                }
                finally
                {
                    diffFile.Close();
                }
            }
            catch (FileNotFoundException fnf)
            {
                Console.WriteLine("File Not found at given location:" + fnf.Message);
            }
            catch (DirectoryNotFoundException dnf)
            {
                Console.WriteLine("Directory Not found at given location:" + dnf.Message);
            }

            Console.WriteLine("xcmp completed finding differences in the given files, Results are available at designated location.");
            Console.ReadKey();
        }
Beispiel #2
0
        public void Diff(string Text1, string Text2)
        {
            this.Text1 = Text1;
            this.Text2 = Text2;

            var dmp = new diff_match_patch();
            var diffs = dmp.diff_main(Text1, Text2);
            Html = dmp.diff_prettyHtml(diffs);

            InsertCount = 0;
            InsertLength = 0;
            DeleteCount = 0;
            DeleteLength = 0;

            foreach (var d in diffs)
            {
                if (d.operation == Operation.INSERT)
                {
                    InsertCount++;
                    InsertLength += d.text.Length;
                }
                if (d.operation == Operation.DELETE)
                {
                    DeleteCount++;
                    DeleteLength += d.text.Length;
                }
            }
        }
Beispiel #3
0
        public static void BaseSentencesCheck(List<Sentence> target, List<Sentence> sample, List<string> errors)
        {
            if (target.Count != sample.Count)
            {
                errors.Add("В файлах для сравнения содержится разное количество предложений");
            }
            else
            {
                var diffEngine = new diff_match_patch();
                for (var i = 0; i < target.Count; ++i)
                {
                    var targetSentece = target[i].Text.ToLower();
                    var sampleSentence = sample[i].Text.ToLower();

                    var diff = diffEngine.diff_main(targetSentece, sampleSentence);

                    if (_isDiffMatters(diff, sampleSentence))
                    {
                        errors.Add(
                            String.Format(
                                "Расхождение в данных (существенное расхождение в {0}-ом по счету предложении). В целевых данных: '{1}', в эталонных данных '{2}'",
                                i, target[i].Text.ToLower(), sample[i].Text.ToLower()));
                    }
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            string left = File.ReadAllText(Server.MapPath("~/Examples/DeOfficiis.txt"));

            string right = File.ReadAllText(Server.MapPath("~/Examples/DeOfficiis_Altered.txt"));
            //string right = File.ReadAllText(Server.MapPath("~/Examples/DeOfficiis_Minor_Altered.txt"));
            //string right = File.ReadAllText(Server.MapPath("~/Examples/TotallyDifferent.txt"));

            GC.Collect(3, GCCollectionMode.Forced); // give the algorithm a fair shot...
            var sw = new System.Diagnostics.Stopwatch();
            sw.Start();

            var differences = new diff_match_patch().diff_main(left, right);

            sw.Stop();

            Repeater1.DataSource = from d in differences
                                   select new {
                                       TypeString = d.operation.ToString(),
                                       SplitPart = HttpContext.Current.Server.HtmlEncode(d.text).Replace("\n", "<br/>")
                                   };

            Repeater1.DataBind();

            Response.Write("Diff-Match-Patch took " + sw.Elapsed.TotalSeconds + " seconds<br/>");
        }
 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();
        }
        public void getChangesTest()
        {
            diff_match_patch testDiff = new diff_match_patch();

            string name = "TestName3.txt", contents = "Here is the contents of the file.";
            Document testDoc = new Document(name, contents);

            string text2 = "Here are the contents of the file.";
            List<Patch> testPatch = testDiff.patch_make(testDoc.FileContents, text2);

            testDoc.changeDocument(testPatch);

            Assert.AreEqual(testDiff.patch_toText(testPatch), testDiff.patch_toText(testDoc.getChanges(0).Values.Last()));
        }
        public void TestConflictResolution(string original, string changeOne, string changeTwo, string expected)
        {
            var patcher = new diff_match_patch();
            var patchOne = patcher.patch_toText(patcher.patch_make(original, changeOne));
            var patchTwo = patcher.patch_toText(patcher.patch_make(original, changeTwo));

            var page = new VersionedWikiPage("test", original);
            var updater = new WikiPageUpdater(patcher);

            updater.ApplyUpdate(page, 0, patchOne);
            updater.ApplyUpdate(page, 0, patchTwo);

            Assert.AreEqual(expected, page.Text);
        }
        public void changeDocumentTest()
        {
            diff_match_patch testDIff = new diff_match_patch();

            string name = "TestName2.txt", contents = "Here is the contents of the file.";
            Document testDoc = new Document(name, contents);

            string text2 = "Here are the contents of the file.";
            List<Patch> testPatch = testDIff.patch_make(testDoc.FileContents, text2);

            testDoc.changeDocument(testPatch);
            testDoc.saveDocument();

            Assert.AreEqual(text2, testDoc.FileContents);
        }
        /// <summary>
        /// Creates a new differential synchronization session on an already established
        /// networking connection.
        /// </summary>
        /// <param name="siteId">The <see cref="SiteId">SiteId</see> for this site.</param>
        /// <param name="context">The <see cref="Context">text context</see> to be operate on.</param>
        /// <param name="connection">The connection that is used to communicate with the other site.</param>
        public DifferentialSynchronizationStrategy(int siteId, ITextContext context, IConnection connection)
        {
            SiteId = siteId;
            DiffMatchPatch =  new diff_match_patch();
            Context = context;
            Connection = connection;
            Shadow = new StringTextContext(context.Data);
            TokenRequestSent = false;

            HasChanged = false;

            TokenState = SiteId == 0 ? TokenState.HavingToken : TokenState.WaitingForToken;

            Connection.Received += ConnectionReceived;
            Context.Changed += ContextChanged;
        }
Beispiel #11
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var text1 = "In the demo they cross out the words that are different and that is what I am trying to achieve.";
            var text2 = "In the they demo cross out the words that are different and that is what I am trying to achieve.";

            var dmp = new diff_match_patch();
            var diffs = dmp.diff_main(text1, text2);
            var html = dmp.diff_prettyHtml(diffs);

            foreach (var d in diffs)
            {
                Result.Text += d.operation.ToString() + ";" + d.text.ToString() + "</br>";
            }

            //Result.Text = html;
        }
  public static void Main(string[] args) {
    string text1 = System.IO.File.ReadAllText("Speedtest1.txt");
    string text2 = System.IO.File.ReadAllText("Speedtest2.txt");

    diff_match_patch dmp = new diff_match_patch();
    dmp.Diff_Timeout = 0;

    // Execute one reverse diff as a warmup.
    dmp.diff_main(text2, text1);
    GC.Collect();
    GC.WaitForPendingFinalizers();

    DateTime ms_start = DateTime.Now;
    dmp.diff_main(text1, text2);
    DateTime ms_end = DateTime.Now;

    Console.WriteLine("Elapsed time: " + (ms_end - ms_start));
  }
        private void cmdCompare_Click(object sender, RoutedEventArgs e)
        {
            List<DiffColor> diffColors=new List<DiffColor>();

            diff_match_patch comparer=new diff_match_patch();
            var result = comparer.diff_main(textEditorA.Text, textEditorB.Text);

            txtResult.Document.Text = "";
            foreach (var diff in result)
            {
                if (diff.operation == Operation.INSERT)
                    diffColors.Add(new DiffColor() { Color = Brushes.Green, StartOffset = txtResult.Document.Text.Length, EndOffset = txtResult.Document.Text.Length + diff.text.Length });
                else if (diff.operation == Operation.DELETE)
                    diffColors.Add(new DiffColor() { Color = Brushes.Red, StartOffset = txtResult.Document.Text.Length, EndOffset = txtResult.Document.Text.Length + diff.text.Length });
                txtResult.Document.Text += diff.text;
            }
            //txtResult.TextArea.TextView.LineTransformers.Clear();
            txtResult.TextArea.TextView.LineTransformers.Add(new DiffColorizer(diffColors));
        }
		/// <summary>
		/// Diff two JSON objects.
		/// 
		/// The output is a JObject that contains enough information to represent the
		/// delta between the two objects and to be able perform patch and reverse operations.
		/// </summary>
		/// <param name="left">The base JSON object</param>
		/// <param name="right">The JSON object to compare against the base</param>
		/// <returns>JSON Patch Document</returns>
		public JToken Diff(JToken left, JToken right)
		{
			if (left == null)
				left = new JValue("");
			if (right == null)
				right = new JValue("");

			if (left.Type == JTokenType.Object && right.Type == JTokenType.Object)
			{
				return ObjectDiff((JObject)left, (JObject)right);
			}

			if (_options.ArrayDiff == ArrayDiffMode.Efficient
				&& left.Type == JTokenType.Array
				&& right.Type == JTokenType.Array)
			{
				return ArrayDiff((JArray)left, (JArray)right);
			}

			if (_options.TextDiff == TextDiffMode.Efficient
				&& left.Type == JTokenType.String
				&& right.Type == JTokenType.String
				&& (left.ToString().Length > _options.MinEfficientTextDiffLength || right.ToString().Length > _options.MinEfficientTextDiffLength))
			{
				var dmp = new diff_match_patch();
				List<Patch> patches = dmp.patch_make(left.ToObject<string>(), right.ToObject<string>());
				return patches.Any()
					? new JArray(dmp.patch_toText(patches), 0, (int)DiffOperation.TextDiff)
					: null;
			}

			if (!JToken.DeepEquals(left, right))
				return new JArray(left, right);

			return null;
		}
        public void UpdateRequestServer_ExistingIsXA1B1A2UpdateRequestXC1_PatchXA1B1A2()
        {
            const string memberIdA = "1";
            const string memberIdB = "2";
            const string memberIdC = "3";
            const string documentId = "MyDoc";
            const string initialContent = "test";
            const string contentA1 = "tests";
            const string contentA2 = "testst";
            const string contentB1 = "testi";
            const string contentC1 = "test ";
            const string contentA1B1 = "testsi";
            const string contentA1B1A2 = "teststi";
            const string resultingContent = "teststi ";
            const string owner = "max";
            const string host = "http://localhost:9000";
            SHA1 sha1 = new SHA1CryptoServiceProvider();
            byte[] initialHash = sha1.ComputeHash(Encoding.UTF8.GetBytes(initialContent));
            byte[] hashA1 = sha1.ComputeHash(Encoding.UTF8.GetBytes(contentA1));
            var diffMatchPath = new diff_match_patch();
            var editor = MockRepository.GenerateStub<SharedTextEditor>();
            editor.Stub(x => x.GetText(documentId)).Return(initialContent).Repeat.Once();
            editor.Stub(x => x.GetText(documentId)).Return(contentA1).Repeat.Once();
            editor.Stub(x => x.GetText(documentId)).Return(contentA1B1).Repeat.Once();
            editor.Stub(x => x.GetText(documentId)).Return(contentA1B1A2).Repeat.Once();
            var communication = MockRepository.GenerateStub<IClientServerCommunication>();

            //act
            var logic = new SharedTextEditorPatchingLogic(owner, host, editor, communication);

            editor.Raise(x => x.FindDocumentRequest += null, editor, documentId);
            logic.OpenDocument(new DocumentDto
            {
                DocumentId = documentId,
                Content = initialContent,
                Owner = owner,
                OwnerHost = host,
                RevisionId = 1
            });

            logic.UpdateRequest(new UpdateDto
            {
                DocumentId = documentId,
                MemberName = memberIdA,
                PreviousHash = initialHash,
                PreviousRevisionId = 1,
                Patch = diffMatchPath.patch_make(initialContent, contentA1)
            });

            logic.UpdateRequest(new UpdateDto
            {
                DocumentId = documentId,
                MemberName = memberIdB,
                PreviousHash = initialHash,
                PreviousRevisionId = 1,
                Patch = diffMatchPath.patch_make(initialContent, contentB1)
            });

            logic.UpdateRequest(new UpdateDto
            {
                DocumentId = documentId,
                MemberName = memberIdA,
                PreviousHash = hashA1,
                PreviousRevisionId = 2,
                Patch = diffMatchPath.patch_make(contentA1, contentA2)
            });

            logic.UpdateRequest(new UpdateDto
            {
                DocumentId = documentId,
                MemberName = memberIdC,
                PreviousHash = initialHash,
                PreviousRevisionId = 1,
                Patch = diffMatchPath.patch_make(initialContent, contentC1)
            });

            //assert
            var args = editor.GetArgumentsForCallsMadeOn(x => x.UpdateText(null, null), x => x.IgnoreArguments());
            Assert.That(args[0][1], Is.EqualTo(initialContent));
            Assert.That(args[1][1], Is.EqualTo(contentA1));
            Assert.That(args[2][1], Is.EqualTo(contentA1B1));
            Assert.That(args[3][1], Is.EqualTo(contentA1B1A2));
            Assert.That(args[4][1], Is.EqualTo(resultingContent));
        }
        public MainWindow()
        {
            //Window for login
            LoginWindow loginWindow = new LoginWindow(this);
            hasLock = false;
            currentTextboxText = "";

            //Starts Windows
            InitializeComponent();
            this.Show();
            loginWindow.ShowDialog();

            //Post Start Area
            //Stops the text from wrapping on its own.
            DocumentText.Document.PageWidth = 10000;

            //Disables to lock options.
            lockRequest.IsEnabled = false;
            releaseLock.IsEnabled = false;

            //Makes document text read only until user creates new file or opens file.
            DocumentText.IsReadOnly = true;

            //diff Match stuff.
            diffMatch = new diff_match_patch();

            //Welcome Message.
            richTextBoxText.AppendText("Welcome to Live Pair Coding Editor!\n");

            //Thread for Messages
            Thread textThread = new Thread(new ThreadStart(getMessages));
            textThread.Start();

            //Thread for document changes
            Thread userThread = new Thread(new ThreadStart(getUsers));
            userThread.Start();

            //Gets the document Changes
            Thread DocChangesThread = new Thread(new ThreadStart(changes));
            DocChangesThread.Start();
        }
Beispiel #17
0
        private void button2_Click(object sender, EventArgs e)
        {
            Func f = ef.FuncList[0];
            Func f1 = ef1.FuncList[0];

            diff_match_patch dfp = new diff_match_patch();
            List<Diff> dfresult = new List<Diff>();
            dfresult = dfp.diff_lineMode(f.BusinFlow.ToString(), f1.BusinFlow.ToString());
            //dfresult = dfp.diff_main("good well \r\ntest", "test well \r\ntest");
             foreach (Diff d in dfresult)
            {
                if (d.operation != Operation.EQUAL)
                {
                    rtbLog.AppendText(d.operation.ToString() + " " + d.text);
                }
            }

            //IDiffer df = new Differ();
            //DiffPlex.Model.DiffResult dfresult = df.CreateLineDiffs(f.BusinFlow.ToString(), f1.BusinFlow.ToString(), false);
            //DiffPlex.Model.d dfresult = df.CreateLineDiffs(f.BusinFlow.ToString(), f1.BusinFlow.ToString(), false);

            // 分析对比结果,怎么分析?
            // 以eques 为分界
            // 到下一个 equas 为止
            // 如何界定多少行
            //

            return;
        }
Beispiel #18
0
        public void ShowDifferenceBetweenTwoFile()
        {
            diff_match_patch DIFF = new diff_match_patch();

            List<Chunk> chunklist1;
            List<Chunk> chunklist2;

            diffs = DIFF.diff_main(richTextBoxCurrentVersion.Text, richTextBoxLastVersion.Text);
            DIFF.diff_cleanupEfficiency(diffs);

            chunklist1 = collectChunks(richTextBoxCurrentVersion);
            chunklist2 = collectChunks(richTextBoxLastVersion);

            paintChunks(richTextBoxCurrentVersion, chunklist1);
            paintChunks(richTextBoxLastVersion, chunklist2);

            richTextBoxCurrentVersion.SelectionLength = 0;
            richTextBoxLastVersion.SelectionLength = 0;

        }
Beispiel #19
0
        private static void Go()
        {
            using (var process = new Process {
                                         StartInfo = new ProcessStartInfo {
                                                                            WorkingDirectory = Directory.GetCurrentDirectory(),
                                                                            UseShellExecute = false,
                                                                            WindowStyle = ProcessWindowStyle.Hidden,
                                                                            FileName = _Runner,
                                                                            Arguments = string.Format("{0} /nologo /output={1} /run={2}", _Assembly, _Output, _Run)
                                                                          }
                                       }) {
            process.Start();
            process.WaitForExit();
            Console.WriteLine("process.ExitCode: {0}", process.ExitCode);

            var xml = File.ReadAllText(_Output);
            var highest = XDocument
              .Parse(xml)
              .XPathSelectElements("//test-case")
              .Where(n => n.Attribute("time") != null)
              .Select(n => new {
                             Name = n.Attribute("name").Value,
                             Time = (int)(decimal.Parse(n.Attribute("time").Value) * 1000)
                           })
              .OrderByDescending(i => i.Time)
              .Take(10)
              .Select(i => string.Format("{0} : {1}", i.Time, string.Join(".", i.Name.Split('.').Reverse().Take(2).Reverse().ToArray())))
              .ToArray();

            Array.ForEach(highest, Console.WriteLine);

            var times = XDocument
              .Parse(xml)
              .XPathSelectElements("//test-case")
              .Where(n => n.Attribute("time") != null)
              .Select(n => decimal.Parse(n.Attribute("time").Value))
              .Select(n => (int)(n * 1000))
              .OrderBy(d => d)
              .ToArray();

            var buckets = new[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

            foreach (var t in times)
              if (t >= 1000)
            ++buckets[19];
              else if (t == 0)
            ++buckets[0];
              else if (t >= 100) {
            var idx = t / 100;
            ++buckets[idx + 9];
              } else {
            var idx = t / 10;
            ++buckets[idx];
              }

            var names = "0-9|10-19|20-29|30-39|40-49|50-59|60-69|70-79|80-89|90-99|100-199|200-299|300-399|400-499|500-599|600-699|700-799|800-899|900-999|1000+".Split('|');

            for (var x = 0; x < names.Length; x++)
              Console.WriteLine("{0,10}:  {1}", names[x], Enumerable.Range(0, buckets[x]).Aggregate("", (c, i) => c + "*"));

            var _CurCount = XDocument
              .Parse(xml)
              .XPathSelectElements("//test-case")
              .Count();

            var delta = _CurCount - _PreviousCount;

            Console.ForegroundColor = delta == 0 ? ConsoleColor.Yellow : delta < 0 ? ConsoleColor.Red : ConsoleColor.Green;
            Console.WriteLine("Count Delta: {0}", delta);
            Console.ResetColor();

            _PreviousCount = _CurCount;

            var counts = XDocument
              .Parse(xml)
              .XPathSelectElements("//test-case")
              .Select(n => n.Attribute("result").Value)
              .GroupBy(s => s, s => s);

            foreach (var ctype in counts) {
              Console.ForegroundColor = ctype.Key == "Success" ? ConsoleColor.Green : ConsoleColor.Red;
              Console.WriteLine("{0}: {1}", ctype.Key, ctype.Count());
              Console.ResetColor();
            }

            var messages = XDocument
              .Parse(xml)
              .XPathSelectElements("//test-case")
              .Where(n => n.Attribute("result") != null)
              .Where(n => n.Attribute("result").Value == "Failure")
              .Select(n => n.XPathSelectElement("./failure/message").Value)
              .Where(s => s.Contains("\"actual\":") && s.Contains("\"expected\":"))
              .Select(s => new {
                             actual = s.Split(new[] {"\"expected\":"}, StringSplitOptions.None)[0],
                             expected = s.Split(new[] {"\"expected\":"}, StringSplitOptions.None)[1]
                           })
              .Select(i => new {
                             actual = i.actual.Split(new[] {"\"actual\":"}, StringSplitOptions.None)[1].TrimEnd(','),
                             expected = i.expected.Substring(0, i.expected.LastIndexOf('}'))
                           })
              .ToArray();

            var differ = new diff_match_patch();
            foreach (var msg in messages) {
              Console.WriteLine("------- ***** -------");
              var diffs = differ.diff_main(msg.actual, msg.expected);

              foreach (var diff in diffs) {
            switch (diff.operation) {
              case Operation.EQUAL:
                break;
              case Operation.INSERT:
                Console.ForegroundColor = ConsoleColor.Green;
                break;
              case Operation.DELETE:
                Console.ForegroundColor = ConsoleColor.Red;
                break;
            }
            Console.Write(diff.text);
            Console.ResetColor();
              }
              Console.WriteLine("------- ***** -------");
            }

            //Console.WriteLine(messages[0].actual);
            //Console.WriteLine("---");
            //Console.WriteLine(messages[0].expected);
              }
        }
Beispiel #20
0
        public double CalculatePercentChanged()
        {
            string page1 = _cache;
            string page2 = Helpers.WebHelper.DownloadWebPage(_url);
            if (page2 == "")
            {
                Error();
                return -1.0;
            }

            diff_match_patch difflib = new diff_match_patch();
            List<Diff> list = difflib.diff_main(page1, page2);

            double levenshtein = difflib.diff_levenshtein(list);
            double length = (page1.Length > page2.Length) ? page1.Length : page2.Length;

            double percentDifferent = levenshtein / length * 100;

            return percentDifferent;
        }
Beispiel #21
0
 private static String GetRevisedTextByDiff(String original, String delta, String revised)
 {
     if (string.Equals(delta, revised) || string.Equals(delta, original))
     {
         return revised;
     }
     // TODO 由于不知道这里的业务逻辑,所以暂时不做处理  ,后续.找到对应的类
     diff_match_patch diff = new diff_match_patch();
     return (String)diff.patch_apply(diff.patch_make(original, delta), revised)[0];
 }
		/// <summary>
		/// Patch a JSON object
		/// </summary>
		/// <param name="left">Unpatched JSON object</param>
		/// <param name="patch">JSON Patch Document</param>
		/// <returns>Patched JSON object</returns>
		/// <exception cref="System.IO.InvalidDataException">Thrown if the patch document is invalid</exception>
		public JToken Patch(JToken left, JToken patch)
		{
			if (patch == null)
				return left;

			if (patch.Type == JTokenType.Object)
			{
				var patchObj = (JObject)patch;
				JProperty arrayDiffCanary = patchObj.Property("_t");

				if (left != null
					&& left.Type == JTokenType.Array
					&& arrayDiffCanary != null
					&& arrayDiffCanary.Value.Type == JTokenType.String
					&& arrayDiffCanary.ToObject<string>() == "a")
				{
					return ArrayPatch((JArray)left, patchObj);
				}

				return ObjectPatch(left as JObject, patchObj);
			}

			if (patch.Type == JTokenType.Array)
			{
				var patchArray = (JArray)patch;

				if (patchArray.Count == 1) // Add
				{
					return patchArray[0];
				}
				else if (patchArray.Count == 2) // Replace
				{
					return patchArray[1];
				}
				else if (patchArray.Count == 3) // Delete, Move or TextDiff
				{
					if (patchArray[2].Type != JTokenType.Integer)
						throw new InvalidDataException("Invalid patch object");

					int op = patchArray[2].Value<int>();

					if (op == 0)
					{
						return null;
					}
					else if (op == 2)
					{
						var dmp = new diff_match_patch();
						List<Patch> patches = dmp.patch_fromText(patchArray[0].ToObject<string>());

						if (patches.Count != 1)
							throw new InvalidDataException("Invalid textline");

						string right = dmp.diff_text2(patches[0].diffs);
						return right;
					}
					else
					{
						throw new InvalidDataException("Invalid patch object");
					}
				}
				else
				{
					throw new InvalidDataException("Invalid patch object");
				}
			}

			return null;
		}
Beispiel #23
0
        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;
        }
        public static string GetDiffHtml(string text1, string text2)
        {
            diff_match_patch dmp = new diff_match_patch();
            dmp.Diff_Timeout = 0;

            var diffs = dmp.diff_main(text1, text2);
            var html = dmp.diff_prettyHtml(diffs);

            return html;
        }
Beispiel #25
0
        private static List<Diff> Compare(IEnumerable<Spell> setA, IEnumerable<Spell> setB, Func<Spell, string> getTextA, Func<Spell, string> getTextB)
        {
            var dmp = new DiffMatchPatch.diff_match_patch();
            var diffs = new List<Diff>();

            // compare the same spell ID in each list one by one, then each line by line
            var A = setA.Where(x => x.ID > 0).OrderBy(x => x.ID).ToList();
            var B = setB.Where(x => x.ID > 0).OrderBy(x => x.ID).ToList();
            int a = 0; // current index in list A
            int b = 0; // current index in list B

            int count = 0;
            int id = 0;
            while (true)
            {
                id++;

                if (a >= A.Count && b >= B.Count)
                    break;

                // reached end of list A, treat remainder of list B as inserts
                if (a >= A.Count)
                {
                    while (b < B.Count)
                        diffs.Add(new Diff(Operation.INSERT, getTextB(B[b++])));
                    break;
                }

                // reached end of list B, treat remainder of list A as deletes
                if (b >= B.Count)
                {
                    while (a < A.Count)
                        diffs.Add(new Diff(Operation.DELETE, getTextA(A[a++])));
                    break;
                }

                // id doesn't exist in either list
                if (A[a].ID > id && B[b].ID > id)
                    continue;

                // id exists in both lists
                if (A[a].ID == id && B[b].ID == id)
                {
                    var textA = getTextA(A[a++]);
                    var textB = getTextB(B[b++]);
                    // ignore equal spells
                    if (textA == textB)
                        continue;
                    diffs.AddRange(dmp.diff_lineMode(textA, textB));
                    count++;
                    continue;
                }

                // id exist only in list A
                if (A[a].ID == id)
                {
                    diffs.Add(new Diff(Operation.DELETE, getTextA(A[a++])));
                    count++;
                    continue;
                }

                // id exists only in list B
                if (B[b].ID == id)
                {
                    diffs.Add(new Diff(Operation.INSERT, getTextB(B[b++])));
                    count++;
                    continue;
                }

                throw new NotImplementedException(); // should never get here
            }

            return diffs;
        }
Beispiel #26
0
        //File Comparison
        static void FileCompare(FileInfo a, FileInfo b, string diffFileURI)
        {
            StreamReader sra = null;
            StreamReader srb = null;
            try
            {
                //Open Text files for Reading
                sra = a.OpenText();
                string sa = sra.ReadToEnd();
                srb = b.OpenText();
                string sb = srb.ReadToEnd();

                //Pass the strings to be matched for Diff
                DiffMatchPatch.diff_match_patch xdiff = new diff_match_patch();
                List<DiffMatchPatch.Diff> diffs = xdiff.diff_main(sa, sb, true);

                //Print the Diff with content
                StringBuilder html = new StringBuilder();
                html.Append("<strong>" + a.DirectoryName + "\\" + a.Name + " compared to " + b.DirectoryName + "\\" + b.Name + "</strong>\n");
                html.Append(xdiff.diff_prettyHtml(diffs));
                StreamWriter diffFile = null;
                try
                {
                    diffFile = File.AppendText(diffFileURI);
                    diffFile.Write(html.ToString());
                }
                catch (Exception e)
                {
                    Console.Write("Exception occurred: " + e.InnerException);
                }
                finally
                {
                    diffFile.Close();
                }
            }
            catch (FileNotFoundException fnf)
            {
                Console.WriteLine("File Not found at given location:" + fnf.Message);
            }
            catch (DirectoryNotFoundException dnf)
            {
                Console.WriteLine("Directory Not found at given location:" + dnf.Message);
            }
        }
Beispiel #27
0
 public WikiPageUpdater(diff_match_patch patcher)
 {
     this.patcher = patcher;
 }
Beispiel #28
0
        private static List <Diff> Compare(IEnumerable <Spell> setA, IEnumerable <Spell> setB, Func <Spell, string> getTextA, Func <Spell, string> getTextB)
        {
            var dmp   = new DiffMatchPatch.diff_match_patch();
            var diffs = new List <Diff>();

            // compare the same spell ID in each list one by one, then each line by line
            var A = setA.Where(x => x.ID > 0).OrderBy(x => x.ID).ToList();
            var B = setB.Where(x => x.ID > 0).OrderBy(x => x.ID).ToList();
            int a = 0; // current index in list A
            int b = 0; // current index in list B

            int count = 0;
            int id    = 0;

            while (true)
            {
                id++;

                if (a >= A.Count && b >= B.Count)
                {
                    break;
                }

                // reached end of list A, treat remainder of list B as inserts
                if (a >= A.Count)
                {
                    while (b < B.Count)
                    {
                        diffs.Add(new Diff(Operation.INSERT, getTextB(B[b++])));
                    }
                    break;
                }

                // reached end of list B, treat remainder of list A as deletes
                if (b >= B.Count)
                {
                    while (a < A.Count)
                    {
                        diffs.Add(new Diff(Operation.DELETE, getTextA(A[a++])));
                    }
                    break;
                }

                // id doesn't exist in either list
                if (A[a].ID > id && B[b].ID > id)
                {
                    continue;
                }

                // id exists in both lists
                if (A[a].ID == id && B[b].ID == id)
                {
                    var textA = getTextA(A[a++]);
                    var textB = getTextB(B[b++]);
                    // ignore equal spells
                    if (textA == textB)
                    {
                        continue;
                    }
                    diffs.AddRange(dmp.diff_lineMode(textA, textB));
                    count++;
                    continue;
                }

                // id exist only in list A
                if (A[a].ID == id)
                {
                    diffs.Add(new Diff(Operation.DELETE, getTextA(A[a++])));
                    count++;
                    continue;
                }

                // id exists only in list B
                if (B[b].ID == id)
                {
                    diffs.Add(new Diff(Operation.INSERT, getTextB(B[b++])));
                    count++;
                    continue;
                }

                throw new NotImplementedException(); // should never get here
            }

            return(diffs);
        }
        private void lstBlocks_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (lstBlocks.SelectedItem != null)
            {
                var blk1 = ((S7FunctionBlock)fld1.GetBlock(lstBlocks.SelectedItem.ToString())).ToString(false);
                var blk2 = ((S7FunctionBlock)fld2.GetBlock(lstBlocks.SelectedItem.ToString())).ToString(false);

                txtResult.TextArea.TextView.LineTransformers.Clear();

                var txt = "";
                diff_match_patch comparer = new diff_match_patch();
                var result = comparer.diff_main(blk1, blk2);

                txtResult.Document.Text = "";
                foreach (var diff in result)
                {
                    if (diff.operation == Operation.INSERT)
                    {
                        var st = txt.Length;
                        txt += diff.text;
                        var stp = txt.Length;

                        txtResult.TextArea.TextView.LineTransformers.Add(new TextColorizer(st, stp, Brushes.Green));
                    }
                    else if (diff.operation == Operation.DELETE)
                    {
                        var st = txt.Length;
                        txt += diff.text;
                        var stp = txt.Length;

                        txtResult.TextArea.TextView.LineTransformers.Add(new TextColorizer(st, stp, Brushes.Red));
                    }
                    else
                    {
                        txt += diff.text;
                    }

                }
                txtResult.Document.Text = txt;

            }
        }
        private void cmdCompare_Click(object sender, RoutedEventArgs e)
        {
            txtResult.TextArea.TextView.LineTransformers.Clear();

            var txt = "";
            diff_match_patch comparer=new diff_match_patch();
            var result = comparer.diff_main(textEditorA.Text, textEditorB.Text);

            txtResult.Document.Text = "";
            foreach (var diff in result)
            {
                if (diff.operation == Operation.INSERT)
                {
                    var st = txt.Length;
                    txt += diff.text;
                    var stp = txt.Length;

                    txtResult.TextArea.TextView.LineTransformers.Add(new TextColorizer(st, stp, Brushes.Green));
                }
                else if (diff.operation == Operation.DELETE)
                {
                    var st = txt.Length;
                    txt += diff.text;
                    var stp = txt.Length;

                    txtResult.TextArea.TextView.LineTransformers.Add(new TextColorizer(st, stp, Brushes.Red));
                }
                else
                {
                    txt += diff.text;
                }

            }
            txtResult.Document.Text = txt;

        }
Beispiel #31
0
        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();
                });
        }