Pipeline/CSV.pm

filter: Statementstmt 100% 236 / 236 Branchbran 100% 142 / 142 Conditioncond 100% 68 / 68 MC/DCmcdc 100% 42 / 42 Subroutinesub 100% 55 / 55 Podpod 100% 2 / 2 totaltotal 100% 545 / 545 CC 99 SCAR 16.6
CC
99
Cov
100%
_options
11.0
_encoding
11.0
_check_header
10.0
CRAP 5.3
« Pipeline/Sugar.pm ↑ Summary Pipeline/JSON.pm »
1 5 ▶use v5.36;
Subroutine BEGIN: called CC=1 SCAR=0.0
2  
3 package Ekorn::Pipeline::CSV;
4  
5 5 ▶use experimental qw(builtin try);
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 5 ▶use builtin qw(blessed);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 5 ▶use Encode qw();
Subroutine BEGIN: called CC=1 SCAR=0.0
9 5 ▶use Exporter qw(import);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 5 ▶use PerlIO::encoding qw();
Subroutine BEGIN: called CC=1 SCAR=0.0
11 5 ▶use Ref::Util qw(
Subroutine BEGIN: called CC=1 SCAR=0.0
12 is_plain_arrayref is_plain_coderef is_plain_hashref
13 5 is_plain_ref);
14 5 ▶use Scalar::Util qw(openhandle);
Subroutine BEGIN: called CC=1 SCAR=0.0
15 5 ▶use Ekorn::Pipeline::Errors qw(croakf);
Subroutine BEGIN: called CC=1 SCAR=0.0
16 5 ▶use Ekorn::Pipeline::Factories qw(gather sink_one source stage);
Subroutine BEGIN: called CC=1 SCAR=0.0
17 5 ▶use namespace::clean -except => 'import';
Subroutine BEGIN: called CC=1 SCAR=0.0
18  
19 5 our $VERSION = 'v0.3.16';
20  
21 5 our @EXPORT_OK = qw(from_csv to_csv);
22 5 our %EXPORT_TAGS = (all => \@EXPORT_OK);
23  
24 # Croak at the line that called Ekorn::Pipeline.
25 5 our @CARP_NOT = @Ekorn::Pipeline::Errors::INTERNAL;
26  
27 # Text::CSV's code for the end of its input, which isn't an error.
28 5 my $EOF = 2012;
29  
30 # What a file's encoding does with text it can't decode or encode:
31 # croak, rather than warn and carry on.
32 5 my $STRICT = Encode::FB_CROAK() | Encode::STOP_AT_PARTIAL();
33  
34 # Each way of munging a header's names that's named, as Text::CSV's
35 # munge_column_names has them.
36 my %MUNGE = (
37 5 ▶ lc => sub ($name) { lc $name },
Subroutine __ANON__: called CC=1 SCAR=0.0
38 4 ▶ uc => sub ($name) { uc $name },
Subroutine __ANON__: called CC=1 SCAR=0.0
39 6 ▶ db => sub ($name) { lc($name =~ s( \W+ )(_)xgr =~ s( \A _+ )()xr) },
Subroutine __ANON__: called CC=1 SCAR=0.0
40 5 none => undef,
41 );
42  
43 # A source of the rows read from the file or filehandle. Given neither,
44 # a stage parsing each value, a text of any number of rows, into its
45 # rows.
46 87 ▶sub from_csv (@options) {
Subroutine from_csv: called CC=2 SCAR=6.9
Pod documented
47 87 my %option = _options(
48 'from_csv', [qw(file fh csv header munge encoding)], @options,
49 );
50 67 ▶ return _reader(\%option) if _has_input(\%option);
Branch: 1 branch
BranchTrueFalseTotal
if _has_input(\%option) 52 15 67
51 15 my($csv, $header, $munge) = ($option{new}->(), @option{qw(header munge)});
52 16 ▶ return stage {
Subroutine __ANON__: called CC=2 SCAR=6.9
53 16 my($next) = _table(
54 $csv, Ekorn::Pipeline::CSV::Text->new($_), 'a value',
55 $header, $munge,
56 );
57 16 my @rows;
58 16 ▶ while (my $row = $next->()) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = &$next()) 17 15 32
59 17 push @rows, $row;
60 }
61 15 return @rows;
62 15 };
63 }
64  
65 # A sink writing each row to the file or filehandle, giving how many.
66 # Given neither, a stage passing on each row as its line, without its
67 # end of line, after the header's, if it has one.
68 54 ▶sub to_csv (@options) {
Subroutine to_csv: called CC=3 SCAR=11.0
Pod documented
69 54 my %option = _options('to_csv', [qw(file fh csv header encoding)], @options);
70 36 ▶ return _writer(\%option) if _has_input(\%option);
Branch: 1 branch
BranchTrueFalseTotal
if _has_input(\%option) 20 16 36
71 16 my($csv, $header) = ($option{new}->(), $option{header});
72 16 ▶ unless ($header) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($header) 7 9 16
73 7 my($line) = _formatter($csv, $header, 'chars');
74 7 ▶ return stage { $line->($_) };
Subroutine __ANON__: called CC=1 SCAR=0.0
75 }
76 9 ▶ return gather {
Subroutine __ANON__: called CC=1 SCAR=0.0
77 9 my($line, $head) = _formatter($csv, $header, 'chars'); # this run's names
78 9 my $first = 1;
79 return (
80 # For each row, without a signature: the header's line first.
81 8 ▶ sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
82 8 ▶ return $line->($_[0]) unless $first;
Branch: 1 branch
BranchTrueFalseTotal
unless $first 2 6 8
83 6 $first = 0;
84 6 return ($head->(), $line->($_[0]));
85 },
86 8 ▶ sub () { return $first ? $head->() : () }, # no rows: the header
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
$first ? : 3 5 8
87 9 );
88 9 };
89 }
90  
91 # Return the options given, checked, with "new", a sub returning the
92 # parser, and "encoding", a file's, as _encoding gives it. Load
93 # Text::CSV first.
94 141 ▶sub _options ($function, $known, @given) {
Subroutine _options: called CC=11 SCAR=24.0
95 141 _load($function);
96 137 ▶ croakf 'Expected options as name => value pairs' if @given % 2;
Branch: 1 branch
BranchTrueFalseTotal
if @given % 2 2 135 137
97 135 my %option = @given;
98 135 my %allowed = map { $_ => 1 } @$known;
99 135 my @unknown = sort grep { !$allowed{$_} } keys %option;
100 135 ▶ croakf 'Expected the options %s, not %s',
Branch: 1 branch
BranchTrueFalseTotal
if @unknown 2 133 135
101 join(', ', @$known[0 .. $#$known - 1]) . " and $known->[-1]", join ', ',
102 @unknown
103 if @unknown;
104 croakf 'Expected file to be a path'
105 133 ▶ if exists $option{file} && !defined $option{file};
Branch: 1 branch
BranchTrueFalseTotal
if exists $option{"file"} and not defined $option{"file"} 2 131 133
Condition100%3/3
exists $option{"file"} and not defined $option{"file"}
!ll&&!rl&&r
55762
MC/DC100%2/2
exists $option{"file"} and not defined $option{"file"}
exists $option{"file"} not defined $option{"file"}
Truth table100%3/3
A and not(B)
A= exists $option{"file"}B= not defined $option{"file"}
ABresult
0X0
100
111
106 croakf 'Expected a file or a filehandle, not both'
107 131 ▶ if defined $option{file} && exists $option{fh};
Branch: 1 branch
BranchTrueFalseTotal
if defined $option{"file"} and exists $option{"fh"} 2 129 131
Condition100%3/3
defined $option{"file"} and exists $option{"fh"}
!ll&&!rl&&r
55742
MC/DC100%2/2
defined $option{"file"} and exists $option{"fh"}
defined $option{"file"} exists $option{"fh"}
Truth table100%3/3
A and B
A= defined $option{"file"}B= exists $option{"fh"}
ABresult
0X0
100
111
108 croakf 'Expected an open filehandle'
109 129 ▶ if exists $option{fh} && !defined openhandle($option{fh});
Branch: 1 branch
BranchTrueFalseTotal
if exists $option{"fh"} and not defined &openhandle($option{"fh"}) 2 127 129
Condition100%3/3
exists $option{"fh"} and not defined &openhandle($option{"fh"})
!ll&&!rl&&r
12162
MC/DC100%2/2
exists $option{"fh"} and not defined &openhandle($option{"fh"})
exists $option{"fh"} not defined &openhandle($option{"fh"})
Truth table100%3/3
A and not(B)
A= exists $option{"fh"}B= not defined &openhandle($option{"fh"})
ABresult
0X0
100
111
110 127 $option{encoding} = _encoding(\%option);
111 117 _check_header(\%option, $function);
112 111 ▶ $option{munge} = _munger(\%option) if exists $option{munge};
Branch: 1 branch
BranchTrueFalseTotal
if exists $option{"munge"} 13 98 111
113 107 ▶ my $raw = defined $option{encoding} && !ref $option{encoding}; # the only one not an object
Condition100%3/3
defined $option{'encoding'} && !ref($option{'encoding'})
!ll&&!rl&&r
39653
MC/DC100%2/2
defined $option{'encoding'} && !ref($option{'encoding'})
defined $option{'encoding'} !ref($option{'encoding'})
Truth table100%3/3
A && not(B)
A= defined $option{'encoding'}B= !ref($option{'encoding'})
ABresult
0X0
100
111
114 107 $option{new} = _parser($option{csv}, $raw);
115 103 return %option;
116 }
117  
118 # Load Text::CSV, croaking for the function given if it can't be.
119 141 ▶sub _load ($function) {
Subroutine _load: called CC=3 SCAR=11.0
120 141 ▶ return if eval { require Text::CSV; 1 };
Branch: 1 branch
BranchTrueFalseTotal
if eval { do { require Text::CSV; 1 } } 137 4 141
121 4 my $error = $@;
122 4 ▶ return croakf q(Can't find Text::CSV, which %s needs; install it from CPAN),
Branch: 1 branch
BranchTrueFalseTotal
if $error =~ m[ \A Can't\ locate\ Text/CSV\.pm\ in\ \@INC ]ux 2 2 4
123 $function
124 if $error =~ m( \A Can't\ locate\ Text/CSV\.pm\ in\ \@INC )x;
125 2 return croakf q(Can't load Text::CSV, which %s needs: %s), $function,
126 $error =~ s( \s* \n .* )()xsr;
127 }
128  
129 # Return a file's encoding: 'raw', for bytes, or Encode's object for the
130 # one named, UTF-8 if none is. Only a file is opened, so only a file
131 # takes one.
132 127 ▶sub _encoding ($option) {
Subroutine _encoding: called CC=11 SCAR=24.0
133 127 ▶ return unless defined $option->{file} || exists $option->{encoding};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $option->{"file"} or exists $option->{"encoding"} 49 78 127
Condition100%3/3
defined $option->{"file"} or exists $option->{"encoding"}
l!l&&r!l&&!r
74449
MC/DC100%2/2
defined $option->{"file"} or exists $option->{"encoding"}
defined $option->{"file"} exists $option->{"encoding"}
Truth table100%3/3
A or B
A= defined $option->{"file"}B= exists $option->{"encoding"}
ABresult
1X1
011
000
134 78 ▶ my $encoding = exists $option->{encoding} ? $option->{encoding} : 'UTF-8';
Branch: 1 branch
BranchTrueFalseTotal
exists $option->{'encoding'} ? : 16 62 78
135 78 ▶ croakf 'Expected encoding only with a file' unless defined $option->{file};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $option->{"file"} 4 74 78
136 74 ▶ return 'raw' if defined $encoding && $encoding eq 'raw';
Branch: 1 branch
BranchTrueFalseTotal
if defined $encoding and $encoding eq "raw" 3 71 74
Condition100%3/3
defined $encoding and $encoding eq "raw"
!ll&&!rl&&r
2693
MC/DC100%2/2
defined $encoding and $encoding eq "raw"
defined $encoding $encoding eq "raw"
Truth table100%3/3
A and B
A= defined $encodingB= $encoding eq "raw"
ABresult
0X0
100
111
137 71 ▶ my $found = !ref $encoding && Encode::find_encoding($encoding // q());
Condition100%5/5
!ref($encoding) && &Encode::find_encoding(scalar($encoding // ''))
!ll&&!rl&&r
2465
$encoding // ""
l!l
672
MC/DC100%2/2
!ref($encoding) && &Encode::find_encoding(scalar($encoding // ''))
!ref($encoding) &Encode::find_encoding(scalar($encoding // ''))
MC/DC100%1/1
$encoding // ""
$encoding
Truth table100%3/3
not(A) && B
A= !ref($encoding)B= &Encode::find_encoding(scalar($encoding // ''))
ABresult
0X0
100
111
Truth table100%2/2
A
A= $encoding
Aresult
11
00
138 71 ▶ croakf 'Expected an encoding Perl knows, not %s', $encoding // 'undef'
Branch: 1 branch
BranchTrueFalseTotal
unless $found 6 65 71
Condition100%2/2
$encoding // "undef"
l!l
42
MC/DC100%1/1
$encoding // "undef"
$encoding
Truth table100%2/2
A
A= $encoding
Aresult
11
00
139 unless $found;
140 65 return $found;
141 }
142  
143 # Croak unless the header is one the function takes: true, false, or
144 # 'skip' to read; true, false, or an array of names to write.
145 117 ▶sub _check_header ($option, $function) {
Subroutine _check_header: called CC=10 SCAR=23.0
146 117 my $header = $option->{header};
147 117 ▶ return if !defined $header || (!ref $header && $header =~ m( \A [01]? \z )x);
Branch: 1 branch
BranchTrueFalseTotal
if not defined $header or not ref $header and $header =~ / \A [01]? \z /ux 96 21 117
Condition100%6/6
not defined $header or not ref $header and $header =~ / \A [01]? \z /ux
l!l&&r!l&&!r
504621
not ref $header and $header =~ / \A [01]? \z /ux
!ll&&!rl&&r
13846
MC/DC100%3/3
not defined $header or not ref $header and $header =~ / \A [01]? \z /ux
not defined $header not ref $header $header =~ / \A [01]? \z /ux
Truth table100%4/4
not(A) or not(B) and C
A= not defined $headerB= not ref $headerC= $header =~ / \A [01]? \z /ux
ABCresult
1XX1
0111
00X0
0100
148 21 ▶ if ($function eq 'from_csv') {
Branch: 1 branch
BranchTrueFalseTotal
if ($function eq "from_csv") 8 13 21
149 8 ▶ croakf q(Expected header to be true, false or 'skip')
Branch: 1 branch
BranchTrueFalseTotal
if ref $header or $header ne "skip" 2 6 8
Condition100%3/3
ref $header or $header ne "skip"
l!l&&r!l&&!r
116
MC/DC100%2/2
ref $header or $header ne "skip"
ref $header $header ne "skip"
Truth table100%3/3
A or B
A= ref $headerB= $header ne "skip"
ABresult
1X1
011
000
150 if ref $header || $header ne 'skip';
151 6 return;
152 }
153 croakf q(Expected header to be true, false or an array reference of names)
154 13 ▶ if !is_plain_arrayref($header) || grep { !defined || ref } @$header;
Branch: 1 branch
BranchTrueFalseTotal
if not Ref::Util::XS::is_plain_arrayref($header) or grep {not defined $_ or ref $_;} @$header 4 9 13
Condition100%6/6
not Ref::Util::XS::is_plain_arrayref($header) or grep {not defined $_ or ref $_;} @$header
l!l&&r!l&&!r
229
!defined($_) || ref $_
l!l&&r!l&&!r
1120
MC/DC100%2/2
not Ref::Util::XS::is_plain_arrayref($header) or grep {not defined $_ or ref $_;} @$header
not Ref::Util::XS::is_plain_arrayref($header) grep {not defined $_ or ref $_;} @$header
MC/DC100%2/2
!defined($_) || ref $_
!defined($_) ref $_
Truth table100%3/3
not(A) or B
A= not Ref::Util::XS::is_plain_arrayref($header)B= grep {not defined $_ or ref $_;} @$header
ABresult
1X1
011
000
Truth table100%3/3
not(A) || B
A= !defined($_)B= ref $_
ABresult
1X1
011
000
155 9 return;
156 }
157  
158 # Return a sub munging a header's name as munge says, or nothing, for a
159 # munge of none.
160 13 ▶sub _munger ($option) {
Subroutine _munger: called CC=7 SCAR=19.5
161 13 my $munge = $option->{munge};
162 13 ▶ croakf 'Expected munge only with a header' unless $option->{header};
Branch: 1 branch
BranchTrueFalseTotal
unless $option->{"header"} 1 12 13
163 12 ▶ if (is_plain_coderef($munge)) {
Branch: 1 branch
BranchTrueFalseTotal
if (Ref::Util::XS::is_plain_coderef($munge)) 1 11 12
164 1 ▶ return sub ($name) { local $_ = $name; $munge->($name) };
Subroutine __ANON__: called CC=1 SCAR=0.0
165 }
166 11 ▶ if (is_plain_hashref($munge)) {
Branch: 1 branch
BranchTrueFalseTotal
if (Ref::Util::XS::is_plain_hashref($munge)) 1 10 11
167 1 ▶ return sub ($name) { exists $munge->{$name} ? $munge->{$name} : $name };
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
exists $munge->{$name} ? : 1 2 3
168 }
169 croakf
170 'Expected munge to be lc, uc, db, none, a hash reference or a code reference'
171 10 ▶ if ref $munge || !exists $MUNGE{$munge // q()};
Branch: 1 branch
BranchTrueFalseTotal
if ref $munge or not exists $MUNGE{$munge // ""} 3 7 10
Condition100%5/5
ref $munge or not exists $MUNGE{$munge // ""}
l!l&&r!l&&!r
127
$munge // ""
l!l
81
MC/DC100%2/2
ref $munge or not exists $MUNGE{$munge // ""}
ref $munge not exists $MUNGE{$munge // ""}
MC/DC100%1/1
$munge // ""
$munge
Truth table100%3/3
A or not(B)
A= ref $mungeB= not exists $MUNGE{$munge // ""}
ABresult
1X1
011
000
Truth table100%2/2
A
A= $munge
Aresult
11
00
172 7 return $MUNGE{$munge};
173 }
174  
175 # Return a sub returning the parser: one made from csv's options, over
176 # the defaults, or csv's object, as it is. Reading a file raw, the
177 # parser leaves bytes that are UTF-8 as bytes, rather than decode them.
178 107 ▶sub _parser ($csv, $raw) {
Subroutine _parser: called CC=7 SCAR=19.5
179 107 ▶ if (blessed($csv)) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($csv)) 25 82 107
180 25 ▶ return sub () { $csv };
Subroutine __ANON__: called CC=1 SCAR=0.0
181 }
182 82 ▶ croakf 'Expected csv to be a hash reference of options, or a parser object'
Branch: 1 branch
BranchTrueFalseTotal
if defined $csv and not Ref::Util::XS::is_plain_hashref($csv) 2 80 82
Condition100%3/3
defined $csv and not Ref::Util::XS::is_plain_hashref($csv)
!ll&&!rl&&r
70102
MC/DC100%2/2
defined $csv and not Ref::Util::XS::is_plain_hashref($csv)
defined $csv not Ref::Util::XS::is_plain_hashref($csv)
Truth table100%3/3
A and not(B)
A= defined $csvB= not Ref::Util::XS::is_plain_hashref($csv)
ABresult
0X0
100
111
183 if defined $csv && !is_plain_hashref($csv);
184 my %settings = (
185 binary => 1,
186 auto_diag => 0,
187 ($raw ? (decode_utf8 => 0) : ()),
188 80 ▶ %{ $csv // {} },
Branch: 1 branch
BranchTrueFalseTotal
$raw ? : 3 77 80
Condition100%2/2
$csv // {}
l!l
1070
MC/DC100%1/1
$csv // {}
$csv
Truth table100%2/2
A
A= $csv
Aresult
11
00
189 );
190 80 ▶ croakf 'Expected csv options the parser knows: %s',
Branch: 1 branch
BranchTrueFalseTotal
unless "Text::CSV"->new({%settings}) 2 78 80
191 scalar Text::CSV->error_diag
192 unless Text::CSV->new({%settings});
193 78 ▶ return sub () { Text::CSV->new({%settings}) };
Subroutine __ANON__: called CC=1 SCAR=0.0
194 }
195  
196 # Return true if the options name a file or a filehandle.
197 103 ▶sub _has_input ($option) {
Subroutine _has_input: called CC=2 SCAR=6.9
198 103 ▶ return defined $option->{file} || !!$option->{fh};
Condition100%3/3
defined $option->{'file'} || !!$option->{'fh'}
l!l&&r!l&&!r
68431
MC/DC100%2/2
defined $option->{'file'} || !!$option->{'fh'}
defined $option->{'file'} !!$option->{'fh'}
Truth table100%3/3
A || B
A= defined $option->{'file'}B= !!$option->{'fh'}
ABresult
1X1
011
000
199 }
200  
201  
202 # Where Perl says an error was raised: its file and line, then the last
203 # filehandle read and how far, if one has been.
204 5 my $PLACE = qr( ,? \s+ at \s+ \S+ \s+ line \s+ \d+ )x;
205 5 my $READ = qr( , \s+ < \S* > \s+ (?: line | chunk ) \s+ \d+ )x;
206  
207 # Return an error's message without the place it was raised, as a
208 # message of ours says where.
209 2 ▶sub _unplaced ($error) {
Subroutine _unplaced: called CC=1 SCAR=0.0
210 2 return "$error" =~ s( $PLACE $READ? \.? \s* \z )()xr;
211 }
212  
213 # Return a sub giving the next row read from $io, by $from, or nothing
214 # at its end; and the context, if a header was read, as the header
215 # says: rows as arrays, or as hashes keyed by the header's names,
216 # munged.
217 69 ▶sub _table ($csv, $io, $from, $header, $munge) {
Subroutine _table: called CC=7 SCAR=19.5
218 69 my $next = _rows($csv, $io, $from);
219 69 ▶ return ($next) unless $header;
Branch: 1 branch
BranchTrueFalseTotal
unless $header 26 43 69
220 43 ▶ my @names = @{ $next->() // [] };
Condition100%2/2
&$next() // []
l!l
412
MC/DC100%1/1
&$next() // []
&$next()
Truth table100%2/2
A
A= &$next()
Aresult
11
00
221 43 ▶ @names = map { $munge->($_) } @names if $munge;
Branch: 1 branch
BranchTrueFalseTotal
if $munge 8 35 43
222 43 my $context = {columns => \@names};
223 43 ▶ return ($next, $context) if $header eq 'skip';
Branch: 1 branch
BranchTrueFalseTotal
if $header eq "skip" 6 37 43
224 37 my %seen;
225 37 for my $name (@names) {
226 croakf q(Expected a header naming each column once, not "%s" twice), $name
227 76 ▶ if $seen{$name}++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen{$name}++ 2 74 76
228 }
229 # Without a signature, as it's called for each row.
230 87 ▶ my $hashes = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
231 87 ▶ my $row = $next->() or return;
Branch: 1 branch
BranchTrueFalseTotal
my $row = &$next() or return 53 33 86
232 53 my %row;
233 53 @row{@names} = @$row;
234 53 return \%row;
235 35 };
236 35 return ($hashes, $context);
237 }
238  
239 # Return a sub giving the next row read from $io, by $from, or nothing at
240 # its end, croaking at a row that won't parse. A byte order mark that
241 # starts the first row is dropped.
242 69 ▶sub _rows ($csv, $io, $from) {
Subroutine _rows: called CC=1 SCAR=0.0
243 69 my $rows_read = 0;
244 # Without a signature, as it's called for each row.
245 216 ▶ return sub {
Subroutine __ANON__: called CC=5 SCAR=16.1
246 216 my $row;
247 216 try {
248 216 $row = $csv->getline($io);
249 }
250 catch ($e) {
251 1 croakf q(Can't read %s: %s), $from, _unplaced($e);
252 }; # the ; ends the statement for Perl::Critic, which doesn't know try
253 215 ▶ unless ($row) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($row) 67 148 215
254 67 my($code, $why, undef, undef, $field) = $csv->error_diag;
255 67 ▶ return if $code == $EOF;
Branch: 1 branch
BranchTrueFalseTotal
if $code == $EOF 63 4 67
256 4 croakf q(Can't parse CSV from %s, record %d, field %d: %s), $from,
257 $rows_read + 1, $field, $why;
258 }
259 # An undefined first field, as blank_is_undef makes, has no mark.
260 148 ▶ $row->[0] =~ s( \A \x{FEFF} )()x if !$rows_read++ && defined $row->[0];
Branch: 1 branch
BranchTrueFalseTotal
if not $rows_read++ and defined $row->[0] 59 89 148
Condition100%3/3
not $rows_read++ and defined $row->[0]
!ll&&!rl&&r
87259
MC/DC100%2/2
not $rows_read++ and defined $row->[0]
not $rows_read++ defined $row->[0]
Truth table100%3/3
not(A) and B
A= not $rows_read++B= defined $row->[0]
ABresult
0X0
100
111
261 148 return $row;
262 69 };
263 }
264  
265 # Return a source of the rows in the file or filehandle.
266 52 ▶sub _reader ($option) {
Subroutine _reader: called CC=3 SCAR=11.0
267 my($path, $given, $new, $encoding, $header, $munge)
268 52 = @{ $option }{qw(file fh new encoding header munge)};
269 52 ▶ my $from = $path // 'the filehandle';
Condition100%2/2
$path // "the filehandle"
l!l
502
MC/DC100%1/1
$path // "the filehandle"
$path
Truth table100%2/2
A
A= $path
Aresult
11
00
270 52 ▶ my $layer = ref $encoding ? sprintf(':encoding(%s)', $encoding->name) : ':raw';
Branch: 1 branch
BranchTrueFalseTotal
ref $encoding ? : 49 3 52
271 54 ▶ return source {
Subroutine __ANON__: called CC=4 SCAR=13.9
272 54 my $fh = $given;
273 54 ▶ unless ($fh) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($fh) 52 2 54
274 # Open for the run, and closed by its end. Text that won't
275 # decode croaks as it's read.
276 52 local $PerlIO::encoding::fallback = $STRICT; ## no critic (Variables::ProhibitPackageVars)
277 52 ▶ open $fh, "<$layer", $path ## no critic (InputOutput::RequireBriefOpen)
Branch: 1 branch
BranchTrueFalseTotal
open $fh, "<$layer", $path or croakf("Can't read %s: %s", $path, $!) 51 1 52
278 or croakf q(Can't read %s: %s), $path, $!;
279 }
280 53 my($next, $context) = _table($new->(), $fh, $from, $header, $munge);
281 return {
282 step => $next,
283 49 ▶ end => $path ? sub ($how) { close $fh } : undef,
Subroutine __ANON__: called CC=1 SCAR=0.0
284 51 ▶ context => $context,
Branch: 1 branch
BranchTrueFalseTotal
$path ? : 49 2 51
285 };
286 52 };
287 }
288  
289 # Return a sub giving a row's line, without its end of line, and, if
290 # there's a header, a sub giving its line: the names given, or the run's
291 # context's columns, which also order a hash's fields. A line is in the
292 # form asked for: characters ('chars'), UTF-8 ('utf8'), or the bytes
293 # its fields hold ('raw'), each of which must be a byte.
294 35 ▶sub _formatter ($csv, $header, $form) {
Subroutine _formatter: called CC=3 SCAR=11.0
295 35 ▶ my $names = is_plain_arrayref($header) ? $header : undef;
Branch: 1 branch
BranchTrueFalseTotal
Ref::Util::XS::is_plain_arrayref($header) ? : 9 26 35
296 35 my $cut = length $csv->eol; # combine ends a line with eol
297 57 ▶ my $text = sub ($row) {
Subroutine __ANON__: called CC=9 SCAR=22.0
298 # The parser is given only bytes: Text::CSV_XS's combine gives
299 # bytes, characters or a mixture as its fields' flags vary, and
300 # a line of bytes is the same from both backends.
301 57 my @fields = @$row;
302 57 for my $at (0 .. $#fields) {
303 106 ▶ next unless defined $fields[$at];
Branch: 1 branch
BranchTrueFalseTotal
unless defined $fields[$at] 4 102 106
304 102 ▶ croakf q(Can't write a row as CSV: field %d is a reference), $at + 1
Branch: 1 branch
BranchTrueFalseTotal
if Ref::Util::XS::is_plain_ref($fields[$at]) 1 101 102
305 if is_plain_ref($fields[$at]);
306 101 ▶ if ($form eq 'raw') {
Branch: 1 branch
BranchTrueFalseTotal
if ($form eq 'raw') { } 2 99 101
307 2 ▶ croakf
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::downgrade($fields[$at], 1) 1 1 2
308 q(Can't write a row as CSV: field %d holds a wide character, and the file is written raw),
309 $at + 1
310 unless utf8::downgrade($fields[$at], 1);
311 }
312 else {
313 99 utf8::encode($fields[$at]);
314 }
315 }
316 55 ▶ croakf q(Can't write a row as CSV: %s), scalar $csv->error_diag
Branch: 1 branch
BranchTrueFalseTotal
unless $csv->combine(@fields) 1 54 55
317 unless $csv->combine(@fields);
318 54 my $line = $csv->string;
319 54 ▶ substr $line, -$cut, $cut, q() if $cut;
Branch: 1 branch
BranchTrueFalseTotal
if $cut 2 52 54
320 54 ▶ utf8::decode($line) if $form eq 'chars';
Branch: 1 branch
BranchTrueFalseTotal
if $form eq "chars" 24 30 54
321 54 return $line;
322 35 };
323 45 ▶ my $line = sub ($row) {
Subroutine __ANON__: called CC=4 SCAR=13.9
324 45 ▶ return $text->($row) if is_plain_arrayref($row);
Branch: 1 branch
BranchTrueFalseTotal
if Ref::Util::XS::is_plain_arrayref($row) 26 19 45
325 19 ▶ croakf 'Expected a row as an array or a hash reference'
Branch: 1 branch
BranchTrueFalseTotal
unless Ref::Util::XS::is_plain_hashref($row) 1 18 19
326 unless is_plain_hashref($row);
327 18 ▶ croakf 'Expected a header naming the columns, to write a hash'
Branch: 1 branch
BranchTrueFalseTotal
unless $header 1 17 18
328 unless $header;
329 # The names are known: the header's line comes first.
330 17 return $text->([@{ $row }{@$names}]);
331 35 };
332 35 ▶ return ($line) unless $header;
Branch: 1 branch
BranchTrueFalseTotal
unless $header 19 16 35
333 # The header's line: the names given, or the run's columns.
334 16 ▶ my $head = sub () {
Subroutine __ANON__: called CC=2 SCAR=6.9
335 16 ▶ $names = _columns() unless $names;
Branch: 1 branch
BranchTrueFalseTotal
unless $names 7 9 16
336 14 return $text->($names);
337 16 };
338 16 return ($line, $head);
339 }
340  
341 # Return the run's context's columns, for a header, croaking if it has
342 # none.
343 7 ▶sub _columns () {
Subroutine _columns: called CC=3 SCAR=11.0
344 7 my $context = Ekorn::Pipeline::run_context();
345 7 ▶ my $columns = is_plain_hashref($context) ? $context->{columns} : undef;
Branch: 1 branch
BranchTrueFalseTotal
Ref::Util::XS::is_plain_hashref($context) ? : 6 1 7
346 7 ▶ croakf q(Expected the run's context to name its columns, for to_csv's header)
Branch: 1 branch
BranchTrueFalseTotal
unless Ref::Util::XS::is_plain_arrayref($columns) 2 5 7
347 unless is_plain_arrayref($columns);
348 5 return $columns;
349 }
350  
351 # Return the form a writer's lines are made in, for _formatter, and a
352 # sub encoding each, if it needs one: a filehandle takes characters, for
353 # its own layers; a file, its encoding's bytes, a character the encoding
354 # can't hold croaking at its row.
355 20 ▶sub _encoder ($encoding, $path) {
Subroutine _encoder: called CC=4 SCAR=13.9
356 20 ▶ return ('chars') unless defined $encoding;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $encoding 2 18 20
357 18 ▶ return ('raw') unless ref $encoding;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $encoding 2 16 18
358 16 ▶ return ('utf8') if $encoding->name =~ m( \A utf-?8 )xi;
Branch: 1 branch
BranchTrueFalseTotal
if $encoding->name =~ / \A utf-?8 /iux 14 2 16
359 2 ▶ my $encode = sub ($text) {
Subroutine __ANON__: called CC=1 SCAR=0.0
360 2 my $bytes;
361 2 try {
362 2 $bytes = $encoding->encode($text, $STRICT);
363 }
364 catch ($e) {
365 1 croakf q(Can't write %s: %s), $path, _unplaced($e);
366 }
367 1 return $bytes;
368 2 };
369 2 return ('chars', $encode);
370 }
371  
372 # Return a sink writing each row to the file or filehandle, giving how
373 # many: after the header's line, if it has one, written even if no row
374 # comes.
375 20 ▶sub _writer ($option) {
Subroutine _writer: called CC=2 SCAR=6.9
376 my($path, $given, $new, $encoding, $header)
377 20 = @{ $option }{qw(file fh new encoding header)};
378 20 ▶ my $to = $path // 'the filehandle';
Condition100%2/2
$path // "the filehandle"
l!l
182
MC/DC100%1/1
$path // "the filehandle"
$path
Truth table100%2/2
A
A= $path
Aresult
11
00
379 20 my($form, $encode) = _encoder($encoding, $path);
380 20 ▶ return sink_one {
Subroutine __ANON__: called CC=5 SCAR=16.1
381 20 my $fh = $given;
382 20 ▶ unless ($fh) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($fh) 18 2 20
383 # Open for the run, and closed by its end. Each line is
384 # encoded as it's made.
385 18 ▶ open $fh, '>:raw', $path ## no critic (InputOutput::RequireBriefOpen)
Branch: 1 branch
BranchTrueFalseTotal
open $fh, ">:raw", $path or croakf("Can't write %s: %s", $path, $!) 17 1 18
386 or croakf q(Can't write %s: %s), $path, $!;
387 }
388 19 my $csv = $new->();
389 19 my($line, $head) = _formatter($csv, $header, $form);
390 19 ▶ my $eol = length $csv->eol ? $csv->eol : "\n";
Branch: 1 branch
BranchTrueFalseTotal
length $csv->eol ? : 1 18 19
391 19 my $n = 0;
392 35 ▶ my $write = sub ($text) {
Subroutine __ANON__: called CC=3 SCAR=11.0
393 35 $text .= $eol;
394 35 ▶ print { $fh } $encode ? $encode->($text) : $text
Branch: 2 branches
BranchTrueFalseTotal
print {$fh;} $encode ? &$encode($text) : $text or croakf("Can't write %s: %s", $to, $!) 33 1 34
$encode ? : 2 33 35
395 or croakf q(Can't write %s: %s), $to, $!;
396 19 };
397 return {
398 # Without a signature, as it's called for each row.
399 29 ▶ step => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
400 29 ▶ $write->($head->()) if $head && !$n;
Branch: 1 branch
BranchTrueFalseTotal
if $head and not $n 5 24 29
Condition100%3/3
$head and not $n
!ll&&!rl&&r
1595
MC/DC100%2/2
$head and not $n
$head not $n
Truth table100%3/3
A and not(B)
A= $headB= not $n
ABresult
0X0
100
111
401 29 $write->($line->($_[0]));
402 26 $n++;
403 },
404 16 ▶ flush => sub () {
Subroutine __ANON__: called CC=3 SCAR=11.0
405 16 ▶ $write->($head->()) if $head && !$n;
Branch: 1 branch
BranchTrueFalseTotal
if $head and not $n 2 14 16
Condition100%3/3
$head and not $n
!ll&&!rl&&r
952
MC/DC100%2/2
$head and not $n
$head not $n
Truth table100%3/3
A and not(B)
A= $headB= not $n
ABresult
0X0
100
111
406 16 return $n;
407 },
408 end => $path
409 17 ▶ ? sub ($how) { close $fh or croakf q(Can't write %s: %s), $path, $! }
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
close $fh or croakf("Can't write %s: %s", $path, $!) 16 1 17
410 : undef,
411 19 ▶ };
Branch: 1 branch
BranchTrueFalseTotal
$path ? : 17 2 19
412 20 };
413 }
414  
415 # The rows of a text, a line at a time, for Text::CSV's getline, which
416 # reads from any object that has one. A filehandle opened on the text
417 # would need a check on an open that can't fail, which no test reaches.
418 5 package Ekorn::Pipeline::CSV::Text { ## no critic (Modules::ProhibitMultiplePackages)
419  
420  
421 16 ▶ sub new ($class, $text) {
Subroutine new: called CC=1 SCAR=0.0
422 16 return bless [split m( (?<= \n ) )x, $text], $class;
423 }
424  
425  
426 48 ▶ sub getline ($self) {
Subroutine getline: called CC=1 SCAR=0.0
427 48 return shift @$self;
428 }
429 }
430  
431 5 1;
432  
433 __END__
« Pipeline/Sugar.pm ↑ Summary Pipeline/JSON.pm »