File: Reporter.pm

package info (click to toggle)
libbadger-perl 0.16-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,400 kB
  • sloc: perl: 11,004; makefile: 9
file content (388 lines) | stat: -rw-r--r-- 11,042 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
package Badger::Reporter;

use Badger::Class
    version      => 0.01,
    debug        => 0,
    base         => 'Badger::Base',
    import       => 'class',
    config       => 'verbose=0 quiet=0 nothing|dryrun=0 progress=0 colour|color=1 progress_module|method:PROGRESS_MODULE',
    utils        => 'self_params params xprintf',
    auto_can     => 'auto_can',
    constants    => 'ARRAY HASH BLANK DELIMITER',
    constant     => {
        NO_REASON       => 'no reason given',
        PROGRESS_MODULE => 'Badger::Progress',
    },
    messages     => {
        bad_colour => 'Invalid colour specified for %s event: %s',
    };

use Badger::Debug ':dump';
use Badger::Rainbow
    ANSI   => 'all',
    import => 'strip_ANSI_escapes';

our $COLOURS = {
    bold      => \&bold,
    dark      => \&dark,
    black     => \&black,
    red       => \&red,
    green     => \&green,
    blue      => \&blue,
    cyan      => \&cyan,
    magenta   => \&magenta,
    yellow    => \&yellow,
    grey      => \&grey,
    white     => \&white,
};



#-----------------------------------------------------------------------
# init methods
#-----------------------------------------------------------------------

sub init {
    my ($self, $config) = @_;
    $self->configure($config)
         ->init_events($config)
         ->init_reporter($config);
    return $self;
}


sub init_events {
    my ($self, $config) = @_;
    my $lookup = $self->{ event       } = { };
    my $events = $self->{ events      } = [ ];
    my $names  = $self->{ event_names } = [ ];
    my ($evspec, $event, $name);

    $self->debug("init_events()") if DEBUG;

    # events can be specified as a list ref of 'whitespace delimited string'
    $evspec = $config->{ events } || [ ];
    $evspec = [ split(DELIMITER, $evspec) ]
        unless ref $evspec eq ARRAY;

    $self->debug("event spec: $evspec ==> ", $self->dump_data($evspec)) if DEBUG;

    # now merge it with any events specifed in $EVENTS class variable(s)
    $evspec = $self->class->list_vars( EVENTS => $evspec );

    $self->debug("event spec: ", $self->dump_data($evspec)) if DEBUG;

    foreach (@$evspec) {
        $self->debug("event: $_") if DEBUG;
        $event = $_;            # avoid aliasing
        $event = { name => $event }
            unless ref $event eq HASH;
        $name  = $event->{ name }
            || return $self->error_msg( missing => 'event name' );

        # set some defaults
        $event->{ message } = '%s'    unless defined $event->{ message };
        $event->{ summary } = '%s %s' unless defined $event->{ summary };

        # TODO: is ignoring duplicates the right thing to do?
        next if $lookup->{ $name };

        push(@$names, $name);
        push(@$events, $event);
        $lookup->{ $name } = $event;
    }

    $self->debug("initalised events: ", $self->dump_data($lookup)) if DEBUG;

    return $self;
}


sub init_reporter {
    my ($self, $config) = @_;
    $self->init_stats;
    $self->init_output;
}


sub init_stats {
    my $self = shift;
    $self->{ count } = 0;
    $self->{ stats } = {
        map { $_ => 0 }
        $self->event_names
    };
    return $self;
}


sub init_output {
    my ($self, $config) = @_;
    my ($event, $cols, $col, $colname);

    # fetch a hash table for all the colo(u)rs we know about
    $cols = $self->{ colours } ||= $self->class->hash_vars(
        COLOURS => $config->{ colours } || $config->{ colors }
    );

    if ($self->{ colour }) {
        foreach $event ($self->events) {
            # if the event specifies a colour then change the 'message' and
            # 'summary' output formats to include ANSI escape sequences
            if ($colname = $event->{ colour } || $event->{ color }) {
                $col = $cols->{ $colname }
                    || return $self->error_msg( bad_colour => $event->{ name } => $colname );
                for (qw( message summary )) {
                    $event->{ $_ } = $col->($event->{ $_ }) if $event->{ $_ };
                }
            }
        }
    }
    else {
        # strip any colour that might have been previously added
        foreach $event ($self->events) {
            $event->{ message } = strip_ANSI_escapes($event->{ message });
            $event->{ summary } = strip_ANSI_escapes($event->{ summary });
        }
    }

    return $self;
}


sub init_progress {
    my ($self, $params) = self_params(@_);
    my $module = $self->{ progress_module };
    class($module)->load;
    return $self->{ progress_counter } = $module->new($params);
}

sub progress {
    my $self = shift;
    return  $self->{ progress_counter }
        ||= $self->init_progress(@_);
}

sub tick {
    my $self     = shift;
    my $progress = $self->{ progress_counter } || return;
    return if $self->{ verbose };
    print $progress->pixel;
}

sub tock {
    my $self     = shift;
    my $progress = $self->{ progress_counter } || return;
    return if $self->{ verbose };
    print $progress->remains;
}

#-----------------------------------------------------------------------
# accessor methods
#-----------------------------------------------------------------------

sub event {
    my $self  = shift;
    # TODO: If we allow events to be added then we should also add them to
    # the events/name list.  That suggests that init_events() needs to be
    # cleaved in twain so that we can re-used the event adding code without
    # having to go through the full configuration process which expects a
    # config and merges events from the $EVENTS package variable(s).
    return @_
        ? $self->{ event }->{ $_[0] }
        : $self->{ event };
}


sub events {
    my $self   = shift;
    my $events = $self->{ events };
    return wantarray
        ? @$events
        :  $events;
}


sub event_names {
    my $self = shift;
    my $names = $self->{ event_names };
    return wantarray
        ? @$names
        :  $names;
}


#-----------------------------------------------------------------------
# basic reporting methods
#-----------------------------------------------------------------------

sub report {
    my $self  = shift;
    my $type  = shift
        || return $self->error_msg( missing => 'event type' );
    my $event = $self->{ event }->{ $type }
        || return $self->error_msg( invalid => 'event type' => $type );

    # TODO: Why don't we store the stats in the event?  Saves splitting
    # things up...
    $self->{ stats }->{ $type }++;
    $self->{ count }++;

    # If we're running in quiet mode, or if the event describes itself as
    # being verbose and we're not running in verbose mode, then we return
    # now.  We also return if the event doesn't have a message format.
    return if $self->{ quiet };
    $self->tick;
    return if $event->{ verbose } && ! $self->{ verbose };
    return unless $event->{ message };

    $self->say( xprintf($event->{ message }, @_) );

    return $event->{ return };      # usually undef
}


sub say_msg {
    my $self = shift;
    print $self->message(@_), "\n";
}


sub say {
    my $self = shift;
    print @_, "\n";
}




#-----------------------------------------------------------------------
# auto_can method generator
#-----------------------------------------------------------------------

sub auto_can {
    my ($self, $name) = @_;
    my $event;

    $self->debug("auto_can($name)") if DEBUG;

    if ($name =~ s/_msg$// && ($event = $self->{ event }->{ $name })) {
        return sub {
            my $self = shift;
            $self->report( $name => $self->message(@_) );
        }
    }
    elsif ($event = $self->{ event }->{ $name }) {
        return sub {
            shift->report( $name => @_ );
        }
    }
    elsif (DEBUG) {
        $self->debug("$name is not an event in ", $self->dump_data($self->{ event }));
    }
    return undef;
}



#-----------------------------------------------------------------------
# summary
#-----------------------------------------------------------------------

sub summary {
    my $self  = shift;
    my $stats = $self->{ stats };
    my ($event, $name, $format, $count, @output);

    $self->debug("summary of stats: ", $self->dump_data($stats)) if DEBUG;

    # TODO: no point worrying about being quiet if we're going to say it
    unless ($self->{ quiet }) {
        foreach $event ($self->events) {
            next unless $format = $event->{ summary };
            $name = $event->{ name };
            next unless $count  = $stats->{ $name };
            push(@output, xprintf($format, $count, $count == 1 ? '' : 's', $name) );
        }
    }

#    $self->init_stats;

    return join("\n", @output);
}



#-----------------------------------------------------------------------
# Command line argument parser and help/usage for scripts to use.
# This is a quick hack until Badger::Config is finished.
#-----------------------------------------------------------------------

sub configure_args {
    my $self = shift;
    my @args = @_ == 1 && ref $_[0] eq ARRAY ? @{$_[0]}
             : @_ ? @_
             : @ARGV;

    $self->debug("configure_args(", $self->dump_data(\@args)) if DEBUG;

    return $self->usage     if grep(/--?h(elp)?/, @args);
    $self->{ dryrun   } = 1 if grep(/--?(n(othing)?|dry[-_]?run)/, @args);
    $self->{ verbose  } = 1 if grep(/--?v(erbose)?/, @args);
    $self->{ quiet    } = 1 if grep(/--?q(uiet)?/, @args);
    $self->{ colour   } = 1 if grep(/--?c(olou?r)?/, @args);
    $self->{ summary  } = 1 if grep(/--?s(ummary)?/, @args);
    $self->{ progress } = 1 if grep(/--?p(rogress)?/, @args);

    # Get any extra configuration from the subclass scheme definition
    # NOTE: This only works in immediate subclasses. A more thorough
    # implementation should call list_vars() and deal with everything,
    # thereby eliminating the above code.  However, that's something for
    # Badger::Config
    my $config = $self->class->list_vars('CONFIG');     # may overwrite above
    if ($config) {
        foreach my $item (@$config) {
            my $name = quotemeta $item->{ name };
            $self->{ $name } = 1 if grep(/--?$name/, @args);
            if (DEBUG) {
                $self->debug("CONFIG $name => ", defined($self->{ name }) ? $self->{ name } : '<undef>');
            }
        }
    }

    $self->{ colour  } = 0 if grep(/--?no[-_]?c(olou?r)?/, @args);
    $self->{ colour  } = 0 if grep(/--?white/, @args);

    $self->init_output;

    return $self;
}




sub usage {
    my $options = shift->options_summary;
    die <<EOF;
$0 [options]

Options:
$options
EOF
}

sub options_summary {
    return <<EOF;
  -h  --help                    This help
  -v  --verbose                 Verbose mode (extra output)
  -p  --progress                Progress mode
  -q  --quiet                   Quiet mode (no output)
  -s  --summary                 Print summary at end
  -n  --nothing --dry-run       Dry run - no action performed
  -c  --colour --color          Colourful output
  -nc --no-colour --no-color    Uncolourful output
EOF
}


1;