| 1 | #!/usr/bin/env perl | ||
| 2 | |||
| 3 | # | ||
| 4 | # Copyright (C) 2021-2023 Joelle Maslak | ||
| 5 | # All Rights Reserved - See License | ||
| 6 | # | ||
| 7 | |||
| 8 | # PODNAME: router-colorizer.pl | ||
| 9 | # ABSTRACT: Colorize router CLI output | ||
| 10 | |||
| 11 | use v5.22; | ||
| 12 | use strict; | ||
| 13 | use warnings; | ||
| 14 | |||
| 15 | use feature 'signatures'; | ||
| 16 | no warnings 'experimental::signatures'; | ||
| 17 | |||
| 18 | use App::RouterColorizer; | ||
| 19 | |||
| 20 | my $TIMER = 0.01; # Delay to wait for more data, in secs. | ||
| 21 | |||
| 22 | MAIN: { | ||
| 23 | my $colorizer = App::RouterColorizer->new(); | ||
| 24 | |||
| 25 | STDOUT->autoflush(1); | ||
| 26 | STDIN->blocking(0); | ||
| 27 | |||
| 28 | my $buffer = ''; | ||
| 29 | my $rin = ''; | ||
| 30 | vec( $rin, fileno(STDIN), 1 ) = 1; | ||
| 31 | while (1) { | ||
| 32 | select( my $rout = $rin, undef, my $eout = $rin, $TIMER ); | ||
| 33 | if ( vec( $rout, fileno(STDIN), 1 ) || vec( $eout, fileno(STDIN), 1 ) ) { | ||
| 34 | # We have characters to potentially read | ||
| 35 | my $tmp = ''; | ||
| 36 | read STDIN, $tmp, 65535, 0; | ||
| 37 | if ( length($tmp) ) { | ||
| 38 | $buffer .= $tmp; | ||
| 39 | |||
| 40 | # We want to process complete lines only, without a | ||
| 41 | # timeout. | ||
| 42 | my ( $process, $newbuf ) = $buffer =~ m/^ (.*) (\n .*) $/sxx; | ||
| 43 | $buffer = $newbuf // $buffer; | ||
| 44 | |||
| 45 | if ( defined($process) ) { | ||
| 46 | print $colorizer->format_text($process); | ||
| 47 | } elsif ( length($buffer) == 1 ) { | ||
| 48 | # One exception to processing complete lines is | ||
| 49 | # single character buffers - for these, we want to | ||
| 50 | # output the single character quickly to not cause | ||
| 51 | # lag in interactive sessions. | ||
| 52 | print $colorizer->format_text($buffer); | ||
| 53 | $buffer = ''; | ||
| 54 | } | ||
| 55 | } else { | ||
| 56 | # End of file | ||
| 57 | print $colorizer->format_text($buffer) unless $buffer eq ''; | ||
| 58 | exit; | ||
| 59 | } | ||
| 60 | } else { | ||
| 61 | # Timeout! | ||
| 62 | if ( $buffer ne "" ) { | ||
| 63 | print $colorizer->format_text($buffer); | ||
| 64 | $buffer = ""; | ||
| 65 | } | ||
| 66 | } | ||
| 67 | } | ||
| 68 | } | ||
| 69 | |||
| 70 | __END__ |