Skip to content

Instantly share code, notes, and snippets.

@jesboat
Created January 16, 2015 03:09
Show Gist options
  • Save jesboat/51504c00499c84a99b8c to your computer and use it in GitHub Desktop.
Save jesboat/51504c00499c84a99b8c to your computer and use it in GitHub Desktop.
deletes branches in a git repo not accessed in the last month
#!/usr/bin/perl
use strict;
use warnings;
use autodie;
use Time::Piece;
use Time::Seconds;
use Getopt::Long;
my $now = localtime;
sub get_recent_branches {
my @branches;
open my($reflog), "git reflog --date=raw |";
while (<$reflog>) {
if (/^(\w+) HEAD\@\{(\d+) /) {
my $then = Time::Piece->new($2);
if ($now - $then > ONE_MONTH) {
next;
}
}
if (/checkout: moving from (\S+) to (\S+)$/) {
push @branches, $2;
}
}
close $reflog;
return @branches;
}
sub list_branches {
my @branches;
open my($git), "git branch |";
while (<$git>) {
m/^[ *] (\S+)$/ or die "couldn't parse branch '$_'";
push @branches, $1;
}
close $git;
return @branches;
}
sub get_old_branches {
my %branches_to_delete;
$branches_to_delete{$_} = 1 foreach list_branches();
delete $branches_to_delete{$_} foreach get_recent_branches();
return keys %branches_to_delete;
}
sub main {
my $dry_run;
GetOptions(
"n|dry-run" => \$dry_run,
) and @ARGV == 0
or die "Usage: $0 [-n | --dry-run]\n";
foreach my $branch (get_old_branches()) {
if ($dry_run) {
print "$branch\n";
} else {
if (system("git", "branch", "-D", "$branch") != 0) {
warn "Failed to delete branch '$branch' (exit code $?)\n";
}
}
}
}
main() unless caller;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment