Skip to content

Instantly share code, notes, and snippets.

@dominicgan
Last active June 2, 2024 04:13
Show Gist options
  • Save dominicgan/3838ff74358b9b19bb4ddc5107b7b3a9 to your computer and use it in GitHub Desktop.
Save dominicgan/3838ff74358b9b19bb4ddc5107b7b3a9 to your computer and use it in GitHub Desktop.
Git pre-push branch name validator
/**
* Validate a branch name through the pre-push hook using husky and
* prevent incorrectly formatted branch names from reaching the server.
*/
const fs = require('fs');
const path = require('path');
const SUCCESS_CODE = 0;
const FAILED_CODE = 1;
function getCurrentBranchName(p = process.cwd()) {
const gitHeadPath = `${p}/.git/HEAD`;
return fs.existsSync(p)
? fs.existsSync(gitHeadPath)
? fs
.readFileSync(gitHeadPath, 'utf-8')
.trim()
.split('/')
.slice(2)
.join('/')
: getCurrentBranchName(path.resolve(p, '..'))
: false;
}
const branchNameRegex =
'^((feature|bugfix|hotfix|framework|chore|poc)/(SQ0|SQ1|SQ2)/|release/).+$';
function validateBranchName(branchName) {
return new RegExp(branchNameRegex).test(branchName);
}
const branchToValidate = getCurrentBranchName();
getCurrentBranchName();
if (validateBranchName(branchToValidate)) {
console.info(
'\x1b[32m%s\x1b[0m',
`Success\n` + `Branch name: ${branchToValidate}\n` + `Branch name is valid!`
);
process.exitCode = SUCCESS_CODE;
} else {
console.error(
'\x1b[31m%s\x1b[0m',
`Error\n` +
`Branch name: ${branchToValidate}\n\n` +
`Your branch name is invalid, please use the appropriate branch name format.\n` +
`Acceptable branch name formats are:\n\n` +
`- bugfix/SQ1/name-of-issue\n` +
`- chore/SQ0/name-of-task\n` +
`- feature/SQ1/name-of-feature\n` +
`- hotfix/SQ1/name-of-issue\n` +
`- poc/SQ1/name-of-task\n` +
``
);
process.exitCode = FAILED_CODE;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment