Remove step check
[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 comment
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=%ad,%s', @{$options->{cmdline}};
67         die "failed to get revs" unless $fd;
68         while (<$fd>) {
69                 chomp;
70                 my ($date, $sub) = split ',', $_, 2;
71
72                 push @commits, str2time($date);
73
74         }
75         close $fd;
76
77         @commits = sort @commits;
78
79         print "...done, " . @commits . " commits.\n";
80
81         my $gap = $commits[$#commits] - $commits[0];
82
83         my $step;
84         if (defined $options->{step}) {
85                 $step = $options->{step};
86         } else {
87                 $step = $gap > $steps{yearly} ? 'monthly' :
88                         $gap > $steps{monthly} ? 'weekly' :
89                         $gap > $steps{weekly}/2 ? 'daily' :
90                         'hourly'
91                 ;
92                 $options->{step} = $step;
93         }
94
95         # truncate each commit (date) to the wanted step
96         # e.g. if the step is 'monthly', then commit YYYY/MM/DD
97         # maps to YYYY/MM
98         my %dataset;
99         for my $commit (@commits) {
100                 my $key;
101                 if (exists $trunc{$step}) {
102                         # LOL -- no, seriously, is there a smarter way to do this?
103                         $key = str2time(strftime($trunc{$step}, localtime($commit)));
104                 } else {
105                         $key = $commit - ($commit % $step);
106                 }
107                 if (exists $dataset{$key}) {
108                         $dataset{$key} += 1;
109                 } else {
110                         $dataset{$key} = 1;
111                 }
112         }
113
114         # fill missing steps and find max
115         my @keys = sort keys %dataset;
116
117         # ensure numeric step, taking into account
118         # that our numerical steps are approximate
119         my $tolerance = 0;
120         if (exists $steps{$step}) {
121                 $step = $steps{$step};
122                 $tolerance = $step/2;
123         }
124
125         my $max = 0;
126         my $key = shift @keys;
127         while (1) {
128                 $max = $dataset{$key} if $max < $dataset{$key};
129                 my $next_step = $key + $step;
130                 my $next = shift @keys;
131                 last unless $next;
132                 while (abs($next - $next_step) > $tolerance) {
133                         # next step is too far away
134                         $dataset{$next_step} = 0;
135                         $next_step += $step;
136                 }
137                 $key = $next;
138         }
139
140         $options->{max} = $max;
141         return \%dataset;
142 }
143
144 # functions to plot the datasets.
145 # each function can be called with either one or two parameters.
146 # when called with two parameters, the first is assumed to be the dataset, and the second the options
147 # (array and hash ref respectively).
148 # when called with a single parameter, it is assumed to be an options hash ref, and the dataset is 
149 # created by calling gather_data with the passed options.
150
151 # google chart API
152 # TODO needs a lot of customization
153 sub google_chart($;$) {
154         my $dataset = shift;
155         my $options = shift;
156         if (! defined $options) {
157                 $options = $dataset;
158                 $dataset = gather_data($options);
159         }
160
161         my $height=$options->{chart_height};
162         my $max = $options->{max};
163
164         my @keys = sort keys %$dataset;
165         my $from = $keys[0];
166         my $to = $keys[@keys-1];
167
168         my @data;
169         while (my $key = shift @keys) {
170                 push @data, $dataset->{$key};
171         }
172
173         my $width=ceil(4*$height/3);
174
175         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";
176
177         my $launch = sprintf $url, join(",",@data);
178         print $launch, "\n";
179         # `git web--browse "$launch"`
180 }
181
182 # gnuplot
183 sub gnuplot_chart($;$) {
184         my $dataset = shift;
185         my $options = shift;
186         if (! defined $options) {
187                 $options = $dataset;
188                 $dataset = gather_data($options);
189         }
190
191         my @keys = sort keys %$dataset;
192         my $step=$options->{step};
193         my $from = $keys[0];
194         my $to = $keys[$#keys];
195
196         my $data = '';
197         while (my $key = shift @keys) {
198                 $data .= "$key $dataset->{$key}\n";
199         }
200         my $max = $options->{max};
201
202         # add a fake datapoint lest to prevent the last
203         # datum from becoming invibile with style data steps
204         if (exists $steps{$step}) {
205                 $to += $steps{$step};
206         } else {
207                 $to += $step;
208         }
209         $data .="$to 0\n";
210
211         # TODO allow customization
212         # in particular, detect (lack of) display and set term to dumb accordingly
213         my $termcmd = $options->{gnuplot_term};
214
215         my $plotsetup = $options->{gnuplot_setup};
216         $plotsetup .= "\nset yrange [0:$max]\n";
217         $plotsetup .= "set xrange ['$from':'$to']\n";
218         my ($formatx, $ticks);
219         if ($to - $from > $steps{yearly}) {
220                 $formatx = "%Y";
221                 $ticks = $steps{yearly};
222         } elsif ($to - $from > $steps{monthly}) {
223                 $formatx = "%b\\n%Y";
224                 $ticks = $steps{monthly};
225         } elsif ($to - $from > 2*$steps{daily}) {
226                 $formatx = "%d\\n%b";
227                 $ticks = $steps{daily};
228         } else {
229                 $formatx = "%H\\n%d";
230                 $ticks = $steps{hourly};
231         }
232         $plotsetup .= "set format x \"$formatx\"\n";
233         $plotsetup .= "set xtics $ticks\n";
234         my $plotstyle = $options->{gnuplot_style};
235         my $plotoptions = $options->{gnuplot_plotwith};
236
237         open my $gp, "|gnuplot -persist";
238
239         my $gp_script = <<GPCMD
240 $termcmd
241 set xdata time
242 set timefmt "%s"
243 $plotsetup
244 $plotstyle
245 plot "-" using 1:2 $plotoptions
246 $data
247 GPCMD
248         ;
249
250         print STDOUT $gp_script;
251         print $gp $gp_script;
252         close $gp;
253 }
254
255 # some defaults
256 my %options = (
257         cmdline => [],
258         # charting/plotting options
259         plotter => \&gnuplot_chart,
260         chart_height => 144,
261         gnuplot_term => '',
262         gnuplot_setup => "set nokey",
263         gnuplot_style => 'set style data steps',
264         gnuplot_plotwith => '',
265 );
266
267 sub parse_step(@) {
268         my $key = shift;
269         my $step = shift;
270         if (exists $steps{$key}) {
271                 $options{step} = $key;
272                 return;
273         }
274         die "this can't happen ($key)" unless $key eq 'step';
275
276         if ($step =~/^\d+$/) {
277                 $options{step} = 0 + $step;
278                 return
279         } else {
280                 if (exists $steps{$step}) {
281                         $options{step} = $step;
282                         return;
283                 }
284                 die "unknown step $step";
285         }
286 }
287
288 my $help = 0;
289 # read our options first
290 Getopt::Long::Configure('pass_through');
291 GetOptions(
292         'hourly' => \&parse_step,
293         'daily' => \&parse_step,
294         'weekly' => \&parse_step,
295         'monthly' => \&parse_step,
296         'yearly' => \&parse_step,
297         'step=s' => sub { parse_step(@_) },
298         'chart-height=i' => sub { $options{chart_height} = $_[1]},
299         google => sub { $options{plotter} = \&google_chart },
300         gnuplot => sub { $options{plotter} = \&gnuplot_chart },
301         'help|?' => \$help,
302 );
303
304 if ($help) {
305         usage();
306         exit;
307 }
308
309 # if anything was left, check for log options
310 if (@ARGV) {
311         $options{cmdline} = \@ARGV;
312 }
313
314 $options{plotter}->(\%options);