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