3-way merge in JavaScript or PHP

2.7k Views Asked by At

Does anyone know of an Open Source three-way merge implementation in JavaScript or PHP? I want to merge plain text files without the need to rely on any server side binaries.

I found a few solutions for creating diffs, but no merge implementations.

4

There are 4 best solutions below

1
On BEST ANSWER
1
On

Not exactly three-way merge, but Google's "Diff Match and Patch libraries offer robust algorithms to perform the operations required for synchronizing plain text". And the implementation is available in Java, JavaScript, C++, C#, Lua and Python.

1
On

After finding that the npm packages 3-way-merge and three-way-merge (the main ones that show up in search results for "three way merge npm") didn't work well, and are not maintained, I stumbled upon this much larger more helpful

https://www.npmjs.com/package/diff3

We ended up writing our solution like so:

var diff3 = require('diff3');
var mergeData = diff3(sourceArray, originalArray, targetArray);

var result = mergeData.map(({ok, conflict}) => {
  if (ok) {
    return ok;
  }
  else if (conflict) {
    return [
      '<<<<<<< target',
      ...conflict.b,
      '>>>>>>> target',
      '<<<<<<< source',
      ...conflict.a,
      '>>>>>>> source'
    ];
  }
}).flat();
0
On

Just finished my work on such a js- and php-tool. Have a look and enjoy:

https://github.com/Krassmus/Textmerger

You'd just need to write

var merged = Textmerger.get().merge(original, mytext, theirtext);

or in PHP

$merged = Textmerger::get()->merge($original, $mytext, $theirtext);

and you're done.