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