blib/lib/IRC/FromANSI/Tiny.pm untested

filter: Statementstmt 0.0% 0 / 54 Branchbran 0.0% 0 / 22 Conditioncond 0.0% 0 / 14 MC/DCmcdc 0.0% 0 / 8 Subroutinesub 0.0% 0 / 4 Podpod 0.0% 0 / 1 totaltotal 0.0% 0 / 103 CC 12 SCAR 48.3
CC
12
Cov
0%
convert
156.0
BEGIN
2.0
BEGIN
2.0
CRAP 125.2
1 package IRC::FromANSI::Tiny;
2 # ABSTRACT: Convert ANSI color codes to IRC
3 our $AUTHORITY = 'cpan:ARODLAND'; # AUTHORITY
4 our $VERSION = '0.02'; # VERSION
5  
6 use strict;
7 use warnings;
8 use Parse::ANSIColor::Tiny;
9  
10 my %irccolors = (
11 black => 1,
12 red => 5,
13 green => 3,
14 yellow => 7,
15 blue => 2,
16 magenta => 6,
17 cyan => 10,
18 white => 14,
19 bright_black => 15,
20 bright_red => 4,
21 bright_green => 9,
22 bright_yellow => 8,
23 bright_blue => 12,
24 bright_magenta => 13,
25 bright_cyan => 11,
26 bright_white => 0,
27 );
28  
29 sub convert {
30 my ($text) = @_;
31 my $ret = "";
32  
33 my $ansi = Parse::ANSIColor::Tiny->new;
34 my $data = $ansi->parse($text);
35 my (%foregrounds, %backgrounds);
36 $foregrounds{$_} = 1 for $ansi->foreground_colors;
37 $backgrounds{$_} = 1 for $ansi->background_colors;
38 my ($foreground, $background, $underline, $bold) = (undef, undef, 0, 0);
39  
40 for my $chunk (@$data) {
41 my ($attrs, $text) = @$chunk;
42 my ($fg) = grep $foregrounds{$_}, @$attrs;
43 my ($bg) = grep $backgrounds{$_}, @$attrs;
44 my $bb = (grep $_ eq 'bold', @$attrs) ? 1 : 0;
45 my $u = (grep $_ eq 'underline', @$attrs) ? 1 : 0;
46  
47 my $set_color;
48 if ($fg) {
49 $foreground = ($b ? 'bright_' : '') . $fg;
50 $set_color = "\cC$irccolors{$foreground}";
51 $bb = 0;
52 }
53 if ($bg) {
54 $background = $bg;
55 $set_color = "\cC" . $irccolors{$foreground || "black"} . ",$irccolors{$background}";
56 }
57 if (!$fg && !$bg && ($foreground || $background)) {
58 undef $foreground;
59 undef $background;
60 if ($text =~ /^\d/) {
61 # Use "reset all" to clear color to avoid a following number
62 # being interpreted as a color code
63 $set_color = "\cO";
64 undef $underline;
65 undef $bold;
66 } else {
67 $set_color = "\cC";
68 }
69 }
70 $ret .= $set_color if length $set_color;
71 if ($bb ^ $bold) {
72 $bold = $bb;
73 $ret .= "\cB";
74 }
75 if ($u ^ $underline) {
76 $underline = $u;
77 $ret .= "\c_";
78 }
79 if ($ret =~ /\D\d$/ && $text =~ /^\d/) {
80 # Avoid a 1-digit color code (e.g. ^C1 or ^C12,3 running into a following
81 # digit that's supposed to be part of the literal text, by making it two-digit.
82 substr($ret, -1, 0, '0');
83 }
84 $ret .= $text;
85 }
86 return $ret;
87 }
88  
89 1;
90  
91 __END__