Skip to content

Instantly share code, notes, and snippets.

@g3tr1ght
Last active October 9, 2021 02:51
Show Gist options
  • Select an option

  • Save g3tr1ght/0f625b5008073c1788cd3aac67053248 to your computer and use it in GitHub Desktop.

Select an option

Save g3tr1ght/0f625b5008073c1788cd3aac67053248 to your computer and use it in GitHub Desktop.
Git. List files changed since diverging from specific/remote/parent branch. Use it to pipe the result to jest or eslint.
const execFileSync = require('child_process').execFileSync;
const exec = (command, args) => {
console.log('> ' + [command].concat(args).join(' '));
const options = {
cwd: process.cwd(),
env: process.env,
stdio: 'pipe',
encoding: 'utf-8',
};
return execFileSync(command, args, options);
};
const execGitCmd = args =>
exec('git', args)
.trim()
.toString()
.split('\n');
const listChangedFiles = () => {
const mergeBase = execGitCmd(['merge-base', 'HEAD', 'master']);
return new Set([
...execGitCmd(['diff', '--name-only', '--diff-filter=ACMRTUB', mergeBase]),
...execGitCmd(['ls-files', '--others', '--exclude-standard']),
]);
};
module.exports = listChangedFiles;
#!/bin/sh
#
# List files changed since diverging from:
# Specific branch passed as an argument to this script,
# or Upstream branch if upstream branch is present,
# or Parent branch if upstream branch is not present
# Arguments:
# Target branch against which you would like to compare
list_changed_files_diffing_target() {
git diff --name-only $1
}
upstream_exists() {
git ls-remote --heads origin $1
}
list_changed_files_diffing_upstream() {
git diff --name-only $1 origin/$1
}
get_first_checkout_log_for_branch() {
git reflog \
| grep -oE "^([0-9a-f]+).+: checkout: moving from (.+) to $1" \
| tail -n 1
}
get_commit_sha_from_log_entry() {
grep -oE "^[0-9a-f]+" <<< $1
}
list_changed_files_diffing_parent() {
local first_checkout_log_for_branch
first_checkout_log_for_branch="$(get_first_checkout_log_for_branch ${current_branch})"
local commit_sha
commit_sha="$(get_commit_sha_from_log_entry ${first_checkout_log_for_branch})"
local parent_branch
parent_branch="$(sed -nE "s,^([0-9a-f]+).*: checkout: moving from (.+) to ${current_branch}\$,\2,p" <<< ${first_checkout_log_for_branch})"
git diff --name-only ${commit_sha}
}
current_branch="$(git rev-parse --abbrev-ref HEAD)"
target_branch=$1
if [[ -n $target_branch ]]; then
list_changed_files_diffing_target "${target_branch}"
else
if [[ -n "$(upstream_exists ${current_branch})" ]]; then
list_changed_files_diffing_upstream ${current_branch}
else
list_changed_files_diffing_parent
fi
fi
{
"scripts": {
"test:affected": "CHANGED_FILES=$(./list_changed_files.sh) && cross-env NODE_ENV=test node ./node_modules/jest/bin/jest.js --testPathPattern=\"^((?!(ADD_PATTERN_TO_SKIP_TESTS_IF_NEEDED)).)*$\" --passWithNoTests --findRelatedTests $CHANGED_FILES",
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment