git-graph: allow user to adjust horizontal scale
[u/fanf2/git-graph.git] / git-graph
CommitLineData
cce87900
TF
1#!/usr/bin/perl
2
3use warnings;
4use strict;
5
6use Getopt::Long qw{:config gnu_getopt posix_default};
37fadc81 7use POSIX;
cce87900
TF
8use Term::ReadKey;
9
10$0 =~ s{^.*/([^/]+)$}{$1};
11
cce87900
TF
12my %opt;
13GetOptions(\%opt, qw{
37fadc81 14 cancel|c
ebb589a0 15 height|h=i
37fadc81
TF
16 overlay|o
17 stack|s
dcf5f346 18 width|w=i
c562dc48 19}) or exit 1;
cce87900 20
22e04a63 21$opt{overlay} = 1 unless $opt{cancel} or $opt{stack};
cce87900 22
37fadc81 23my @terminal = GetTerminalSize;
c562dc48 24my $width = $terminal[0] - 11;
ebb589a0 25my $height = $opt{height} // $terminal[1] - 2;
37fadc81 26
cce87900
TF
27my %add;
28my %del;
29
30my $addmax = 0;
31my $delmax = 0;
32my $canmax = 0;
33
c562dc48
TF
34my $date;
35
36for (qx{git log --pretty=format:%ct --shortstat --since='$height days ago'}) {
37 next if m{^\s*$};
38 if (m{^(\d{10})\n$}) {
39 $date = int ($1 / 86400);
40 next;
41 }
42 m{^\ \d+\ files?\ changed
43 (?:,\ (\d+)\ insertion[s()+]+)?
44 (?:,\ (\d+)\ deletion[s()-]+)?$}x
45 or die "$0: bad stats $_";
cce87900
TF
46 my ($add,$del) = ($1 || 0, $2 || 0);
47 $add{$date} += $add;
48 $del{$date} += $del;
49 $addmax = $add{$date} if $addmax < $add{$date};
50 $delmax = $del{$date} if $delmax < $del{$date};
bceb4717 51 my $can = abs $add{$date} - $del{$date};
cce87900
TF
52 $canmax = $can if $canmax < $can;
53}
54
dcf5f346
TF
55my $max = $opt{width} ? $opt{width} :
56 $opt{cancel} ? $canmax :
cce87900
TF
57 $opt{stack} ? $addmax + $delmax :
58 $addmax > $delmax ? $addmax : $delmax;
cce87900
TF
59my $scale = $width / $max;
60
37fadc81
TF
61my $today = int (time / 86400);
62
63for my $date ($today - $height .. $today) {
d419a729
TF
64 my $add = 0;
65 my $del = 0;
66 my $mod = 0;
37fadc81
TF
67 $add{$date} //= 0;
68 $del{$date} //= 0;
d419a729 69 if ($opt{cancel} or $opt{overlay}) {
cce87900
TF
70 if ($add{$date} > $del{$date}) {
71 $add = $add{$date} - $del{$date};
cce87900
TF
72 } else {
73 $del = $del{$date} - $add{$date};
cce87900
TF
74 }
75 }
76 if ($opt{overlay}) {
d419a729
TF
77 $mod = $add{$date} < $del{$date} ?
78 $add{$date} : $del{$date};
cce87900
TF
79 }
80 if ($opt{stack}) {
81 $add = $add{$date};
82 $del = $del{$date};
cce87900 83 }
37fadc81
TF
84 my $greg = strftime "%b %d %w", localtime $date * 86400;
85 $greg =~ s{(\d)$}{substr "sMTWTFs", $1, 1}e;
dcf5f346 86 my $line = sprintf "$greg \e[33m%s\e[32m%s\e[31m%s\e[0m\n",
37fadc81
TF
87 "#" x ($mod && 1 + $mod * $scale),
88 "+" x ($add && 1 + $add * $scale),
89 "-" x ($del && 1 + $del * $scale);
dcf5f346
TF
90 if (length $line > $width) {
91 $line = sprintf "## %d ##\e[32m++ %d ++\e[31m-- %d --\e[0m\n",
92 $mod, $add, $del;
93 $line = "$greg \e[33m" . "#"x($width + 16 - length $line) . $line;
94 }
95 print $line;
cce87900 96}
cb4ff77a 97printf " \e[33m#\e[0m <- %-8.1f %s %8d ->\n",
bceb4717 98 1/$scale, " " x ($width - 25), $max;