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