| 1 | package App::cpm::Logger; | ||
| 2 | use v5.24; | ||
| 3 | use warnings; | ||
| 4 | use experimental qw(lexical_subs signatures); | ||
| 5 | |||
| 6 | use App::cpm::Util 'WIN32'; | ||
| 7 | use List::Util 'max'; | ||
| 8 | |||
| 9 | our $COLOR; | ||
| 10 | our $SILENT; | ||
| 11 | our $VERBOSE; | ||
| 12 | our $SHOW_PROGRESS; | ||
| 13 | |||
| 14 | my %color = ( | ||
| 15 | resolve => 36, | ||
| 16 | fetch => 36, | ||
| 17 | configure => 36, | ||
| 18 | build => 36, | ||
| 19 | test => 36, | ||
| 20 | install => 36, | ||
| 21 | FAIL => 31, | ||
| 22 | DONE => 32, | ||
| 23 | WARN => 33, | ||
| 24 | ); | ||
| 25 | |||
| 26 | our $HAS_WIN32_COLOR; | ||
| 27 | |||
| 28 | sub new ($class, %args) { | ||
| 29 | bless \%args, $class; | ||
| 30 | } | ||
| 31 | |||
| 32 | sub log ($self, %argv) { | ||
| 33 | my $silent = ref $self ? $self->{silent} : $SILENT; | ||
| 34 | return if $silent; | ||
| 35 | |||
| 36 | my $type = $argv{type} || ""; | ||
| 37 | my $message = $argv{message}; | ||
| 38 | chomp $message; | ||
| 39 | my $optional = $argv{optional} ? " ($argv{optional})" : ""; | ||
| 40 | my $result = $argv{result}; | ||
| 41 | my $is_color = ref $self ? $self->{color} : $COLOR; | ||
| 42 | my $verbose = ref $self ? $self->{verbose} : $VERBOSE; | ||
| 43 | my $show_progress = ref $self ? $self->{show_progress} : $SHOW_PROGRESS; | ||
| 44 | |||
| 45 | if ($is_color and WIN32) { | ||
| 46 | if (!defined $HAS_WIN32_COLOR) { | ||
| 47 | $HAS_WIN32_COLOR = eval { require Win32::Console::ANSI; 1 } ? 1 : 0; | ||
| 48 | } | ||
| 49 | $is_color = 0 if !$HAS_WIN32_COLOR; | ||
| 50 | } | ||
| 51 | |||
| 52 | if ($is_color) { | ||
| 53 | $type = "\e[$color{$type}m$type\e[m" if $type && $color{$type}; | ||
| 54 | $result = "\e[$color{$result}m$result\e[m" if $result && $color{$result}; | ||
| 55 | $optional = "\e[1;37m$optional\e[m" if $optional; | ||
| 56 | } | ||
| 57 | |||
| 58 | my $r = $show_progress ? "\r" : ""; | ||
| 59 | if ($verbose) { | ||
| 60 | # type -> 5 + 9 + 3 | ||
| 61 | $type = $is_color && $type ? sprintf("%-17s", $type) : sprintf("%-9s", $type || ""); | ||
| 62 | warn $r . sprintf "%d %s %s %s%s\n", $argv{pid} || $$, $result, $type, $message, $optional; | ||
| 63 | } else { | ||
| 64 | warn $r . join(" ", $result, $type ? $type : (), $message . $optional) . "\n"; | ||
| 65 | } | ||
| 66 | } | ||
| 67 | |||
| 68 | 1; |