Skip to content

Instantly share code, notes, and snippets.

@adamtaylor
Created June 18, 2019 17:21
Show Gist options
  • Save adamtaylor/d1e86803a2617b29c22b8c328ec99b89 to your computer and use it in GitHub Desktop.
Save adamtaylor/d1e86803a2617b29c22b8c328ec99b89 to your computer and use it in GitHub Desktop.
Script to delete branches that have been rebased before merging and therefore can't be easily identified as merged.
#!perl
use strict;
use warnings;
use feature 'say';
# Very crude argument handling/safety check
say "Usage: $0 for_real # really perform actions";
my $for_real = $ARGV[0];
# Find the unmerged branches
my @branches = `git branch -r --no-merged origin/master`;
say "Checking " . @branches . " branches for deletion";
my @to_del;
my $count = 0;
foreach my $branch ( @branches ) {
chomp $branch;
$branch =~ s/^\s+//g;
# Skip the dev branch, the master branch and the current (*) branch
next if $branch eq 'dev' or $branch eq 'master' or $branch =~ /\*/;
( my $trimmed_branch = $branch ) =~ s/origin\///;
# Look for a commit referencing merging the branch. If it exists, the branch
# is assumed safe for deletion.
#
# The reason we find the branch merged, even though git thinks the branch is
# unmerged, is that the branch was rebased before it was merged - so the
# history and commit hashes were rewritten. The rebased branch was never
# pushed back to the remote so git cannot match up the commits and considers
# it unmerged.
my $commit = `git log origin/master --grep "Merge branch '$trimmed_branch'"`;
# We found the commit merging the branch, go ahead and delete it.
if ( $commit ) {
say $commit;
push @to_del, $branch;
if ( $for_real ) {
say "git branch -d $trimmed_branch";
`git branch -d $trimmed_branch`;
say "git push --delete origin $trimmed_branch";
`git push --delete origin $trimmed_branch`;
}
else {
say "Would have run:";
say "git branch -d $branch";
say "git push --delete origin $trimmed_branch";
}
$count++;
}
}
if ( $for_real) {
say "Deleted $count branches";
}
else {
say "Would have deleted $count branches";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment