Created
September 24, 2020 02:01
-
-
Save cagerton/f1eacb6fddd4dd1a0d49d0389f26ea1d to your computer and use it in GitHub Desktop.
Git based diff utility for NodeJS
This file contains hidden or 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
import {join} from 'path'; | |
import fs from "fs"; | |
import os from "os"; | |
import {spawnSync} from "child_process"; | |
/** | |
* Use the local `git` executable to render a diff between two strings. | |
* This is intended for test/development environments. Consider using | |
* `jsdiff` if you need to compare potentially malicious strings. | |
*/ | |
function gitDiffStrings(actual: string, expected: string) { | |
const basePath = path.join(os.tmpdir(), 'node_git_diff_render'); | |
const tmpDir = fs.mkdtempSync(basePath); | |
const actualPath = path.join(tmpDir, 'actual'); | |
const expectedPath = path.join(tmpDir, 'expected'); | |
fs.writeFileSync(actualPath, `${actual}\n`, {mode: 0o600}) | |
fs.writeFileSync(expectedPath, `${expected}\n`, {mode: 0o600}) | |
const res = spawnSync('git', [ | |
'diff', | |
'--no-index', | |
'--color=always', | |
'expected', | |
'actual', | |
], {cwd: tmpDir}); | |
fs.rmdirSync(tmpDir, {recursive: true}); | |
return res.stdout.toString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment