Skip to content

Instantly share code, notes, and snippets.

@prabirshrestha
Created November 5, 2010 05:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prabirshrestha/663700 to your computer and use it in GitHub Desktop.
Save prabirshrestha/663700 to your computer and use it in GitHub Desktop.
DiffMatchPatch command line
/* to build:
* download DiffMatchPatch from http://code.google.com/p/google-diff-match-patch/
* then in command line run
* "%WINDIR%\Microsoft.NET\Framework\v3.5\csc.exe" /out:DiffMatchPatch.exe DiffMatchPatch.cs DiffMatchPatchProgram.cs
*
* to create patch:
* DiffMatchPatch.exe file1 file2 destination
* to apply patch
* DiffMatchPatch.exe patch file_to_patch
*/
namespace DiffMatchPatch
{
using System;
using System.IO;
class Program
{
public static int Main(string[] args)
{
if (!(args.Length == 3 || args.Length == 2))
{
Console.WriteLine("usage: to create patch => DiffMatchPatch.exe file1 file2 destination");
Console.WriteLine(" to apply patch => DiffMatchPatch.exe patch file_to_patch");
return 1;
}
if (args.Length == 3)
return CreatePatch(args);
else
return ApplyPatch(args);
}
public static int CreatePatch(string[] args)
{
string text1 = GetFileContents(args[0]);
string text2 = GetFileContents(args[1]);
var diffMatchPatch = new diff_match_patch();
var patches = diffMatchPatch.patch_make(text1, text2);
WriteFile(args[2], diffMatchPatch.patch_toText(patches));
return 0;
}
public static int ApplyPatch(string[] args)
{
var patchText = GetFileContents(args[0]);
var fileToPatch = GetFileContents(args[1]);
var diffMatchPatch = new diff_match_patch();
var patches = diffMatchPatch.patch_fromText(patchText);
var result = diffMatchPatch.patch_apply(patches, fileToPatch);
var boolResult = (bool[])result[1];
foreach (var r in boolResult)
{
if (!r)
{
Console.WriteLine("Applying patch failed");
return 1;
}
}
File.Delete(args[1]);
WriteFile(args[1], result[0].ToString());
return 0;
}
private static string GetFileContents(string path)
{
if (!File.Exists(path))
{
Console.WriteLine(path + " doesn't exisit");
Environment.Exit(1);
}
using (var fs = File.OpenText(path))
{
return fs.ReadToEnd();
}
}
private static void WriteFile(string path, string content)
{
if (File.Exists(path))
{
Console.WriteLine("file already exists");
Environment.Exit(1);
}
File.WriteAllText(path, content);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment