The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.
#!/usr/bin/env perl
# Inspired by @trisweb:
# http://github.com/holman/spark/wiki/Wicked-Cool-Usage 

use strict;
use warnings;

use Getopt::Long::Descriptive;
use Encode qw/encode decode/;
use DateTime;
use List::AllUtils qw/max sum/;
use Math::Round qw/round/;
use Term::Spark qw/show_graph/;

binmode STDOUT, ':encoding(UTF-8)';
    
our $VERSION = '0.006'; # VERSION
# PODNAME: git-spark


my ($option, $usage) = describe_options(
    'usage: git spark %o [AUTHOR]',
    ['hours|o=i'      => 'Commits from the last x hours'],
    ['days|d=i'       => 'Commits from the last x days'],
    ['weeks|w=i'      => 'Commits from the last x weeks'],
    ['months|m=i'     => 'Commits from the last x months'],
    ['years|y=i'      => 'Commits from the last x years'],
    ['scale|s=i'      => 'Set the max value of the graph. Use this option to compare this graph with other graphs.'],
    ['help|h'         => 'Show this message'],
);

my $author = $ARGV[0] || $ENV{USER};
my $scale  = $option->scale || 0;

print($usage), exit 0 if $option->help;
print($usage), exit 0 
    if (!$option->hours  && 
        !$option->days   && 
        !$option->weeks  && 
        !$option->months && 
        !$option->years);

foreach my $key (qw/hours days weeks months years/) {
    spark($option->$key, $key, $author, $scale) if $option->$key;
}

sub spark {
    my ($value, $units, $author, $scale) = @_;

    my @data  = countCommits(@_);
    my $total = sum @data;
    my $avg   = round($total / ($#data + 1));
    my $max   = max @data;

    print "Commits by $author over the last $value $units\n";
    print "total: $total   avg: $avg   max: $max\n";
    print join(" ", @data) . "\n";
    print show_graph( max => $max, values => \@data ), "\n";
}

sub countCommits {
    my ($value, $units, $author) = @_;

    my @commits;
    foreach my $i (0..($value - 1)) {
        my $cmd = "git log " .
                  "--author=${author} " .
                  "--before='${i} ${units}' " . 
                  "--after='" . ($i + 1) . " ${units}' " .
                  "--format=oneline | wc -l";
        my $count = `$cmd`;
        chomp($count);
        push @commits, $count;
    }

    return reverse @commits;
}

__END__

=pod

=encoding utf-8

=head1 NAME

git-spark

=head1 DESCRIPTION

See L<App::Git::Spark> for documentation.

=head1 AUTHOR

Eric Johnson <cpan at iijo dot nospamthanks dot org>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2013 by Eric Johnson.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut