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