bin/jq-lite

filter: Statementstmt 72.2% 357 / 494 Branchbran 63.8% 189 / 296 Conditioncond 58.3% 101 / 173 MC/DCmcdc 30.2% 29 / 96 Subroutinesub 86.4% 32 / 37 Podpod n/a totaltotal 64.6% 708 / 1096 CC 90 SCAR 23.4
CC
90
Cov
67%
_validate_query_syntax
26.8
__ANON__
13.6
__ANON__
10.1
CRAP 10.4
« blib/lib/JQ/Lite/Util/Paths.pm ↑ Summary lib/JQ/Lite/Value.pm »
1 #!/usr/bin/env perl
2  
3 63 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 63 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 63 ▶use JSON::PP;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 63 ▶use IO::File;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 63 ▶use FindBin;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 63 ▶use Term::ANSIColor;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 63 ▶use Getopt::Long qw(GetOptions :config no_ignore_case bundling no_pass_through);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 63 ▶use lib "$FindBin::Bin/../lib";
Subroutine BEGIN: called CC=1 SCAR=0.0
11 63 ▶use JQ::Lite;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 63 ▶use JQ::Lite::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14 63 my $decoder;
15 my $decoder_module;
16 63 my $decoder_debug = 0;
17 63 my $decoder_choice;
18 63 my $raw_input = 0;
19 63 my $raw_output = 0;
20 63 my $compact_output = 0;
21 63 my $ascii_output = 0;
22 63 my $color_output = 0;
23 63 my $null_input = 0;
24 63 my $slurp_input = 0;
25 63 my @query_files;
26 63 my $force_yaml = 0;
27 63 my $exit_status = 0;
28 63 my $yaml_module;
29 my $yaml_loader;
30 63 my %arg_vars;
31 63 my @slurpfiles;
32 63 my $slurpfile_probably_missing_file = 0;
33  
34 24 ▶sub _exit_with_error {
Subroutine _exit_with_error: called CC=3 SCAR=11.8
35 24 my ($tag, $default_message, $exit_code, $message) = @_;
36 24 ▶ $message = defined($message) && $message ne '' ? $message : $default_message;
Branch: 1 branch
BranchTrueFalseTotal
defined $message && $message ne '' ? : 24 0 24
Condition33%1/3
defined $message and $message ne ""
!ll&&!rl&&r
0024
MC/DC0%0/2
defined $message and $message ne ""
defined $message $message ne ""
Truth table33%1/3
A and B
A= defined $messageB= $message ne ""
ABresult
0X0
100
111
37 24 $message =~ s/\s+\z//;
38 24 warn "[$tag]$message\n";
39 24 exit $exit_code;
40 }
41  
42 16 ▶sub _usage_error {
Subroutine _usage_error: called CC=1 SCAR=0.0
43 16 my ($message) = @_;
44 16 _exit_with_error('USAGE', 'invalid usage', 5, $message);
45 }
46  
47 2 ▶sub _input_error {
Subroutine _input_error: called CC=1 SCAR=0.0
48 2 my ($message) = @_;
49 2 _exit_with_error('INPUT', 'input error', 4, $message);
50 }
51  
52 3 ▶sub _compile_error {
Subroutine _compile_error: called CC=1 SCAR=0.0
53 3 my ($message) = @_;
54 3 _exit_with_error('COMPILE', 'compile error', 2, $message);
55 }
56  
57 3 ▶sub _runtime_error {
Subroutine _runtime_error: called CC=1 SCAR=0.0
58 3 my ($message) = @_;
59 3 _exit_with_error('RUNTIME', 'runtime error', 3, $message);
60 }
61  
62 46 ▶sub _validate_query_syntax {
Subroutine _validate_query_syntax: called CC=25 SCAR=32.9
63 46 my ($query) = @_;
64  
65 46 ▶ return if !defined $query || $query eq '';
Branch: 1 branch
BranchTrueFalseTotal
if not defined $query or $query eq "" 0 46 46
Condition33%1/3
not defined $query or $query eq ""
l!l&&r!l&&!r
0046
MC/DC0%0/2
not defined $query or $query eq ""
not defined $query $query eq ""
Truth table33%1/3
not(A) or B
A= not defined $queryB= $query eq ""
ABresult
1X1
011
000
66  
67 46 my @stack;
68 my $string;
69 46 my $escape = 0;
70  
71 46 for my $char (split //, $query) {
72 352 ▶ if (defined $string) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $string) 8 344 352
73 8 ▶ if ($escape) {
Branch: 1 branch
BranchTrueFalseTotal
if ($escape) 2 6 8
74 2 $escape = 0;
75 2 next;
76 }
77  
78 6 ▶ if ($char eq '\\') {
Branch: 1 branch
BranchTrueFalseTotal
if ($char eq "\\") 2 4 6
79 2 $escape = 1;
80 2 next;
81 }
82  
83 4 ▶ if ($char eq $string) {
Branch: 1 branch
BranchTrueFalseTotal
if ($char eq $string) 3 1 4
84 3 undef $string;
85 }
86 4 next;
87 }
88  
89 344 ▶ if ($char eq "'" || $char eq '"') {
Branch: 1 branch
BranchTrueFalseTotal
if ($char eq "'" or $char eq "\"") 3 341 344
Condition66%2/3
$char eq "'" or $char eq "\""
l!l&&r!l&&!r
03341
MC/DC50%1/2
$char eq "'" or $char eq "\""
$char eq "'" $char eq "\""
Truth table66%2/3
A or B
A= $char eq "'"B= $char eq "\""
ABresult
1X1
011
000
90 3 $string = $char;
91 3 next;
92 }
93  
94 341 ▶ if ($char eq '(' || $char eq '[' || $char eq '{') {
Branch: 1 branch
BranchTrueFalseTotal
if ($char eq "(" or $char eq "[" or $char eq "{") 19 322 341
Condition83%5/6
$char eq "(" or $char eq "[" or $char eq "{"
l!l&&r!l&&!r
190322
$char eq "(" or $char eq "["
l!l&&r!l&&!r
712322
MC/DC66%2/3
$char eq "(" or $char eq "[" or $char eq "{"
$char eq "(" $char eq "[" $char eq "{"
Truth table75%3/4
A or B or C
A= $char eq "("B= $char eq "["C= $char eq "{"
ABCresult
1XX1
01X1
0011
0000
95 19 push @stack, $char;
96 19 next;
97 }
98  
99 322 ▶ if ($char eq ')' || $char eq ']' || $char eq '}') {
Branch: 1 branch
BranchTrueFalseTotal
if ($char eq ")" or $char eq "]" or $char eq "}") 18 304 322
Condition83%5/6
$char eq ")" or $char eq "]" or $char eq "}"
l!l&&r!l&&!r
180304
$char eq ")" or $char eq "]"
l!l&&r!l&&!r
711304
MC/DC66%2/3
$char eq ")" or $char eq "]" or $char eq "}"
$char eq ")" $char eq "]" $char eq "}"
Truth table75%3/4
A or B or C
A= $char eq ")"B= $char eq "]"C= $char eq "}"
ABCresult
1XX1
01X1
0011
0000
100 18 my $open = pop @stack;
101 18 my %pairs = (
102 ')' => '(',
103 ']' => '[',
104 '}' => '{',
105 );
106 18 ▶ if (!defined $open || $open ne $pairs{$char}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $open or $open ne $pairs{$char}) 0 18 18
Condition33%1/3
not defined $open or $open ne $pairs{$char}
l!l&&r!l&&!r
0018
MC/DC0%0/2
not defined $open or $open ne $pairs{$char}
not defined $open $open ne $pairs{$char}
Truth table33%1/3
not(A) or B
A= not defined $openB= $open ne $pairs{$char}
ABresult
1X1
011
000
107 0 _compile_error('Invalid query syntax: unmatched brackets');
108 }
109 }
110 }
111  
112 46 ▶ if (defined $string || @stack) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $string or @stack) 1 45 46
Condition66%2/3
defined $string or @stack
l!l&&r!l&&!r
0145
MC/DC50%1/2
defined $string or @stack
defined $string @stack
Truth table66%2/3
A or B
A= defined $stringB= @stack
ABresult
1X1
011
000
113 1 _compile_error('Invalid query syntax: unmatched brackets');
114 }
115  
116 45 my @pipeline_parts = JQ::Lite::Util::_split_top_level_pipes($query);
117 45 ▶ if (grep { !defined $_ || $_ !~ /\S/ } @pipeline_parts) {
Branch: 1 branch
BranchTrueFalseTotal
if (grep {not defined $_ && $_ =~ /\S/;} @pipeline_parts) 1 44 45
Condition66%2/3
defined $_ && $_ =~ /\S/
!ll&&!rl&&r
0156
MC/DC50%1/2
defined $_ && $_ =~ /\S/
defined $_ $_ =~ /\S/
Truth table66%2/3
A && B
A= defined $_B= $_ =~ /\S/
ABresult
0X0
100
111
118 1 _compile_error('Invalid query syntax: empty filter segment');
119 }
120  
121 44 for my $segment (@pipeline_parts) {
122 55 my @comma_parts = JQ::Lite::Util::_split_top_level_commas($segment);
123 55 ▶ if (grep { !defined $_ || $_ !~ /\S/ } @comma_parts) {
Branch: 1 branch
BranchTrueFalseTotal
if (grep {not defined $_ && $_ =~ /\S/;} @comma_parts) 1 54 55
Condition66%2/3
defined $_ && $_ =~ /\S/
!ll&&!rl&&r
0155
MC/DC50%1/2
defined $_ && $_ =~ /\S/
defined $_ $_ =~ /\S/
Truth table66%2/3
A && B
A= defined $_B= $_ =~ /\S/
ABresult
0X0
100
111
124 1 _compile_error('Invalid query syntax: empty filter segment');
125 }
126 }
127 }
128  
129 4 ▶sub _is_truthy {
Subroutine _is_truthy: called CC=4 SCAR=13.9
130 4 my ($value) = @_;
131  
132 4 ▶ return 0 unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 2 2 4
133  
134 2 ▶ if (ref($value) eq 'JSON::PP::Boolean') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $value eq "JSON::PP::Boolean") 1 1 2
135 1 ▶ return $value ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$value ? : 0 1 1
136 }
137  
138 1 return 1;
139 }
140  
141 # ---------- Help text ----------
142 63 my $USAGE = <<'USAGE';
143 jq-lite - minimal jq-style JSON filter (pure Perl)
144  
145 Usage:
146 jq-lite [options] '.query' [file.json]
147 jq-lite [options] -f query.jq [file.json]
148  
149 Options:
150 -R, --raw-input Read input as raw text instead of JSON (one filter run per line)
151 -r, --raw-output Print raw strings instead of JSON-encoded values
152 -c, --compact-output Print JSON results on a single line (no pretty-printing)
153 -a, --ascii-output Escape all non-ASCII characters in JSON output
154 --color Colorize JSON output (keys, strings, numbers, booleans)
155 --use <Module> Force JSON decoder module (e.g. JSON::PP, JSON::XS, Cpanel::JSON::XS)
156 --debug Show which JSON module is being used
157 -e, --exit-status Set exit code to 1 when the final result is false, null, or empty
158 --arg NAME VALUE Set jq-style variable $NAME to the string VALUE
159 --rawfile NAME FILE Set jq-style variable $NAME to the raw contents of FILE
160 --slurpfile NAME FILE Set jq-style variable $NAME to an array of JSON values from FILE
161 --argjson NAME JSON Set jq-style variable $NAME to a JSON-decoded value
162 --argfile NAME FILE Set jq-style variable $NAME to a JSON-decoded value from FILE
163 -f, --from-file FILE Read jq filter from FILE instead of the command line
164 (use '-' to read the filter from STDIN)
165 -n, --null-input Use null as input instead of reading JSON data
166 -s, --slurp Read entire input stream as an array of JSON values
167 --yaml Parse input as YAML (auto-detected for .yml/.yaml files)
168 -h, --help Show this help message
169 --help-functions Show list of all supported functions
170 -v, --version Show version information
171  
172 Examples:
173 cat users.json | jq-lite '.users[].name'
174 jq-lite '.users[] | select(.age > 25)' users.json
175 jq-lite -r '.users[] | .name' users.json
176 jq-lite '.meta has "version"' config.json
177 jq-lite --color '.items | sort | reverse | first' data.json
178  
179 Homepage:
180 https://metacpan.org/pod/JQ::Lite
181 USAGE
182  
183 # ---------- Option parsing (Getopt::Long) ----------
184 63 my ($want_help, $want_version, $help_functions) = (0, 0, 0);
185  
186 63 my @getopt_errors;
187 my $getopt_ok;
188 {
189 63 my $orig_warn = $SIG{__WARN__};
190 10 ▶ local $SIG{__WARN__} = sub {
Subroutine __ANON__: called CC=3 SCAR=11.2
191 10 my ($msg) = @_;
192 10 ▶ if ($msg =~ /^\[(?:COMPILE|RUNTIME|INPUT|USAGE)\]/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($msg =~ /^\[(?:COMPILE|RUNTIME|INPUT|USAGE)\]/) 9 1 10
193 9 ▶ if ($orig_warn) {
Branch: 1 branch
BranchTrueFalseTotal
if ($orig_warn) { } 0 9 9
194 0 $orig_warn->($msg);
195 }
196 else {
197 9 CORE::warn($msg);
198 }
199 9 return;
200 }
201  
202 1 push @getopt_errors, $msg;
203 63 };
204  
205 $getopt_ok = GetOptions(
206 'raw-input|R' => \$raw_input,
207 'raw-output|r' => \$raw_output,
208 'compact-output|c'=> \$compact_output,
209 'ascii-output|a' => \$ascii_output,
210 'color' => \$color_output,
211 'use=s' => \$decoder_choice,
212 'debug' => \$decoder_debug,
213 'exit-status|e' => \$exit_status,
214 'null-input|n' => \$null_input,
215 'slurp|s' => \$slurp_input,
216 'yaml' => \$force_yaml,
217 'help|h' => \$want_help,
218 'help-functions' => \$help_functions,
219 'version|v' => \$want_version,
220 'from-file|f=s' => \@query_files,
221 5 ▶ 'slurpfile=s' => sub {
Subroutine __ANON__: called CC=8 SCAR=23.1
222 5 my ($opt_name, $var_name) = @_;
223 5 ▶ _usage_error('--slurpfile requires a variable name') if !defined $var_name || $var_name eq '';
Branch: 1 branch
BranchTrueFalseTotal
if not defined $var_name or $var_name eq "" 0 5 5
Condition33%1/3
not defined $var_name or $var_name eq ""
l!l&&r!l&&!r
005
MC/DC0%0/2
not defined $var_name or $var_name eq ""
not defined $var_name $var_name eq ""
Truth table33%1/3
not(A) or B
A= not defined $var_nameB= $var_name eq ""
ABresult
1X1
011
000
224 5 ▶ if ($var_name !~ /^[A-Za-z_]\w*$/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($var_name =~ /^[A-Za-z_]\w*$/) 0 5 5
225 0 _usage_error("Invalid variable name '$var_name' for --slurpfile");
226 }
227 5 ▶ _usage_error('--slurpfile requires a file path') if !@ARGV;
Branch: 1 branch
BranchTrueFalseTotal
unless @ARGV 0 5 5
228 5 my $file_path = shift @ARGV;
229 5 ▶ $file_path = '' unless defined $file_path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $file_path 0 5 5
230  
231 5 ▶ $slurpfile_probably_missing_file = 1 if @ARGV == 0 && $file_path =~ /^\./;
Branch: 1 branch
BranchTrueFalseTotal
if @ARGV == 0 and $file_path =~ /^\./ 1 4 5
Condition66%2/3
@ARGV == 0 and $file_path =~ /^\./
!ll&&!rl&&r
401
MC/DC50%1/2
@ARGV == 0 and $file_path =~ /^\./
@ARGV == 0 $file_path =~ /^\./
Truth table66%2/3
A and B
A= @ARGV == 0B= $file_path =~ /^\./
ABresult
0X0
100
111
232  
233 5 push @slurpfiles, $var_name, $file_path;
234 },
235 3 ▶ 'arg=s' => sub {
Subroutine __ANON__: called CC=6 SCAR=18.5
236 3 my ($opt_name, $var_name) = @_;
237 3 ▶ _usage_error('--arg requires a variable name') if !defined $var_name || $var_name eq '';
Branch: 1 branch
BranchTrueFalseTotal
if not defined $var_name or $var_name eq "" 0 3 3
Condition33%1/3
not defined $var_name or $var_name eq ""
l!l&&r!l&&!r
003
MC/DC0%0/2
not defined $var_name or $var_name eq ""
not defined $var_name $var_name eq ""
Truth table33%1/3
not(A) or B
A= not defined $var_nameB= $var_name eq ""
ABresult
1X1
011
000
238 3 ▶ if ($var_name !~ /^[A-Za-z_]\w*$/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($var_name =~ /^[A-Za-z_]\w*$/) 1 2 3
239 1 _usage_error("Invalid variable name '$var_name' for --arg");
240 }
241 2 ▶ _usage_error('--arg requires a value') if !@ARGV;
Branch: 1 branch
BranchTrueFalseTotal
unless @ARGV 1 1 2
242 1 my $value = shift @ARGV;
243 1 ▶ $value = '' unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 0 1 1
244 1 $arg_vars{$var_name} = "$value";
245 },
246 7 ▶ 'argjson=s' => sub {
Subroutine __ANON__: called CC=7 SCAR=19.7
247 7 my ($opt_name, $var_name) = @_;
248 7 ▶ _usage_error('--argjson requires a variable name') if !defined $var_name || $var_name eq '';
Branch: 1 branch
BranchTrueFalseTotal
if not defined $var_name or $var_name eq "" 0 7 7
Condition33%1/3
not defined $var_name or $var_name eq ""
l!l&&r!l&&!r
007
MC/DC0%0/2
not defined $var_name or $var_name eq ""
not defined $var_name $var_name eq ""
Truth table33%1/3
not(A) or B
A= not defined $var_nameB= $var_name eq ""
ABresult
1X1
011
000
249 7 ▶ if ($var_name !~ /^[A-Za-z_]\w*$/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($var_name =~ /^[A-Za-z_]\w*$/) 1 6 7
250 1 _usage_error("Invalid variable name '$var_name' for --argjson");
251 }
252 6 ▶ _usage_error('--argjson requires a value') if !@ARGV;
Branch: 1 branch
BranchTrueFalseTotal
unless @ARGV 1 5 6
253 5 my $value_text = shift @ARGV;
254 5 ▶ $value_text = '' unless defined $value_text;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value_text 0 5 5
255  
256 5 my $decoded = eval { JQ::Lite::Util::_decode_json($value_text) };
257 5 ▶ if (my $err = $@) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = $@) 2 3 5
258 2 $err =~ s/\s+\z//;
259 2 _usage_error("invalid JSON for --argjson $var_name: $err");
260 }
261  
262 3 $arg_vars{$var_name} = $decoded;
263 },
264 3 ▶ 'argfile=s' => sub {
Subroutine __ANON__: called CC=9 SCAR=23.0
265 3 my ($opt_name, $var_name) = @_;
266 3 ▶ _usage_error('--argfile requires a variable name') if !defined $var_name || $var_name eq '';
Branch: 1 branch
BranchTrueFalseTotal
if not defined $var_name or $var_name eq "" 0 3 3
Condition33%1/3
not defined $var_name or $var_name eq ""
l!l&&r!l&&!r
003
MC/DC0%0/2
not defined $var_name or $var_name eq ""
not defined $var_name $var_name eq ""
Truth table33%1/3
not(A) or B
A= not defined $var_nameB= $var_name eq ""
ABresult
1X1
011
000
267 3 ▶ if ($var_name !~ /^[A-Za-z_]\w*$/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($var_name =~ /^[A-Za-z_]\w*$/) 0 3 3
268 0 _usage_error("Invalid variable name '$var_name' for --argfile");
269 }
270 3 ▶ _usage_error('--argfile requires a file path') if !@ARGV;
Branch: 1 branch
BranchTrueFalseTotal
unless @ARGV 0 3 3
271 3 my $file_path = shift @ARGV;
272 3 ▶ $file_path = '' unless defined $file_path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $file_path 0 3 3
273  
274 3 ▶ my $fh = IO::File->new($file_path, 'r')
Branch: 1 branch
BranchTrueFalseTotal
my $fh = "IO::File"->new($file_path, "r") or _usage_error("Cannot open file '${file_path}' for --argfile ${var_name}: $!") 2 1 3
275 or _usage_error("Cannot open file '$file_path' for --argfile $var_name: $!");
276 2 local $/;
277 2 my $json_text = <$fh>;
278 2 ▶ $json_text = '' unless defined $json_text;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $json_text 0 2 2
279 2 $fh->close;
280  
281 2 my $decoded = eval { JQ::Lite::Util::_decode_json($json_text) };
282 2 ▶ if (my $err = $@) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = $@) 1 1 2
283 1 $err =~ s/\s+\z//;
284 1 _usage_error("invalid JSON in --argfile $var_name: $err");
285 }
286  
287 1 $arg_vars{$var_name} = $decoded;
288 },
289 2 ▶ 'rawfile=s' => sub {
Subroutine __ANON__: called CC=8 SCAR=22.3
290 2 my ($opt_name, $var_name) = @_;
291 2 ▶ _usage_error('--rawfile requires a variable name') if !defined $var_name || $var_name eq '';
Branch: 1 branch
BranchTrueFalseTotal
if not defined $var_name or $var_name eq "" 0 2 2
Condition33%1/3
not defined $var_name or $var_name eq ""
l!l&&r!l&&!r
002
MC/DC0%0/2
not defined $var_name or $var_name eq ""
not defined $var_name $var_name eq ""
Truth table33%1/3
not(A) or B
A= not defined $var_nameB= $var_name eq ""
ABresult
1X1
011
000
292 2 ▶ if ($var_name !~ /^[A-Za-z_]\w*$/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($var_name =~ /^[A-Za-z_]\w*$/) 0 2 2
293 0 _usage_error("Invalid variable name '$var_name' for --rawfile");
294 }
295 2 ▶ _usage_error('--rawfile requires a file path') if !@ARGV;
Branch: 1 branch
BranchTrueFalseTotal
unless @ARGV 0 2 2
296 2 my $file_path = shift @ARGV;
297 2 ▶ $file_path = '' unless defined $file_path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $file_path 0 2 2
298  
299 open my $fh, '<', $file_path
300 2 ▶ or do {
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $file_path or do { _usage_error("Cannot open file '${file_path}' for --rawfile ${var_name}: $!") } 1 1 2
301 1 _usage_error("Cannot open file '$file_path' for --rawfile $var_name: $!");
302 };
303 1 local $/;
304 1 my $content = <$fh>;
305 1 close $fh;
306 1 ▶ $content = '' unless defined $content;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $content 0 1 1
307  
308 1 $arg_vars{$var_name} = $content;
309 },
310 63 );
311 }
312  
313 54 ▶if (!$getopt_ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($getopt_ok) 1 53 54
314 1 ▶ my $message = @getopt_errors ? $getopt_errors[0] : 'invalid option(s)';
Branch: 1 branch
BranchTrueFalseTotal
@getopt_errors ? : 1 0 1
315 1 $message =~ s/\s+\z//;
316 1 _usage_error($message);
317 }
318  
319 53 ▶if ($help_functions) {
Branch: 1 branch
BranchTrueFalseTotal
if ($help_functions) 0 53 53
320 0 print_supported_functions();
321 0 exit 0;
322 }
323  
324 53 ▶if ($want_help) {
Branch: 1 branch
BranchTrueFalseTotal
if ($want_help) 0 53 53
325 0 print $USAGE;
326 0 exit 0;
327 }
328  
329 53 ▶if ($want_version) {
Branch: 1 branch
BranchTrueFalseTotal
if ($want_version) 0 53 53
330 0 print "jq-lite $JQ::Lite::VERSION\n";
331 0 exit 0;
332 }
333  
334 53 ▶$SIG{PIPE} = sub { exit 0 };
Subroutine __ANON__: called CC=1 SCAR=0.0
335  
336 63 ▶END {
Subroutine END: called CC=5 SCAR=17.5
337 63 ▶ return unless defined fileno(STDOUT);
Branch: 1 branch
BranchTrueFalseTotal
unless defined fileno STDOUT 0 63 63
338  
339 63 ▶ if (!close STDOUT) {
Branch: 1 branch
BranchTrueFalseTotal
if (not close STDOUT) 1 62 63
340 # On older perls a closed pipeline can report EINVAL instead of
341 # EPIPE. Both conditions indicate the writer has no consumer, so do
342 # not emit a warning in either case.
343 63 ▶ return if $!{EPIPE} || $!{EINVAL};
Subroutine BEGIN: called CC=1 SCAR=0.4
Branch: 1 branch
BranchTrueFalseTotal
if $!{"EPIPE"} or $!{"EINVAL"} 1 0 1
Condition33%1/3
$!{"EPIPE"} or $!{"EINVAL"}
l!l&&r!l&&!r
100
MC/DC0%0/2
$!{"EPIPE"} or $!{"EINVAL"}
$!{"EPIPE"} $!{"EINVAL"}
Truth table33%1/3
A or B
A= $!{"EPIPE"}B= $!{"EINVAL"}
ABresult
1X1
011
000
344 0 warn "Unable to flush stdout: $!";
345 }
346 }
347  
348 # ---------- Positional args: '.query' and [file.json] ----------
349 # Unknown options are already rejected above; only query and file remain.
350 53 my ($query, $filename);
351  
352 53 ▶my $non_help_option_used = $raw_input
Condition84%33/39
$raw_input || $raw_output || $compact_output || $ascii_output || $color_output || defined $decoder_choice || $decoder_debug || $exit_status || $null_input || $slurp_input || $force_yaml || @query_files || keys %arg_vars || @slurpfiles
l!l&&r!l&&!r
39410
$raw_input or $raw_output or $compact_output or $ascii_output or $color_output or defined $decoder_choice or $decoder_debug or $exit_status or $null_input or $slurp_input or $force_yaml or @query_files or keys %arg_vars
l!l&&r!l&&!r
37214
$raw_input or $raw_output or $compact_output or $ascii_output or $color_output or defined $decoder_choice or $decoder_debug or $exit_status or $null_input or $slurp_input or $force_yaml or @query_files
l!l&&r!l&&!r
36116
$raw_input or $raw_output or $compact_output or $ascii_output or $color_output or defined $decoder_choice or $decoder_debug or $exit_status or $null_input or $slurp_input or $force_yaml
l!l&&r!l&&!r
35117
$raw_input or $raw_output or $compact_output or $ascii_output or $color_output or defined $decoder_choice or $decoder_debug or $exit_status or $null_input or $slurp_input
l!l&&r!l&&!r
35018
$raw_input or $raw_output or $compact_output or $ascii_output or $color_output or defined $decoder_choice or $decoder_debug or $exit_status or $null_input
l!l&&r!l&&!r
28718
$raw_input or $raw_output or $compact_output or $ascii_output or $color_output or defined $decoder_choice or $decoder_debug or $exit_status
l!l&&r!l&&!r
24425
$raw_input or $raw_output or $compact_output or $ascii_output or $color_output or defined $decoder_choice or $decoder_debug
l!l&&r!l&&!r
24029
$raw_input or $raw_output or $compact_output or $ascii_output or $color_output or defined $decoder_choice
l!l&&r!l&&!r
24029
$raw_input or $raw_output or $compact_output or $ascii_output or $color_output
l!l&&r!l&&!r
24029
$raw_input or $raw_output or $compact_output or $ascii_output
l!l&&r!l&&!r
24029
$raw_input or $raw_output or $compact_output
l!l&&r!l&&!r
71729
$raw_input or $raw_output
l!l&&r!l&&!r
7046
MC/DC57%8/14
$raw_input || $raw_output || $compact_output || $ascii_output || $color_output || defined $decoder_choice || $decoder_debug || $exit_status || $null_input || $slurp_input || $force_yaml || @query_files || keys %arg_vars || @slurpfiles
$raw_input $raw_output $compact_output $ascii_output $color_output defined $decoder_choice $decoder_debug $exit_status $null_input $slurp_input $force_yaml @query_files keys %arg_vars @slurpfiles
Truth table60%9/15
A or B or C or D or E or F or G or H or I or J or K or L or M || N
A= $raw_inputB= $raw_outputC= $compact_outputD= $ascii_outputE= $color_outputF= defined $decoder_choiceG= $decoder_debugH= $exit_statusI= $null_inputJ= $slurp_inputK= $force_yamlL= @query_filesM= keys %arg_varsN= @slurpfiles
ABCDEFGHIJKLMNresult
1XXXXXXXXXXXXX1
01XXXXXXXXXXXX1
001XXXXXXXXXXX1
0001XXXXXXXXXX1
00001XXXXXXXXX1
000001XXXXXXXX1
0000001XXXXXXX1
00000001XXXXXX1
000000001XXXXX1
0000000001XXXX1
00000000001XXX1
000000000001XX1
0000000000001X1
000000000000011
000000000000000
353 || $raw_output
354 || $compact_output
355 || $ascii_output
356 || $color_output
357 || defined $decoder_choice
358 || $decoder_debug
359 || $exit_status
360 || $null_input
361 || $slurp_input
362 || $force_yaml
363 || @query_files
364 || keys(%arg_vars)
365 || @slurpfiles;
366  
367 53 ▶if (@query_files) {
Branch: 1 branch
BranchTrueFalseTotal
if (@query_files) 3 50 53
368 3 ▶ _usage_error('--from-file may only be specified once') if @query_files > 1;
Branch: 1 branch
BranchTrueFalseTotal
if @query_files > 1 0 3 3
369  
370 3 my $file = $query_files[0];
371 3 ▶ if (defined $file && $file eq '-') {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $file and $file eq "-") 2 1 3
Condition66%2/3
defined $file and $file eq "-"
!ll&&!rl&&r
012
MC/DC50%1/2
defined $file and $file eq "-"
defined $file $file eq "-"
Truth table66%2/3
A and B
A= defined $fileB= $file eq "-"
ABresult
0X0
100
111
372 2 ▶ if (!$null_input && !@ARGV) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($null_input or @ARGV) 1 1 2
Condition66%2/3
$null_input or @ARGV
l!l&&r!l&&!r
101
MC/DC50%1/2
$null_input or @ARGV
$null_input @ARGV
Truth table66%2/3
A or B
A= $null_inputB= @ARGV
ABresult
1X1
011
000
373 1 _usage_error('Cannot use --from-file - when reading JSON from STDIN. Provide input file or use --null-input.');
374 }
375 }
376  
377 2 ▶ if (defined $file && $file eq '-') {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $file and $file eq '-') { } 1 1 2
Condition66%2/3
defined $file and $file eq "-"
!ll&&!rl&&r
011
MC/DC50%1/2
defined $file and $file eq "-"
defined $file $file eq "-"
Truth table66%2/3
A and B
A= defined $fileB= $file eq "-"
ABresult
0X0
100
111
378 1 local $/;
379 1 $query = <STDIN>;
380 1 ▶ $query = '' unless defined $query;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $query 0 1 1
381 }
382 else {
383 1 ▶ my $fh = IO::File->new($file, 'r')
Branch: 1 branch
BranchTrueFalseTotal
my $fh = "IO::File"->new($file, "r") or _input_error("Cannot open query file '${file}': $!") 1 0 1
384 or _input_error("Cannot open query file '$file': $!");
385 1 local $/;
386 1 ▶ $query = <$fh> // '';
Condition50%1/2
readline $fh // ""
l!l
10
MC/DC0%0/1
readline $fh // ""
readline $fh
Truth table50%1/2
A
A= readline $fh
Aresult
11
00
387 1 $fh->close;
388 }
389 }
390  
391 52 ▶if (@ARGV == 0) {
Branch: 3 branches
BranchTrueFalseTotal
if (@ARGV == 0) { } 4 48 52
elsif (@ARGV == 1) { } 35 13 48
elsif (@ARGV == 2) { } 13 0 13
392 4 ▶ if (!defined $query) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $query) 3 1 4
393 3 ▶ if ($slurpfile_probably_missing_file) {
Branch: 1 branch
BranchTrueFalseTotal
if ($slurpfile_probably_missing_file) 1 2 3
394 1 _usage_error('--slurpfile requires a file path');
395 }
396  
397 2 ▶ if ($raw_input) {
Branch: 1 branch
BranchTrueFalseTotal
if ($raw_input) 2 0 2
398 2 ▶ my $reason = $slurp_input
Branch: 1 branch
BranchTrueFalseTotal
$slurp_input ? : 1 1 2
399 ? '--raw-input requires a query when used with --slurp.'
400 : '--raw-input requires a query when not using --slurp.';
401 2 _usage_error($reason);
402 }
403  
404 0 ▶ if ($null_input) {
Branch: 1 branch
BranchTrueFalseTotal
if ($null_input) { } 0 0 0
405 0 $query = '.';
406 } else {
407 0 ▶ if ($non_help_option_used) {
Branch: 1 branch
BranchTrueFalseTotal
if ($non_help_option_used) 0 0 0
408 0 _usage_error('filter expression is required');
409 }
410  
411 # If no args and no options, show help
412 0 print $USAGE;
413 0 exit 0;
414 }
415 }
416 }
417 elsif (@ARGV == 1) {
418 # Single arg: query or file
419 35 ▶ if (!$null_input && -f $ARGV[0] && !defined $query) {
Branch: 2 branches
BranchTrueFalseTotal
if (not $null_input and -f $ARGV[0] and not defined $query) { } 0 35 35
elsif (not defined $query) { } 34 1 35
Condition83%5/6
not $null_input and -f $ARGV[0] and not defined $query
!ll&&!rl&&r
3410
not $null_input and -f $ARGV[0]
!ll&&!rl&&r
7271
MC/DC0%0/3
not $null_input and -f $ARGV[0] and not defined $query
not $null_input -f $ARGV[0] not defined $query
Truth table75%3/4
not(A) and B and not(C)
A= not $null_inputB= -f $ARGV[0]C= not defined $query
ABCresult
0XX0
10X0
1100
1111
420 0 $filename = $ARGV[0];
421 # No query -> go to interactive mode (handled later)
422 }
423 elsif (!defined $query) {
424 34 $query = $ARGV[0];
425 }
426 else {
427 # Query already provided via -f; treat arg as filename if it exists
428 1 my $f = $ARGV[0];
429 1 ▶ if ($null_input) {
Branch: 1 branch
BranchTrueFalseTotal
if ($null_input) 0 1 1
430 0 _usage_error('--null-input cannot be combined with file input');
431 }
432 1 ▶ if (-f $f) {
Branch: 1 branch
BranchTrueFalseTotal
if (-f $f) { } 1 0 1
433 1 $filename = $f;
434 } else {
435 0 _input_error("Cannot open file '$f': $!");
436 }
437 }
438 }
439 elsif (@ARGV == 2) {
440 # Two args: query + file (in this order)
441 13 ▶ _usage_error('--null-input cannot be combined with file input') if $null_input;
Branch: 1 branch
BranchTrueFalseTotal
if $null_input 0 13 13
442  
443 13 ▶ if (!defined $query) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $query) { } 13 0 13
444 13 $query = $ARGV[0];
445 } else {
446 0 _usage_error('Cannot provide both --from-file and a query argument');
447 }
448  
449 13 my $f = $ARGV[1];
450 13 ▶ if (-f $f) {
Branch: 1 branch
BranchTrueFalseTotal
if (-f $f) { } 12 1 13
451 12 $filename = $f;
452 } else {
453 1 _input_error("Cannot open file '$f': $!");
454 }
455 }
456 else {
457 0 _usage_error("Usage: jq-lite [options] '.query' [file.json]\n" .
458 " jq-lite [options] -f query.jq [file.json]");
459 }
460  
461 # ---------- JSON decoder selection ----------
462 48 ▶if ($decoder_choice) {
Branch: 1 branch
BranchTrueFalseTotal
if ($decoder_choice) { } 0 48 48
463 0 ▶ if ($decoder_choice eq 'JSON::MaybeXS') {
Branch: 4 branches
BranchTrueFalseTotal
if ($decoder_choice eq 'JSON::MaybeXS') { } 0 0 0
elsif ($decoder_choice eq 'Cpanel::JSON::XS') { } 0 0 0
elsif ($decoder_choice eq 'JSON::XS') { } 0 0 0
elsif ($decoder_choice eq 'JSON::PP') { } 0 0 0
464 0 require JSON::MaybeXS;
465 0 $decoder = \&JSON::MaybeXS::decode_json;
466 0 $decoder_module = 'JSON::MaybeXS';
467 }
468 elsif ($decoder_choice eq 'Cpanel::JSON::XS') {
469 0 require Cpanel::JSON::XS;
470 0 $decoder = \&Cpanel::JSON::XS::decode_json;
471 0 $decoder_module = 'Cpanel::JSON::XS';
472 }
473 elsif ($decoder_choice eq 'JSON::XS') {
474 0 require JSON::XS;
475 0 $decoder = \&JSON::XS::decode_json;
476 0 $decoder_module = 'JSON::XS';
477 }
478 elsif ($decoder_choice eq 'JSON::PP') {
479 0 require JSON::PP;
480 0 $decoder = \&JQ::Lite::Util::_decode_json;
481 0 $decoder_module = 'JSON::PP';
482 }
483 else {
484 0 _usage_error("Unknown JSON module: $decoder_choice");
485 }
486 }
487 else {
488 48 ▶ if (eval { require JSON::MaybeXS; 1 }) {
Branch: 3 branches
BranchTrueFalseTotal
if (eval { do { require JSON::MaybeXS; 1 } }) { } 48 0 48
elsif (eval { do { require Cpanel::JSON::XS; 1 } }) { } 0 0 0
elsif (eval { do { require JSON::XS; 1 } }) { } 0 0 0
489 48 $decoder = \&JSON::MaybeXS::decode_json;
490 48 $decoder_module = 'JSON::MaybeXS';
491 }
492 0 elsif (eval { require Cpanel::JSON::XS; 1 }) {
493 0 $decoder = \&Cpanel::JSON::XS::decode_json;
494 0 $decoder_module = 'Cpanel::JSON::XS';
495 }
496 0 elsif (eval { require JSON::XS; 1 }) {
497 0 $decoder = \&JSON::XS::decode_json;
498 0 $decoder_module = 'JSON::XS';
499 }
500 else {
501 0 require JSON::PP;
502 0 $decoder = \&JQ::Lite::Util::_decode_json;
503 0 $decoder_module = 'JSON::PP';
504 }
505 }
506  
507 48 ▶warn "[DEBUG] Using $decoder_module\n" if $decoder_debug;
Branch: 1 branch
BranchTrueFalseTotal
if $decoder_debug 0 48 48
508  
509 # ---------- --slurpfile handling ----------
510 48 ▶if (@slurpfiles) {
Branch: 1 branch
BranchTrueFalseTotal
if (@slurpfiles) 4 44 48
511 4 ▶ for (my $i = 0; $i < @slurpfiles; $i += 2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @slurpfiles) 4 2 6
512 4 my ($var_name, $file_path) = @slurpfiles[$i, $i + 1];
513  
514 4 ▶ _usage_error('--slurpfile requires a variable name') if !defined $var_name || $var_name eq '';
Branch: 1 branch
BranchTrueFalseTotal
if not defined $var_name or $var_name eq "" 0 4 4
Condition33%1/3
not defined $var_name or $var_name eq ""
l!l&&r!l&&!r
004
MC/DC0%0/2
not defined $var_name or $var_name eq ""
not defined $var_name $var_name eq ""
Truth table33%1/3
not(A) or B
A= not defined $var_nameB= $var_name eq ""
ABresult
1X1
011
000
515 4 ▶ if ($var_name !~ /^[A-Za-z_]\w*$/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($var_name =~ /^[A-Za-z_]\w*$/) 0 4 4
516 0 _usage_error("Invalid variable name '$var_name' for --slurpfile");
517 }
518  
519 4 ▶ _usage_error('--slurpfile requires a file path') if !defined $file_path || $file_path eq '';
Branch: 1 branch
BranchTrueFalseTotal
if not defined $file_path or $file_path eq "" 0 4 4
Condition33%1/3
not defined $file_path or $file_path eq ""
l!l&&r!l&&!r
004
MC/DC0%0/2
not defined $file_path or $file_path eq ""
not defined $file_path $file_path eq ""
Truth table33%1/3
not(A) or B
A= not defined $file_pathB= $file_path eq ""
ABresult
1X1
011
000
520  
521 4 ▶ my $fh = IO::File->new($file_path, 'r')
Branch: 1 branch
BranchTrueFalseTotal
my $fh = "IO::File"->new($file_path, "r") or _usage_error("cannot read file: $file_path") 3 1 4
522 or _usage_error("cannot read file: $file_path");
523 3 local $/;
524 3 my $json_text = <$fh>;
525 3 ▶ $json_text = '' unless defined $json_text;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $json_text 0 3 3
526 3 $fh->close;
527  
528 3 my $decoded = eval { _decode_json_stream($json_text) };
529 3 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 1 2 3
530 1 _usage_error("invalid JSON in slurpfile $var_name");
531 }
532  
533 2 $arg_vars{$var_name} = $decoded;
534 }
535 }
536  
537 # ---------- Validate query before reading input ----------
538 46 ▶if (defined $query) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $query) 46 0 46
539 46 _validate_query_syntax($query);
540 }
541  
542 # ---------- Read JSON input ----------
543 43 my $json_text;
544 43 my $use_yaml = 0;
545 43 ▶if ($null_input) {
Branch: 2 branches
BranchTrueFalseTotal
if ($null_input) { } 8 35 43
elsif (defined $filename) { } 13 22 35
546 8 ▶ $json_text = $slurp_input ? '[]' : 'null';
Branch: 1 branch
BranchTrueFalseTotal
$slurp_input ? : 1 7 8
547 }
548 elsif (defined $filename) {
549 13 ▶ open my $fh, '<', $filename or _input_error("Cannot open file '$filename': $!");
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $filename or _input_error("Cannot open file '${filename}': $!") 13 0 13
550 13 local $/;
551 13 $json_text = <$fh>;
552 13 close $fh;
553 13 ▶ $use_yaml = 1 if !$force_yaml && $filename =~ /\.ya?ml\z/i;
Branch: 1 branch
BranchTrueFalseTotal
if not $force_yaml and $filename =~ /\.ya?ml\z/i 1 12 13
Condition66%2/3
not $force_yaml and $filename =~ /\.ya?ml\z/i
!ll&&!rl&&r
0121
MC/DC50%1/2
not $force_yaml and $filename =~ /\.ya?ml\z/i
not $force_yaml $filename =~ /\.ya?ml\z/i
Truth table66%2/3
not(A) and B
A= not $force_yamlB= $filename =~ /\.ya?ml\z/i
ABresult
0X0
100
111
554 }
555 else {
556 # When no file is given, if STDIN is a TTY, error out to avoid blocking
557 22 ▶ if (-t STDIN) {
Branch: 1 branch
BranchTrueFalseTotal
if (-t STDIN) 0 22 22
558 0 _input_error('No input provided. Pass a file or pipe JSON via STDIN.');
559 }
560 22 local $/;
561 22 $json_text = <STDIN>;
562 }
563  
564 43 ▶$use_yaml = 0 if $raw_input;
Branch: 1 branch
BranchTrueFalseTotal
if $raw_input 4 39 43
565 43 ▶$use_yaml = 1 if $force_yaml && !$null_input;
Branch: 1 branch
BranchTrueFalseTotal
if $force_yaml and not $null_input 1 42 43
Condition66%2/3
$force_yaml and not $null_input
!ll&&!rl&&r
4201
MC/DC50%1/2
$force_yaml and not $null_input
$force_yaml not $null_input
Truth table66%2/3
A and not(B)
A= $force_yamlB= not $null_input
ABresult
0X0
100
111
566  
567 43 ▶if ($use_yaml) {
Branch: 1 branch
BranchTrueFalseTotal
if ($use_yaml) 2 41 43
568 2 $json_text = convert_yaml_to_json($json_text);
569 2 ▶ warn "[DEBUG] Parsing YAML with $yaml_module\n" if $decoder_debug && $yaml_module;
Branch: 1 branch
BranchTrueFalseTotal
if $decoder_debug and $yaml_module 0 2 2
Condition33%1/3
$decoder_debug and $yaml_module
!ll&&!rl&&r
200
MC/DC0%0/2
$decoder_debug and $yaml_module
$decoder_debug $yaml_module
Truth table33%1/3
A and B
A= $decoder_debugB= $yaml_module
ABresult
0X0
100
111
570 }
571  
572 # ---------- JQ::Lite core ----------
573 43 my $jq = JQ::Lite->new(raw => $raw_output, vars => \%arg_vars);
574  
575 43 ▶if ($raw_input) {
Branch: 1 branch
BranchTrueFalseTotal
if ($raw_input) 4 39 43
576 4 $use_yaml = 0; # Raw input is plain text; ignore YAML handling
577 }
578  
579 43 my @raw_lines;
580 43 ▶if ($raw_input) {
Branch: 1 branch
BranchTrueFalseTotal
if ($raw_input) 4 39 43
581 4 ▶ my $text = $json_text // '';
Condition50%1/2
$json_text // ""
l!l
40
MC/DC0%0/1
$json_text // ""
$json_text
Truth table50%1/2
A
A= $json_text
Aresult
11
00
582 4 my $encoder = JSON::PP->new->utf8->allow_nonref;
583  
584 4 ▶ if ($slurp_input) {
Branch: 1 branch
BranchTrueFalseTotal
if ($slurp_input) { } 2 2 4
585 2 $json_text = $encoder->encode($text);
586 }
587 else {
588 2 @raw_lines = split /\r?\n/, $text, -1;
589 2 ▶ if (@raw_lines && $raw_lines[-1] eq '' && $text =~ /\r?\n\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if (@raw_lines and $raw_lines[-1] eq "" and $text =~ /\r?\n\z/) 2 0 2
Condition33%2/6
@raw_lines and $raw_lines[-1] eq "" and $text =~ /\r?\n\z/
!ll&&!rl&&r
002
@raw_lines and $raw_lines[-1] eq ""
!ll&&!rl&&r
002
MC/DC0%0/3
@raw_lines and $raw_lines[-1] eq "" and $text =~ /\r?\n\z/
@raw_lines $raw_lines[-1] eq "" $text =~ /\r?\n\z/
Truth table25%1/4
A and B and C
A= @raw_linesB= $raw_lines[-1] eq ""C= $text =~ /\r?\n\z/
ABCresult
0XX0
10X0
1100
1111
590 2 pop @raw_lines;
591 }
592 }
593 }
594  
595 43 ▶if (!$raw_input && $slurp_input && !$null_input) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $raw_input and $slurp_input and not $null_input) 2 41 43
Condition100%6/6
not $raw_input and $slurp_input and not $null_input
!ll&&!rl&&r
4012
not $raw_input and $slurp_input
!ll&&!rl&&r
4363
MC/DC100%3/3
not $raw_input and $slurp_input and not $null_input
not $raw_input $slurp_input not $null_input
Truth table100%4/4
not(A) and B and not(C)
A= not $raw_inputB= $slurp_inputC= not $null_input
ABCresult
0XX0
10X0
1100
1111
596 2 my $decoded = eval { _decode_json_stream($json_text) };
597 2 ▶ if (!$decoded && $@) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $decoded and $@) 0 2 2
Condition33%1/3
not $decoded and $@
!ll&&!rl&&r
200
MC/DC0%0/2
not $decoded and $@
not $decoded $@
Truth table33%1/3
not(A) and B
A= not $decodedB= $@
ABresult
0X0
100
111
598 0 _input_error("Failed to decode JSON stream for --slurp: $@");
599 }
600  
601 2 $json_text = JSON::PP->new->encode($decoded);
602 }
603  
604 43 ▶if (!$raw_input) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($raw_input) 39 4 43
605 39 ▶ eval { JQ::Lite::Util::_decode_json($json_text); 1 }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { JQ::Lite::Util::_decode_json($json_text); 1 } } or _input_error("Failed to parse JSON input: $@") 38 1 39
606 or _input_error("Failed to parse JSON input: $@");
607 }
608  
609 2 ▶sub convert_yaml_to_json {
Subroutine convert_yaml_to_json: called CC=6 SCAR=20.7
610 2 my ($text) = @_;
611 2 ▶ $text = '' unless defined $text;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $text 0 2 2
612  
613 2 ▶ ($yaml_loader, $yaml_module) = _build_yaml_loader() unless $yaml_loader;
Branch: 1 branch
BranchTrueFalseTotal
unless $yaml_loader 2 0 2
614  
615 2 my @docs = eval { $yaml_loader->($text) };
616 2 ▶ if (my $err = $@) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = $@) 0 2 2
617 0 $err =~ s/\s+\z//;
618 0 _input_error("Failed to parse YAML input: $err");
619 }
620  
621 2 my $data;
622 2 ▶ if (!@docs) {
Branch: 2 branches
BranchTrueFalseTotal
if (not @docs) { } 0 2 2
elsif (@docs == 1) { } 2 0 2
623 0 $data = undef;
624 }
625 elsif (@docs == 1) {
626 2 $data = $docs[0];
627 }
628 else {
629 0 $data = \@docs;
630 }
631  
632 2 return JSON::PP->new->allow_nonref->encode($data);
633 }
634  
635 2 ▶sub _build_yaml_loader {
Subroutine _build_yaml_loader: called CC=3 SCAR=16.8
636 0 ▶ if (eval { require YAML::XS; 1 }) {
Branch: 2 branches
BranchTrueFalseTotal
if (eval { do { require YAML::XS; 1 } }) { } 0 2 2
elsif (eval { do { require YAML::PP; 1 } }) { } 2 0 2
637 0 ▶ return (sub { YAML::XS::Load($_[0]) }, 'YAML::XS');
Subroutine __ANON__: not called CC=1 SCAR=6.9
638 }
639 2 elsif (eval { require YAML::PP; 1 }) {
640 2 require YAML::PP;
641 2 my $yp = YAML::PP->new(boolean => 'JSON::PP');
642 2 ▶ return (sub { $yp->load_string($_[0]) }, 'YAML::PP');
Subroutine __ANON__: called CC=1 SCAR=0.0
643 }
644 else {
645 0 require CPAN::Meta::YAML;
646 return (
647 0 ▶ sub {
Subroutine __ANON__: not called CC=4 SCAR=26.1
648 0 ▶ my $string = shift // '';
Condition0%0/2
shift() // ""
l!l
00
MC/DC0%0/1
shift() // ""
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
649 0 my $docs = CPAN::Meta::YAML->read_string($string);
650 0 ▶ if (!defined $docs) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $docs) 0 0 0
651 0 my $err;
652 {
653 0 ▶ no warnings 'once';
Subroutine BEGIN: called CC=1 SCAR=0.2
654 0 $err = $CPAN::Meta::YAML::errstr;
655 }
656 0 ▶ $err ||= 'Unknown YAML parsing error';
Condition0%0/2
$err ||= "Unknown YAML parsing error"
l!l
00
MC/DC0%0/1
$err ||= "Unknown YAML parsing error"
$err
Truth table0%0/2
A
A= $err
Aresult
11
00
657 0 die $err;
658 }
659 0 return @{$docs};
660 },
661 0 'CPAN::Meta::YAML'
662 );
663 }
664 }
665  
666 5 ▶sub _decode_json_stream {
Subroutine _decode_json_stream: called CC=5 SCAR=16.1
667 5 my ($text) = @_;
668 5 ▶ $text = '' unless defined $text;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $text 0 5 5
669  
670 5 my $length = length $text;
671 5 my $offset = 0;
672 5 my @values;
673 5 my $decoder = JSON::PP->new->utf8->allow_nonref;
674  
675 5 while (1) {
676 11 ▶ while ($offset < $length && substr($text, $offset, 1) =~ /\s/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($offset < $length and substr($text, $offset, 1) =~ /\s/) 6 11 17
Condition100%3/3
$offset < $length and substr($text, $offset, 1) =~ /\s/
!ll&&!rl&&r
476
MC/DC100%2/2
$offset < $length and substr($text, $offset, 1) =~ /\s/
$offset < $length substr($text, $offset, 1) =~ /\s/
Truth table100%3/3
A and B
A= $offset < $lengthB= substr($text, $offset, 1) =~ /\s/
ABresult
0X0
100
111
677 6 $offset++;
678 }
679 11 ▶ last if $offset >= $length;
Branch: 1 branch
BranchTrueFalseTotal
if $offset >= $length 4 7 11
680  
681 7 my ($value, $consumed);
682 7 ($value, $consumed) = $decoder->decode_prefix(substr($text, $offset));
683  
684 6 push @values, $value;
685 6 $offset += $consumed;
686 }
687  
688 4 return \@values;
689 }
690  
691 # ---------- Colorization ----------
692 0 ▶sub colorize_json {
Subroutine colorize_json: not called CC=1 SCAR=6.9
693 0 my $json = shift;
694  
695 0 $json =~ s/"([^"]+)"(?=\s*:)/color("cyan")."\"$1\"".color("reset")/ge;
696 0 $json =~ s/(:\s*)"([^"]*)"/$1.color("green")."\"$2\"".color("reset")/ge;
697 0 $json =~ s/(:\s*)(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)/$1.color("yellow")."$2".color("reset")/ge;
698 0 $json =~ s/(:\s*)(true|false|null)/$1.color("magenta")."$2".color("reset")/ge;
699  
700 0 return $json;
701 }
702  
703 # ---------- Output ----------
704 39 ▶sub print_results {
Subroutine print_results: called CC=8 SCAR=21.4
705 39 my @results = @_;
706 39 my $pp = JSON::PP->new->utf8->allow_nonref->canonical;
707 39 ▶ $pp->pretty unless $compact_output;
Branch: 1 branch
BranchTrueFalseTotal
unless $compact_output 19 20 39
708 39 $pp->ascii($ascii_output);
709  
710 39 for my $r (@results) {
711 2089 ▶ if (!defined $r) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $r) { } 2 2087 2089
elsif ($raw_output and not ref $r) { } 0 2087 2087
712 2 print "null\n";
713 }
714 ▶ elsif ($raw_output && !ref($r)) {
Condition33%1/3
$raw_output and not ref $r
!ll&&!rl&&r
208700
MC/DC0%0/2
$raw_output and not ref $r
$raw_output not ref $r
Truth table33%1/3
A and not(B)
A= $raw_outputB= not ref $r
ABresult
0X0
100
111
715 0 print "$r\n";
716 }
717 else {
718 2087 my $json = $pp->encode($r);
719 2087 ▶ $json = colorize_json($json) if $color_output;
Branch: 1 branch
BranchTrueFalseTotal
if $color_output 0 2087 2087
720 2087 print $json;
721 2086 ▶ print "\n" unless $json =~ /\n\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $json =~ /\n\z/ 23 2063 2086
722 }
723 }
724 }
725  
726 # ---------- Interactive mode ----------
727 42 ▶if ($raw_input && !defined $query) {
Branch: 1 branch
BranchTrueFalseTotal
if ($raw_input and not defined $query) 0 42 42
Condition66%2/3
$raw_input and not defined $query
!ll&&!rl&&r
3840
MC/DC0%0/2
$raw_input and not defined $query
$raw_input not defined $query
Truth table66%2/3
A and not(B)
A= $raw_inputB= not defined $query
ABresult
0X0
100
111
728 0 ▶ my $reason = $slurp_input
Branch: 1 branch
BranchTrueFalseTotal
$slurp_input ? : 0 0 0
729 ? '--raw-input requires a query when used with --slurp.'
730 : '--raw-input requires a query when not using --slurp.';
731 0 _usage_error($reason);
732 }
733  
734 42 ▶if (!defined $query) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $query) 0 42 42
735 0 system("stty -icanon -echo");
736  
737 0 ▶ $SIG{INT} = sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
738 0 system("stty sane");
739 0 print "\n[EXIT]\n";
740 0 exit 0;
741 0 };
742  
743 0 my $input = '';
744 0 my @last_results;
745  
746 0 my $ok = eval {
747 0 @last_results = $jq->run_query($json_text, '.');
748 0 1;
749 };
750 0 ▶ if (!$ok || !@last_results) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok and @last_results) 0 0 0
Condition0%0/3
$ok and @last_results
!ll&&!rl&&r
000
MC/DC0%0/2
$ok and @last_results
$ok @last_results
Truth table0%0/3
A and B
A= $okB= @last_results
ABresult
0X0
100
111
751 0 my $data = eval { JQ::Lite::Util::_decode_json($json_text) };
752 0 ▶ if ($data) {
Branch: 1 branch
BranchTrueFalseTotal
if ($data) 0 0 0
753 0 @last_results = ($data);
754 }
755 }
756  
757 0 system("clear");
758 0 ▶ if (@last_results) {
Branch: 1 branch
BranchTrueFalseTotal
if (@last_results) { } 0 0 0
759 0 print_results(@last_results);
760 } else {
761 0 print "[INFO] Failed to load initial JSON data.\n";
762 }
763  
764 0 print "\nType query (ESC to quit):\n";
765 0 print "> $input\n";
766  
767 0 while (1) {
768 0 my $char;
769 0 sysread(STDIN, $char, 1);
770  
771 0 my $ord = ord($char);
772 0 ▶ last if $ord == 27; # ESC
Branch: 1 branch
BranchTrueFalseTotal
if $ord == 27 0 0 0
773  
774 0 ▶ if ($ord == 127 || $char eq "\b") {
Branch: 1 branch
BranchTrueFalseTotal
if ($ord == 127 or $char eq "\cH") { } 0 0 0
Condition0%0/3
$ord == 127 or $char eq "\b"
l!l&&r!l&&!r
000
MC/DC0%0/2
$ord == 127 or $char eq "\b"
$ord == 127 $char eq "\b"
Truth table0%0/3
A or B
A= $ord == 127B= $char eq "\b"
ABresult
1X1
011
000
775 0 ▶ chop $input if length($input);
Branch: 1 branch
BranchTrueFalseTotal
if length $input 0 0 0
776 } else {
777 0 $input .= $char;
778 }
779  
780 0 system("clear");
781  
782 0 my @results;
783 0 my $ok = eval {
784 0 @results = $jq->run_query($json_text, $input);
785 0 1;
786 };
787  
788 0 ▶ if ($ok && @results) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ok and @results) 0 0 0
Condition0%0/3
$ok and @results
!ll&&!rl&&r
000
MC/DC0%0/2
$ok and @results
$ok @results
Truth table0%0/3
A and B
A= $okB= @results
ABresult
0X0
100
111
789 0 @last_results = @results;
790 }
791  
792 0 ▶ if (!$ok) {
Branch: 2 branches
BranchTrueFalseTotal
if (not $ok) { } 0 0 0
elsif (not @results) { } 0 0 0
793 0 print "[INFO] Invalid or partial query. Showing last valid results.\n";
794 } elsif (!@results) {
795 0 print "[INFO] Query returned no results. Showing last valid results.\n";
796 }
797  
798 0 ▶ if (@last_results) {
Branch: 1 branch
BranchTrueFalseTotal
if (@last_results) { } 0 0 0
799 eval {
800 0 print_results(@last_results);
801 0 1;
802 0 ▶ } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { print_results(@last_results); 1 } } or do { my $e = $@ || "Unknown error"; print "[RUNTIME]Failed to print: $e\n" } 0 0 0
803 0 ▶ my $e = $@ || 'Unknown error';
Condition0%0/2
$@ || 'Unknown error'
l!l
00
MC/DC0%0/1
$@ || 'Unknown error'
$@
Truth table0%0/2
A
A= $@
Aresult
11
00
804 0 print "[RUNTIME]Failed to print: $e\n";
805 };
806 } else {
807 0 print "[INFO] No previous valid results.\n";
808 }
809  
810 0 print "\n> $input\n";
811 }
812  
813 0 system("stty sane");
814 0 print "\nGoodbye.\n";
815 0 exit 0;
816 }
817  
818 # ---------- One-shot mode ----------
819 42 my @results;
820  
821 42 ▶if ($raw_input && !$slurp_input) {
Branch: 1 branch
BranchTrueFalseTotal
if ($raw_input and not $slurp_input) { } 2 40 42
Condition100%3/3
$raw_input and not $slurp_input
!ll&&!rl&&r
3822
MC/DC100%2/2
$raw_input and not $slurp_input
$raw_input not $slurp_input
Truth table100%3/3
A and not(B)
A= $raw_inputB= not $slurp_input
ABresult
0X0
100
111
822 2 my $encoder = JSON::PP->new->utf8->allow_nonref;
823 2 for my $line (@raw_lines) {
824 5002 my $encoded_line = $encoder->encode($line);
825 5002 my @line_results = eval { $jq->run_query($encoded_line, $query) };
826 5002 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 5002 5002
827 0 ▶ my $err = $@ || 'Unknown error';
Condition0%0/2
$@ || 'Unknown error'
l!l
00
MC/DC0%0/1
$@ || 'Unknown error'
$@
Truth table0%0/2
A
A= $@
Aresult
11
00
828 0 $err =~ s/\s+\z//;
829 0 _runtime_error($err);
830 }
831 5002 push @results, @line_results;
832 }
833 }
834 else {
835 40 @results = eval { $jq->run_query($json_text, $query) };
836 40 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 3 37 40
837 3 ▶ my $err = $@ || 'Unknown error';
Condition50%1/2
$@ || 'Unknown error'
l!l
30
MC/DC0%0/1
$@ || 'Unknown error'
$@
Truth table50%1/2
A
A= $@
Aresult
11
00
838 3 $err =~ s/\s+\z//;
839 3 _runtime_error($err);
840 }
841 }
842  
843 39 my $status = 0;
844 39 ▶if ($exit_status) {
Branch: 1 branch
BranchTrueFalseTotal
if ($exit_status) 4 35 39
845 4 ▶ my $last = @results ? $results[-1] : undef;
Branch: 1 branch
BranchTrueFalseTotal
@results ? : 3 1 4
846 4 ▶ $status = _is_truthy($last) ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
_is_truthy($last) ? : 1 3 4
847 }
848  
849 0 ▶sub print_supported_functions {
Subroutine print_supported_functions: not called CC=1 SCAR=6.9
850 0 print <<'EOF';
851  
852 Supported Functions:
853 length - Count array elements, hash keys, or characters in scalars
854 keys - Extract sorted keys from a hash or indexes from an array
855 keys_unsorted - Extract object keys without sorting (jq-compatible)
856 values - Extract values from a hash (v0.34)
857 leaf_paths() - Emit only terminal paths to leaf values
858 sort - Sort array items
859 sort_desc - Sort array items in descending order
860 sort_by(KEY) - Sort array of objects by key
861 pluck(KEY) - Collect a key's value from each object in an array
862 pick(KEYS...) - Build new objects containing only the supplied keys (arrays handled element-wise)
863 merge_objects() - Merge arrays of objects into a single hash (last-write-wins)
864 unique - Remove duplicate values
865 unique_by(KEY) - Remove duplicates by projecting each item on KEY
866 reverse - Reverse an array
867 first / last - Get first / last element of an array
868 limit(N) - Limit array to first N elements
869 drop(N) - Skip the first N elements of an array
870 rest - Drop the first element of an array
871 tail(N) - Return the final N elements of an array
872 chunks(N) - Split array into subarrays each containing up to N items
873 range(START; END[, STEP])
874 - Emit numbers from START (default 0) up to but not including END using STEP (default 1)
875 enumerate() - Pair each array element with its zero-based index
876 transpose() - Rotate arrays-of-arrays from rows into columns
877 scalars - Pass through only scalar inputs (string/number/bool/null)
878 objects - Pass through only object inputs
879 count - Count total number of matching items
880 map(EXPR) - Map/filter array items with a subquery
881 map_values(FILTER)
882 - Apply FILTER to each value in an object (dropping keys when FILTER yields no result)
883 if COND then A [elif COND then B ...] [else Z] end
884 - jq-style conditional branching across optional elif/else chains
885 foreach(EXPR as $var (init; update [; extract]))
886 - jq-compatible streaming reducer with lexical bindings and optional emitters
887 walk(FILTER) - Recursively apply FILTER to every value in arrays and objects
888 recurse([FILTER])
889 - Emit the current value and depth-first descendants using optional FILTER for children
890 add / sum - Sum all numeric values in an array
891 sum_by(KEY) - Sum numeric values projected from each array item
892 avg_by(KEY) - Average numeric values projected from each array item
893 median_by(KEY) - Return the median of numeric values projected from each array item
894 min_by(PATH) - Return the element with the smallest projected value
895 max_by(PATH) - Return the element with the largest projected value
896 product - Multiply all numeric values in an array
897 min / max - Return minimum / maximum numeric value in an array
898 avg - Return the average of numeric values in an array
899 median - Return the median of numeric values in an array
900 mode - Return the most frequent value in an array (ties pick earliest occurrence)
901 percentile(P) - Return the requested percentile (0-100 or 0-1) of numeric array values
902 variance - Return the variance of numeric values in an array
903 stddev - Return the standard deviation of numeric values in an array
904 abs - Convert numbers (and array elements) to their absolute value
905 ceil() - Round numbers up to the nearest integer
906 floor() - Round numbers down to the nearest integer
907 round() - Round numbers to the nearest integer (half-up semantics)
908 clamp(MIN, MAX) - Clamp numeric values within an inclusive range
909 tostring() - Convert values into their JSON string representation
910 @json - Format the input as JSON text (jq-style formatter)
911 @csv - Format arrays/scalars as a single CSV row
912 @tsv - Format arrays/scalars as a single TSV row
913 @base64 - Encode input as a Base64 string
914 @base64d - Decode Base64-encoded text into strings/arrays
915 @uri - Percent-encode text (URL-safe)
916 tojson() - Encode values as JSON text regardless of type
917 fromjson() - Decode JSON text into native values (arrays handled element-wise)
918 tonumber() / to_number()
919 - Coerce numeric-looking strings/booleans into numbers
920 nth(N) - Get the Nth element of an array (zero-based index)
921 index(VALUE) - Return the zero-based index of VALUE within arrays or strings
922 rindex(VALUE) - Return the zero-based index of the last VALUE within arrays or strings
923 indices(VALUE) - Return every index where VALUE occurs within arrays or strings
924 group_by(KEY) - Group array items by field
925 group_count(KEY) - Count grouped items by field
926 join(SEPARATOR) - Join array elements with a string
927 split(SEPARATOR) - Split string values (and arrays of strings) by a literal separator
928 substr(START[, LENGTH])
929 - Extract substring using zero-based indices (arrays handled element-wise)
930 slice(START[, LENGTH])
931 - Return a subarray using zero-based indices (negative starts count from the end)
932 replace(OLD; NEW)
933 - Replace literal substrings (arrays handled element-wise)
934 to_entries - Convert objects/arrays into [{"key","value"}, ...] pairs
935 from_entries - Convert entry arrays back into an object
936 with_entries(FILTER)
937 - Transform entries using FILTER and rebuild an object
938 delpaths(PATHS) - Delete keys at the supplied PATHS array (jq-compatible)
939 has - Check if objects contain a key or arrays expose an index
940 contains - Check if strings include a fragment, arrays contain an element, or hashes have a key
941 contains_subset(VALUE)
942 - recursive array multiset containment (not identical to jq contains)
943 inside(CONTAINER) - Check if the input value is contained within CONTAINER
944 any([FILTER]) - Return true if any input (optionally filtered) is truthy
945 all([FILTER]) - Return true if every input (optionally filtered) is truthy
946 not - Logical negation following jq truthiness rules
947 test("pattern"[, "flags"]) - Check strings against regexes (flags: i, m, s, x)
948 explode() - Convert strings to arrays of Unicode code points
949 implode() - Turn arrays of code points back into strings
950 flatten - Explicitly flatten arrays (same as .[])
951 flatten_all() - Recursively flatten nested arrays into a single array
952 flatten_depth(N) - Flatten nested arrays up to N levels deep
953 arrays - Pass through inputs that are arrays, discarding others
954 del(KEY) - Remove a key from objects in the result
955 compact - Remove undefined values from arrays
956 path - Return available keys for objects or indexes for arrays
957 paths - Emit every path to nested values as an array of keys/indices
958 getpath(PATH) - Retrieve the value(s) at the supplied path array or expression
959 setpath(PATH; VALUE)
960 - Set or create value(s) at a path using literal or filter input
961 is_empty - Check if an array or object is empty
962 upper() - Convert scalars and array elements to uppercase
963 lower() - Convert scalars and array elements to lowercase
964 ascii_upcase() - ASCII-only uppercase conversion (leaves non-ASCII untouched)
965 ascii_downcase() - ASCII-only lowercase conversion (leaves non-ASCII untouched)
966 titlecase() - Convert scalars and array elements to title case
967 trim() - Strip leading/trailing whitespace from strings (recurses into arrays)
968 ltrimstr(PFX) - Remove PFX when it appears at the start of strings (arrays handled element-wise)
969 rtrimstr(SFX) - Remove SFX when it appears at the end of strings (arrays handled element-wise)
970 startswith(PFX) - Check if a string (or array of strings) begins with PFX
971 endswith(SFX) - Check if a string (or array of strings) ends with SFX
972 empty - Discard all output (for side-effect use)
973 type() - Return the type of value ("string", "number", "boolean", "array", "object", "null")
974 lhs // rhs - jq-style alternative operator yielding rhs when lhs is null/missing
975 default(VALUE) - Substitute VALUE when result is undefined
976  
977 EOF
978 }
979  
980 39 print_results(@results);
981  
982 38 exit $status;
983  
984 __END__
« blib/lib/JQ/Lite/Util/Paths.pm ↑ Summary lib/JQ/Lite/Value.pm »