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