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