App-Git-Workflow
view release on metacpan or search on metacpan
lib/App/Git/Workflow/Command/BranchClean.pm view on Meta::CPAN
%option = (
exclude => [],
max_age => ( $ENV{GIT_WORKFLOW_MAX_AGE} || $workflow->config('workflow.max') || 120 ),
tag_prefix => '',
tag_suffix => '',
);
get_options(
\%option,
'remote|r',
'all|a',
'exclude|e=s@',
'exclude_file|exclude-file|f=s',
'max_age|max-age|m=i',
'min_age|min-age|n=i',
'tag|t!',
'tag_prefix|tag-prefix|p=s',
'tag_suffix|tag-suffix|s=s',
'test!',
) or return;
# get the list of branches to look at
my $max = 0;
my @branches = $workflow->branches($option{remote} ? 'remote' : $option{all} ? 'both' : undef );
my @excludes = @{ $option{exclude} };
my $action = 'do_' . ( $ARGV[0] || 'delete' );
my ($total, $deleted) = (0, 0);
if (!$self->can($action)) {
warn "Unknown action $ARGV[0]!\n";
Pod::Usage::pod2usage( %p2u_extra, -verbose => 1 );
return 1;
}
if ($option{exclude_file}) {
for my $exclude ($workflow->slurp($option{exclude_file})) {
chomp $exclude;
next if !$exclude;
next if $exclude =~ /^\s*(?:[#].*)$/xms;
push @excludes, $exclude;
}
}
BRANCH:
for my $branch (@branches) {
# skip master branches
next BRANCH if $branch =~ m{^ (?:[^/]+/)? master $}xms;
next BRANCH if grep {$branch =~ /$_/} @excludes;
# get branch details
my $details = $workflow->commit_details($branch, branches => 0);
# don't delete young branches even if merged
next BRANCH if too_young_to_die($details);
$max = $details->{time} if $max < $details->{time};
$deleted += __PACKAGE__->$action($branch, $details);
$total++;
}
warn "Deleted $deleted of $total branches\nMax = " . (int $max/60/60/24) . "\n";
return;
}
sub do_delete {
my ($self, $branch, $details) = @_;
my $too_old = too_old($details);
my $in_master;
if (!$too_old) {
$in_master = in_master($details);
}
if ( $in_master || $too_old ) {
warn 'deleting ' . ($in_master ? 'merged' : 'old') . " branch $branch\n";
my ($remote, $name) = $branch =~ m{/} ? split m{/}, $branch, 2 : (undef, $branch);
if ( $option{tag} ) {
my $tag = $option{tag_prefix} . $name . $option{tag_suffix};
$workflow->git->tag(qw/-a -m /, "Converting '$name' to the tag '$tag'", $tag) if !$option{test};
}
if ( !$option{test} ) {
if ($remote) {
eval {
$workflow->git->push($remote, '--no-verify', ":refs/heads/$name");
1;
} or do {
return 0;
}
}
else {
$workflow->git->branch('-D', "$name");
}
}
return 1;
}
return 0;
}
sub in_master {
my ($details) = @_;
my %branches = map { $_ => 1 } $workflow->branches('both', $details->{sha});
return $branches{master} || $branches{'origin/master'};
}
sub too_old {
my ($details) = @_;
return if !$option{max_age};
return time - $option{max_age} * 60 * 60 * 24 > $details->{time};
}
( run in 2.675 seconds using v1.01-cache-2.11-cpan-39bf76dae61 )