Last active
January 12, 2022 16:55
-
-
Save wesleybliss/7111b06de8a0674490c3f6bd173dd447 to your computer and use it in GitHub Desktop.
Git Prune
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
const shell = require('shelljs') | |
const inquirer = require('inquirer') | |
const chalk = require('chalk') | |
/** | |
* Gets a list of Git branches | |
* | |
* @return {Array[String]} | |
*/ | |
const getBranches = () => { | |
const cmd = [ | |
'git for-each-ref', | |
'--sort=-committerdate', | |
'refs/heads', | |
'--format="%(refname:short)"' | |
].join(' ') | |
const res = shell.exec(cmd, { silent:true }) | |
if (res.code !== 0) { | |
shell.echo('Error: could not list Git branches') | |
shell.exit(1) | |
return process.exit(1) | |
} | |
return res | |
.split('\n') | |
.filter(Boolean) | |
.filter(it => !['master', 'develop'].includes(it)) | |
} | |
const askForBranch = branches => { | |
const questions = [ | |
{ | |
type: 'checkbox', | |
name: 'queue', | |
message: 'Which branches should I delete?', | |
choices: branches, | |
pageSize: 20 | |
} | |
] | |
return inquirer.prompt(questions) | |
} | |
const confirmDeletion = queue => { | |
const questions = [ | |
{ | |
type: 'confirm', | |
name: 'hasConfirmed', | |
message: 'Really delete these branches?\n' + queue.join('\n'), | |
default: false | |
} | |
] | |
return inquirer.prompt(questions) | |
} | |
const deleteBranch = name => { | |
const cmd = `git branch -D ${name}` | |
const res = shell.exec(cmd, { silent:true }) | |
return (res.code === 0) | |
} | |
const start = async () => { | |
const branches = getBranches() | |
const { queue } = await askForBranch(branches) | |
if (!queue || queue.length < 1) { | |
console.info('Cancelled - no branches selected') | |
return process.exit(0) | |
} | |
const { hasConfirmed } = await confirmDeletion(queue) | |
if (!hasConfirmed) { | |
console.info('Cancelled - no branches deleted') | |
return process.exit(0) | |
} | |
console.info('Deleting', queue.length, 'branches...') | |
const success = chalk.green.bold('SUCCESS') | |
const failure = chalk.red.bold('FAILURE') | |
const results = queue.map(it => { | |
const msg = deleteBranch(it) ? success : failure | |
return `${msg} ${it}` | |
}) | |
console.info(results.join('\n')) | |
} | |
start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment