Skip to content

Instantly share code, notes, and snippets.

@drwpow
Last active March 4, 2022 16:33
Show Gist options
  • Save drwpow/86b11688babd6d1251b90e22ef7354ba to your computer and use it in GitHub Desktop.
Save drwpow/86b11688babd6d1251b90e22ef7354ba to your computer and use it in GitHub Desktop.
List files in Node that have changed between branch and main

Git diff files in Node

Useful for when you want to run a CI job only on files that have changed. Usage:

import { getChangedFiles } from './git-diff.js';

getChangedFiles('main');             // get list of diffs from "main"
getChangedFiles('[current branch]'); // get list of diffs from previous commit

⚠️ Requires git installed on the machine

import { execSync } from 'child_process';
/** get an array of files that have changed between current branch and target branch */
export function getChangedFiles(targetBranch) {
let currentBranch =
process.env.CIRCLE_BRANCH ||
execSync('git rev-parse --abbrev-ref HEAD').toString().trim();
let diff =
currentBranch === targetBranch
? `HEAD..HEAD~1` // if this is the targetBranch, compare previous commit to this
: `${currentBranch}..${targetBranch}`; // otherwise compare latest-to-latest
return execSync(`git --no-pager diff --minimal --name-only ${diff}`)
.toString()
.split('\n')
.map((ln) => ln.trim())
.filter((ln) => !!ln);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment