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