Skip to content

Instantly share code, notes, and snippets.

@benjroy
Created February 24, 2020 22:42
Show Gist options
  • Save benjroy/507a9a47ca331489841008f615198e5e to your computer and use it in GitHub Desktop.
Save benjroy/507a9a47ca331489841008f615198e5e to your computer and use it in GitHub Desktop.
expectCleanGitRepo
const { execSync } = require('child_process');
function gitStatus(options = {}) {
const {
path = process.cwd(),
// https://git-scm.com/docs/git-status#Documentation/git-status.txt---short
short = false,
// pathspecs to exclude: https://git-scm.com/docs/gitglossary#Documentation/gitglossary.txt-aiddefpathspecapathspec
exclude = [],
} = options;
const excludePathspecs = exclude.map(pathspec => `':(exclude)${pathspec}'`);
const flag = short ? '--short' : '--long';
const command = `git status ${flag} -- . ${excludePathspecs.join(' ')}`;
return execSync(command, { cwd: path }).toString();
}
// options:
// (optional) path = '/path/to/directory' <directory where to run `git status -- .`>
// (optional) exclude = [] list of paths to exclude from git status check
function expectCleanGitRepo(options = {}) {
const { path, exclude } = options;
const shortStatus = gitStatus({ short: true, path, exclude });
if (shortStatus.length === 0) return; // all good, repo is clean!
// prepare a readable error message
const message = `git repo state is not clean`;
const longStatus = gitStatus({ short: false, path, exclude });
throw new Error(`${message}\n\n${longStatus}`);
}
module.exports = expectCleanGitRepo;
@benjroy
Copy link
Author

benjroy commented Feb 24, 2020

posttest:

const expectCleanGitRepo = require('./expectCleanGitRepo');

if (process.env.CI) {
  expectCleanGitRepo({
    path: process.cwd(),
    exclude: ['VERSION'],
  });
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment