f6c3ca18b8e1332196b93025a25b2c2a74660e52
[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 }) or exit 1;
19
20 $opt{overlay} = 1 unless $opt{cancel} or $opt{stack};
21
22 my @terminal = GetTerminalSize;
23 my $width = $terminal[0] - 11;
24 my $height = $opt{height} // $terminal[1] - 2;
25
26 my %add;
27 my %del;
28
29 my $addmax = 0;
30 my $delmax = 0;
31 my $canmax = 0;
32
33 my $date;
34
35 for (qx{git log --pretty=format:%ct --shortstat --since='$height days ago'}) {
36 next if m{^\s*$};
37 if (m{^(\d{10})\n$}) {
38 $date = int ($1 / 86400);
39 next;
40 }
41 m{^\ \d+\ files?\ changed
42 (?:,\ (\d+)\ insertion[s()+]+)?
43 (?:,\ (\d+)\ deletion[s()-]+)?$}x
44 or die "$0: bad stats $_";
45 my ($add,$del) = ($1 || 0, $2 || 0);
46 $add{$date} += $add;
47 $del{$date} += $del;
48 $addmax = $add{$date} if $addmax < $add{$date};
49 $delmax = $del{$date} if $delmax < $del{$date};
50 my $can = abs $add{$date} - $del{$date};
51 $canmax = $can if $canmax < $can;
52 }
53
54 my $max = $opt{cancel} ? $canmax :
55 $opt{stack} ? $addmax + $delmax :
56 $addmax > $delmax ? $addmax : $delmax;
57 my $scale = $width / $max;
58
59 my $today = int (time / 86400);
60
61 for my $date ($today - $height .. $today) {
62 my $add = 0;
63 my $del = 0;
64 my $mod = 0;
65 $add{$date} //= 0;
66 $del{$date} //= 0;
67 if ($opt{cancel} or $opt{overlay}) {
68 if ($add{$date} > $del{$date}) {
69 $add = $add{$date} - $del{$date};
70 } else {
71 $del = $del{$date} - $add{$date};
72 }
73 }
74 if ($opt{overlay}) {
75 $mod = $add{$date} < $del{$date} ?
76 $add{$date} : $del{$date};
77 }
78 if ($opt{stack}) {
79 $add = $add{$date};
80 $del = $del{$date};
81 }
82 my $greg = strftime "%b %d %w", localtime $date * 86400;
83 $greg =~ s{(\d)$}{substr "sMTWTFs", $1, 1}e;
84 printf "$greg \e[33m%s\e[32m%s\e[31m%s\e[0m\n",
85 "#" x ($mod && 1 + $mod * $scale),
86 "+" x ($add && 1 + $add * $scale),
87 "-" x ($del && 1 + $del * $scale);
88 }
89 printf " \e[33m#\e[0m <- %-8.1f %s %8d ->\n",
90 1/$scale, " " x ($width - 25), $max;