Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save JamieMason/8445356b3600565184adb2c4a071326e to your computer and use it in GitHub Desktop.
Save JamieMason/8445356b3600565184adb2c4a071326e to your computer and use it in GitHub Desktop.
List all remote git branches which have been merged into master and can be safely deleted.
const chalk = require('chalk');
const execa = require('execa');
const SPLIT = '~~~~';
execa('git', [
'for-each-ref',
'--sort=-committerdate',
'--sort=-authoremail',
'refs/remotes/',
'--merged',
'origin/master',
`--format="%(HEAD) %(refname:short)${SPLIT}%(objectname:short)${SPLIT}%(contents:subject)${SPLIT}%(authorname)${SPLIT}%(authoremail)${SPLIT}%(committerdate:relative)"`
])
.then(getLines)
.then(lines => lines.map(readLine))
.then(groupByAuthor)
.then(toArray)
.then(writeReport);
function getLines(result) {
return result.stdout.split('\n')
}
function readLine(line) {
const fields = line.replace(/^"|"$/g, '').trim().split(SPLIT);
return {
shortRefName: fields[0].replace('origin/', ''),
shortObjectName: fields[1],
subject: fields[2],
authorName: fields[3],
authorEmail: fields[4].replace(/>|</g, ''),
relativeCommitterDate: fields[5]
};
}
function groupByAuthor(commits) {
return commits.reduce(function(commitsByAuthorEmail, commit) {
const key = commit.authorEmail.toLowerCase();
(commitsByAuthorEmail[key] = commitsByAuthorEmail[key] || {
authorName: commit.authorName,
authorEmail: commit.authorEmail,
commits: []
});
commitsByAuthorEmail[key].commits.push(commit);
return commitsByAuthorEmail;
}, {});
}
function toArray(object) {
return Object.keys(object).map(key => object[key]);
}
function writeReport(authors) {
authors.forEach(function(author) {
console.log(chalk.yellow('%s %s'), author.authorName, author.authorEmail);
console.log(chalk.grey('git push origin --delete ' + author.commits.map(commit => commit.shortRefName).join(' ')));
console.log('');
author.commits.forEach(function(commit) {
console.log(' %s (%s) %s', commit.shortRefName, commit.relativeCommitterDate, chalk.grey(commit.subject));
});
console.log('');
});
}
@JamieMason
Copy link
Author

Output is something like this but in colour;

Jane Doe [email protected]
git push origin --delete issue-100 issue-96

    issue-100 (4 months ago) Add new feature to product
    issue-96 (5 months ago) Fix some bug in whatever

Jack Pipe [email protected]
git push origin --delete issue-12 issue-90

    issue-12 (3 months ago) Refactor the legacy thing
    issue-90 (5 months ago) Increase performance of core

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