-
-
Save lucthev/f7096f85442ec448cb64 to your computer and use it in GitHub Desktop.
Example usage of the generic-diff module
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
one | |
-two | |
+twos | |
three |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
one | |
two | |
three |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
one | |
twos | |
three |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
'use strict' | |
var diff = require('generic-diff') | |
var fs = require('fs') | |
var os = require('os') | |
// Takes an array of edits containing “one or more” items each, and turns | |
// it into an array of edits with exactly one item per edit. | |
function flatten (changes) { | |
return changes.reduce(function (arr, edit) { | |
return arr.concat(edit.items.map(function (item) { | |
return { | |
item: item, | |
added: edit.added, | |
removed: edit.removed | |
} | |
})) | |
}, []) | |
} | |
// Read two files passed in on the command line, splitting them at | |
// newlines. | |
var before = process.argv[2] | |
before = fs.readFileSync(before, { encoding: 'utf-8' }) | |
before = before.split(/\r?\n/) | |
var after = process.argv[3] | |
after = fs.readFileSync(after, { encoding: 'utf-8' }) | |
after = after.split(/\r?\n/) | |
// Perform the diff. Prepend added lines with a '+', removed lines with | |
// a '-', and unchanged lines with a space. | |
var changes = flatten(diff(before, after)) | |
changes = changes.map(function (edit) { | |
var pre = ' ' | |
if (edit.added) { | |
pre = '+' | |
} else if (edit.removed) { | |
pre = '-' | |
} | |
return pre + edit.item | |
}) | |
// That’s it! | |
console.log(changes.join(os.EOL)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment