14
Feb 10

Difference engines

Screen shot 2010-02-14 at 9.52.16 AMSo something that I have wanted to put into bildrCode since the start is something called a difference engine. A difference engine takes two files and shows you the difference between them. The really nice thing about implementing something like this into a wiki or bildrCode is that you can quickly see what changes were made in whatever version. See on the right, anything added to the file is highlighted in green, while anything subtracted is crossed out in red.

Early on, I decided to use the one that wikipedia uses. It is free and open source so why not. Ill tell you why not. It is a series of classes and files, and NO documentation at all. The best I could get was to output the differences alone, but out of context. (none of the text that was common between the files)

So how did I do this? PEAR, a class library for PHP has one it turns out. So I just had to get PEAR (already done I found out) setup, and send it what it needed.

Anyone who is reading this because they couldn’t get PEAR’s Text_Diff working… It wants 2 arrays, not strings. In the documentation it has it reading 2 files. I wanted to compare 2 blobs from the database. So you need a way to take those and send it to Text_Diff in a way it wants.

The example from PEAR’s site used “file” to read the files. Checking the docs for PHP’s “file” shows that it reads a file, and splits it into an array using the end of line as the split marker. EG a 10 line long text thing, will be split into a 10 element array (each line in its own part of the array) [0] = first line, [1] – second line etc.

So we need to do the same thing with our blob of text stored in the DB. So after getting both of them (new and old), you want to do a explode on them (separately ) based on the end of a line. First you want to clean all the end of line characters because they come in so many flavors. (\r\n, \n, \r). So we do a simple preg replace to find all 3 of those and replace them with just “\n”s. This way we can split up the text on “\n” and not wonder if it worked.

$current_file = preg_replace('/\r\n|\r/', "\n", $files['code']);
$old_file = preg_replace('/\r\n|\r/', "\n", $files['old_code']);

$current_file = explode("\n", $current_file);
$old_file = explode("\n", $old_file);

So now you have 2 ready-to-go Arrays to work with. No you just need to place them into Text_Diff and it will do the rest.

$diff = new Text_Diff($current_file, $old_file);
$renderer = new Text_Diff_Renderer_inline();

echo $renderer->render($diff);

That’s it. But if you have any questions about this, or need a full working version (wont help you install PEAR though) email me.


Comments are closed.


Copyright © 2010 ASM | a blog
Proudly powered by WordPress, Free WordPress Themes, and Search Marketing