#!/usr/local/bin/perl -w
###########################################
# karma - travis-ci data reveals
#   developers who broke the build
# Mike Schilli, 2012 (m@perlmeister.com)
###########################################
use strict;
use JSON qw( from_json );
use DateTime;
use DateTime::Format::Strptime;
use Log::Log4perl qw(:easy);
use LWP::Simple qw( get );

Log::Log4perl->easy_init($DEBUG);

my $github_api_url = 
  "https://api.github.com/repos";
my $travis_api_url = 
  "http://travis-ci.org";

my( $repo ) = @ARGV;
die "usage: $0 name/repo" if 
  !defined $repo;

my $build_json = get( 
  "$travis_api_url/$repo/builds.json" );
my $build_data = from_json( $build_json );

my $f = DateTime::Format::Strptime->new(
  pattern   => "%Y-%m-%dT%H:%M:%SZ",
  time_zone => "America/Los_Angeles",
);

my $last_week_dt = DateTime->today(
  time_zone => "local" )->
      add( weeks => -1 );

my %build_breakers = ();

for my $build ( @$build_data ) {

  if( $build->{ result } == 0 ) {
    DEBUG "Build $build->{ commit } ok";
    next;
  }

  my $build_dt = $f->parse_datetime( 
    $build->{ started_at } );

  if( $build_dt < $last_week_dt ) {
    DEBUG "Ignoring old build $build_dt";
  }
        
  my $github_request = 
    "$github_api_url/$repo/commits/" .
    "$build->{ commit }";

  DEBUG "Fetching $github_request";

  my $github_json = get( 
    "$github_api_url/$repo/commits" .
    "/$build->{ commit }" );
  my $github_data = 
    from_json( $github_json );

  my $committer = $github_data->
     { commit }->{ committer }->{ email };

  DEBUG "$committer broke build ",
    "$build->{ commit }";
  $build_breakers{ $committer }++;
}

for my $build_breaker ( 
        sort keys %build_breakers ) {
  print "$build_breaker: ",
    "-$build_breakers{ $build_breaker }\n";
}
