cb8a4061c10c5d5bcf68ca9f8154590eb667e0bc
[barcat.git] / graph
1 #!/usr/bin/env perl
2 use 5.014;
3 use warnings;
4 use utf8;
5 use List::Util qw( min max sum );
6 use open qw( :std :utf8 );
7
8 our $VERSION = '1.01';
9
10 use Getopt::Long '2.33', qw( :config gnu_getopt );
11 sub podexit { require Pod::Usage; Pod::Usage::pod2usage(-exitval => 0, @_) }
12 GetOptions(\my %opt,
13         'color|c!',
14         'trim|length|l=i',
15         'markers|m=s',
16         'width|w=i',
17         'usage|h' => sub { podexit() },
18         'help'    => sub { podexit(-verbose => 2) },
19 ) or exit 64;  # EX_USAGE
20 $opt{width} ||= $ENV{COLUMNS} || 80;
21 $opt{color} //= 1;
22
23 my (@lines, @values);
24 while (readline) {
25         chomp;
26         push @values, s/^\h* ( -? [0-9]* (?:\.[0-9]+)? )//x && $1;
27         if (defined $opt{trim}) {
28                 my $trimpos = abs $opt{trim};
29                 if ($trimpos <= 1) {
30                         $_ = substr $_, 0, 1;
31                 }
32                 elsif (length > $trimpos) {
33                         substr($_, $trimpos - 1) = '…';
34                 }
35         }
36         push @lines, $_;
37 }
38 @lines or exit;
39
40 my @order  = sort { $b <=> $a } grep { length } @values;
41 my $maxval = $order[0];
42 my $minval = min $order[-1], 0;
43 my $lenval = max map { length } @order;
44 my $len    = defined $opt{trim} && $opt{trim} <= 0 ? -$opt{trim} + 1 :
45         1 + max map { length } @lines;  # left padding
46 my $size   = ($maxval - $minval) &&
47         ($opt{width} - $lenval - $len) / ($maxval - $minval);  # bar multiplication
48
49 my @barmark;
50 if ($opt{markers} // 1 and $size > 0) {
51         sub orderpos { (($order[$_[0]] + $order[$_[0] + .5]) / 2 - $minval) * $size }
52         $barmark[ (sum(@order) / @order - $minval) * $size ] = '=';  # average
53         $barmark[ orderpos($#order * .31731) ] = '>';
54         $barmark[ orderpos($#order * .68269) ] = '<';
55         $barmark[ orderpos($#order / 2) ] = '+';  # mean
56         $barmark[ -$minval * $size ] = '|' if $minval < 0;  # zero
57         defined and $opt{color} and $_ = "\e[36m$_\e[0m" for @barmark;
58 }
59
60 for my $nr (0 .. $#lines) {
61         my $val = $values[$nr];
62         if (length $val) {
63                 my $color = !$opt{color} ? 0 :
64                         $val == $order[0] ? 32 : # max
65                         $val == $order[-1] ? 31 : # min
66                         90;
67                 printf "\e[%sm", $color if $color;
68                 printf "%*s", $lenval, $val;
69                 print "\e[0m" if $color;
70         }
71         printf '%-*s', $len, $lines[$nr];
72         print $barmark[$_] // '-' for 1 .. $size && (($val || 0) - $minval) * $size;
73         say '';
74 }
75
76 __END__
77
78 =head1 NAME
79
80 graph - append bar chart to input numbers
81
82 =head1 SYNOPSIS
83
84 B<graph> [<options>] [<input>]
85
86 =head1 DESCRIPTION
87
88 Each line starting with a number is given a bar to visualise relative sizes.
89
90 =head1 OPTIONS
91
92 =over
93
94 =item --no-color
95
96 Disable colored output of values and bar markers.
97
98 =item -l, --length=[-]<size>
99
100 Trim line contents (between number and bars)
101 to a maximum number of characters.
102 The exceeding part is replaced by an abbreviation sign,
103 unless C<--length=0>.
104
105 Prepend a dash (i.e. make negative) to enforce padding
106 regardless of encountered contents.
107
108 =item -m, --markers=
109
110 Statistical positions to indicate on bars.
111 Cannot be customized yet,
112 only disabled by providing an empty argument.
113
114 Any value enables all marker characters:
115
116 =over 2
117
118 =item B<=>
119
120 Average:
121 the sum of all values divided by the number of counted lines.
122
123 =item B<+>
124
125 Mean, median:
126 the middle value or average between middle values.
127
128 =item B<<>
129
130 Standard deviation left of the mean.
131 Only 16% of all values are lower.
132
133 =item B<< > >>
134
135 Standard deviation right of the mean.
136 The part between B<< <--> >> encompass all I<normal> results,
137 or 68% of all entries.
138
139 =back
140
141 =item -w, --width=<columns>
142
143 Override the maximum number of columns to use.
144 Appended graphics will extend to fill up the entire screen.
145
146 =back
147
148 =head1 EXAMPLES
149
150 Commonly used after counting, such as users on the current server:
151
152     users | sed 's/ /\n/g' | sort | uniq -c | graph
153
154 Letter frequencies in text files:
155
156     cat /usr/share/games/fortunes/*.u8 |
157     perl -CO -nE 'say for grep length, split /\PL*/, uc' |
158     sort | uniq -c | graph
159
160 Memory usage of user processes:
161
162     ps xo %mem,pid,cmd | graph -l40
163
164 Sizes (in megabytes) of all root files and directories:
165
166     du -d0 -m * | graph
167
168 Number of HTTP requests per day:
169
170     cat log/access.log | cut -d\  -f4 | cut -d: -f1 | uniq -c | graph
171
172 Any kind of database query with leading counts:
173
174     echo 'SELECT count(*),schemaname FROM pg_tables GROUP BY 2' |
175     psql -t | graph
176
177 Git statistics, such commit count by year:
178
179     git log --pretty=%ci | cut -b-4 | uniq -c | graph
180
181 Or the most frequent authors:
182
183     git shortlog -sn | graph | head -3
184
185 =head1 AUTHOR
186
187 Mischa POSLAWSKY <perl@shiar.org>
188
189 =head1 LICENSE
190
191 GPL3+.