Debian Codegraph @

bin/circle-parse-yamllog

raw
1 #!/usr/bin/perl
2
3 use strict;
4 use warnings;
5
6 use File::Slurp qw( slurp );
7 use Getopt::Long;
8 use POSIX qw( mktime strftime );
9 use POSIX::strptime qw( strptime );
10 use Text::Balanced qw( extract_bracketed );
11 use YAML qw( LoadFile );
12
13 GetOptions(
14 'timestamp|t=s' => \(my $TIMESTAMP = "%Y/%m/%d %H:%M:%S"),
15 'theme=s' => \(my $THEME = "../circle-fe-term/share/circle-fe-term.theme"), # TODO
16 ) or exit 1;
17
18 my $filename = shift @ARGV; defined $filename or die "Require a filename\n";
19
20 my %theme;
21 {
22 foreach ( slurp $THEME ) {
23 next unless m/^(.*?)=(.*)$/;
24 $theme{$1} = $2;
25 }
26 }
27
28 open my $inh, "<", $filename or
29 die "Cannot read $filename - $!";
30
31 my $headline = <$inh>;
32 my ( $start, $items, $timefmt ) = $headline =~ m/^!LOG START="([^"]+)" ITEMS="([^"]+)" TIMESTAMP_FMT="([^"]+)"$/ or
33 die "Unable to parse headline - is this a yamllog file?\n";
34
35 # The first string part of each log line is formatted as per $timefmt, but
36 # we'll need to know how many spaces it contains in order to strip it
37 my $timere = join " +", ( "\\S+" ) x ( 1 + ( () = $timefmt =~ m/ +/g ) );
38 $timere = qr/$timere/;
39
40 my @startt = ( strptime $start, "%Y/%m/%d %H:%M:%S" )[0..5];
41
42 while( <$inh> ) {
43 my $line = $_; chomp $line;
44 my ( $time, $type, $data ) = $line =~ m/^($timere) +(\S+) +(.*)$/ or
45 die "Unparseable line> $line\n";
46
47 my @thist = strptime $time, $timefmt;
48 $thist[$_] //= $startt[$_] for 0 .. 5;
49 $time = mktime @thist[0..5];
50
51 # YAML::Load doesn't like flow forms at toplevel. Lets cheat
52 $data = YAML::Load( "data: $data" )->{data};
53
54 my $timestamp = strftime $TIMESTAMP, localtime $time;
55
56 my $template = $theme{$type} or (print "<<unrecognised event $type>>\n"), next;
57
58 my $text = process( $template, $data );
59
60 print "$timestamp: $text\n";
61 }
62
63 sub process
64 {
65 my ( $template, $args ) = @_;
66
67 my $ret = "";
68 while( length $template ) {
69 if( $template =~ s/^\$(\w+)// ) {
70 my $val = $args->{$1};
71 my @parts = ref $val eq "ARRAY" ? @$val : ( $val );
72 foreach my $part ( @parts ) {
73 $ret .= ref $part eq "ARRAY" ? $part->[0] : $part;
74 }
75 }
76 elsif( $template =~ m/^{/ ) {
77 my $piece = extract_bracketed( $template, "{}" );
78 s/^{//, s/}$// for $piece;
79
80 my ( $code, $content ) = split( m/ /, $piece, 2 );
81 $ret .= process( $content, $args );
82 }
83 else {
84 $template =~ s/^([^\$\{]+)//;
85 $ret .= $1;
86 }
87 }
88
89 return $ret;
90 }