Pipeline/JSON.pm

filter: Statementstmt 100% 169 / 169 Branchbran 100% 74 / 74 Conditioncond 100% 30 / 30 MC/DCmcdc 100% 19 / 19 Subroutinesub 100% 42 / 42 Podpod 100% 4 / 4 totaltotal 100% 338 / 338 CC 49 SCAR 15.2
CC
49
Cov
100%
_options
13.0
__ANON__
9.0
_chunk
5.0
CRAP 4.6
« Pipeline/CSV.pm ↑ Summary Pipeline/Operators.pm »
1 5 ▶use v5.36;
Subroutine BEGIN: called CC=1 SCAR=0.0
2  
3 package Ekorn::Pipeline::JSON;
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 Exporter qw(import);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 5 ▶use JSON::MaybeXS qw();
Subroutine BEGIN: called CC=1 SCAR=0.0
10 5 ▶use Ref::Util qw(is_plain_arrayref is_plain_hashref);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 5 ▶use Scalar::Util qw(openhandle);
Subroutine BEGIN: called CC=1 SCAR=0.0
12 5 ▶use Ekorn::Pipeline::Errors qw(croakf);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 5 ▶use Ekorn::Pipeline::Factories qw(gather sink_one source stage);
Subroutine BEGIN: called CC=1 SCAR=0.0
14 5 ▶use namespace::clean -except => 'import';
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16 5 our $VERSION = 'v0.4.0';
17  
18 5 our @EXPORT_OK = qw(from_json from_jsonl to_json to_jsonl);
19 5 our %EXPORT_TAGS = (all => \@EXPORT_OK);
20  
21 # Croak at the line that called Ekorn::Pipeline.
22 5 our @CARP_NOT = @Ekorn::Pipeline::Errors::INTERNAL;
23  
24 # How much a source reads at a time, before reading on to the end of the
25 # line, so that no number is cut in two; the tests make it small.
26 5 our $BLOCK = 65_536;
27  
28 # A source of one JSON document, read from the file or filehandle: its
29 # elements, if it's an array, or itself. Given neither, a stage decoding
30 # each value, one document, the same way.
31 40 ▶sub from_json (@options) {
Subroutine from_json: called CC=2 SCAR=6.9
Pod documented
32 40 my %option = _options(@options);
33 32 ▶ return _reader(\%option, 'json') if _has_input(\%option);
Branch: 1 branch
BranchTrueFalseTotal
if _has_input(\%option) 27 5 32
34 5 my $json = $option{new}->();
35 17 ▶ return stage {
Subroutine __ANON__: called CC=2 SCAR=6.9
36 17 my $document;
37 17 try {
38 17 $document = $json->decode($_);
39 }
40 catch ($e) {
41 4 _undecodable($json, 'a value', _unplaced($e));
42 }
43 13 ▶ return is_plain_arrayref($document) ? @$document : $document;
Branch: 1 branch
BranchTrueFalseTotal
Ref::Util::XS::is_plain_arrayref($document) ? : 8 5 13
44 5 };
45 }
46  
47 # A source of the documents in a file or filehandle of JSON Lines, each
48 # as it is. Given neither, a stage decoding each value, a text of one or
49 # more lines, into each line's document.
50 42 ▶sub from_jsonl (@options) {
Subroutine from_jsonl: called CC=2 SCAR=6.9
Pod documented
51 42 my %option = _options(@options);
52 34 ▶ return _reader(\%option, 'lines') if _has_input(\%option);
Branch: 1 branch
BranchTrueFalseTotal
if _has_input(\%option) 30 4 34
53 4 my $new = $option{new};
54 10 ▶ return gather {
Subroutine __ANON__: called CC=1 SCAR=0.0
55 10 my $json = $new->(); # this run's, as its parser holds what it's read
56  
57 # Without a signature, as it's called for each value.
58 18 ▶ return sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
59 18 my @documents;
60 18 try {
61 18 @documents = $json->incr_parse($_[0]);
62 }
63 catch ($e) {
64 2 _undecodable($json, 'a value', _unplaced($e));
65 }
66 16 _complete($json, 'a value');
67 14 return @documents;
68 10 };
69 4 };
70 }
71  
72 # A sink writing every value to the file or filehandle as one JSON
73 # document, an array, giving how many. Given neither, a stage passing on
74 # every value as that array's text, once they've all come.
75 27 ▶sub to_json (@options) {
Subroutine to_json: called CC=2 SCAR=6.9
Pod documented
76 27 my %option = _options(@options);
77 19 my $json = $option{new}->();
78 19 ▶ return _writer(\%option, 'json', $json) if _has_input(\%option);
Branch: 1 branch
BranchTrueFalseTotal
if _has_input(\%option) 11 8 19
79 7 ▶ return gather {
Subroutine __ANON__: called CC=1 SCAR=0.0
80 7 my @values; # this run's
81 return (
82 12 ▶ sub { push @values, $_[0]; return }, # for each value: no signature
Subroutine __ANON__: called CC=1 SCAR=0.0
83 7 ▶ sub () { _encoded($json, \@values) =~ s( \n \z )()xr },
Subroutine __ANON__: called CC=1 SCAR=0.0
84 7 );
85 8 };
86 }
87  
88 # A sink writing each value to the file or filehandle as a line of JSON
89 # Lines, giving how many. Given neither, a stage passing on each value
90 # as its line, without its newline.
91 27 ▶sub to_jsonl (@options) {
Subroutine to_jsonl: called CC=3 SCAR=11.0
Pod documented
92 27 my %option = _options(@options);
93 19 my $json = $option{new}->();
94 19 ▶ croakf q(Expected an encoder that doesn't indent, to write JSON Lines)
Branch: 1 branch
BranchTrueFalseTotal
if _indents($json) 2 17 19
95 if _indents($json);
96 17 ▶ return _writer(\%option, 'lines', $json) if _has_input(\%option);
Branch: 1 branch
BranchTrueFalseTotal
if _has_input(\%option) 5 12 17
97 12 ▶ return stage { _encoded($json, $_) };
Subroutine __ANON__: called CC=1 SCAR=0.0
98 }
99  
100 # Return the options given, checked, with "new", a sub returning the
101 # encoder: one made from json's options, over the defaults, or json's
102 # object, as it is.
103 136 ▶sub _options (@given) {
Subroutine _options: called CC=13 SCAR=25.6
104 136 ▶ croakf 'Expected options as name => value pairs' if @given % 2;
Branch: 1 branch
BranchTrueFalseTotal
if @given % 2 4 132 136
105 132 my %option = @given;
106 132 my @unknown = sort grep { !m( \A (?: file | fh | json ) \z )x } keys %option;
107 132 ▶ croakf 'Expected the options file, fh and json, not %s', join ', ', @unknown
Branch: 1 branch
BranchTrueFalseTotal
if @unknown 8 124 132
108 if @unknown;
109 croakf 'Expected file to be a path'
110 124 ▶ if exists $option{file} && !defined $option{file};
Branch: 1 branch
BranchTrueFalseTotal
if exists $option{"file"} and not defined $option{"file"} 4 120 124
Condition100%3/3
exists $option{"file"} and not defined $option{"file"}
!ll&&!rl&&r
53674
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
111 croakf 'Expected a file or a filehandle, not both'
112 120 ▶ if defined $option{file} && exists $option{fh};
Branch: 1 branch
BranchTrueFalseTotal
if defined $option{"file"} and exists $option{"fh"} 4 116 120
Condition100%3/3
defined $option{"file"} and exists $option{"fh"}
!ll&&!rl&&r
53634
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
113 croakf 'Expected an open filehandle'
114 116 ▶ if exists $option{fh} && !defined openhandle($option{fh});
Branch: 1 branch
BranchTrueFalseTotal
if exists $option{"fh"} and not defined &openhandle($option{"fh"}) 4 112 116
Condition100%3/3
exists $option{"fh"} and not defined &openhandle($option{"fh"})
!ll&&!rl&&r
101114
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
115 112 my $json = $option{json};
116 112 ▶ if (blessed($json)) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($json)) 43 69 112
117 43 ▶ $option{new} = sub () { $json };
Subroutine __ANON__: called CC=1 SCAR=0.0
118 43 return %option;
119 }
120 69 ▶ croakf 'Expected json to be a hash reference of options, or an encoder object'
Branch: 1 branch
BranchTrueFalseTotal
if defined $json and not Ref::Util::XS::is_plain_hashref($json) 4 65 69
Condition100%3/3
defined $json and not Ref::Util::XS::is_plain_hashref($json)
!ll&&!rl&&r
53124
MC/DC100%2/2
defined $json and not Ref::Util::XS::is_plain_hashref($json)
defined $json not Ref::Util::XS::is_plain_hashref($json)
Truth table100%3/3
A and not(B)
A= defined $jsonB= not Ref::Util::XS::is_plain_hashref($json)
ABresult
0X0
100
111
121 if defined $json && !is_plain_hashref($json);
122 65 ▶ my %settings = (utf8 => 1, allow_nonref => 1, %{ $json // {} });
Condition100%2/2
$json // {}
l!l
1253
MC/DC100%1/1
$json // {}
$json
Truth table100%2/2
A
A= $json
Aresult
11
00
123 65 try {
124 65 JSON::MaybeXS->new(%settings);
125 }
126 catch ($e) {
127 4 croakf 'Expected json options the encoder knows: %s', _unplaced($e);
128 }
129 61 ▶ $option{new} = sub () { JSON::MaybeXS->new(%settings) };
Subroutine __ANON__: called CC=1 SCAR=0.0
130 61 return %option;
131 }
132  
133 # Return true if the options name a file or a filehandle.
134 102 ▶sub _has_input ($option) {
Subroutine _has_input: called CC=2 SCAR=6.9
135 102 ▶ return defined $option->{file} || !!$option->{fh};
Condition100%3/3
defined $option->{'file'} || !!$option->{'fh'}
l!l&&r!l&&!r
621129
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
136 }
137  
138 # Return true if the encoder indents, so writes a document over many
139 # lines.
140 35 ▶sub _indents ($json) {
Subroutine _indents: called CC=2 SCAR=6.9
141 35 ▶ return $json->can('get_indent') && $json->get_indent;
Condition100%3/3
$json->can('get_indent') && $json->get_indent
!ll&&!rl&&r
1313
MC/DC100%2/2
$json->can('get_indent') && $json->get_indent
$json->can('get_indent') $json->get_indent
Truth table100%3/3
A && B
A= $json->can('get_indent')B= $json->get_indent
ABresult
0X0
100
111
142 }
143  
144 # Return an error's message without the place it was raised, as a
145 # message of ours says where.
146 13 ▶sub _unplaced ($error) {
Subroutine _unplaced: called CC=1 SCAR=0.0
147 13 return "$error" =~ s( ,? \s+ at \s+ \S+ \s+ line \s+ \d+ \.? \s* \z )()xr;
148 }
149  
150 # Croak that what's read from $from can't be decoded, and why. The
151 # decoder is reset, for the next run, if it's the caller's.
152 15 ▶sub _undecodable ($json, $from, $why) {
Subroutine _undecodable: called CC=1 SCAR=0.0
153 15 $json->incr_reset;
154 15 return croakf q(Can't decode JSON from %s: %s), $from, $why;
155 }
156  
157 # Croak unless the decoder has a whole number of documents: it croaks,
158 # asked for the text it holds, if it's inside one.
159 66 ▶sub _complete ($json, $from) {
Subroutine _complete: called CC=1 SCAR=0.0
160 66 try {
161 66 $json->incr_text;
162 }
163 catch ($e) {
164 6 _undecodable($json, $from, 'it ends inside a document');
165 }; # the ; ends the statement for Perl::Critic, which doesn't know try
166 60 return;
167 }
168  
169 # Return a source of the documents in the file or filehandle: as they
170 # come, for JSON Lines; or, for one document, its elements, if it's an
171 # array, or itself, once the input has ended.
172 57 ▶sub _reader ($option, $format) {
Subroutine _reader: called CC=2 SCAR=6.9
173 57 my($path, $given, $new) = @{ $option }{qw(file fh new)};
174 57 ▶ my $from = $path // 'the filehandle';
Condition100%2/2
$path // "the filehandle"
l!l
516
MC/DC100%1/1
$path // "the filehandle"
$path
Truth table100%2/2
A
A= $path
Aresult
11
00
175 59 ▶ return source {
Subroutine __ANON__: called CC=4 SCAR=13.9
176 59 my $fh = $given;
177 59 ▶ unless ($fh) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($fh) 53 6 59
178 # Open for the run, and closed by its end.
179 53 ▶ open $fh, '<:raw', $path ## no critic (InputOutput::RequireBriefOpen)
Branch: 1 branch
BranchTrueFalseTotal
open $fh, "<:raw", $path or croakf("Can't read %s: %s", $path, $!) 52 1 53
180 or croakf q(Can't read %s: %s), $path, $!;
181 }
182 58 my $json = $new->(); # this run's, or the caller's, reset
183 58 $json->incr_reset;
184 58 my(@documents, $ended);
185  
186 # Without a signature, as it's called for each value.
187 138 ▶ my $step = sub {
Subroutine __ANON__: called CC=9 SCAR=22.0
188 138 while (1) {
189 436 ▶ return splice @documents if @documents && $format eq 'lines';
Branch: 1 branch
BranchTrueFalseTotal
if @documents and $format eq "lines" 65 371 436
Condition100%3/3
@documents and $format eq "lines"
!ll&&!rl&&r
3294265
MC/DC100%2/2
@documents and $format eq "lines"
@documents $format eq "lines"
Truth table100%3/3
A and B
A= @documentsB= $format eq "lines"
ABresult
0X0
100
111
190 371 ▶ if ($ended) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ended) 65 306 371
191 65 ▶ return unless @documents;
Branch: 1 branch
BranchTrueFalseTotal
unless @documents 44 21 65
192 21 my($only) = splice @documents;
193 21 ▶ return is_plain_arrayref($only) ? @$only : $only;
Branch: 1 branch
BranchTrueFalseTotal
Ref::Util::XS::is_plain_arrayref($only) ? : 17 4 21
194 }
195 306 my $chunk = _chunk($fh, $from);
196 305 ▶ unless (defined $chunk) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $chunk) 50 255 305
197 50 _complete($json, $from);
198 46 $ended = 1;
199 46 next;
200 }
201 255 my @read;
202 255 try {
203 255 @read = $json->incr_parse($chunk);
204 }
205 catch ($e) {
206 1 _undecodable($json, $from, _unplaced($e));
207 }
208 254 push @documents, @read;
209 254 ▶ _undecodable(
Branch: 1 branch
BranchTrueFalseTotal
if $format eq "json" and @documents > 1 2 252 254
Condition100%3/3
$format eq "json" and @documents > 1
!ll&&!rl&&r
681842
MC/DC100%2/2
$format eq "json" and @documents > 1
$format eq "json" @documents > 1
Truth table100%3/3
A and B
A= $format eq "json"B= @documents > 1
ABresult
0X0
100
111
210 $json, $from,
211 'it holds more than one document; read JSON Lines with from_jsonl',
212 ) if $format eq 'json' && @documents > 1;
213 }
214 58 };
215 58 ▶ return {step => $step, end => $path ? sub ($how) { close $fh } : undef};
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
$path ? : 52 6 58
216 57 };
217 }
218  
219 # Return the next chunk of $fh, read from $from: up to $BLOCK, and on to
220 # the end of its line; nothing at its end.
221 306 ▶sub _chunk ($fh, $from) {
Subroutine _chunk: called CC=5 SCAR=16.1
222 306 my $chunk;
223 306 my $read = read $fh, $chunk, $BLOCK;
224 306 ▶ croakf q(Can't read %s: %s), $from, $! unless defined $read;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $read 1 305 306
225 305 ▶ return unless $read;
Branch: 1 branch
BranchTrueFalseTotal
unless $read 50 255 305
226 255 local $/ = "\n";
227 255 ▶ if (substr($chunk, -1) ne "\n") {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($chunk, -1) ne "\n") 219 36 255
228 219 my $rest = readline $fh;
229 219 ▶ $chunk .= $rest if defined $rest;
Branch: 1 branch
BranchTrueFalseTotal
if defined $rest 206 13 219
230 }
231 255 return $chunk;
232 }
233  
234 # Return $value encoded.
235 53 ▶sub _encoded ($json, $value) {
Subroutine _encoded: called CC=1 SCAR=0.0
236 53 my $text;
237 53 try {
238 53 $text = $json->encode($value);
239 }
240 catch ($e) {
241 2 croakf q(Can't encode a value as JSON: %s), _unplaced($e);
242 }; # the ; ends the statement for Perl::Critic, which doesn't know try
243 51 return $text;
244 }
245  
246 # Return a sink writing each value, encoded, to the file or filehandle,
247 # as the format says, giving how many. One document is an array,
248 # written as the values come: an encoder that indents has its values'
249 # lines indented in it.
250 16 ▶sub _writer ($option, $format, $json) {
Subroutine _writer: called CC=3 SCAR=11.0
251 16 my($path, $given) = @{ $option }{qw(file fh)};
252 16 ▶ my $to = $path // 'the filehandle';
Condition100%2/2
$path // "the filehandle"
l!l
115
MC/DC100%1/1
$path // "the filehandle"
$path
Truth table100%2/2
A
A= $path
Aresult
11
00
253 16 my $indent = _indents($json);
254 16 ▶ my($before, $between, $after)
Branch: 1 branch
BranchTrueFalseTotal
$indent ? : 1 15 16
255 = $indent ? ("[\n", ",\n", "\n]\n") : ('[', ',', "]\n");
256 16 ▶ return sink_one {
Subroutine __ANON__: called CC=5 SCAR=16.1
257 16 my $fh = $given;
258 16 ▶ unless ($fh) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($fh) 11 5 16
259 # Open for the run, and closed by its end.
260 11 ▶ open $fh, '>:raw', $path ## no critic (InputOutput::RequireBriefOpen)
Branch: 1 branch
BranchTrueFalseTotal
open $fh, ">:raw", $path or croakf("Can't write %s: %s", $path, $!) 10 1 11
261 or croakf q(Can't write %s: %s), $path, $!;
262 }
263 15 my $n = 0;
264 36 ▶ my $write = sub (@text) {
Subroutine __ANON__: called CC=2 SCAR=6.9
265 36 ▶ print { $fh } @text or croakf q(Can't write %s: %s), $to, $!;
Branch: 1 branch
BranchTrueFalseTotal
print {$fh;} @text or croakf("Can't write %s: %s", $to, $!) 35 1 36
266 15 };
267  
268 # Without a signature, as it's called for each value.
269 my $step
270 = $format eq 'lines'
271 11 ▶ ? sub { $write->(_encoded($json, $_[0]), "\n"); $n++ }
Subroutine __ANON__: called CC=1 SCAR=0.0
272 15 ▶ : sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
273 15 my $text = _encoded($json, $_[0]) =~ s( \n \z )()xr;
274 15 ▶ $text =~ s( ^ )( )xmg if $indent;
Branch: 1 branch
BranchTrueFalseTotal
if $indent 2 13 15
275 15 ▶ $write->($n++ ? $between : $before, $text);
Branch: 1 branch
BranchTrueFalseTotal
$n++ ? : 7 8 15
276 15 ▶ };
Branch: 1 branch
BranchTrueFalseTotal
$format eq 'lines' ? : 5 10 15
277 return {
278 step => $step,
279 14 ▶ flush => sub () {
Subroutine __ANON__: called CC=3 SCAR=11.0
280 14 ▶ $write->($n ? $after : "[]\n") if $format eq 'json';
Branch: 2 branches
BranchTrueFalseTotal
if $format eq "json" 10 4 14
$n ? : 8 2 10
281 14 return $n;
282 },
283 end => $path
284 10 ▶ ? 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, $!) 9 1 10
285 : undef,
286 15 ▶ };
Branch: 1 branch
BranchTrueFalseTotal
$path ? : 10 5 15
287 16 };
288 }
289  
290 5 1;
291  
292 __END__
« Pipeline/CSV.pm ↑ Summary Pipeline/Operators.pm »