Skip to content

Instantly share code, notes, and snippets.

@cagerton
Created September 24, 2020 02:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cagerton/f1eacb6fddd4dd1a0d49d0389f26ea1d to your computer and use it in GitHub Desktop.
Save cagerton/f1eacb6fddd4dd1a0d49d0389f26ea1d to your computer and use it in GitHub Desktop.
Git based diff utility for NodeJS
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