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