Last active
September 15, 2021 03:26
-
-
Save allenhwkim/31595030b2cc2214088743a456551f53 to your computer and use it in GitHub Desktop.
Delete all remote stale branches
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 | |
console.log(`************************************************************************* | |
* This script will | |
* 1. Clean up local branches after merge and deleted (git remote prune origin) | |
* 2. Ask you to delete remote your stale branches that are | |
* - more than 3 months old | |
* - and, created by you | |
* To delete all users' stale branches, add --all at the end | |
************************************************************************`); | |
const execSync = require('child_process').execSync; | |
const inquirer = require('inquirer'); | |
const allUsers = process.argv[2] === '--all'; | |
console.log({allUsers}); | |
// Clean up local branches after merge and deleted | |
const result1 = execSync('git remote prune origin', {encoding: 'utf8'}); | |
console.log(result1); | |
const allBranches = execSync('git branch -r', {encoding: 'utf8'}).split('\n').map(el => el.trim()); | |
// Current user name, that will be used to delete only your branches | |
const gitUserName = execSync('git config user.name', {encoding: 'utf8'}); | |
// Get date 3 months ago | |
const maxDate = new Date( | |
new Date().getFullYear(), | |
new Date().getMonth() - 3, | |
new Date().getDate() | |
).toISOString().slice(0, 10) | |
allBranches.reduce( async (previousPromise, branch) => { | |
const resp = await previousPromise; | |
if (resp && resp.delete) { | |
const command = `git push -d ${resp.branch.split('/').join(' ')}`; | |
const result = execSync(command, {encoding: 'utf8'}); | |
console.log(result); | |
} | |
const command = `git log --no-merges -n 1 --format="%an|%cs" ${branch}`; | |
const [userName, date] = execSync(command, {encoding: 'utf8'}).split('|'); | |
const userMatch = allUsers || (userName.trim() === gitUserName.trim()); | |
if (userMatch && date < maxDate) { | |
const answers = await inquirer.prompt([{ | |
type: 'confirm', name: 'delete', | |
message: `Delete ${branch} by ${userName} at ${date}`} | |
]); | |
return Promise.resolve({delete: answers.delete, branch}); | |
} else { | |
return Promise.resolve({}); | |
} | |
}, Promise.resolve()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment