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