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