Skip to content

Instantly share code, notes, and snippets.

@smockle
Created September 17, 2019 02:02
Show Gist options
  • Save smockle/7e5b0ce24852698a3bd067f5fef04b0b to your computer and use it in GitHub Desktop.
Save smockle/7e5b0ce24852698a3bd067f5fef04b0b to your computer and use it in GitHub Desktop.
Output a regular expression which matches branch names _except_ the given name
#!/usr/bin/env node
//@ts-check
const branchName = process.argv[2];
if (!branchName) {
throw new TypeError(`Expected a branch name but did not receive one.`)
}
const validCharactersRegExp = /[a-zA-Z0-9\-\_]/;
const validCharacters = [
[ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" ],
[ "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" ],
[ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" ],
[ "\\\-", "_" ]
];
branchName.split("").forEach(character => {
if (!validCharactersRegExp.test(character)) {
throw new TypeError(`${character} is an unusable character.`);
}
});
branchName.split("").forEach((character, index) => {
const pattern = validCharacters.reduce((acc, characterArray) => {
const index = characterArray.indexOf(character === "-" ? "\\\-" : character);
const firstCharacter = characterArray[0];
const lastCharacter = characterArray[characterArray.length - 1];
const secondCharacter = characterArray[1];
const penultimateCharacter = characterArray[characterArray.length - 2];
const characterBefore = characterArray[index - 1];
const characterAfter = characterArray[index + 1];
const separator = characterArray.length > 2 ? "-" : ""
const pattern = (() => {
switch(true) {
case index === 0:
return `${secondCharacter}${separator}${lastCharacter}`;
case index === characterArray.length - 1:
return `${firstCharacter}${separator}${penultimateCharacter}`;
case index > 0 && index < characterArray.length - 1:
return `${firstCharacter}${separator}${characterBefore}${characterAfter}${separator}${lastCharacter}`;
default:
return `${firstCharacter}${separator}${lastCharacter}`;
}
})();
return `${acc}${pattern}`;
}, "");
console.log(`${branchName.substr(0,index)}[${pattern}]*`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment