Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP library to generate code diff (github style)?

Tags:

php

git-diff

diff

I'm looking for an free php library that can generate code diff HTML. Basically just like GitHub's code diffs pages.

I've been searching all around and can't find anything. Does anyone know of anything out there that does what I'm looking for?

like image 549
krische Avatar asked Mar 08 '13 21:03

krische


2 Answers

It looks like I found what I'm looking for after doing more Google searches with different wording.

php-diff seems to do exactly what I want. Just a php function that accepts two strings and generates all the HTML do display the diff in a web page.

like image 120
krische Avatar answered Sep 29 '22 13:09

krische


To add my two cents here...

Unfortunately, there are no really good diff libraries for displaying/generating diffs in PHP. That said, I recently did find a circuitous way to do this using PHP. The solution involved:

  • A pure JavaScript approach for rendering the Diff
  • Shelling out to git with PHP to generate the Diff to render

First, there is an excellent JavaScript library for rendering GitHub-style diffs called diff2html. This renders diffs very cleanly and with modern styling. However diff2html requires a true git diff to render as it is intended to literally render git diffs--just like GitHub.

If we let diff2html handle the rendering of the diff, then all we have left to do is create the git diff to have it render.

To do that in PHP, you can shell out to the local git binary running on the server. You can use git to calculate a diff on two arbitrary files using the --no-index option. You can also specify how many lines before/after the found diffs to return with the -U option.

On the server it would look something like this:

// File names to save data to diff in
$leftFile  = '/tmp/fileA.txt'; 
$rightFile = '/tmp/fileB.txt';

file_put_contents($leftFile, $leftData);
file_put_contents($rightFile, $rightData);

// Generate git diff and save shell output
$diff = shell_exec("git diff -U1000 --no-index $leftFile $rightFile");

// Strip off first line of output
$diff = substr($diff, strpos($diff, "\n"));

// Delete the files we just created
unlink($leftFile);
unlink($rightFile);

Then you need to get $diff back to the front-end. You should review the docs for diff2html but the end result will look something like this in JavaScript (assuming you pass $diff as diffString):

function renderDiff(el, diffString) {
    var diff2htmlUi = new Diff2HtmlUI({diff: diffString});
        diff2htmlUi.draw(el);
}
like image 39
DJ Sipe Avatar answered Sep 29 '22 11:09

DJ Sipe