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