value-length option to override $lenval
[barcat.git] / graph
1 #!/usr/bin/env perl
2 use 5.018;
3 use warnings;
4 use utf8;
5 use List::Util qw( min max sum );
6 use open qw( :std :utf8 );
7 use experimental qw( lexical_subs );
8
9 our $VERSION = '1.02';
10
11 use Getopt::Long '2.33', qw( :config gnu_getopt );
12 sub podexit {
13         require Pod::Usage;
14         Pod::Usage::pod2usage(-exitval => 0, -perldocopt => '-oman', @_);
15 }
16 my %opt;
17 GetOptions(\%opt,
18         'color|c!',
19         'C' => sub { $opt{color} = 0 },
20         'field|f=s',
21         'interval|t:i',
22         'trim|length|l=s' => sub {
23                 my ($optname, $optval) = @_;
24                 $optval =~ s/%$// and $opt{trimpct}++;
25                 $optval =~ m/^-?[0-9]+$/ or die(
26                         "Value \"$optval\" invalid for option $optname",
27                         " (number or percentage expected)\n"
28                 );
29                 $opt{trim} = $optval;
30         },
31         'value-length=i',
32         'markers|m=s',
33         'unmodified|u!',
34         'width|w=i',
35         'usage|h' => sub { podexit() },
36         'help'    => sub { podexit(-verbose => 2) },
37 ) or exit 64;  # EX_USAGE
38
39 $opt{width} ||= $ENV{COLUMNS} || 80;
40 $opt{color} //= -t *STDOUT;  # enable on tty
41 $opt{trim}   *= $opt{width} / 100 if $opt{trimpct};
42
43 if (defined $opt{interval}) {
44         $opt{interval} ||= 1;
45         $SIG{ALRM} = sub {
46                 show_lines();
47                 alarm $opt{interval};
48         };
49         alarm $opt{interval};
50 }
51
52 $SIG{INT} = 'IGNORE';  # continue after assumed eof
53
54 my (@lines, @values);
55 my $anchor = !defined $opt{field} ? qr/\A/ :
56         $opt{field} =~ /^[0-9]+$/ ? qr/(?:\S*\h+){$opt{field}}\K/ :
57         $opt{field};
58 while (readline) {
59         s/\r?\n\z//;
60         s/^\h*// unless $opt{unmodified};
61         push @values, s/$anchor ( \h* -? [0-9]* \.? [0-9]+ |)/\n/x && $1;
62         if (defined $opt{trim}) {
63                 my $trimpos = abs $opt{trim};
64                 if ($trimpos <= 1) {
65                         $_ = substr $_, 0, 1;
66                 }
67                 elsif (length > $trimpos) {
68                         substr($_, $trimpos - 1) = '…';
69                 }
70         }
71         push @lines, $_;
72 }
73
74 $SIG{INT} = 'DEFAULT';
75
76 sub show_lines {
77
78 state $nr = 0;
79 @lines and @lines > $nr or return;
80
81 my @order  = sort { $b <=> $a } grep { length } @values;
82 my $maxval = $order[0];
83 my $minval = min $order[-1], 0;
84 my $lenval = $opt{'value-length'} // max map { length } @order;
85 my $len    = defined $opt{trim} && $opt{trim} <= 0 ? -$opt{trim} + 1 :
86         max map { length $values[$_] && length $lines[$_] } 0 .. $#lines;  # left padding
87 my $size   = ($maxval - $minval) &&
88         ($opt{width} - $lenval - $len) / ($maxval - $minval);  # bar multiplication
89
90 my @barmark;
91 if ($opt{markers} // 1 and $size > 0) {
92         my sub orderpos { (($order[$_[0]] + $order[$_[0] + .5]) / 2 - $minval) * $size }
93         $barmark[ (sum(@order) / @order - $minval) * $size ] = '=';  # average
94         $barmark[ orderpos($#order * .31731) ] = '>';
95         $barmark[ orderpos($#order * .68269) ] = '<';
96         $barmark[ orderpos($#order / 2) ] = '+';  # mean
97         $barmark[ -$minval * $size ] = '|' if $minval < 0;  # zero
98         defined and $opt{color} and $_ = "\e[36m$_\e[0m" for @barmark;
99
100         state $lastmax = $maxval;
101         if ($maxval > $lastmax) {
102                 print ' ' x ($lenval + $len);
103                 printf "\e[90m" if $opt{color};
104                 printf '%-*s',
105                         ($lastmax - $minval) * $size + .5,
106                         '-' x (($values[$nr - 1] - $minval) * $size);
107                 print "\e[92m" if $opt{color};
108                 say '+' x (($maxval - $lastmax - $minval) * $size + .5);
109                 print "\e[0m" if $opt{color};
110                 $lastmax = $maxval;
111         }
112 }
113
114 while ($nr <= $#lines) {
115         my $val = $values[$nr];
116         if (length $val) {
117                 my $color = !$opt{color} ? 0 :
118                         $val == $order[0] ? 32 : # max
119                         $val == $order[-1] ? 31 : # min
120                         90;
121                 $val = sprintf "%*s", $lenval, $val;
122                 $val = "\e[${color}m$val\e[0m" if $color;
123         }
124         my $line = $lines[$nr] =~ s/\n/$val/r;
125         printf '%-*s', $len + length($val), $line;
126         print $barmark[$_] // '-' for 1 .. $size && (($values[$nr] || 0) - $minval) * $size;
127         say '';
128         $nr++;
129 }
130
131 }
132 show_lines();
133
134 __END__
135
136 =head1 NAME
137
138 graph - append bar chart to input numbers
139
140 =head1 SYNOPSIS
141
142 B<graph> [<options>] [<input>]
143
144 =head1 DESCRIPTION
145
146 Visualizes relative sizes of values read from input (file(s) or STDIN).
147 Contents are concatenated similar to I<cat>,
148 but numbers are reformatted and a bar graph is appended to each line.
149
150 =head1 OPTIONS
151
152 =over
153
154 =item -c, --[no-]color
155
156 Force colored output of values and bar markers.
157 Defaults on if output is a tty,
158 disabled otherwise such as when piped or redirected.
159
160 =item -f, --field=(<number>|<regexp>)
161
162 Compare values after a given number of whitespace separators,
163 or matching a regular expression.
164
165 Unspecified or I<-f0> means values are at the start of each line.
166 With I<-f1> the second word is taken instead.
167 A string can indicate the starting position of a value
168 (such as I<-f:> if preceded by colons),
169 or capture the numbers itself,
170 for example I<-f'(\d+)'> for the first digits anywhere.
171
172 =item -t, --interval[=<seconds>]
173
174 Interval time to output partial progress.
175
176 =item -l, --length=[-]<size>[%]
177
178 Trim line contents (between number and bars)
179 to a maximum number of characters.
180 The exceeding part is replaced by an abbreviation sign,
181 unless C<--length=0>.
182
183 Prepend a dash (i.e. make negative) to enforce padding
184 regardless of encountered contents.
185
186 =item -m, --markers=
187
188 Statistical positions to indicate on bars.
189 Cannot be customized yet,
190 only disabled by providing an empty argument.
191
192 Any value enables all marker characters:
193
194 =over 2
195
196 =item B<=>
197
198 Average:
199 the sum of all values divided by the number of counted lines.
200
201 =item B<+>
202
203 Mean, median:
204 the middle value or average between middle values.
205
206 =item B<<>
207
208 Standard deviation left of the mean.
209 Only 16% of all values are lower.
210
211 =item B<< > >>
212
213 Standard deviation right of the mean.
214 The part between B<< <--> >> encompass all I<normal> results,
215 or 68% of all entries.
216
217 =back
218
219 =item -u, --unmodified
220
221 Do not strip leading whitespace.
222 Keep original value alignment, which may be significant in some programs.
223
224 =item --value-length=<size>
225
226 Reserved space for numbers.
227
228 =item -w, --width=<columns>
229
230 Override the maximum number of columns to use.
231 Appended graphics will extend to fill up the entire screen.
232
233 =back
234
235 =head1 EXAMPLES
236
237 Commonly used after counting, such as users on the current server:
238
239     users | sed 's/ /\n/g' | sort | uniq -c | graph
240
241 Letter frequencies in text files:
242
243     cat /usr/share/games/fortunes/*.u8 |
244     perl -CO -nE 'say for grep length, split /\PL*/, uc' |
245     sort | uniq -c | graph
246
247 Memory usage of user processes:
248
249     ps xo %mem,pid,cmd | graph -l40
250
251 Sizes (in megabytes) of all root files and directories:
252
253     du -d0 -m * | graph
254
255 Number of HTTP requests per day:
256
257     cat log/access.log | cut -d\  -f4 | cut -d: -f1 | uniq -c | graph
258
259 Any kind of database query with leading counts:
260
261     echo 'SELECT count(*),schemaname FROM pg_tables GROUP BY 2' |
262     psql -t | graph -u
263
264 Exchange rate USD/EUR history from CSV download provided by ECB:
265
266     curl https://sdw.ecb.europa.eu/export.do \
267          -Gd 'node=SEARCHRESULTS&q=EXR.D.USD.EUR.SP00.A&exportType=csv' |
268     grep '^[12]' | graph -f',\K' --value-length=7
269
270 Total population history from the World Bank dataset (XML):
271
272     curl http://api.worldbank.org/v2/country/1W/indicator/SP.POP.TOTL |
273     xmllint --xpath '//*[local-name()="date" or local-name()="value"]' - |
274     sed -r 's,</wb:value>,\n,g; s,(<[^>]+>)+, ,g' | graph -f1
275
276 Movies per year from prepared JSON data:
277
278     curl https://github.com/prust/wikipedia-movie-data/raw/master/movies.json |
279     jq '.[].year' | uniq -c | graph
280
281 Pokémon height comparison:
282
283         curl https://github.com/Biuni/PokemonGO-Pokedex/raw/master/pokedex.json |
284         jq -r '.pokemon[] | [.height,.num,.name] | join(" ")' | graph
285
286 Git statistics, such commit count by year:
287
288     git log --pretty=%ci | cut -b-4 | uniq -c | graph
289
290 Or the most frequent authors:
291
292     git shortlog -sn | graph | head -3
293
294 Latency history:
295
296     ping google.com | graph -f'time=\K' -t
297
298 =head1 AUTHOR
299
300 Mischa POSLAWSKY <perl@shiar.org>
301
302 =head1 LICENSE
303
304 GPL3+.