Gather user names too
[git-chart] / git-chart
1 #!/usr/bin/perl
2
3 # List of general TODO
4 # * default to something else than "the whole history", probably
5 # * if no commits are specified and a commit grouping step is specified,
6 #   limit commits proportionally (e.g. --daily => one week worth of commits)
7 # * allow the steps to be counted from the most recent rather than from the
8 #   oldest commit
9
10 use strict;
11 use warnings;
12 use POSIX qw(ceil strftime);
13 use Getopt::Long;
14 use Date::Parse;
15
16 my $SECS_PER_DAY = 24*3600;
17
18 my %steps = (
19         hourly => 3600,
20         daily => $SECS_PER_DAY,
21         weekly => 7*$SECS_PER_DAY,
22         monthly => 30*$SECS_PER_DAY,
23         yearly => 12*30*$SECS_PER_DAY,
24 );
25
26 my %trunc = (
27         hourly => "%Y-%m-%d %H:00",
28         daily => "%Y-%m-%d 00:00",
29         monthly => "%Y-%m-01 00:00",
30         yearly => "%Y-01-01 00:00",
31 );
32
33 sub usage() {
34         # TODO
35         print <<EOU
36 Usage: git chart [options...] [log specs...]
37
38 Creates a chart plotting the distribution over time of the commits
39 specified as <log specs>. By default, commits are grouped by hour, day,
40 week, month or year depending on the time spanned, but this can be
41 controlled by the user.
42
43 Options:
44         --hourly, --daily, --weekly, --monthly, --yearly:
45                 force a specific commit grouping
46         --step=<integer>:
47                 force commits to be grouped each <integer> seconds
48         --gnuplot:
49                 produce a chart with gnuplot (default)
50         --google:
51                 produce a chart with Google Charts
52         --chart-height=<integer>:
53                 set the Google Charts height; the width is set
54                 to a 4:3 ratio (default: 100)
55 EOU
56
57 }
58
59 sub gather_data($) {
60         my $options = shift;
61
62         print "Gathering data ...\n";
63
64         my @commits;
65
66         open my $fd, '-|', qw(git log --date=local), '--pretty=%aN%x00%ad%x00%s', @{$options->{cmdline}};
67         die "failed to get revs" unless $fd;
68         while (<$fd>) {
69                 chomp;
70                 my ($author, $date, $sub) = split '\0', $_, 3;
71
72                 push @commits, { date => str2time($date), author => $author };
73
74         }
75         close $fd;
76
77         @commits = sort { $a->{date} cmp $b->{date} } @commits;
78
79         print "...done, " . @commits . " commits.\n";
80
81         die "No commits!" if (@commits < 1);
82
83         my $gap = $commits[$#commits]->{date} - $commits[0]->{date};
84
85         my $step;
86         if (defined $options->{step}) {
87                 $step = $options->{step};
88         } else {
89                 $step = $gap > $steps{yearly} ? 'monthly' :
90                         $gap > $steps{monthly} ? 'weekly' :
91                         $gap > $steps{weekly}/2 ? 'daily' :
92                         'hourly'
93                 ;
94                 $options->{step} = $step;
95         }
96
97         # truncate each commit (date) to the wanted step
98         # e.g. if the step is 'monthly', then commit YYYY/MM/DD
99         # maps to YYYY/MM
100         my %dataset;
101         for my $commit (@commits) {
102                 my $date = $commit->{date};
103                 my $key;
104                 if (exists $trunc{$step}) {
105                         # LOL -- no, seriously, is there a smarter way to do this?
106                         $key = str2time(strftime($trunc{$step}, localtime($date)));
107                 } elsif ($step eq 'weekly') {
108                         # horrible special case: do it daily, and then subtract
109                         # as many days as necessary to go back to the previous sunday
110                         # TODO config week start
111                         $key = str2time(strftime($trunc{daily}, localtime($date)));
112                         my $wd = strftime("%w", localtime($date));
113                         $key -= $wd*$steps{daily};
114                 } else {
115                         $key = $date - ($date % $step);
116                 }
117                 if (exists $dataset{$key}) {
118                         $dataset{$key} += 1;
119                 } else {
120                         $dataset{$key} = 1;
121                 }
122         }
123
124         # fill missing steps and find max
125         my @keys = sort keys %dataset;
126
127         # ensure numeric step, taking into account
128         # that our numerical steps are approximate
129         my $tolerance = 0;
130         if (exists $steps{$step}) {
131                 $step = $steps{$step};
132                 $tolerance = $step/2;
133         }
134
135         my $max = 0;
136         my $key = shift @keys;
137         while (1) {
138                 $max = $dataset{$key} if $max < $dataset{$key};
139                 my $next_step = $key + $step;
140                 my $next = shift @keys;
141                 last unless $next;
142                 while (abs($next - $next_step) > $tolerance) {
143                         # next step is too far away
144                         $dataset{$next_step} = 0;
145                         $next_step += $step;
146                 }
147                 $key = $next;
148         }
149
150         $options->{max} = $max;
151         return \%dataset;
152 }
153
154 # functions to plot the datasets.
155 # each function can be called with either one or two parameters.
156 # when called with two parameters, the first is assumed to be the dataset, and the second the options
157 # (array and hash ref respectively).
158 # when called with a single parameter, it is assumed to be an options hash ref, and the dataset is 
159 # created by calling gather_data with the passed options.
160
161 # google chart API
162 # TODO needs a lot of customization
163 sub google_chart($;$) {
164         my $dataset = shift;
165         my $options = shift;
166         if (! defined $options) {
167                 $options = $dataset;
168                 $dataset = gather_data($options);
169         }
170
171         my $height=$options->{chart_height};
172         my $max = $options->{max};
173
174         my @keys = sort keys %$dataset;
175         my $from = $keys[0];
176         my $to = $keys[@keys-1];
177
178         my @data;
179         while (my $key = shift @keys) {
180                 push @data, $dataset->{$key};
181         }
182
183         my $width=ceil(4*$height/3);
184
185         my $url="https://chart.googleapis.com/chart?chs=${width}x${height}&cht=bvg&chd=t:%s&chds=0,$max&chbh=a&chxt=y&chxr=0,0,$max";
186
187         my $launch = sprintf $url, join(",",@data);
188         print $launch, "\n";
189         # `git web--browse "$launch"`
190 }
191
192 # gnuplot
193 sub gnuplot_chart($;$) {
194         my $dataset = shift;
195         my $options = shift;
196         if (! defined $options) {
197                 $options = $dataset;
198                 $dataset = gather_data($options);
199         }
200
201         my @keys = sort keys %$dataset;
202         my $step=$options->{step};
203         my $from = $keys[0];
204         my $to = $keys[$#keys];
205
206         my $data = '';
207         while (my $key = shift @keys) {
208                 $data .= "$key $dataset->{$key}\n";
209         }
210         my $max = $options->{max} + 1;
211
212         # add a fake datapoint lest to prevent the last
213         # datum from becoming invibile with style data steps
214         if (exists $steps{$step}) {
215                 $to += $steps{$step};
216         } else {
217                 $to += $step;
218         }
219         $data .="$to 0\n";
220
221         # TODO allow customization
222         # in particular, detect (lack of) display and set term to dumb accordingly
223         my $termcmd = $options->{gnuplot_term};
224
225         my $plotsetup = $options->{gnuplot_setup};
226         $plotsetup .= "\nset yrange [0:$max]\n";
227         $plotsetup .= "set xrange ['$from':'$to']\n";
228         my ($formatx, $ticks);
229         if ($to - $from > $steps{yearly}) {
230                 $formatx = "%Y";
231                 $ticks = $steps{yearly};
232         } elsif ($to - $from > $steps{monthly}) {
233                 $formatx = "%b\\n%Y";
234                 $ticks = $steps{monthly};
235         } elsif ($to - $from > $steps{weekly}/2) {
236                 $formatx = "%d\\n%b";
237                 $ticks = $steps{daily};
238         } else {
239                 $formatx = "%H\\n%d";
240                 $ticks = $steps{hourly};
241         }
242         $plotsetup .= "set format x \"$formatx\"\n";
243         $plotsetup .= "set xtics $ticks\n";
244         my $plotstyle = $options->{gnuplot_style};
245         my $plotoptions = $options->{gnuplot_plotwith};
246
247         open my $gp, "|gnuplot -persist";
248
249         my $gp_script = <<GPCMD
250 $termcmd
251 set xdata time
252 set timefmt "%s"
253 $plotsetup
254 $plotstyle
255 plot "-" using 1:2 $plotoptions
256 $data
257 GPCMD
258         ;
259
260         print STDOUT $gp_script;
261         print $gp $gp_script;
262         close $gp;
263 }
264
265 # some defaults
266 my %options = (
267         cmdline => [],
268         # charting/plotting options
269         plotter => \&gnuplot_chart,
270         chart_height => 144,
271         gnuplot_term => '',
272         gnuplot_setup => "set nokey",
273         gnuplot_style => 'set style data steps',
274         gnuplot_plotwith => '',
275 );
276
277 sub parse_step(@) {
278         my $key = shift;
279         my $step = shift;
280         if (exists $steps{$key}) {
281                 $options{step} = $key;
282                 return;
283         }
284         die "this can't happen ($key)" unless $key eq 'step';
285
286         if ($step =~/^\d+$/) {
287                 $options{step} = 0 + $step;
288                 return
289         } else {
290                 if (exists $steps{$step}) {
291                         $options{step} = $step;
292                         return;
293                 }
294                 die "unknown step $step";
295         }
296 }
297
298 my $help = 0;
299 # read our options first
300 Getopt::Long::Configure('pass_through');
301 GetOptions(
302         'hourly' => \&parse_step,
303         'daily' => \&parse_step,
304         'weekly' => \&parse_step,
305         'monthly' => \&parse_step,
306         'yearly' => \&parse_step,
307         'step=s' => sub { parse_step(@_) },
308         'chart-height=i' => sub { $options{chart_height} = $_[1]},
309         google => sub { $options{plotter} = \&google_chart },
310         gnuplot => sub { $options{plotter} = \&gnuplot_chart },
311         'help|?' => \$help,
312 );
313
314 if ($help) {
315         usage();
316         exit;
317 }
318
319 # if anything was left, check for log options
320 if (@ARGV) {
321         $options{cmdline} = \@ARGV;
322 }
323
324 $options{plotter}->(\%options);