blib/lib/Punk/Command.pm

filter: Statementstmt 77.0% 838 / 1087 Branchbran 54.5% 346 / 634 Conditioncond 46.6% 167 / 358 MC/DCmcdc 22.9% 47 / 205 Subroutinesub 87.1% 68 / 78 Podpod 100% 11 / 11 totaltotal 62.2% 1477 / 2373 CC 505 SCAR 48.6
CC
505
Cov
65%
dev
1056.0
api_sync
450.9
routes
152.8
CRAP 128.5
↑ Summary blib/lib/Punk/DevError.pm »
1 package Punk::Command;
2  
3 51 ▶use 5.010;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 51 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 51 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 51 ▶use Carp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
7 51 ▶use Cwd ();
Subroutine BEGIN: called CC=1 SCAR=0.0
8 51 ▶use File::Spec ();
Subroutine BEGIN: called CC=1 SCAR=0.0
9 51 ▶use File::Basename ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10 51 ▶use Getopt::Long ();
Subroutine BEGIN: called CC=1 SCAR=0.0
11 51 ▶use Punk ();
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 51 our $VERSION = '0.69';
14  
15 # The whole punk command line. bin/punk is two lines - `exit
16 # Punk::Command->main(@ARGV)` - and everything else is here: a registry of
17 # command specs, one dispatcher that owns option parsing and help generation,
18 # and the command bodies. Exit codes: 0 fine, 1 something is wrong with the
19 # application or its environment, 2 the command was used wrongly (misuse
20 # prints the generated usage to STDERR).
21 #
22 # A compiled-at-boot framework is opaque from the outside: everything is
23 # resolved and frozen inside one coderef at to_app. These commands exist to
24 # open that up - what the router actually holds, what the spec actually maps
25 # to, what the configuration actually resolved to, and which C ABIs are
26 # actually in play.
27  
28 # ---- the registry ------------------------------------------------------------
29 #
30 # A command is a spec registered by name. Help is GENERATED from the spec, so
31 # `punk help X`, `punk X --help` and every misuse path read one source and
32 # cannot drift - the invariant the old %USAGE heredocs tried to hold by hand.
33 #
34 # Punk::Command->register(greet => {
35 # abstract => 'one line for the command list',
36 # display => 'greet <what>', # the list row, when the name alone misleads
37 # usage => '[options]', # after "usage: punk serve "
38 # desc => 'a paragraph for the help page',
39 # options => [ { spec => 'port=i', arg => 'N',
40 # doc => 'listen port', default => 5000 } ],
41 # commands => { sync => \%subspec }, # nested verbs (punk api sync)
42 # code => sub { my ($opt, @args) = @_; ...; return 0 },
43 # hidden => 0,
44 # hints => [ [ qr/pattern/, 'the next move worth spelling out' ] ],
45 # }, $owner);
46 #
47 # Two owners claiming one name croak naming both (the install_kw rule).
48 # Registration order is display order. A command body signals misuse with
49 # `die { usage_error => $msg }` (message + usage + exit 2); any other die
50 # becomes `punk <cmd>: msg` + exit 1, with the spec's hints appended when
51 # their pattern matches.
52 #
53 # An unknown command X gets one shot at `require Punk::Command::<ucfirst X>`,
54 # whose load-time job is to call register - the seam a plugin dist uses to add
55 # `punk queue ...`. No namespace scanning, no cost on the common path.
56  
57 51 our ($OUT, $ERR); # the test seam: filehandles replacing STDOUT/STDERR
58  
59 51 our (%SPECS, @ORDER, %OWNER);
60 51 our @DOCTOR;
61 51 my %DOCTOR_OWNER;
62  
63 620 ▶sub register {
Subroutine register: called CC=7 SCAR=20.3
Pod documented
64 620 my ($class, $name, $spec, $owner) = @_;
65 620 ▶ $owner //= caller;
Condition66%2/3
$owner //= caller
l!l&&r!l&&!r
76130
MC/DC0%0/2
$owner //= caller
$owner caller
Truth table66%2/3
A //= B
A= $ownerB= caller
ABresult
1X1
011
000
66 620 ▶ Carp::croak('Punk::Command: register needs a name and a spec hashref')
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and length $name and ref $spec eq "HASH" 1 619 620
Condition50%3/6
defined $name and length $name and ref $spec eq "HASH"
!ll&&!rl&&r
01619
defined $name and length $name
!ll&&!rl&&r
00620
MC/DC33%1/3
defined $name and length $name and ref $spec eq "HASH"
defined $name length $name ref $spec eq "HASH"
Truth table50%2/4
A and B and C
A= defined $nameB= length $nameC= ref $spec eq "HASH"
ABCresult
0XX0
10X0
1100
1111
67 unless defined $name && length $name && ref $spec eq 'HASH';
68 619 ▶ if (my $prev = $OWNER{$name}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $prev = $Punk::Command::OWNER{$name}) 1 618 619
69 1 Carp::croak("Punk::Command: command '$name' is registered by both "
70 . "$prev and $owner");
71 }
72 618 $OWNER{$name} = $owner;
73 618 push @ORDER, $name;
74 618 ▶ $spec->{name} //= $name; # so a diagnostic can name the command it is about
Condition33%1/3
$spec->{"name"} //= $name
l!l&&r!l&&!r
06180
MC/DC0%0/2
$spec->{"name"} //= $name
$spec->{"name"} $name
Truth table33%1/3
A //= B
A= $spec->{"name"}B= $name
ABresult
1X1
011
000
75 618 $SPECS{$name} = $spec;
76 618 return $class;
77 }
78  
79 # A doctor row: label plus a probe returning (ok, detail). Core rows register
80 # here too, so a plugin's rows land in the same report.
81 7 ▶sub register_doctor {
Subroutine register_doctor: called CC=3 SCAR=11.1
Pod documented
82 7 my ($class, $label, $probe, $owner) = @_;
83 7 ▶ $owner //= caller;
Condition33%1/3
$owner //= caller
l!l&&r!l&&!r
700
MC/DC0%0/2
$owner //= caller
$owner caller
Truth table33%1/3
A //= B
A= $ownerB= caller
ABresult
1X1
011
000
84 7 ▶ if (my $prev = $DOCTOR_OWNER{$label}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $prev = $DOCTOR_OWNER{$label}) 1 6 7
85 1 Carp::croak("Punk::Command: doctor row '$label' is registered by "
86 . "both $prev and $owner");
87 }
88 6 $DOCTOR_OWNER{$label} = $owner;
89 6 push @DOCTOR, [ $label, $probe ];
90 6 return $class;
91 }
92  
93 # every command takes these; a spec's own option with the same key wins
94 51 my @SHARED_OPTIONS = (
95 { spec => 'dir=s', arg => 'PATH',
96 doc => 'the application (default: found by walking up for app.psgi)' },
97 );
98  
99 874 ▶sub _opt_key {
Subroutine _opt_key: called CC=1 SCAR=0.0
100 874 my ($spec) = @_;
101 874 my ($name) = $spec =~ /^([^=|!+\@]+)/;
102 874 $name =~ tr/-/_/;
103 874 return $name;
104 }
105  
106 # ---- the dispatcher ----------------------------------------------------------
107  
108 71 ▶sub main {
Subroutine main: called CC=35 SCAR=37.9
Pod documented
109 71 my ($class, @argv) = @_;
110 71 ▶ local *STDOUT = $OUT if $OUT;
Branch: 1 branch
BranchTrueFalseTotal
if $Punk::Command::OUT 27 44 71
111 71 ▶ local *STDERR = $ERR if $ERR;
Branch: 1 branch
BranchTrueFalseTotal
if $Punk::Command::ERR 27 44 71
112  
113 71 ▶ if (!@argv || $argv[0] eq '-h' || $argv[0] eq '--help') {
Branch: 1 branch
BranchTrueFalseTotal
if (not @argv or $argv[0] eq "-h" or $argv[0] eq "--help") 2 69 71
Condition66%4/6
not @argv or $argv[0] eq "-h" or $argv[0] eq "--help"
l!l&&r!l&&!r
2069
not @argv or $argv[0] eq "-h"
l!l&&r!l&&!r
2069
MC/DC33%1/3
not @argv or $argv[0] eq "-h" or $argv[0] eq "--help"
not @argv $argv[0] eq "-h" $argv[0] eq "--help"
Truth table50%2/4
not(A) or B or C
A= not @argvB= $argv[0] eq "-h"C= $argv[0] eq "--help"
ABCresult
1XX1
01X1
0011
0000
114 2 _usage_all(\*STDOUT);
115 2 return 0;
116 }
117 69 ▶ if ($argv[0] eq '-v' || $argv[0] eq '--version') {
Branch: 1 branch
BranchTrueFalseTotal
if ($argv[0] eq "-v" or $argv[0] eq "--version") 1 68 69
Condition66%2/3
$argv[0] eq "-v" or $argv[0] eq "--version"
l!l&&r!l&&!r
0168
MC/DC50%1/2
$argv[0] eq "-v" or $argv[0] eq "--version"
$argv[0] eq "-v" $argv[0] eq "--version"
Truth table66%2/3
A or B
A= $argv[0] eq "-v"B= $argv[0] eq "--version"
ABresult
1X1
011
000
118 1 print "punk $Punk::VERSION\n";
119 1 return 0;
120 }
121  
122 68 my $name = shift @argv;
123 68 ▶ return _cmd_help(@argv) if $name eq 'help';
Branch: 1 branch
BranchTrueFalseTotal
if $name eq "help" 11 57 68
124  
125 57 ▶ my $spec = $SPECS{$name} // _probe($name);
Condition100%3/3
$Punk::Command::SPECS{$name} // _probe($name)
l!l&&r!l&&!r
5511
MC/DC100%2/2
$Punk::Command::SPECS{$name} // _probe($name)
$Punk::Command::SPECS{$name} _probe($name)
Truth table100%3/3
A // B
A= $Punk::Command::SPECS{$name}B= _probe($name)
ABresult
1X1
011
000
126 57 ▶ unless ($spec) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($spec) 1 56 57
127 1 print STDERR "punk: unknown command '$name'\n\n";
128 1 _usage_all(\*STDERR);
129 1 return 2;
130 }
131  
132 # descend nested verbs (punk api sync, punk queue jobs ...)
133 56 my $path = $name;
134 56 ▶ while ($spec->{commands}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($spec->{"commands"}) 21 55 76
135 21 ▶ my $tok = (@argv && $argv[0] !~ /^-/) ? $argv[0] : undef;
Branch: 1 branch
BranchTrueFalseTotal
@argv && !($argv[0] =~ /^-/) ? : 21 0 21
Condition33%1/3
@argv and not $argv[0] =~ /^-/
!ll&&!rl&&r
0021
MC/DC0%0/2
@argv and not $argv[0] =~ /^-/
@argv not $argv[0] =~ /^-/
Truth table33%1/3
A and not(B)
A= @argvB= not $argv[0] =~ /^-/
ABresult
0X0
100
111
136 21 ▶ if (defined $tok && $spec->{commands}{$tok}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $tok and $spec->{"commands"}{$tok}) 20 1 21
Condition66%2/3
defined $tok and $spec->{"commands"}{$tok}
!ll&&!rl&&r
0120
MC/DC50%1/2
defined $tok and $spec->{"commands"}{$tok}
defined $tok $spec->{"commands"}{$tok}
Truth table66%2/3
A and B
A= defined $tokB= $spec->{"commands"}{$tok}
ABresult
0X0
100
111
137 20 shift @argv;
138 20 $spec = $spec->{commands}{$tok};
139 20 $path .= " $tok";
140 20 next;
141 }
142 1 ▶ last if $spec->{code};
Branch: 1 branch
BranchTrueFalseTotal
if $spec->{"code"} 0 1 1
143 1 ▶ if (defined $tok) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $tok) 1 0 1
144 1 my @verbs = sort keys %{ $spec->{commands} };
145 1 ▶ print STDERR @verbs == 1
Branch: 1 branch
BranchTrueFalseTotal
@verbs == 1 ? : 1 0 1
146 ? "punk $path: expected '$verbs[0]'\n\n"
147 : "punk $path: unknown subcommand '$tok' (expected one of: "
148 . join(', ', @verbs) . ")\n\n";
149 }
150 1 _usage_cmd($path, $spec, \*STDERR);
151 1 return 2;
152 }
153  
154 # a raw spec owns its own argv - options, help, everything - which is
155 # what an adapter over another CLI wants (punk queue X == punk-queue X)
156 55 ▶ if ($spec->{raw}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($spec->{"raw"}) 0 55 55
157 0 my $code = eval { $spec->{code}->({}, @argv) };
158 0 ▶ if (my $err = $@) { return _fail($path, $err, $spec->{hints}) }
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = $@) 0 0 0
159 0 ▶ return defined $code ? int $code : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $code ? : 0 0 0
160 }
161  
162 # A command may bring options it cannot know at registration time: `new`
163 # asks the kit named in argv for its own. Resolved before Getopt so the
164 # kit's options parse and show up in help like any other, rather than
165 # being scraped out of a leftover argv by the command body.
166 55 my (@extra, @options);
167 {
168 # Both halves under one eval: resolving them can croak (a kit that
169 # will not load), and so can merging them (an option the command
170 # already declares). Either is a die that has to become one line and
171 # an exit code, not a raw croak out of main.
172 55 my $ok = eval {
173 @extra = $spec->{extra_options}
174 55 ▶ ? $spec->{extra_options}->(@argv) : ();
Branch: 1 branch
BranchTrueFalseTotal
$spec->{'extra_options'} ? : 9 46 55
175 55 @options = _options_for($spec, \@extra);
176 54 1;
177 };
178 55 ▶ return _fail($path, $@, $spec->{hints}) unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 1 54 55
179 }
180  
181 54 my (%opt, @gspec);
182 54 for my $o (@options) {
183 296 my $k = _opt_key($o->{spec});
184 296 ▶ if ($o->{spec} =~ /\@$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($o->{'spec'} =~ /\@$/) { } 0 296 296
185 0 ▶ $opt{$k} = [ @{ $o->{default} || [] } ];
Condition0%0/2
$o->{'default'} || []
l!l
00
MC/DC0%0/1
$o->{'default'} || []
$o->{'default'}
Truth table0%0/2
A
A= $o->{'default'}
Aresult
11
00
186 0 push @gspec, $o->{spec} => $opt{$k};
187 }
188 else {
189 296 ▶ $opt{$k} = $o->{default} if exists $o->{default};
Branch: 1 branch
BranchTrueFalseTotal
if exists $o->{"default"} 25 271 296
190 296 push @gspec, $o->{spec} => \$opt{$k};
191 }
192 }
193 {
194 54 my $saved = Getopt::Long::Configure(
195 qw(no_auto_abbrev no_ignore_case bundling));
196 54 my $ok = do {
197 2 ▶ local $SIG{__WARN__} = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
198 2 my ($w) = @_;
199 2 $w =~ s/\s+\z//;
200 2 print STDERR "punk $path: $w\n";
201 54 };
202 54 eval { Getopt::Long::GetOptionsFromArray(\@argv, @gspec) };
203 };
204 54 my $err = $@;
205 54 Getopt::Long::Configure($saved);
206 0 ▶ if ($err) { print STDERR "punk $path: $err"; return 2 }
Branch: 1 branch
BranchTrueFalseTotal
if ($err) 0 54 54
207 54 ▶ unless ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 2 52 54
208 2 print STDERR "\n";
209 2 _usage_cmd($path, $spec, \*STDERR, \@extra);
210 2 return 2;
211 }
212 }
213 52 ▶ if ($opt{help}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt{"help"}) 4 48 52
214 4 _usage_cmd($path, $spec, \*STDOUT, \@extra);
215 4 return 0;
216 }
217 48 delete $opt{help};
218  
219 48 my $code = eval { $spec->{code}->(\%opt, @argv) };
220 48 ▶ if (my $err = $@) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = $@) 11 37 48
221 11 ▶ if (ref $err eq 'HASH' && defined $err->{usage_error}) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $err eq "HASH" and defined $err->{"usage_error"}) 7 4 11
Condition66%2/3
ref $err eq "HASH" and defined $err->{"usage_error"}
!ll&&!rl&&r
407
MC/DC50%1/2
ref $err eq "HASH" and defined $err->{"usage_error"}
ref $err eq "HASH" defined $err->{"usage_error"}
Truth table66%2/3
A and B
A= ref $err eq "HASH"B= defined $err->{"usage_error"}
ABresult
0X0
100
111
222 7 print STDERR "punk $path: $err->{usage_error}\n\n";
223 7 _usage_cmd($path, $spec, \*STDERR, \@extra);
224 7 return 2;
225 }
226 4 return _fail($path, $err, $spec->{hints});
227 }
228 37 ▶ return defined $code ? int $code : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $code ? : 37 0 37
229 }
230  
231 # the plugin seam: Punk::Command::<Ucfirst> registers at load
232 4 ▶sub _probe {
Subroutine _probe: called CC=3 SCAR=11.0
233 4 my ($name) = @_;
234 4 ▶ return unless $name =~ /^[a-z][a-z0-9_-]*$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $name =~ /^[a-z][a-z0-9_-]*$/ 0 4 4
235 4 (my $mod = ucfirst $name) =~ s/[-_](\w)/\U$1/g;
236 4 ▶ return unless eval { require "Punk/Command/$mod.pm"; 1 };
Branch: 1 branch
BranchTrueFalseTotal
unless eval { do { require "Punk/Command/$mod.pm"; 1 } } 3 1 4
237 1 return $SPECS{$name};
238 }
239  
240 11 ▶sub _cmd_help {
Subroutine _cmd_help: called CC=8 SCAR=20.9
241 11 my ($topic, @rest) = @_;
242 11 ▶ if (defined $topic && length $topic) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $topic and length $topic) 10 1 11
Condition66%2/3
defined $topic and length $topic
!ll&&!rl&&r
1010
MC/DC50%1/2
defined $topic and length $topic
defined $topic length $topic
Truth table66%2/3
A and B
A= defined $topicB= length $topic
ABresult
0X0
100
111
243 10 ▶ my $spec = $SPECS{$topic} // _probe($topic);
Condition66%2/3
$Punk::Command::SPECS{$topic} // _probe($topic)
l!l&&r!l&&!r
802
MC/DC50%1/2
$Punk::Command::SPECS{$topic} // _probe($topic)
$Punk::Command::SPECS{$topic} _probe($topic)
Truth table66%2/3
A // B
A= $Punk::Command::SPECS{$topic}B= _probe($topic)
ABresult
1X1
011
000
244 10 ▶ unless ($spec) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($spec) 2 8 10
245 2 print STDERR "punk help: no such command '$topic'\n\n";
246 2 _usage_all(\*STDERR);
247 2 return 2;
248 }
249 8 my $path = $topic;
250 8 ▶ while (@rest && $spec->{commands} && $spec->{commands}{$rest[0]}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@rest and $spec->{"commands"} and $spec->{"commands"}{$rest[0]}) 1 8 9
Condition66%4/6
@rest and $spec->{"commands"} and $spec->{"commands"}{$rest[0]}
!ll&&!rl&&r
801
@rest and $spec->{"commands"}
!ll&&!rl&&r
801
MC/DC33%1/3
@rest and $spec->{"commands"} and $spec->{"commands"}{$rest[0]}
@rest $spec->{"commands"} $spec->{"commands"}{$rest[0]}
Truth table50%2/4
A and B and C
A= @restB= $spec->{"commands"}C= $spec->{"commands"}{$rest[0]}
ABCresult
0XX0
10X0
1100
1111
251 1 my $t = shift @rest;
252 1 $spec = $spec->{commands}{$t};
253 1 $path .= " $t";
254 }
255 8 _usage_cmd($path, $spec, \*STDOUT);
256 8 return 0;
257 }
258 1 _usage_all(\*STDOUT);
259 1 return 0;
260 }
261  
262 # croaks arrive with an "at FILE line N." tail that means nothing to someone
263 # running a command; one actionable line is the whole message
264 5 ▶sub _fail {
Subroutine _fail: called CC=4 SCAR=13.9
265 5 my ($path, $err, $hints) = @_;
266 5 $err = "$err";
267 5 $err =~ s/ at \S+ line \d+\.?\s*\z//;
268 5 $err =~ s/\s+\z//;
269 5 $err =~ s/\A(?:Punk::Generate|Punk::Kit::[\w:]+): //;
270 5 print STDERR "punk $path: $err\n";
271 5 ▶ for my $h (@{ $hints || [] }) {
Condition100%2/2
$hints || []
l!l
32
MC/DC100%1/1
$hints || []
$hints
Truth table100%2/2
A
A= $hints
Aresult
11
00
272 5 ▶ print STDERR " $h->[1]\n" if $err =~ $h->[0];
Branch: 1 branch
BranchTrueFalseTotal
if $err =~ /$h->[0]/ 1 4 5
273 }
274 5 return 1;
275 }
276  
277 # ---- generated help ----------------------------------------------------------
278  
279 77 ▶sub _options_for {
Subroutine _options_for: called CC=9 SCAR=22.3
280 77 my ($spec, $extra) = @_;
281 77 ▶ my @own = @{ $spec->{options} || [] };
Condition100%2/2
$spec->{'options'} || []
l!l
716
MC/DC100%1/1
$spec->{'options'} || []
$spec->{'options'}
Truth table100%2/2
A
A= $spec->{'options'}
Aresult
11
00
282 77 my %own_key = map { _opt_key($_->{spec}) => 1 } @own;
283  
284 # An option a command brought at run time cannot quietly replace one it
285 # declared: which of the two Getopt bound would decide what the command
286 # does, and that is not a thing to leave to ordering.
287 77 my @extra;
288 77 ▶ for my $o (@{ $extra || [] }) {
Condition50%1/2
$extra || []
l!l
770
MC/DC0%0/1
$extra || []
$extra
Truth table50%1/2
A
A= $extra
Aresult
11
00
289 5 my $k = _opt_key($o->{spec});
290 Carp::croak("Punk::Command: option '--$k' is defined by both "
291 . "'" . ($spec->{name} // '?') . "' and "
292 . ($o->{owner} // 'a kit'))
293 5 ▶ if $own_key{$k} || $k eq 'help';
Branch: 1 branch
BranchTrueFalseTotal
if $own_key{$k} or $k eq "help" 1 4 5
Condition57%4/7
$own_key{$k} or $k eq "help"
l!l&&r!l&&!r
104
$spec->{"name"} // "?"
l!l
10
$o->{"owner"} // "a kit"
l!l
10
MC/DC50%1/2
$own_key{$k} or $k eq "help"
$own_key{$k} $k eq "help"
MC/DC0%0/1
$spec->{"name"} // "?"
$spec->{"name"}
MC/DC0%0/1
$o->{"owner"} // "a kit"
$o->{"owner"}
Truth table66%2/3
A or B
A= $own_key{$k}B= $k eq "help"
ABresult
1X1
011
000
Truth table50%1/2
A
A= $spec->{"name"}
Aresult
11
00
Truth table50%1/2
A
A= $o->{"owner"}
Aresult
11
00
294 4 push @extra, $o;
295 }
296 76 my %extra_key = map { _opt_key($_->{spec}) => 1 } @extra;
297  
298 return (
299 76 (grep { !$own_key{ _opt_key($_->{spec}) }
300 76 ▶ && !$extra_key{ _opt_key($_->{spec}) } } @SHARED_OPTIONS),
Condition66%2/3
$own_key{_opt_key($_->{'spec'})} || $extra_key{_opt_key($_->{'spec'})}
l!l&&r!l&&!r
21055
MC/DC50%1/2
$own_key{_opt_key($_->{'spec'})} || $extra_key{_opt_key($_->{'spec'})}
$own_key{_opt_key($_->{'spec'})} $extra_key{_opt_key($_->{'spec'})}
Truth table66%2/3
A || B
A= $own_key{_opt_key($_->{'spec'})}B= $extra_key{_opt_key($_->{'spec'})}
ABresult
1X1
011
000
301 @own,
302 @extra,
303 { spec => 'help|h', doc => 'this' },
304 );
305 }
306  
307 6 ▶sub _usage_all {
Subroutine _usage_all: called CC=8 SCAR=20.8
308 6 my ($fh) = @_;
309 6 print {$fh} "punk - the Punk command line\n\n"
310 . "usage: punk <command> [options]\n\ncommands:\n";
311 6 my @rows;
312 6 for my $name (@ORDER) {
313 75 my $spec = $SPECS{$name};
314 75 ▶ next if $spec->{hidden};
Branch: 1 branch
BranchTrueFalseTotal
if $spec->{"hidden"} 9 66 75
315 66 ▶ push @rows, [ $spec->{display} // $name, $spec->{abstract} // '' ];
Condition60%3/5
$spec->{"display"} // $name
l!l&&r!l&&!r
30360
$spec->{"abstract"} // ""
l!l
660
MC/DC0%0/2
$spec->{"display"} // $name
$spec->{"display"} $name
MC/DC0%0/1
$spec->{"abstract"} // ""
$spec->{"abstract"}
Truth table66%2/3
A // B
A= $spec->{"display"}B= $name
ABresult
1X1
011
000
Truth table50%1/2
A
A= $spec->{"abstract"}
Aresult
11
00
316 }
317 6 push @rows, [ 'help [command]', "this, or a command's own options" ];
318 6 my $w = 0;
319 6 ▶ length $_->[0] > $w and $w = length $_->[0] for @rows;
Branch: 1 branch
BranchTrueFalseTotal
length $_->[0] > $w and $w = length $_->[0] 12 60 72
320 6 printf {$fh} " %-*s %s\n", $w, @{$_}[0, 1] for @rows;
321 6 print {$fh} "\n punk --version\n";
322 6 return;
323 }
324  
325 25 ▶sub _usage_cmd {
Subroutine _usage_cmd: called CC=32 SCAR=40.6
326 25 my ($path, $spec, $fh, $extra) = @_;
327 25 ▶ if ($spec->{raw}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($spec->{"raw"}) 0 25 25
328 # the adapted CLI owns its own help
329 0 ▶ print {$fh} 'usage: punk ' . $path . ' '
Condition0%0/2
$spec->{"usage"} // "<command> [options]"
l!l
00
MC/DC0%0/1
$spec->{"usage"} // "<command> [options]"
$spec->{"usage"}
Truth table0%0/2
A
A= $spec->{"usage"}
Aresult
11
00
330 0 . ($spec->{usage} // '<command> [options]') . "\n";
331 0 ▶ print {$fh} "\n$spec->{desc}\n" if $spec->{desc};
Branch: 1 branch
BranchTrueFalseTotal
if $spec->{"desc"} 0 0 0
332 0 print {$fh} "\nsee `punk $path help` for its commands\n";
333 0 return;
334 }
335 25 ▶ if ($spec->{commands} && !$spec->{code}
Branch: 1 branch
BranchTrueFalseTotal
if ($spec->{"commands"} and not $spec->{"code"} and 1 == keys %{$$spec{"commands"};}) 3 22 25
Condition66%4/6
$spec->{"commands"} and not $spec->{"code"} and 1 == keys %{$$spec{"commands"};}
!ll&&!rl&&r
2203
$spec->{"commands"} and not $spec->{"code"}
!ll&&!rl&&r
2203
MC/DC33%1/3
$spec->{"commands"} and not $spec->{"code"} and 1 == keys %{$$spec{"commands"};}
$spec->{"commands"} not $spec->{"code"} 1 == keys %{$$spec{"commands"};}
Truth table50%2/4
A and not(B) and C
A= $spec->{"commands"}B= not $spec->{"code"}C= 1 == keys %{$$spec{"commands"};}
ABCresult
0XX0
10X0
1100
1111
336 3 && 1 == keys %{ $spec->{commands} }) {
337 # one mandatory verb reads better spelled out: "usage: punk api sync"
338 3 my ($verb) = keys %{ $spec->{commands} };
339 3 return _usage_cmd("$path $verb", $spec->{commands}{$verb}, $fh);
340 }
341 22 ▶ print {$fh} "usage: punk $path " . ($spec->{usage} // '[options]') . "\n";
Condition100%2/2
$spec->{"usage"} // "[options]"
l!l
1210
MC/DC100%1/1
$spec->{"usage"} // "[options]"
$spec->{"usage"}
Truth table100%2/2
A
A= $spec->{"usage"}
Aresult
11
00
342 22 ▶ print {$fh} "\n$spec->{desc}\n" if $spec->{desc};
Branch: 1 branch
BranchTrueFalseTotal
if $spec->{"desc"} 22 0 22
343 22 ▶ if ($spec->{commands}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($spec->{"commands"}) 0 22 22
344 0 my @names = sort keys %{ $spec->{commands} };
345 0 my $w = 0;
346 0 ▶ length $_ > $w and $w = length $_ for @names;
Branch: 1 branch
BranchTrueFalseTotal
length $_ > $w and $w = length $_ 0 0 0
347 0 print {$fh} "\ncommands:\n";
348 0 ▶ printf {$fh} " %-*s %s\n", $w, $_,
Condition0%0/2
$spec->{"commands"}{$_}{"abstract"} // ""
l!l
00
MC/DC0%0/1
$spec->{"commands"}{$_}{"abstract"} // ""
$spec->{"commands"}{$_}{"abstract"}
Truth table0%0/2
A
A= $spec->{"commands"}{$_}{"abstract"}
Aresult
11
00
349 0 $spec->{commands}{$_}{abstract} // '' for @names;
350 }
351 # Options a kit brought get their own heading, so it is clear which of
352 # them go away when --kit does.
353 22 ▶ my @extra = @{ $extra || [] };
Condition100%2/2
$extra || []
l!l
139
MC/DC100%1/1
$extra || []
$extra
Truth table100%2/2
A
A= $extra
Aresult
11
00
354 22 my %is_extra = map { _opt_key($_->{spec}) => 1 } @extra;
355 22 my @options = _options_for($spec, \@extra);
356 22 my (@rows, @extra_rows);
357 22 for my $o (@options) {
358 135 ▶ next if $o->{hidden};
Branch: 1 branch
BranchTrueFalseTotal
if $o->{"hidden"} 0 135 135
359 135 my ($long) = $o->{spec} =~ /^([^=|!+\@]+)/;
360 135 (my $shown = $long) =~ tr/_/-/;
361 my $left = "--$shown" . (defined $o->{arg} && length $o->{arg}
362 135 ▶ ? " $o->{arg}" : '');
Branch: 1 branch
BranchTrueFalseTotal
defined $o->{'arg'} && length $o->{'arg'} ? : 80 55 135
Condition66%2/3
defined $o->{"arg"} and length $o->{"arg"}
!ll&&!rl&&r
55080
MC/DC50%1/2
defined $o->{"arg"} and length $o->{"arg"}
defined $o->{"arg"} length $o->{"arg"}
Truth table66%2/3
A and B
A= defined $o->{"arg"}B= length $o->{"arg"}
ABresult
0X0
100
111
363 135 ▶ my $doc = $o->{doc} // '';
Condition50%1/2
$o->{"doc"} // ""
l!l
1350
MC/DC0%0/1
$o->{"doc"} // ""
$o->{"doc"}
Truth table50%1/2
A
A= $o->{"doc"}
Aresult
11
00
364 $doc .= " (default: $o->{default})"
365 if defined $o->{default} && !ref $o->{default}
366 135 ▶ && length $o->{default};
Branch: 1 branch
BranchTrueFalseTotal
if defined $o->{"default"} and not ref $o->{"default"} and length $o->{"default"} 19 116 135
Condition66%4/6
defined $o->{"default"} and not ref $o->{"default"} and length $o->{"default"}
!ll&&!rl&&r
116019
defined $o->{"default"} and not ref $o->{"default"}
!ll&&!rl&&r
116019
MC/DC33%1/3
defined $o->{"default"} and not ref $o->{"default"} and length $o->{"default"}
defined $o->{"default"} not ref $o->{"default"} length $o->{"default"}
Truth table50%2/4
A and not(B) and C
A= defined $o->{"default"}B= not ref $o->{"default"}C= length $o->{"default"}
ABCresult
0XX0
10X0
1100
1111
367 135 ▶ push @{ $is_extra{ _opt_key($o->{spec}) } ? \@extra_rows : \@rows },
Branch: 1 branch
BranchTrueFalseTotal
$is_extra{_opt_key($o->{'spec'})} ? : 2 133 135
368 [ $left, $doc ];
369 }
370 22 my $w = 0;
371 22 ▶ length $_->[0] > $w and $w = length $_->[0] for @rows, @extra_rows;
Branch: 1 branch
BranchTrueFalseTotal
length $_->[0] > $w and $w = length $_->[0] 44 91 135
372 22 print {$fh} "\noptions:\n";
373 22 printf {$fh} " %-*s %s\n", $w, @{$_}[0, 1] for @rows;
374 22 ▶ if (@extra_rows) {
Branch: 1 branch
BranchTrueFalseTotal
if (@extra_rows) 2 20 22
375 2 ▶ my $title = $extra[0]{section} // 'more options';
Condition50%1/2
$extra[0]{"section"} // "more options"
l!l
20
MC/DC0%0/1
$extra[0]{"section"} // "more options"
$extra[0]{"section"}
Truth table50%1/2
A
A= $extra[0]{"section"}
Aresult
11
00
376 2 print {$fh} "\n$title:\n";
377 2 printf {$fh} " %-*s %s\n", $w, @{$_}[0, 1] for @extra_rows;
378 }
379 22 ▶ if ($spec->{examples}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($spec->{"examples"}) 9 13 22
380 9 print {$fh} "\nexamples:\n";
381 9 print {$fh} " $_\n" for @{ $spec->{examples} };
382 }
383 22 return;
384 }
385  
386 # ---- legacy public surface ---------------------------------------------------
387  
388 51 our @COMMANDS = qw(routes api doctor config console dev);
389  
390 0 ▶sub commands { grep { !$SPECS{$_}{hidden} } @ORDER }
Subroutine commands: not called CC=1 SCAR=6.9
Pod documented
391  
392 # ---- punk routes -------------------------------------------------------------
393  
394 # The compiled routing table. Targets come back from the coderef through B,
395 # not from the declaration, so what is printed is what the route actually
396 # resolved to - which is the question you have when a route misbehaves.
397 9 ▶sub routes {
Subroutine routes: called CC=49 SCAR=50.3
Pod documented
398 9 my (%opt) = @_;
399 9 ▶ my $app = _load_app($opt{dir}) or return 1;
Branch: 1 branch
BranchTrueFalseTotal
my $app = _load_app($opt{"dir"}) or return 1 8 1 9
400  
401 8 my @rows;
402 8 ▶ my $recs = eval { $app->{registrar}{router}->records } || [];
Condition50%1/2
eval { do { $app->{'registrar'}{'router'}->records } } || []
l!l
80
MC/DC0%0/1
eval { do { $app->{'registrar'}{'router'}->records } } || []
eval { do { $app->{'registrar'}{'router'}->records } }
Truth table50%1/2
A
A= eval { do { $app->{'registrar'}{'router'}->records } }
Aresult
11
00
403 8 for my $rec (@$recs) {
404 push @rows, {
405 method => $rec->{method} // '?',
406 path => $rec->{path} // '?',
407 target => _code_name($rec->{code}),
408 26 ▶ guards => scalar @{ $rec->{guards} || [] },
Condition50%1/2
$rec->{'guards'} || []
l!l
260
MC/DC0%0/1
$rec->{'guards'} || []
$rec->{'guards'}
Truth table50%1/2
A
A= $rec->{'guards'}
Aresult
11
00
409 name => $rec->{name},
410 26 ▶ kind => 'route',
Condition50%2/4
$rec->{"method"} // "?"
l!l
260
$rec->{"path"} // "?"
l!l
260
MC/DC0%0/1
$rec->{"method"} // "?"
$rec->{"method"}
MC/DC0%0/1
$rec->{"path"} // "?"
$rec->{"path"}
Truth table50%1/2
A
A= $rec->{"method"}
Aresult
11
00
Truth table50%1/2
A
A= $rec->{"path"}
Aresult
11
00
411 };
412 }
413  
414 # API operations live in their mount, not the router: the spec is the
415 # routing table for everything under the mount's prefix.
416 8 ▶ for my $m (@{ $app->{registrar}{api_mounts} || [] }) {
Condition50%1/2
$app->{'registrar'}{'api_mounts'} || []
l!l
80
MC/DC0%0/1
$app->{'registrar'}{'api_mounts'} || []
$app->{'registrar'}{'api_mounts'}
Truth table50%1/2
A
A= $app->{'registrar'}{'api_mounts'}
Aresult
11
00
417 3 ▶ my $prefix = $m->{prefix} // '';
Condition50%1/2
$m->{"prefix"} // ""
l!l
30
MC/DC0%0/1
$m->{"prefix"} // ""
$m->{"prefix"}
Truth table50%1/2
A
A= $m->{"prefix"}
Aresult
11
00
418 3 ▶ my $api = $m->{api} or next;
Branch: 1 branch
BranchTrueFalseTotal
my $api = $m->{"api"} or next 3 0 3
419 3 ▶ my $ops = eval { $api->operations } || [];
Condition50%1/2
eval { do { $api->operations } } || []
l!l
30
MC/DC0%0/1
eval { do { $api->operations } } || []
eval { do { $api->operations } }
Truth table50%1/2
A
A= eval { do { $api->operations } }
Aresult
11
00
420 3 ▶ my $by_id = ref $m->{ops} eq 'HASH' ? $m->{ops} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $m->{'ops'} eq 'HASH' ? : 3 0 3
421 3 for my $op (sort { $a->{path} cmp $b->{path}
422 9 ▶ || $a->{method} cmp $b->{method} } @$ops) {
Condition66%2/3
$Punk::Command::a->{'path'} cmp $Punk::Command::b->{'path'} || $Punk::Command::a->{'method'} cmp $Punk::Command::b->{'method'}
l!l&&r!l&&!r
630
MC/DC0%0/2
$Punk::Command::a->{'path'} cmp $Punk::Command::b->{'path'} || $Punk::Command::a->{'method'} cmp $Punk::Command::b->{'method'}
$Punk::Command::a->{'path'} cmp $Punk::Command::b->{'path'} $Punk::Command::a->{'method'} cmp $Punk::Command::b->{'method'}
Truth table66%2/3
A || B
A= $Punk::Command::a->{'path'} cmp $Punk::Command::b->{'path'}B= $Punk::Command::a->{'method'} cmp $Punk::Command::b->{'method'}
ABresult
1X1
011
000
423 9 my $rec = $by_id->{ $op->{operationId} };
424 9 ▶ my $code = ref $rec eq 'HASH' ? $rec->{code} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $rec eq 'HASH' ? : 9 0 9
425 push @rows, {
426 method => uc $op->{method},
427 path => $prefix . $op->{path},
428 target => (ref $code eq 'CODE'
429 ? _code_name($code) : $op->{operationId}),
430 guards => (ref $rec eq 'HASH'
431 9 ▶ ? scalar @{ $rec->{guards} || [] } : 0),
Condition50%1/2
$rec->{'guards'} || []
l!l
90
MC/DC0%0/1
$rec->{'guards'} || []
$rec->{'guards'}
Truth table50%1/2
A
A= $rec->{'guards'}
Aresult
11
00
432 # an operationId IS the name: it is what url_for takes, and
433 # it shares the one namespace with the route names
434 name => $op->{operationId},
435 9 ▶ kind => 'api',
Branch: 2 branches
BranchTrueFalseTotal
ref $code eq 'CODE' ? : 9 0 9
ref $rec eq 'HASH' ? : 9 0 9
436 };
437 }
438 }
439  
440 8 ▶ for my $w (@{ $app->{registrar}{ws_routes} || [] }) {
Condition50%1/2
$app->{'registrar'}{'ws_routes'} || []
l!l
08
MC/DC0%0/1
$app->{'registrar'}{'ws_routes'} || []
$app->{'registrar'}{'ws_routes'}
Truth table50%1/2
A
A= $app->{'registrar'}{'ws_routes'}
Aresult
11
00
441 push @rows, {
442 method => 'WS',
443 path => $w->{path} // '?',
444 target => (ref $w->{target} ? _code_name($w->{target})
445 : ($w->{target} // '?')),
446 0 ▶ guards => scalar @{ $w->{guards} || [] },
Branch: 1 branch
BranchTrueFalseTotal
ref $w->{'target'} ? : 0 0 0
Condition0%0/6
$w->{"path"} // "?"
l!l
00
$w->{"target"} // "?"
l!l
00
$w->{'guards'} || []
l!l
00
MC/DC0%0/1
$w->{"path"} // "?"
$w->{"path"}
MC/DC0%0/1
$w->{"target"} // "?"
$w->{"target"}
MC/DC0%0/1
$w->{'guards'} || []
$w->{'guards'}
Truth table0%0/2
A
A= $w->{"path"}
Aresult
11
00
Truth table0%0/2
A
A= $w->{"target"}
Aresult
11
00
Truth table0%0/2
A
A= $w->{'guards'}
Aresult
11
00
447 kind => 'ws',
448 };
449 }
450  
451 8 ▶ for my $m (@{ $app->{registrar}{mounts} || [] }) {
Condition50%1/2
$app->{'registrar'}{'mounts'} || []
l!l
80
MC/DC0%0/1
$app->{'registrar'}{'mounts'} || []
$app->{'registrar'}{'mounts'}
Truth table50%1/2
A
A= $app->{'registrar'}{'mounts'}
Aresult
11
00
452 push @rows, {
453 method => 'ANY',
454 path => ($m->{prefix} // '') . '/*',
455 target => $m->{dir} ? "static $m->{dir}"
456 : $m->{md_dir} ? "markdown $m->{md_dir}"
457 : 'mounted psgi app',
458 guards => 0,
459 8 ▶ kind => $m->{md_dir} ? 'markdown' : 'mount',
Branch: 3 branches
BranchTrueFalseTotal
$m->{'dir'} ? : 8 0 8
$m->{'md_dir'} ? : 0 0 0
$m->{'md_dir'} ? : 0 8 8
Condition50%1/2
$m->{"prefix"} // ""
l!l
80
MC/DC0%0/1
$m->{"prefix"} // ""
$m->{"prefix"}
Truth table50%1/2
A
A= $m->{"prefix"}
Aresult
11
00
460 };
461 }
462  
463 8 ▶ unless (@rows) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@rows) 0 8 8
464 0 print "no routes\n";
465 0 return 0;
466 }
467  
468 8 ▶ if (defined $opt{method}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opt{"method"}) 0 8 8
469 0 my $want = uc $opt{method};
470 0 @rows = grep { $_->{method} eq $want } @rows;
471 }
472 8 ▶ if (defined $opt{kind}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opt{"kind"}) 0 8 8
473 0 @rows = grep { $_->{kind} eq $opt{kind} } @rows;
474 }
475 # exact, not a glob: a name is an identifier, and the question `--name`
476 # answers is "which route is this, that my template names?"
477 8 ▶ if (defined $opt{name}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opt{"name"}) 3 5 8
478 3 ▶ @rows = grep { defined $_->{name} && $_->{name} eq $opt{name} } @rows;
Condition100%3/3
defined $_->{'name'} && $_->{'name'} eq $opt{'name'}
!ll&&!rl&&r
862
MC/DC100%2/2
defined $_->{'name'} && $_->{'name'} eq $opt{'name'}
defined $_->{'name'} $_->{'name'} eq $opt{'name'}
Truth table100%3/3
A && B
A= defined $_->{'name'}B= $_->{'name'} eq $opt{'name'}
ABresult
0X0
100
111
479 }
480 8 ▶ if (defined $opt{path}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opt{"path"}) 0 8 8
481 0 my $re = _glob_re($opt{path});
482 0 @rows = grep { $_->{path} =~ $re } @rows;
483 }
484 8 ▶ unless (@rows) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@rows) 1 7 8
485 1 print "no matching routes\n";
486 1 return 0;
487 }
488  
489 23 ▶ @rows = sort { $a->{path} cmp $b->{path} || $a->{method} cmp $b->{method} }
Condition66%2/3
$Punk::Command::a->{'path'} cmp $Punk::Command::b->{'path'} || $Punk::Command::a->{'method'} cmp $Punk::Command::b->{'method'}
l!l&&r!l&&!r
2210
MC/DC0%0/2
$Punk::Command::a->{'path'} cmp $Punk::Command::b->{'path'} || $Punk::Command::a->{'method'} cmp $Punk::Command::b->{'method'}
$Punk::Command::a->{'path'} cmp $Punk::Command::b->{'path'} $Punk::Command::a->{'method'} cmp $Punk::Command::b->{'method'}
Truth table66%2/3
A || B
A= $Punk::Command::a->{'path'} cmp $Punk::Command::b->{'path'}B= $Punk::Command::a->{'method'} cmp $Punk::Command::b->{'method'}
ABresult
1X1
011
000
490 7 ▶ @rows if $opt{sort};
Branch: 1 branch
BranchTrueFalseTotal
if $opt{"sort"} 1 6 7
491  
492 7 ▶ if ($opt{json}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt{"json"}) 0 7 7
493 0 require File::Raw::JSON;
494 0 print File::Raw::JSON::file_json_encode(\@rows), "\n";
495 0 return 0;
496 }
497  
498 7 my $w_m = _widest('method', \@rows, 6);
499 7 my $w_p = _widest('path', \@rows, 4);
500 # the NAME column appears only when a route has one, so a table from an
501 # application that names nothing prints exactly as it did before
502 7 my $named = grep { defined $_->{name} } @rows;
503 7 ▶ my $w_n = $named ? _widest('name', \@rows, 4) : 0;
Branch: 1 branch
BranchTrueFalseTotal
$named ? : 6 1 7
504 7 ▶ printf "%-*s %-*s %s%s\n", $w_m, 'METHOD', $w_p, 'PATH',
Branch: 1 branch
BranchTrueFalseTotal
$named ? : 6 1 7
505 ($named ? sprintf('%-*s ', $w_n, 'NAME') : ''), 'TARGET';
506 7 for my $r (@rows) {
507 printf "%-*s %-*s %s%s%s\n", $w_m, $r->{method}, $w_p, $r->{path},
508 ($named ? sprintf('%-*s ', $w_n, $r->{name} // '') : ''),
509 $r->{target},
510 $r->{guards} ? " [$r->{guards} guard"
511 29 ▶ . ($r->{guards} > 1 ? 's' : '') . ']' : '';
Branch: 3 branches
BranchTrueFalseTotal
$named ? : 27 2 29
$r->{'guards'} ? : 0 29 29
$r->{'guards'} > 1 ? : 0 0 0
Condition100%2/2
$r->{"name"} // ""
l!l
1314
MC/DC100%1/1
$r->{"name"} // ""
$r->{"name"}
Truth table100%2/2
A
A= $r->{"name"}
Aresult
11
00
512 }
513 7 ▶ printf "\n%d route%s\n", scalar @rows, @rows == 1 ? '' : 's';
Branch: 1 branch
BranchTrueFalseTotal
@rows == 1 ? : 2 5 7
514 7 return 0;
515 }
516  
517 # a path glob for --path: * is one segment's worth, ** crosses slashes
518 0 ▶sub _glob_re {
Subroutine _glob_re: not called CC=3 SCAR=24.8
519 0 my ($glob) = @_;
520 my $re = join '',
521 0 ▶ map { $_ eq '**' ? '.*' : $_ eq '*' ? '[^/]*' : quotemeta $_ }
Branch: 2 branches
BranchTrueFalseTotal
$_ eq '**' ? : 0 0 0
$_ eq '*' ? : 0 0 0
522 0 grep { length }
523 split /(\*\*|\*)/, $glob;
524 0 return qr/^$re$/;
525 }
526  
527 # ---- punk doctor -------------------------------------------------------------
528  
529 # Punk reaches four other distributions through C ABI tables resolved at
530 # runtime, each gated on the version it was compiled against. When those drift
531 # the symptom is a croak on a request path, a long way from the cause; this
532 # reports the whole picture at once.
533 4 ▶sub doctor {
Subroutine doctor: called CC=29 SCAR=38.7
Pod documented
534 4 my (%opt) = @_;
535 4 my $bad = 0;
536  
537 4 print "punk doctor\n\n";
538  
539 4 require Punk;
540 4 _line('Punk', $Punk::VERSION, 'ok');
541 4 _line('perl', sprintf('%vd', $^V), 'ok');
542  
543 4 print "\nprerequisites\n";
544 4 for my $mod (qw(Open::API Template::Stencil File::Raw::JSON File::Raw::XML
545 JSON::Schema::Fast YAML::XS Hyperman)) {
546 28 my $v = _module_version($mod);
547 28 ▶ $bad++ unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 0 28 28
548 28 ▶ _line($mod, $v // '-', defined $v ? 'ok' : 'MISSING');
Branch: 1 branch
BranchTrueFalseTotal
defined $v ? : 28 0 28
Condition50%1/2
$v // "-"
l!l
280
MC/DC0%0/1
$v // "-"
$v
Truth table50%1/2
A
A= $v
Aresult
11
00
549 }
550  
551 4 print "\noptional\n";
552 4 for my $mod (qw(DBI Future Open::API::UI Plack)) {
553 16 my $v = _module_version($mod);
554 16 ▶ _line($mod, $v // '-', defined $v ? 'ok' : 'not installed');
Branch: 1 branch
BranchTrueFalseTotal
defined $v ? : 16 0 16
Condition50%1/2
$v // "-"
l!l
160
MC/DC0%0/1
$v // "-"
$v
Truth table50%1/2
A
A= $v
Aresult
11
00
555 }
556 { # a database backend is only useful with a driver behind it
557 4 my @drv = eval { require DBI; DBI->available_drivers } ;
558 4 ▶ _line('DBD drivers', (@drv ? join(' ', sort @drv) : '-'),
Branch: 3 branches
BranchTrueFalseTotal
if @drv or not $@ 4 0 4
@drv ? : 4 0 4
@drv ? : 4 0 4
Condition33%1/3
@drv or not $@
l!l&&r!l&&!r
400
MC/DC0%0/2
@drv or not $@
@drv not $@
Truth table33%1/3
A or not(B)
A= @drvB= not $@
ABresult
1X1
011
000
559 @drv ? 'ok' : 'none') if @drv || !$@;
560 }
561  
562 # The part that cannot be read off a version number: whether each table
563 # resolved, and at which version.
564 4 print "\nC ABIs\n";
565 4 for my $abi (_abi_report()) {
566 32 ▶ $bad++ if $abi->{state} ne 'ok';
Branch: 1 branch
BranchTrueFalseTotal
if $abi->{"state"} ne "ok" 0 32 32
567 32 _line($abi->{name}, $abi->{detail}, $abi->{state});
568 }
569  
570 # Load every Punk::Command::* on @INC first.
571 #
572 # A plugin's command module registers at load, and nothing loads it until
573 # somebody types its name - which is right for `punk dev`, where the cost
574 # of scanning would be paid on every invocation, and wrong here. `doctor`
575 # is the command whose whole job is "what have I got installed", and a
576 # row that only appears when you were already running that plugin's
577 # command is a row nobody will ever see when they need it.
578 #
579 # A module that dies on load is skipped rather than fatal: doctor is what
580 # somebody runs when something is already broken.
581 4 _load_command_plugins();
582  
583 # rows other distributions registered (register_doctor) - a probe returns
584 # (ok, detail); a die is a failed row, not a failed doctor
585 4 ▶ if (@DOCTOR) {
Branch: 1 branch
BranchTrueFalseTotal
if (@Punk::Command::DOCTOR) 4 0 4
586 4 print "\nplugins\n";
587 4 for my $row (@DOCTOR) {
588 4 my ($label, $probe) = @$row;
589 4 my ($ok, $detail) = eval { $probe->() };
590 4 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 4 4
591 0 my $e = $@; $e =~ s/ at \S+ line \d+\.?\s*\z//; $e =~ s/\s+\z//;
592 0 ($ok, $detail) = (0, $e);
593 }
594 4 ▶ $bad++ unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 4 4
595 4 ▶ _line($label, $detail // '-', $ok ? 'ok' : 'FAILED');
Branch: 1 branch
BranchTrueFalseTotal
$ok ? : 4 0 4
Condition50%1/2
$detail // "-"
l!l
40
MC/DC0%0/1
$detail // "-"
$detail
Truth table50%1/2
A
A= $detail
Aresult
11
00
596 }
597 }
598  
599 4 ▶ if (my $app = _load_app($opt{dir}, quiet => 1)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $app = _load_app($opt{"dir"}, "quiet", 1)) 1 3 4
600 1 print "\napplication\n";
601 1 _line('class', $app->{class}, 'ok');
602 1 _line('root', $app->{root}, 'ok');
603 1 ▶ my $n = eval { scalar @{ $app->{registrar}{router}->records } } || 0;
Condition50%1/2
eval { do { scalar @{$app->{'registrar'}{'router'}->records;} } } || 0
l!l
10
MC/DC0%0/1
eval { do { scalar @{$app->{'registrar'}{'router'}->records;} } } || 0
eval { do { scalar @{$app->{'registrar'}{'router'}->records;} } }
Truth table50%1/2
A
A= eval { do { scalar @{$app->{'registrar'}{'router'}->records;} } }
Aresult
11
00
604 1 ▶ _line('routes', $n, $n ? 'ok' : 'none');
Branch: 1 branch
BranchTrueFalseTotal
$n ? : 1 0 1
605 1 ▶ if (my $cfg = $app->{registrar}{config}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cfg = $app->{"registrar"}{"config"}) 1 0 1
606 1 _line('config', join(' ', @{ $cfg->files }), 'ok');
607 1 ▶ my $s = eval { $cfg->secret_paths } || [];
Condition50%1/2
eval { do { $cfg->secret_paths } } || []
l!l
10
MC/DC0%0/1
eval { do { $cfg->secret_paths } } || []
eval { do { $cfg->secret_paths } }
Truth table50%1/2
A
A= eval { do { $cfg->secret_paths } }
Aresult
11
00
608 1 ▶ _line('secrets', (@$s ? scalar(@$s) . ' resolved' : 'none'), 'ok');
Branch: 1 branch
BranchTrueFalseTotal
@$s ? : 0 1 1
609 }
610 }
611  
612 4 ▶ print "\n", $bad ? "$bad problem" . ($bad > 1 ? 's' : '') . " found\n"
Branch: 2 branches
BranchTrueFalseTotal
$bad ? : 0 4 4
$bad > 1 ? : 0 0 0
613 : "no problems found\n";
614 4 ▶ return $bad ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$bad ? : 0 4 4
615 }
616  
617 # ---- punk config check -------------------------------------------------------
618  
619 # Resolving configuration is fatal by design - a missing secret should stop a
620 # deployment, not produce an empty password. That makes it a thing worth
621 # testing before the deployment: this walks every layer for every secret
622 # reference and reports all of them, rather than dying on the first.
623 5 ▶sub config_check {
Subroutine config_check: called CC=24 SCAR=34.1
Pod documented
624 5 my (%opt) = @_;
625 5 ▶ my $root = $opt{root} || _find_root($opt{dir}) or do {
Branch: 1 branch
BranchTrueFalseTotal
my $root = $opt{"root"} || _find_root($opt{"dir"}) or do { print STDERR 'punk config: no application found (looked for app.psgi upwards from ' . ($opt{"dir"} || Cwd::getcwd()) . ")\n"; return 2 } 4 1 5
Condition66%2/3
$opt{'root'} || _find_root($opt{'dir'})
l!l&&r!l&&!r
041
MC/DC50%1/2
$opt{'root'} || _find_root($opt{'dir'})
$opt{'root'} _find_root($opt{'dir'})
Truth table66%2/3
A || B
A= $opt{'root'}B= _find_root($opt{'dir'})
ABresult
1X1
011
000
626 print STDERR "punk config: no application found "
627 . "(looked for app.psgi upwards from "
628 1 ▶ . ($opt{dir} || Cwd::getcwd()) . ")\n";
Condition33%1/3
$opt{'dir'} || Cwd::getcwd()
l!l&&r!l&&!r
010
MC/DC0%0/2
$opt{'dir'} || Cwd::getcwd()
$opt{'dir'} Cwd::getcwd()
Truth table33%1/3
A || B
A= $opt{'dir'}B= Cwd::getcwd()
ABresult
1X1
011
000
629 1 return 2;
630 };
631 4 ▶ my $file = $opt{file} || File::Spec->catfile($root, 'config', 'punk.yml');
Condition33%1/3
$opt{'file'} || 'File::Spec'->catfile($root, 'config', 'punk.yml')
l!l&&r!l&&!r
040
MC/DC0%0/2
$opt{'file'} || 'File::Spec'->catfile($root, 'config', 'punk.yml')
$opt{'file'} 'File::Spec'->catfile($root, 'config', 'punk.yml')
Truth table33%1/3
A || B
A= $opt{'file'}B= 'File::Spec'->catfile($root, 'config', 'punk.yml')
ABresult
1X1
011
000
632 4 ▶ my $env = $opt{env} || $ENV{PUNK_ENV} || 'production';
Condition40%2/5
$opt{'env'} || $ENV{'PUNK_ENV'} || 'production'
l!l
04
$opt{"env"} or $ENV{"PUNK_ENV"}
l!l&&r!l&&!r
004
MC/DC0%0/2
$opt{'env'} || $ENV{'PUNK_ENV'} || 'production'
$opt{"env"} $ENV{"PUNK_ENV"}
Truth table33%1/3
A or B
A= $opt{"env"}B= $ENV{"PUNK_ENV"}
ABresult
1X1
011
000
633  
634 4 ▶ unless (-f $file) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-f $file) 0 4 4
635 0 print STDERR "punk config: no such file: $file\n";
636 0 return 2;
637 }
638  
639 4 printf "config %s\nenv %s\n\n", $file, $env;
640  
641 4 my @layers = _layer_files($file, $env);
642 4 my @present = grep { -f $_->[1] } @layers;
643 4 print "layers\n";
644 4 for my $l (@layers) {
645 12 ▶ _line($l->[0], $l->[1], -f $l->[1] ? 'ok' : 'absent');
Branch: 1 branch
BranchTrueFalseTotal
-f $l->[1] ? : 4 8 12
646 }
647  
648 4 ▶ unless (@present) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@present) 0 4 4
649 0 print STDERR "\nno layer files exist\n";
650 0 return 1;
651 }
652  
653 # Every secret reference in every layer, resolved independently so one
654 # failure does not hide the rest.
655 4 my @refs;
656 4 for my $l (@present) {
657 4 my $doc = eval { _yaml_file($l->[1]) };
658 4 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 4 4
659 0 print "\n", _fmt('', $l->[1], 'UNPARSEABLE'), " $@";
660 0 return 1;
661 }
662 4 ▶ _walk_secrets($doc, '', sub { push @refs, { %{ $_[0] }, layer => $l->[1] } });
Subroutine __ANON__: called CC=1 SCAR=0.0
663 }
664  
665 4 my $bad = 0;
666 4 ▶ if (@refs) {
Branch: 1 branch
BranchTrueFalseTotal
if (@refs) { } 2 2 4
667 2 print "\nsecrets\n";
668 2 for my $r (@refs) {
669 4 my ($ok, $detail) = _try_resolver($r->{kind}, $r->{value});
670 4 ▶ $bad++ unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 3 1 4
671 4 ▶ _line($r->{path}, "$r->{kind}: $detail", $ok ? 'ok' : 'FAILED');
Branch: 1 branch
BranchTrueFalseTotal
$ok ? : 1 3 4
672 }
673 }
674 else {
675 2 print "\nno secret references\n";
676 }
677  
678 # Then the authoritative pass, which also applies the guardrail.
679 4 print "\nload\n";
680 4 require Punk::Config;
681 4 my $cfg = eval {
682 4 local $ENV{PUNK_ENV} = $env;
683 Punk::Config->load(file => $file, env => $env,
684 4 ▶ ($opt{secrets} ? (secrets => $opt{secrets}) : ()));
Subroutine BEGIN: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
$opt{'secrets'} ? : 0 4 4
685 };
686 4 ▶ if (!$cfg) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($cfg) 1 3 4
687 1 ▶ my $err = $@ || 'failed';
Condition50%1/2
$@ || 'failed'
l!l
10
MC/DC0%0/1
$@ || 'failed'
$@
Truth table50%1/2
A
A= $@
Aresult
11
00
688 1 $err =~ s/ at \S+ line \d+\.?\s*\z//;
689 1 _line('Punk::Config->load', $err, 'FAILED');
690 1 return 1;
691 }
692 3 _line('Punk::Config->load', 'ok', 'ok');
693  
694 3 ▶ if ($opt{dump}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt{"dump"}) 2 1 3
695 2 print "\nresolved (secrets redacted)\n";
696 2 require Data::Dumper;
697 2 my $d = Data::Dumper->new([ _redact_inline($cfg->config) ]);
698 2 $d->Sortkeys(1)->Indent(1)->Terse(1);
699 2 print $d->Dump;
700 }
701  
702 3 ▶ print "\n", $bad ? "$bad secret" . ($bad > 1 ? 's' : '')
Branch: 2 branches
BranchTrueFalseTotal
$bad ? : 0 3 3
$bad > 1 ? : 0 0 0
703 . " could not be resolved\n" : "configuration is sound\n";
704 3 ▶ return $bad ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$bad ? : 0 3 3
705 }
706  
707 # A copy of the resolved configuration with every value whose KEY says it is
708 # a credential replaced. A reference such as { $env: ... } is already redacted
709 # by the loader; a password somebody typed straight into the file is not, and
710 # a dump is the thing that gets pasted into a ticket.
711 30 ▶sub _redact_inline {
Subroutine _redact_inline: called CC=7 SCAR=20.1
712 30 my ($v, $hide) = @_;
713 30 ▶ if (ref $v eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $v eq "HASH") 15 15 30
714 return { map {
715 15 my $k = $_;
716 26 ▶ ($k => _redact_inline($v->{$k},
Condition33%1/3
$hide || $k =~ /pass|secret|token|api_?key|private/i
l!l&&r!l&&!r
0220
MC/DC0%0/2
$hide || $k =~ /pass|secret|token|api_?key|private/i
$hide $k =~ /pass|secret|token|api_?key|private/i
Truth table33%1/3
A || B
A= $hideB= $k =~ /pass|secret|token|api_?key|private/i
ABresult
1X1
011
000
717 $hide || $k =~ /pass|secret|token|api_?key|private/i))
718 } keys %$v };
719 }
720 15 ▶ return [ map { _redact_inline($_, $hide) } @$v ] if ref $v eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $v eq "ARRAY" 1 14 15
721 14 ▶ return $v if ref $v || !defined $v || !$hide;
Branch: 1 branch
BranchTrueFalseTotal
if ref $v or not defined $v or not $hide 8 6 14
Condition50%3/6
ref $v or not defined $v or not $hide
l!l&&r!l&&!r
086
ref $v or not defined $v
l!l&&r!l&&!r
0014
MC/DC33%1/3
ref $v or not defined $v or not $hide
ref $v not defined $v not $hide
Truth table50%2/4
A or not(B) or not(C)
A= ref $vB= not defined $vC= not $hide
ABCresult
1XX1
01X1
0011
0000
722 6 return '[redacted]';
723 }
724  
725 # ---- punk api sync -----------------------------------------------------------
726  
727 # A spec-first application whose spec has moved on. Adds a stub for every
728 # operation the document declares and the controllers do not implement, and
729 # never touches one that is already there - so this is the command that makes
730 # `punk new --api` a workflow rather than a one-shot.
731 5 ▶sub api_sync {
Subroutine api_sync: called CC=45 SCAR=61.1
Pod documented
732 5 my (%opt) = @_;
733 5 ▶ my $root = $opt{root} || _find_root($opt{dir}) or do {
Branch: 1 branch
BranchTrueFalseTotal
my $root = $opt{"root"} || _find_root($opt{"dir"}) or do { print STDERR "punk api: no application found\n"; return 2 } 4 1 5
Condition66%2/3
$opt{'root'} || _find_root($opt{'dir'})
l!l&&r!l&&!r
041
MC/DC50%1/2
$opt{'root'} || _find_root($opt{'dir'})
$opt{'root'} _find_root($opt{'dir'})
Truth table66%2/3
A || B
A= $opt{'root'}B= _find_root($opt{'dir'})
ABresult
1X1
011
000
734 1 print STDERR "punk api: no application found\n";
735 1 return 2;
736 };
737 4 ▶ my $class = _class_of($root) or do {
Branch: 1 branch
BranchTrueFalseTotal
my $class = _class_of($root) or do { print STDERR "punk api: cannot work out the application class in $root\n"; return 2 } 4 0 4
738 0 print STDERR "punk api: cannot work out the application class in $root\n";
739 0 return 2;
740 };
741 4 ▶ my $spec = $opt{spec} || File::Spec->catfile($root, 'openapi.json');
Condition33%1/3
$opt{'spec'} || 'File::Spec'->catfile($root, 'openapi.json')
l!l&&r!l&&!r
040
MC/DC0%0/2
$opt{'spec'} || 'File::Spec'->catfile($root, 'openapi.json')
$opt{'spec'} 'File::Spec'->catfile($root, 'openapi.json')
Truth table33%1/3
A || B
A= $opt{'spec'}B= 'File::Spec'->catfile($root, 'openapi.json')
ABresult
1X1
011
000
742 4 ▶ unless (-f $spec) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-f $spec) 0 4 4
743 0 print STDERR "punk api: no such spec: $spec\n";
744 0 return 2;
745 }
746  
747 4 require Punk::Generate;
748 4 ▶ my $plan = eval { Punk::Generate->api_plan($spec) } or do {
Branch: 1 branch
BranchTrueFalseTotal
my $plan = eval { do { "Punk::Generate"->api_plan($spec) } } or do { my $err = $@; $err =~ s/ at \S+ line \d+\.?\s*\z//; print STDERR "punk api: $err\n"; return 1 } 4 0 4
749 0 my $err = $@; $err =~ s/ at \S+ line \d+\.?\s*\z//;
750 0 print STDERR "punk api: $err\n";
751 0 return 1;
752 };
753  
754 4 (my $path = $class) =~ s{::}{/}g;
755 4 my $ctrl_dir = File::Spec->catdir($root, 'lib', $path, 'Controller', 'API');
756 # the checker class holds security checkers, not operations - counting its
757 # subs would make every checker look like an operation the spec dropped
758 4 my $auth = $plan->{auth_class};
759 4 ▶ my %implemented = _implemented_ops($ctrl_dir,
Branch: 1 branch
BranchTrueFalseTotal
$auth ? : 0 4 4
760 ($auth ? (skip => qr/\A\Q$auth\E\.pm\z/) : ()));
761  
762 4 my (@added, @created, @orphans);
763 4 my %declared;
764  
765 4 for my $group (@{ $plan->{groups} }) {
766 4 my @new = grep { !$implemented{ $_->{id} } } @{ $group->{ops} };
767 4 $declared{ $_->{id} } = 1 for @{ $group->{ops} };
768 4 ▶ next unless @new;
Branch: 1 branch
BranchTrueFalseTotal
unless @new 2 2 4
769  
770 # Where a new operation's siblings already live wins over where a
771 # fresh generation would have put it. Adding a tag to a spec changes
772 # how untagged operations group, and a sync should not scatter an
773 # operation away from the others on its own path because of that.
774 2 my $file = File::Spec->catfile($ctrl_dir, "$group->{group}.pm");
775 # Only for operations that fell through to Default - a tag the author
776 # wrote is a placement decision, and it outranks any guess made here.
777 2 ▶ if (!-f $file && !length($group->{group_label} // '')) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-f $file or length($group->{"group_label"} // "")) 0 2 2
Condition20%1/5
-f $file or length($group->{"group_label"} // "")
l!l&&r!l&&!r
200
$group->{"group_label"} // ""
l!l
00
MC/DC0%0/2
-f $file or length($group->{"group_label"} // "")
-f $file $group->{"group_label"}
Truth table33%1/3
A or B
A= -f $fileB= $group->{"group_label"}
ABresult
1X1
011
000
778 0 my %by_home;
779 0 for my $op (@new) {
780 0 my ($seg) = grep { length } split m{/}, $op->{path};
781 0 ▶ my $home = Punk::Generate->ident($seg // '');
Condition0%0/2
$seg // ""
l!l
00
MC/DC0%0/1
$seg // ""
$seg
Truth table0%0/2
A
A= $seg
Aresult
11
00
782 0 ▶ my $f = length $home
Branch: 1 branch
BranchTrueFalseTotal
length $home ? : 0 0 0
783 ? File::Spec->catfile($ctrl_dir, "$home.pm") : '';
784 0 ▶ push @{ $by_home{ (length $f && -f $f) ? $f : $file } }, $op;
Branch: 1 branch
BranchTrueFalseTotal
length $f && -f $f ? : 0 0 0
Condition0%0/3
length $f and -f $f
!ll&&!rl&&r
000
MC/DC0%0/2
length $f and -f $f
length $f -f $f
Truth table0%0/3
A and B
A= length $fB= -f $f
ABresult
0X0
100
111
785 }
786 0 ▶ if (keys %by_home > 1 || !exists $by_home{$file}) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %by_home > 1 or not exists $by_home{$file}) 0 0 0
Condition0%0/3
keys %by_home > 1 or not exists $by_home{$file}
l!l&&r!l&&!r
000
MC/DC0%0/2
keys %by_home > 1 or not exists $by_home{$file}
keys %by_home > 1 not exists $by_home{$file}
Truth table0%0/3
A or not(B)
A= keys %by_home > 1B= not exists $by_home{$file}
ABresult
1X1
011
000
787 0 for my $f (sort keys %by_home) {
788 0 my $ops = $by_home{$f};
789 0 my $base = File::Basename::basename($f);
790 0 ▶ if (-f $f) {
Branch: 1 branch
BranchTrueFalseTotal
if (-f $f) { } 0 0 0
791 0 _insert_stubs($f, $ops, $opt{dry_run});
792 }
793 else {
794 Punk::Generate->write_skel('controller_api.tmpl', $f,
795 { name => $class, path => $path, api => 1,
796 0 ▶ %$group, ops => $ops }) unless $opt{dry_run};
Branch: 1 branch
BranchTrueFalseTotal
unless $opt{"dry_run"} 0 0 0
797 0 my $stem = $base;
798 0 $stem =~ s/\.pm\z//; # s///r is 5.14
799 0 push @created, [ $stem, scalar @$ops ];
800 }
801 0 push @added, map { [ $_->{id}, $base ] } @$ops;
802 }
803 0 next;
804 }
805 }
806 2 ▶ if (-f $file) {
Branch: 1 branch
BranchTrueFalseTotal
if (-f $file) { } 2 0 2
807 2 _insert_stubs($file, \@new, $opt{dry_run});
808 2 push @added, map { [ $_->{id}, "$group->{group}.pm" ] } @new;
809 }
810 else {
811 0 ▶ unless ($opt{dry_run}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($opt{"dry_run"}) 0 0 0
812 0 Punk::Generate->write_skel('controller_api.tmpl', $file,
813 { name => $class, path => $path, api => 1,
814 %$group, ops => \@new });
815 }
816 0 push @created, [ $group->{group}, scalar @new ];
817 0 push @added, map { [ $_->{id}, "$group->{group}.pm" ] } @new;
818 }
819 }
820  
821 # Checkers for schemes the spec has started requiring since.
822 4 my $auth_file;
823 4 ▶ if (@{ $plan->{schemes} }) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$plan->{"schemes"};}) 0 4 4
824 0 $auth_file = File::Spec->catfile($ctrl_dir, "$plan->{auth_class}.pm");
825 0 ▶ unless (-f $auth_file) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-f $auth_file) 0 0 0
826 0 ▶ unless ($opt{dry_run}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($opt{"dry_run"}) 0 0 0
827 Punk::Generate->write_skel('controller_auth.tmpl', $auth_file,
828 { name => $class, path => $path, api => 1,
829 auth_class => $plan->{auth_class},
830 0 schemes => $plan->{schemes} });
831 }
832 push @created, [ $plan->{auth_class},
833 0 scalar @{ $plan->{schemes} } ];
834 }
835 }
836  
837 4 @orphans = sort grep { !$declared{$_} } keys %implemented;
838  
839 4 ▶ my $pre = $opt{dry_run} ? 'would add' : 'added';
Branch: 1 branch
BranchTrueFalseTotal
$opt{'dry_run'} ? : 1 3 4
840 4 ▶ if (@added) {
Branch: 1 branch
BranchTrueFalseTotal
if (@added) { } 2 2 4
841 2 ▶ printf "%s %d stub%s\n", $pre, scalar @added, @added == 1 ? '' : 's';
Branch: 1 branch
BranchTrueFalseTotal
@added == 1 ? : 2 0 2
842 2 printf " %-28s %s\n", $_->[0], $_->[1] for @added;
843 }
844 else {
845 2 print "every operation in the spec is implemented\n";
846 }
847 4 ▶ if (@created) {
Branch: 1 branch
BranchTrueFalseTotal
if (@created) 0 4 4
848 0 ▶ printf "\n%s %d file%s\n", ($opt{dry_run} ? 'would create' : 'created'),
Branch: 2 branches
BranchTrueFalseTotal
$opt{'dry_run'} ? : 0 0 0
@created == 1 ? : 0 0 0
849 scalar @created, @created == 1 ? '' : 's';
850 0 printf " %s.pm (%d)\n", @$_ for @created;
851 }
852 4 ▶ if (@orphans) {
Branch: 1 branch
BranchTrueFalseTotal
if (@orphans) 1 3 4
853 # Reported, never removed: a sub the spec no longer declares may still
854 # be wanted, and deleting someone's code is not this command's job.
855 1 ▶ printf "\n%d method%s with no operation in the spec (left alone)\n",
Branch: 1 branch
BranchTrueFalseTotal
@orphans == 1 ? : 1 0 1
856 scalar @orphans, @orphans == 1 ? '' : 's';
857 1 print " $_\n" for @orphans;
858 }
859 0 ▶ if ($auth_file && -f $auth_file && @{ $plan->{schemes} }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($auth_file and -f $auth_file and @{$plan->{"schemes"};}) 0 4 4
Condition33%2/6
$auth_file and -f $auth_file and @{$plan->{"schemes"};}
!ll&&!rl&&r
400
$auth_file and -f $auth_file
!ll&&!rl&&r
400
MC/DC0%0/3
$auth_file and -f $auth_file and @{$plan->{"schemes"};}
$auth_file -f $auth_file @{$plan->{"schemes"};}
Truth table25%1/4
A and B and C
A= $auth_fileB= -f $auth_fileC= @{$plan->{"schemes"};}
ABCresult
0XX0
10X0
1100
1111
860 0 my %have = _implemented_ops($ctrl_dir,
861 only => qr/\A\Q$plan->{auth_class}\E\.pm\z/);
862 0 my @miss = grep { !$have{ $_->{method} } } @{ $plan->{schemes} };
863 printf "\n%d security checker%s missing from %s.pm: %s\n",
864 scalar @miss, @miss == 1 ? '' : 's', $plan->{auth_class},
865 0 ▶ join(', ', map { $_->{method} } @miss) if @miss;
Branch: 2 branches
BranchTrueFalseTotal
if @miss 0 0 0
@miss == 1 ? : 0 0 0
866 }
867 4 return 0;
868 }
869  
870 # ---- punk console ------------------------------------------------------------
871  
872 1 ▶sub console {
Subroutine console: called CC=20 SCAR=40.4
Pod documented
873 1 my (%opt) = @_;
874 1 ▶ my $app = _load_app($opt{dir}) or return 1;
Branch: 1 branch
BranchTrueFalseTotal
my $app = _load_app($opt{"dir"}) or return 1 1 0 1
875  
876 # Named so the evals below can see them by name rather than by closure.
877 1 our $app_ = $app->{registrar};
878 1 our $psgi_ = $app->{psgi};
879 1 our $ctx_ = _console_context($app);
880  
881 # --eval: one expression, its dump, and out - the scripting form.
882 1 ▶ if (defined $opt{eval}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opt{"eval"}) 0 1 1
883 0 my @out = eval _console_wrap($opt{eval});
884 0 ▶ if ($@) { print STDERR "!! $@"; return 1 }
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
885 0 ▶ print _console_dump(@out) if @out;
Branch: 1 branch
BranchTrueFalseTotal
if @out 0 0 0
886 0 return 0;
887 }
888  
889 1 my $class = $app->{class};
890 1 print "punk console - $class\n"
891 . " \$app the Punk::App registrar\n"
892 . " \$psgi the compiled PSGI coderef\n"
893 . " \$c a throwaway context (\$c->model, \$c->render, ...)\n"
894 . " q, exit or ctrl-d to leave\n\n";
895  
896 # Term::ReadLine::Stub reads nothing from a pipe, so it is for terminals
897 # only; falling back to STDIN keeps the console scriptable.
898 1 my $tty = -t STDIN;
899 0 ▶ my $term = $tty ? eval { require Term::ReadLine;
Branch: 1 branch
BranchTrueFalseTotal
$tty ? : 0 1 1
900 0 Term::ReadLine->new('punk') } : undef;
901  
902 # History survives sessions when the reader supports it - only on a
903 # terminal, so piped input never rewrites the file.
904 my $hist = $ENV{PUNK_HISTFILE}
905 1 ▶ // File::Spec->catfile($ENV{HOME} || '.', '.punk_history');
Condition40%2/5
$ENV{"PUNK_HISTFILE"} // "File::Spec"->catfile($ENV{"HOME"} || ".", ".punk_history")
l!l&&r!l&&!r
010
$ENV{'HOME'} || '.'
l!l
10
MC/DC0%0/2
$ENV{"PUNK_HISTFILE"} // "File::Spec"->catfile($ENV{"HOME"} || ".", ".punk_history")
$ENV{"PUNK_HISTFILE"} "File::Spec"->catfile($ENV{"HOME"} || ".", ".punk_history")
MC/DC0%0/1
$ENV{'HOME'} || '.'
$ENV{'HOME'}
Truth table33%1/3
A // B
A= $ENV{"PUNK_HISTFILE"}B= "File::Spec"->catfile($ENV{"HOME"} || ".", ".punk_history")
ABresult
1X1
011
000
Truth table50%1/2
A
A= $ENV{'HOME'}
Aresult
11
00
906 1 ▶ if ($term && $term->can('ReadHistory')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($term and $term->can("ReadHistory")) 0 1 1
Condition33%1/3
$term and $term->can("ReadHistory")
!ll&&!rl&&r
100
MC/DC0%0/2
$term and $term->can("ReadHistory")
$term $term->can("ReadHistory")
Truth table33%1/3
A and B
A= $termB= $term->can("ReadHistory")
ABresult
0X0
100
111
907 0 ▶ $term->ReadHistory($hist) if -f $hist;
Branch: 1 branch
BranchTrueFalseTotal
if -f $hist 0 0 0
908 }
909  
910 1 while (1) {
911 2 ▶ my $line = $term ? $term->readline('punk> ') : do {
Branch: 1 branch
BranchTrueFalseTotal
$term ? : 0 2 2
912 2 ▶ print 'punk> ' if $tty;
Branch: 1 branch
BranchTrueFalseTotal
if $tty 0 2 2
913 2 my $l = <STDIN>;
914 2 $l;
915 };
916 2 ▶ last unless defined $line;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $line 1 1 2
917 1 chomp $line;
918 1 ▶ next unless $line =~ /\S/;
Branch: 1 branch
BranchTrueFalseTotal
unless $line =~ /\S/ 0 1 1
919 1 ▶ last if $line =~ /^\s*(?:q|quit|exit)\s*$/;
Branch: 1 branch
BranchTrueFalseTotal
if $line =~ /^\s*(?:q|quit|exit)\s*$/ 0 1 1
920 1 my @out = eval _console_wrap($line);
921 0 ▶ if ($@) { print "!! $@"; next }
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 1 1
922 1 ▶ next unless @out;
Branch: 1 branch
BranchTrueFalseTotal
unless @out 0 1 1
923 1 print _console_dump(@out);
924 }
925 1 ▶ if ($term && $term->can('WriteHistory')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($term and $term->can("WriteHistory")) 0 1 1
Condition33%1/3
$term and $term->can("WriteHistory")
!ll&&!rl&&r
100
MC/DC0%0/2
$term and $term->can("WriteHistory")
$term $term->can("WriteHistory")
Truth table33%1/3
A and B
A= $termB= $term->can("WriteHistory")
ABresult
0X0
100
111
926 0 eval { $term->WriteHistory($hist) };
927 }
928 1 print "\n";
929 1 return 0;
930 }
931  
932 # ---- punk dev ----------------------------------------------------------------
933  
934 # The application compiles at boot, which is exactly why a dev server has to
935 # restart rather than reload: there is no live structure to patch. The server
936 # runs in a child, the parent watches for changes and replaces it.
937 0 ▶sub dev {
Subroutine dev: not called CC=32 SCAR=69.6
Pod documented
938 0 my (%opt) = @_;
939 0 ▶ my $root = $opt{root} || _find_root($opt{dir}) or do {
Branch: 1 branch
BranchTrueFalseTotal
my $root = $opt{"root"} || _find_root($opt{"dir"}) or do { print STDERR "punk dev: no application found\n"; return 2 } 0 0 0
Condition0%0/3
$opt{'root'} || _find_root($opt{'dir'})
l!l&&r!l&&!r
000
MC/DC0%0/2
$opt{'root'} || _find_root($opt{'dir'})
$opt{'root'} _find_root($opt{'dir'})
Truth table0%0/3
A || B
A= $opt{'root'}B= _find_root($opt{'dir'})
ABresult
1X1
011
000
940 0 print STDERR "punk dev: no application found\n";
941 0 return 2;
942 };
943 0 my $psgi = File::Spec->catfile($root, 'app.psgi');
944 0 ▶ my $port = $opt{port} || 5000;
Condition0%0/2
$opt{'port'} || 5000
l!l
00
MC/DC0%0/1
$opt{'port'} || 5000
$opt{'port'}
Truth table0%0/2
A
A= $opt{'port'}
Aresult
11
00
945 0 ▶ my $host = $opt{host} || '127.0.0.1';
Condition0%0/2
$opt{'host'} || '127.0.0.1'
l!l
00
MC/DC0%0/1
$opt{'host'} || '127.0.0.1'
$opt{'host'}
Truth table0%0/2
A
A= $opt{'host'}
Aresult
11
00
946 0 ▶ my $workers = $opt{workers} || 1;
Condition0%0/2
$opt{'workers'} || 1
l!l
00
MC/DC0%0/1
$opt{'workers'} || 1
$opt{'workers'}
Truth table0%0/2
A
A= $opt{'workers'}
Aresult
11
00
947  
948 0 ▶ unless (eval { require Hyperman; 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (eval { do { require Hyperman; 1 } }) 0 0 0
949 0 print STDERR "punk dev: Hyperman is not installed\n";
950 0 return 1;
951 }
952  
953 0 ▶ my @watch_rel = @{ $opt{watch} || [] };
Condition0%0/2
$opt{'watch'} || []
l!l
00
MC/DC0%0/1
$opt{'watch'} || []
$opt{'watch'}
Truth table0%0/2
A
A= $opt{'watch'}
Aresult
11
00
954 0 ▶ @watch_rel = qw(lib config root/templates) unless @watch_rel;
Branch: 1 branch
BranchTrueFalseTotal
unless @watch_rel 0 0 0
955 0 my @watch = grep { -d $_ }
956 0 ▶ map { File::Spec->file_name_is_absolute($_)
Branch: 1 branch
BranchTrueFalseTotal
'File::Spec'->file_name_is_absolute($_) ? : 0 0 0
957 ? $_ : File::Spec->catdir($root, $_) } @watch_rel;
958 0 printf "punk dev http://%s:%d\n", $host, $port;
959 0 printf "watching %s\n\n", join(' ', map { _rel($root, $_) } @watch)
960 0 ▶ if @watch && !$opt{no_reload};
Branch: 1 branch
BranchTrueFalseTotal
if @watch and not $opt{"no_reload"} 0 0 0
Condition0%0/3
@watch and not $opt{"no_reload"}
!ll&&!rl&&r
000
MC/DC0%0/2
@watch and not $opt{"no_reload"}
@watch not $opt{"no_reload"}
Truth table0%0/3
A and not(B)
A= @watchB= not $opt{"no_reload"}
ABresult
0X0
100
111
961  
962 0 my $child;
963 0 my $stop = 0;
964 0 ▶ local $SIG{INT} = local $SIG{TERM} = sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
965 0 $stop = 1;
966 0 ▶ kill 'TERM', $child if $child;
Branch: 1 branch
BranchTrueFalseTotal
if $child 0 0 0
967 0 };
968  
969 0 require POSIX;
970 0 ▶ my %seen = $opt{no_reload} ? () : _mtimes(@watch);
Branch: 1 branch
BranchTrueFalseTotal
$opt{'no_reload'} ? : 0 0 0
971  
972 0 ▶ while (!$stop) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($stop) 0 0 0
973 0 $child = fork();
974 0 ▶ defined $child or die "punk dev: cannot fork: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
defined $child or die "punk dev: cannot fork: $!\n" 0 0 0
975 0 ▶ unless ($child) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($child) 0 0 0
976 0 ▶ chdir $root or die "punk dev: cannot chdir to $root: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
chdir $root or die "punk dev: cannot chdir to ${root}: $!\n" 0 0 0
977 # punk dev IS the development opt-in: the environment defaults
978 # to production everywhere else. --env overrides even an
979 # inherited setting - saying it on the command line is explicit.
980 0 ▶ $ENV{PUNK_ENV} = $opt{env} if defined $opt{env};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opt{"env"} 0 0 0
981 0 ▶ $ENV{PUNK_ENV} //= 'development';
Condition0%0/2
$ENV{"PUNK_ENV"} //= "development"
l!l
00
MC/DC0%0/1
$ENV{"PUNK_ENV"} //= "development"
$ENV{"PUNK_ENV"}
Truth table0%0/2
A
A= $ENV{"PUNK_ENV"}
Aresult
11
00
982 # app.psgi reads $0 to find lib/ and its own root, exactly as a
983 # server loading the file would
984 0 local $0 = $psgi;
985 0 my $app = do $psgi;
986 0 ▶ die($@ || $! || "punk dev: $psgi did not return an app\n")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $app eq "CODE" 0 0 0
Condition0%0/5
$@ || $! || "punk dev: $psgi did not return an app\n"
l!l
00
$@ or $!
l!l&&r!l&&!r
000
MC/DC0%0/2
$@ || $! || "punk dev: $psgi did not return an app\n"
$@ $!
Truth table0%0/3
A or B
A= $@B= $!
ABresult
1X1
011
000
987 unless ref $app eq 'CODE';
988 0 Hyperman->run(app => $app, host => $host, port => $port,
989 workers => $workers);
990 0 exit 0;
991 }
992  
993 0 ▶ if ($opt{no_reload}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt{"no_reload"}) 0 0 0
994 0 waitpid $child, 0;
995 0 last;
996 }
997  
998 # One watch loop for both waits: until a change while the child runs,
999 # and - after it exits on its own (a compile error, most likely) -
1000 # until a change gives any reason to try again. Respinning
1001 # immediately would just spin.
1002 0 ▶ while (!$stop) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($stop) 0 0 0
1003 0 select undef, undef, undef, 0.5;
1004 0 ▶ if ($child && waitpid($child, POSIX::WNOHANG()) == $child) {
Branch: 1 branch
BranchTrueFalseTotal
if ($child and waitpid($child, POSIX::WNOHANG()) == $child) 0 0 0
Condition0%0/3
$child and waitpid($child, POSIX::WNOHANG()) == $child
!ll&&!rl&&r
000
MC/DC0%0/2
$child and waitpid($child, POSIX::WNOHANG()) == $child
$child waitpid($child, POSIX::WNOHANG()) == $child
Truth table0%0/3
A and B
A= $childB= waitpid($child, POSIX::WNOHANG()) == $child
ABresult
0X0
100
111
1005 0 $child = 0;
1006 0 print "\n-- the application exited; waiting for a change --\n";
1007 }
1008 0 my %now = _mtimes(@watch);
1009 0 ▶ next if _same(\%seen, \%now);
Branch: 1 branch
BranchTrueFalseTotal
if _same(\%seen, \%now) 0 0 0
1010 0 ▶ my ($what) = grep { ($seen{$_} // 0) != ($now{$_} // 0) }
Condition0%0/4
$seen{$_} // 0
l!l
00
$now{$_} // 0
l!l
00
MC/DC0%0/1
$seen{$_} // 0
$seen{$_}
MC/DC0%0/1
$now{$_} // 0
$now{$_}
Truth table0%0/2
A
A= $seen{$_}
Aresult
11
00
Truth table0%0/2
A
A= $now{$_}
Aresult
11
00
1011 sort keys %now;
1012 0 ▶ printf "\n-- %s changed, restarting --\n", _rel($root, $what // '');
Condition0%0/2
$what // ""
l!l
00
MC/DC0%0/1
$what // ""
$what
Truth table0%0/2
A
A= $what
Aresult
11
00
1013 0 %seen = %now;
1014 0 ▶ if ($child) {
Branch: 1 branch
BranchTrueFalseTotal
if ($child) 0 0 0
1015 0 kill 'TERM', $child;
1016 0 waitpid $child, 0;
1017 0 $child = 0;
1018 }
1019 0 last;
1020 }
1021 }
1022 0 ▶ if ($child) {
Branch: 1 branch
BranchTrueFalseTotal
if ($child) 0 0 0
1023 0 kill 'TERM', $child;
1024 0 waitpid $child, 0;
1025 }
1026 0 print "\n";
1027 0 return 0;
1028 }
1029  
1030 # ---- punk serve --------------------------------------------------------------
1031  
1032 # The other command that needs no application. `dev` serves an application and
1033 # refuses without one; this serves a directory of files and never looks for
1034 # one - the whole server is Punk::Static->app, which carries no framework
1035 # state at all.
1036 #
1037 # There is no watch-and-restart loop here, unlike `dev`: a file is read on the
1038 # request that asks for it, so there is nothing compiled to invalidate.
1039 2 ▶sub _cmd_serve {
Subroutine _cmd_serve: called CC=16 SCAR=48.2
1040 2 my ($opt, @args) = @_;
1041 2 my $dir = shift(@args);
1042 2 ▶ die { usage_error => "unexpected argument '$args[0]'" } if @args;
Branch: 1 branch
BranchTrueFalseTotal
if @args 1 1 2
1043 1 ▶ $dir = $opt->{dir} unless defined $dir && length $dir;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $dir and length $dir 0 1 1
Condition33%1/3
defined $dir and length $dir
!ll&&!rl&&r
001
MC/DC0%0/2
defined $dir and length $dir
defined $dir length $dir
Truth table33%1/3
A and B
A= defined $dirB= length $dir
ABresult
0X0
100
111
1044 1 ▶ $dir = '.' unless defined $dir && length $dir;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $dir and length $dir 0 1 1
Condition33%1/3
defined $dir and length $dir
!ll&&!rl&&r
001
MC/DC0%0/2
defined $dir and length $dir
defined $dir length $dir
Truth table33%1/3
A and B
A= defined $dirB= length $dir
ABresult
0X0
100
111
1045  
1046 1 ▶ -d $dir or die "no such directory: $dir\n";
Branch: 1 branch
BranchTrueFalseTotal
-d $dir or die "no such directory: $dir\n" 0 1 1
1047  
1048 0 ▶ unless (eval { require Hyperman; 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (eval { do { require Hyperman; 1 } }) 0 0 0
1049 0 print STDERR "punk serve: Hyperman is not installed\n";
1050 0 return 1;
1051 }
1052  
1053 0 require Punk::Static;
1054 my $app = Punk::Static->app($dir,
1055 ($opt->{no_index} ? () : (index => $opt->{index})),
1056 ($opt->{list} ? (list => 1) : ()),
1057 0 ▶ (defined $opt->{max_age} ? (max_age => $opt->{max_age}) : ()),
Branch: 3 branches
BranchTrueFalseTotal
$opt->{'no_index'} ? : 0 0 0
$opt->{'list'} ? : 0 0 0
defined $opt->{'max_age'} ? : 0 0 0
1058 );
1059  
1060 0 ▶ my $port = $opt->{port} || 8000;
Condition0%0/2
$opt->{'port'} || 8000
l!l
00
MC/DC0%0/1
$opt->{'port'} || 8000
$opt->{'port'}
Truth table0%0/2
A
A= $opt->{'port'}
Aresult
11
00
1061 0 ▶ my $host = $opt->{host} || '127.0.0.1';
Condition0%0/2
$opt->{'host'} || '127.0.0.1'
l!l
00
MC/DC0%0/1
$opt->{'host'} || '127.0.0.1'
$opt->{'host'}
Truth table0%0/2
A
A= $opt->{'host'}
Aresult
11
00
1062 0 printf "punk serve http://%s:%d\n", $host, $port;
1063 0 ▶ printf "serving %s\n\n", Cwd::abs_path($dir) // $dir;
Condition0%0/3
Cwd::abs_path($dir) // $dir
l!l&&r!l&&!r
000
MC/DC0%0/2
Cwd::abs_path($dir) // $dir
Cwd::abs_path($dir) $dir
Truth table0%0/3
A // B
A= Cwd::abs_path($dir)B= $dir
ABresult
1X1
011
000
1064  
1065 # access_log takes an open handle and formats Combined Log Format in C,
1066 # buffered and flushed once per wakeup - a request log with no per-request
1067 # Perl frame, which is the only reason it is on by default.
1068 Hyperman->run(app => $app, host => $host, port => $port,
1069 workers => ($opt->{workers} || 1),
1070 0 ▶ ($opt->{quiet} ? () : (access_log => \*STDERR)));
Branch: 1 branch
BranchTrueFalseTotal
$opt->{'quiet'} ? : 0 0 0
Condition0%0/2
$opt->{'workers'} || 1
l!l
00
MC/DC0%0/1
$opt->{'workers'} || 1
$opt->{'workers'}
Truth table0%0/2
A
A= $opt->{'workers'}
Aresult
11
00
1071 0 return 0;
1072 }
1073  
1074 # ---- finding and loading an application --------------------------------------
1075  
1076 # app.psgi is the marker: it is what a server is pointed at, so it is what
1077 # identifies the root. Walk up from where the command was run.
1078 35 ▶sub _find_root {
Subroutine _find_root: called CC=7 SCAR=19.7
1079 35 my ($dir) = @_;
1080 35 ▶ my $here = Cwd::abs_path($dir || Cwd::getcwd()) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $here = Cwd::abs_path($dir || Cwd::getcwd()) or return undef 35 0 35
Condition66%2/3
$dir || Cwd::getcwd()
l!l&&r!l&&!r
3320
MC/DC0%0/2
$dir || Cwd::getcwd()
$dir Cwd::getcwd()
Truth table66%2/3
A || B
A= $dirB= Cwd::getcwd()
ABresult
1X1
011
000
1081 35 for (1 .. 40) {
1082 57 ▶ return $here if -f File::Spec->catfile($here, 'app.psgi');
Branch: 1 branch
BranchTrueFalseTotal
if -f "File::Spec"->catfile($here, "app.psgi") 27 30 57
1083 30 my $up = Cwd::abs_path(File::Spec->catdir($here, File::Spec->updir));
1084 30 ▶ last if !$up || $up eq $here;
Branch: 1 branch
BranchTrueFalseTotal
if not $up or $up eq $here 8 22 30
Condition66%2/3
not $up or $up eq $here
l!l&&r!l&&!r
0822
MC/DC50%1/2
not $up or $up eq $here
not $up $up eq $here
Truth table66%2/3
not(A) or B
A= not $upB= $up eq $here
ABresult
1X1
011
000
1085 22 $here = $up;
1086 }
1087 8 return undef;
1088 }
1089  
1090 # The application class, from the psgi's own `Class->to_app`.
1091 23 ▶sub _class_of {
Subroutine _class_of: called CC=4 SCAR=16.1
1092 23 my ($root) = @_;
1093 23 my $psgi = File::Spec->catfile($root, 'app.psgi');
1094 23 ▶ open my $fh, '<', $psgi or return undef;
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $psgi or return undef 23 0 23
1095 23 local $/;
1096 23 my $src = <$fh>;
1097 23 close $fh;
1098 23 ▶ return $1 if $src =~ /([A-Za-z_][\w:]*)\s*->\s*to_app\b/;
Branch: 1 branch
BranchTrueFalseTotal
if $src =~ /([A-Za-z_][\w:]*)\s*->\s*to_app\b/ 23 0 23
1099 0 ▶ return $1 if $src =~ /^\s*use\s+([A-Za-z_][\w:]*)\s*;/m;
Branch: 1 branch
BranchTrueFalseTotal
if $src =~ /^\s*use\s+([A-Za-z_][\w:]*)\s*;/m 0 0 0
1100 0 return undef;
1101 }
1102  
1103 # Load the application, with the reason out through $err rather than printed:
1104 # the two callers below want it said in two different ways.
1105 17 ▶sub _load_app_info {
Subroutine _load_app_info: called CC=11 SCAR=27.8
1106 17 my ($dir, $errref, %o) = @_;
1107 17 ▶ my $say = sub { $$errref = $_[0]; return undef };
Subroutine __ANON__: called CC=1 SCAR=0.0
1108  
1109 17 my $root = _find_root($dir);
1110 17 ▶ return $say->("no application found (looked for app.psgi upwards from "
Branch: 1 branch
BranchTrueFalseTotal
unless $root 5 12 17
Condition66%2/3
$dir || Cwd::getcwd()
l!l&&r!l&&!r
140
MC/DC0%0/2
$dir || Cwd::getcwd()
$dir Cwd::getcwd()
Truth table66%2/3
A || B
A= $dirB= Cwd::getcwd()
ABresult
1X1
011
000
1111 . ($dir || Cwd::getcwd()) . ")") unless $root;
1112  
1113 12 my $class = _class_of($root);
1114 12 ▶ return $say->("cannot work out the application class in $root")
Branch: 1 branch
BranchTrueFalseTotal
unless $class 0 12 12
1115 unless $class;
1116  
1117 12 my $psgi_file = File::Spec->catfile($root, 'app.psgi');
1118 12 my $cwd = Cwd::getcwd();
1119 12 my $psgi = do {
1120 12 local $0 = $psgi_file; # app.psgi finds lib/ and its root through it
1121 12 do $psgi_file;
1122 };
1123 # app.psgi chdirs to the application root and everything relative in
1124 # punk.yml is written for that. A caller that will go on to open the
1125 # database wants to be left there; one that only reads the compiled
1126 # tables wants its own directory back.
1127 12 ▶ chdir($o{chdir} ? $root : $cwd);
Branch: 1 branch
BranchTrueFalseTotal
$o{'chdir'} ? : 1 11 12
1128 12 ▶ unless (ref $psgi eq 'CODE') {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $psgi eq "CODE") 0 12 12
1129 0 ▶ my $err = $@ || $! || 'it returned no coderef';
Condition0%0/5
$@ || $! || 'it returned no coderef'
l!l
00
$@ or $!
l!l&&r!l&&!r
000
MC/DC0%0/2
$@ || $! || 'it returned no coderef'
$@ $!
Truth table0%0/3
A or B
A= $@B= $!
ABresult
1X1
011
000
1130 0 ▶ chdir $cwd unless $o{chdir};
Branch: 1 branch
BranchTrueFalseTotal
unless $o{"chdir"} 0 0 0
1131 0 return $say->("$psgi_file did not load: $err");
1132 }
1133 12 ▶ my $registrar = $class->can('punk_app') ? $class->punk_app : undef;
Branch: 1 branch
BranchTrueFalseTotal
$class->can('punk_app') ? : 12 0 12
1134 12 ▶ return $say->("$class is not a Punk application") unless $registrar;
Branch: 1 branch
BranchTrueFalseTotal
unless $registrar 0 12 12
1135  
1136 12 return { root => $root, class => $class, psgi => $psgi,
1137 registrar => $registrar };
1138 }
1139  
1140 14 ▶sub _load_app {
Subroutine _load_app: called CC=3 SCAR=11.0
1141 14 my ($dir, %o) = @_;
1142 14 my $err;
1143 14 my $app = _load_app_info($dir, \$err, %o);
1144 14 ▶ print STDERR "punk: $err\n" if !$app && !$o{quiet};
Branch: 1 branch
BranchTrueFalseTotal
unless $app or $o{"quiet"} 1 13 14
Condition100%3/3
$app or $o{"quiet"}
l!l&&r!l&&!r
1031
MC/DC100%2/2
$app or $o{"quiet"}
$app $o{"quiet"}
Truth table100%3/3
A or B
A= $appB= $o{"quiet"}
ABresult
1X1
011
000
1145 14 return $app;
1146 }
1147  
1148 # The public form, for a command in another distribution: same load, but the
1149 # failure is a die, because a command body's die already becomes one prefixed
1150 # line through _fail.
1151 #
1152 # my $app = Punk::Command->load_app(dir => $opt->{dir}, chdir => 1);
1153 # my $users = $app->{registrar}->model_instance('User');
1154 #
1155 # `chdir => 1` leaves the process in the application root, which is what
1156 # anything opening a relative dsn from punk.yml needs; without it the
1157 # directory the caller started in is restored.
1158 3 ▶sub load_app {
Subroutine load_app: called CC=2 SCAR=6.9
Pod documented
1159 3 my ($class, %o) = @_;
1160 3 my $dir = delete $o{dir};
1161 3 my $err;
1162 3 my $app = _load_app_info($dir, \$err, %o);
1163 3 ▶ die "$err\n" unless $app;
Branch: 1 branch
BranchTrueFalseTotal
unless $app 1 2 3
1164 2 return $app;
1165 }
1166  
1167 # Every Punk/Command/*.pm an @INC entry holds, loaded once. Only that exact
1168 # directory, only a plain .pm, and each in its own eval - this walks
1169 # directories a user did not ask it to walk, so it does as little as it can.
1170 4 ▶sub _load_command_plugins {
Subroutine _load_command_plugins: called CC=8 SCAR=21.1
1171 4 my %seen;
1172 4 for my $inc (@INC) {
1173 61 ▶ next if ref $inc;
Branch: 1 branch
BranchTrueFalseTotal
if ref $inc 0 61 61
1174 61 my $dir = File::Spec->catdir($inc, 'Punk', 'Command');
1175 61 ▶ next unless -d $dir;
Branch: 1 branch
BranchTrueFalseTotal
unless -d $dir 57 4 61
1176 4 ▶ opendir(my $dh, $dir) or next;
Branch: 1 branch
BranchTrueFalseTotal
opendir my $dh, $dir or next 4 0 4
1177 4 my @mods = grep { /\A[A-Za-z]\w*\.pm\z/ } readdir $dh;
1178 4 closedir $dh;
1179 4 for my $file (sort @mods) {
1180 4 ▶ next if $seen{$file}++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen{$file}++ 0 4 4
1181 4 (my $mod = "Punk/Command/$file") =~ s{/}{/}g;
1182 4 ▶ next if $INC{$mod};
Branch: 1 branch
BranchTrueFalseTotal
if $INC{$mod} 0 4 4
1183 4 eval { require $mod; 1 };
1184 }
1185 }
1186 4 return;
1187 }
1188  
1189 # ---- reporting helpers -------------------------------------------------------
1190  
1191 117 ▶sub _fmt {
Subroutine _fmt: called CC=6 SCAR=17.9
1192 117 my ($name, $detail, $state) = @_;
1193 117 ▶ my $mark = $state eq 'ok' ? ' ' : $state =~ /^(?:absent|none|not installed)$/
Branch: 2 branches
BranchTrueFalseTotal
$state eq 'ok' ? : 105 12 117
$state =~ /^(?:absent|none|not installed)$/ ? : 8 4 12
1194 ? '-' : '!';
1195 117 ▶ return sprintf "%s %-26s %s%s", $mark, $name,
Branch: 2 branches
BranchTrueFalseTotal
defined $detail ? : 117 0 117
$state eq 'ok' || $state =~ /^(?:absent|none|not installed)$/ ? : 113 4 117
Condition100%3/3
$state eq "ok" or $state =~ /^(?:absent|none|not installed)$/
l!l&&r!l&&!r
10584
MC/DC100%2/2
$state eq "ok" or $state =~ /^(?:absent|none|not installed)$/
$state eq "ok" $state =~ /^(?:absent|none|not installed)$/
Truth table100%3/3
A or B
A= $state eq "ok"B= $state =~ /^(?:absent|none|not installed)$/
ABresult
1X1
011
000
1196 (defined $detail ? $detail : ''),
1197 ($state eq 'ok' || $state =~ /^(?:absent|none|not installed)$/
1198 ? '' : " <- $state");
1199 }
1200  
1201 117 ▶sub _line { print _fmt(@_), "\n" }
Subroutine _line: called CC=1 SCAR=0.0
1202  
1203 20 ▶sub _widest {
Subroutine _widest: called CC=4 SCAR=13.9
1204 20 my ($key, $rows, $min) = @_;
1205 20 my $w = $min;
1206 20 ▶ for (@$rows) { my $l = length($_->{$key} // ''); $w = $l if $l > $w }
Branch: 1 branch
BranchTrueFalseTotal
if $l > $w 18 67 85
Condition100%2/2
$_->{$key} // ""
l!l
7114
MC/DC100%1/1
$_->{$key} // ""
$_->{$key}
Truth table100%2/2
A
A= $_->{$key}
Aresult
11
00
1207 20 return $w;
1208 }
1209  
1210 0 ▶sub _rel {
Subroutine _rel: not called CC=4 SCAR=30.0
1211 0 my ($root, $path) = @_;
1212 0 ▶ return '' unless defined $path && length $path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path and length $path 0 0 0
Condition0%0/3
defined $path and length $path
!ll&&!rl&&r
000
MC/DC0%0/2
defined $path and length $path
defined $path length $path
Truth table0%0/3
A and B
A= defined $pathB= length $path
ABresult
0X0
100
111
1213 0 my $r = File::Spec->abs2rel($path, $root);
1214 0 ▶ return $r =~ /^\.\./ ? $path : $r;
Branch: 1 branch
BranchTrueFalseTotal
$r =~ /^\.\./ ? : 0 0 0
1215 }
1216  
1217 # The name behind a coderef: a target string resolves to a real named sub, so
1218 # this reports where the request will actually land. Anonymous handlers get
1219 # their file and line, which is the equivalent answer for them.
1220 35 ▶sub _code_name {
Subroutine _code_name: called CC=13 SCAR=27.1
1221 35 my ($code) = @_;
1222 35 ▶ return '?' unless ref $code eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $code eq "CODE" 0 35 35
1223 35 require B;
1224 35 my $cv = B::svref_2object($code);
1225 35 ▶ my $gv = eval { $cv->GV } or return 'sub {...}';
Branch: 1 branch
BranchTrueFalseTotal
my $gv = eval { do { $cv->GV } } or return "sub {...}" 35 0 35
1226 35 ▶ my $name = eval { $gv->NAME } // '';
Condition50%1/2
eval { do { $gv->NAME } } // ""
l!l
350
MC/DC0%0/1
eval { do { $gv->NAME } } // ""
eval { do { $gv->NAME } }
Truth table50%1/2
A
A= eval { do { $gv->NAME } }
Aresult
11
00
1227 35 ▶ my $stash = eval { $gv->STASH->NAME } // '';
Condition50%1/2
eval { do { $gv->STASH->NAME } } // ""
l!l
350
MC/DC0%0/1
eval { do { $gv->STASH->NAME } } // ""
eval { do { $gv->STASH->NAME } }
Truth table50%1/2
A
A= eval { do { $gv->STASH->NAME } }
Aresult
11
00
1228 35 ▶ if ($name eq '__ANON__' || !length $name) {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "__ANON__" or not length $name) 18 17 35
Condition66%2/3
$name eq "__ANON__" or not length $name
l!l&&r!l&&!r
18017
MC/DC50%1/2
$name eq "__ANON__" or not length $name
$name eq "__ANON__" not length $name
Truth table66%2/3
A or not(B)
A= $name eq "__ANON__"B= not length $name
ABresult
1X1
011
000
1229 18 ▶ my $file = eval { $cv->FILE } // '';
Condition50%1/2
eval { do { $cv->FILE } } // ""
l!l
180
MC/DC0%0/1
eval { do { $cv->FILE } } // ""
eval { do { $cv->FILE } }
Truth table50%1/2
A
A= eval { do { $cv->FILE } }
Aresult
11
00
1230 18 ▶ my $line = eval { $gv->LINE } // 0;
Condition50%1/2
eval { do { $gv->LINE } } // 0
l!l
180
MC/DC0%0/1
eval { do { $gv->LINE } } // 0
eval { do { $gv->LINE } }
Truth table50%1/2
A
A= eval { do { $gv->LINE } }
Aresult
11
00
1231 18 ▶ $file = File::Basename::basename($file) if length $file;
Branch: 1 branch
BranchTrueFalseTotal
if length $file 18 0 18
1232 # a magic-CV closure (the static app, a docs route) reports the C file
1233 # it was created in, which tells a reader nothing useful
1234 18 ▶ return 'native handler' if $file =~ /\.h\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $file =~ /\.h\z/ 15 3 18
1235 3 ▶ return length $file ? "sub {...} at $file:$line" : 'sub {...}';
Branch: 1 branch
BranchTrueFalseTotal
length $file ? : 3 0 3
1236 }
1237 17 ▶ return length $stash ? "${stash}::${name}" : $name;
Branch: 1 branch
BranchTrueFalseTotal
length $stash ? : 17 0 17
1238 }
1239  
1240 44 ▶sub _module_version {
Subroutine _module_version: called CC=3 SCAR=11.1
1241 44 my ($mod) = @_;
1242 44 (my $file = $mod) =~ s{::}{/}g;
1243 44 ▶ return undef unless eval { require "$file.pm"; 1 };
Branch: 1 branch
BranchTrueFalseTotal
unless eval { do { require "$file.pm"; 1 } } 0 44 44
1244 51 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
1245 44 my $v = ${"${mod}::VERSION"};
1246 44 ▶ return defined $v ? "$v" : 'installed';
Branch: 1 branch
BranchTrueFalseTotal
defined $v ? : 44 0 44
1247 }
1248  
1249 # Which ABI tables resolved, and at what version. Compiled-against comes from
1250 # Punk itself; provided comes from asking the provider.
1251 4 ▶sub _abi_report {
Subroutine _abi_report: called CC=26 SCAR=37.7
1252 4 my @out;
1253  
1254 push @out, {
1255 name => 'Open::API (oa_abi)',
1256 detail => do {
1257 4 my $want = eval { Punk::_oa_abi_version() };
1258 4 my $ok = eval { Punk::_oa_available() };
1259 4 ▶ defined $want ? "v$want" . ($ok ? ', resolved' : '') : 'unknown';
Branch: 3 branches
BranchTrueFalseTotal
defined $want ? : 4 0 4
$ok ? : 4 0 4
eval { do { Punk::_oa_available() } } ? : 4 0 4
1260 },
1261 4 state => (eval { Punk::_oa_available() } ? 'ok' : 'NOT RESOLVED'),
1262 };
1263  
1264 4 push @out, do {
1265 4 my $ok = eval { require Punk::View::Stencil;
1266 4 Punk::View::Stencil::_abi_ok() };
1267 4 ▶ { name => 'Template::Stencil (st_abi)',
Branch: 2 branches
BranchTrueFalseTotal
$ok ? : 4 0 4
$ok ? : 4 0 4
1268 detail => $ok ? 'resolved' : 'not resolved',
1269 state => $ok ? 'ok' : 'NOT RESOLVED' };
1270 };
1271  
1272 4 push @out, do {
1273 4 my $v = eval { require Hyperman; Hyperman::_abi_version() };
1274 4 ▶ my $d = eval { Hyperman->can('detach') } ? ', detach' : '';
Branch: 1 branch
BranchTrueFalseTotal
eval { do { 'Hyperman'->can('detach') } } ? : 4 0 4
1275 4 ▶ { name => 'Hyperman (hm_abi)',
Branch: 3 branches
BranchTrueFalseTotal
defined $v ? : 4 0 4
defined $v && $v >= 2 ? : 4 0 4
defined $v ? : 0 0 0
Condition33%1/3
defined $v and $v >= 2
!ll&&!rl&&r
004
MC/DC0%0/2
defined $v and $v >= 2
defined $v $v >= 2
Truth table33%1/3
A and B
A= defined $vB= $v >= 2
ABresult
0X0
100
111
1276 detail => defined $v ? "v$v$d" : 'not available',
1277 state => (defined $v && $v >= 2) ? 'ok'
1278 : defined $v ? 'TOO OLD (websockets need v2)' : 'MISSING' };
1279 };
1280  
1281 4 push @out, do {
1282 4 my $p = eval { require File::Raw::JSON; File::Raw::JSON::_abi_ptr() };
1283 4 ▶ { name => 'File::Raw::JSON (frj_abi)',
Branch: 2 branches
BranchTrueFalseTotal
$p ? : 4 0 4
$p ? : 4 0 4
1284 detail => $p ? 'resolved' : 'not resolved',
1285 state => $p ? 'ok' : 'NOT RESOLVED' };
1286 };
1287  
1288 4 push @out, do {
1289 4 my $p = eval { require File::Raw::XML; File::Raw::XML::_abi_ptr() };
1290 4 my $v = eval { File::Raw::XML::_abi_version() };
1291 4 ▶ { name => 'File::Raw::XML (frx_abi)',
Branch: 2 branches
BranchTrueFalseTotal
$p ? : 4 0 4
$p ? : 4 0 4
Condition50%1/2
$v // "?"
l!l
40
MC/DC0%0/1
$v // "?"
$v
Truth table50%1/2
A
A= $v
Aresult
11
00
1292 detail => $p ? "v" . ($v // '?') . ", resolved" : 'not resolved',
1293 state => $p ? 'ok' : 'NOT RESOLVED' };
1294 };
1295  
1296 # Frozen holds the i18n catalogues. Hard, unlike the markdown pair
1297 # below: an app with the I18n plugin cannot boot without it, so a
1298 # missing table is a fault rather than a note.
1299 4 push @out, do {
1300 4 my $ok = eval { Punk::_fz_available() };
1301 4 my $want = eval { Punk::_fz_abi_version() };
1302 4 my $have = eval { require Frozen; Frozen::_abi_version() };
1303 4 ▶ { name => 'Frozen (fz_abi)',
Branch: 4 branches
BranchTrueFalseTotal
$ok ? : 4 0 4
defined $have ? : 0 0 0
$ok ? : 4 0 4
defined $have ? : 0 0 0
1304 detail => $ok ? "v$have, resolved"
1305 : defined $have ? "v$have present, v$want wanted"
1306 : 'not available',
1307 state => $ok ? 'ok'
1308 : defined $have ? 'TOO OLD (upgrade Frozen)' : 'MISSING' };
1309 };
1310  
1311 # The markdown mount's two. Both are optional in the sense that an app
1312 # without a markdown keyword never touches them, so a missing one is
1313 # reported rather than treated as a fault.
1314 4 push @out, do {
1315 4 my $ok = eval { Punk::_mds_available() };
1316 4 my $v = eval { Punk::_mds_abi_version() };
1317 4 ▶ { name => 'Markdown::Simple (mds_abi)',
Branch: 3 branches
BranchTrueFalseTotal
$ok ? : 4 0 4
defined $v ? : 0 0 0
$ok ? : 4 0 4
1318 detail => $ok ? "v$v, resolved"
1319 : defined $v ? "v$v wanted, not resolved" : 'not available',
1320 state => $ok ? 'ok' : 'not resolved (only needed by `markdown`)' };
1321 };
1322  
1323 4 push @out, do {
1324 4 my $ok = eval { Punk::_sg_available() };
1325 4 my $v = eval { Punk::_sg_abi_version() };
1326 4 ▶ { name => 'Search::Trigram (sg_abi)',
Branch: 3 branches
BranchTrueFalseTotal
$ok ? : 4 0 4
defined $v ? : 0 0 0
$ok ? : 4 0 4
1327 detail => $ok ? "v$v, resolved"
1328 : defined $v ? "v$v wanted, not resolved" : 'not available',
1329 state => $ok ? 'ok'
1330 : 'not resolved (only needed by `markdown` search)' };
1331 };
1332  
1333 4 return @out;
1334 }
1335  
1336 # ---- config helpers ----------------------------------------------------------
1337  
1338 # The same three layers punk_config.h builds: the file, the environment's, and
1339 # the gitignored local one.
1340 4 ▶sub _layer_files {
Subroutine _layer_files: called CC=2 SCAR=7.0
1341 4 my ($file, $env) = @_;
1342 4 my ($stem, $ext) = $file =~ /\A(.*?)(\.[^.\/]*)?\z/;
1343 4 ▶ $ext = '' unless defined $ext;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ext 0 4 4
1344 4 return ( [ 'base', "$stem$ext" ],
1345 [ $env, "$stem.$env$ext" ],
1346 [ 'local', "$stem.local$ext" ] );
1347 }
1348  
1349 4 ▶sub _yaml_file {
Subroutine _yaml_file: called CC=3 SCAR=11.1
1350 4 my ($file) = @_;
1351 4 require YAML::XS;
1352 4 ▶ open my $fh, '<', $file or die "cannot read $file: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $file or die "cannot read ${file}: $!\n" 4 0 4
1353 4 local $/;
1354 4 my $body = <$fh>;
1355 4 close $fh;
1356 4 my $doc = YAML::XS::Load($body);
1357 4 ▶ return ref $doc eq 'HASH' ? $doc : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $doc eq 'HASH' ? : 4 0 4
1358 }
1359  
1360 # Every single-key { $env: ... } / { $file: ... } / { $exec: [...] } in the
1361 # document, with the dotted path it sits at.
1362 45 ▶sub _walk_secrets {
Subroutine _walk_secrets: called CC=9 SCAR=22.0
1363 45 my ($node, $path, $cb) = @_;
1364 45 ▶ if (ref $node eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $node eq 'HASH') { } 25 20 45
elsif (ref $node eq 'ARRAY') { } 1 19 20
1365 25 my @k = keys %$node;
1366 25 ▶ if (@k == 1 && $k[0] =~ /\A\$(env|file|exec|literal)\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if (@k == 1 and $k[0] =~ /\A\$(env|file|exec|literal)\z/) 4 21 25
Condition100%3/3
@k == 1 and $k[0] =~ /\A\$(env|file|exec|literal)\z/
!ll&&!rl&&r
11104
MC/DC100%2/2
@k == 1 and $k[0] =~ /\A\$(env|file|exec|literal)\z/
@k == 1 $k[0] =~ /\A\$(env|file|exec|literal)\z/
Truth table100%3/3
A and B
A= @k == 1B= $k[0] =~ /\A\$(env|file|exec|literal)\z/
ABresult
0X0
100
111
1367 $cb->({ path => ($path || '(root)'), kind => $k[0],
1368 4 ▶ value => $node->{ $k[0] } });
Condition50%1/2
$path || '(root)'
l!l
40
MC/DC0%0/1
$path || '(root)'
$path
Truth table50%1/2
A
A= $path
Aresult
11
00
1369 4 return;
1370 }
1371 _walk_secrets($node->{$_}, ($path ? "$path.$_" : $_), $cb)
1372 21 ▶ for sort keys %$node;
Branch: 1 branch
BranchTrueFalseTotal
$path ? : 27 12 39
1373 }
1374 elsif (ref $node eq 'ARRAY') {
1375 1 _walk_secrets($node->[$_], "$path\[$_]", $cb) for 0 .. $#$node;
1376 }
1377 41 return;
1378 }
1379  
1380 4 ▶sub _try_resolver {
Subroutine _try_resolver: called CC=21 SCAR=38.3
1381 4 my ($kind, $value) = @_;
1382 4 ▶ if ($kind eq '$literal') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "\$literal") 0 4 4
1383 0 return (1, 'inline value');
1384 }
1385 4 ▶ if ($kind eq '$env') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "\$env") 2 2 4
1386 2 ▶ my $name = ref $value ? '(not a name)' : ($value // '');
Branch: 1 branch
BranchTrueFalseTotal
ref $value ? : 0 2 2
Condition50%1/2
$value // ""
l!l
20
MC/DC0%0/1
$value // ""
$value
Truth table50%1/2
A
A= $value
Aresult
11
00
1387 2 ▶ return (0, "$name is not set") unless defined $ENV{$name};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ENV{$name} 1 1 2
1388 1 return (1, "$name is set");
1389 }
1390 2 ▶ if ($kind eq '$file') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "\$file") 1 1 2
1391 1 ▶ my $f = ref $value ? '(not a path)' : ($value // '');
Branch: 1 branch
BranchTrueFalseTotal
ref $value ? : 0 1 1
Condition50%1/2
$value // ""
l!l
10
MC/DC0%0/1
$value // ""
$value
Truth table50%1/2
A
A= $value
Aresult
11
00
1392 1 ▶ return (0, "$f does not exist") unless -e $f;
Branch: 1 branch
BranchTrueFalseTotal
unless -e $f 1 0 1
1393 0 ▶ return (0, "$f is not readable") unless -r $f;
Branch: 1 branch
BranchTrueFalseTotal
unless -r $f 0 0 0
1394 0 return (1, $f);
1395 }
1396 1 ▶ if ($kind eq '$exec') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq "\$exec") 1 0 1
1397 1 ▶ my @cmd = ref $value eq 'ARRAY' ? @$value : ($value // '');
Branch: 1 branch
BranchTrueFalseTotal
ref $value eq 'ARRAY' ? : 1 0 1
Condition0%0/2
$value // ""
l!l
00
MC/DC0%0/1
$value // ""
$value
Truth table0%0/2
A
A= $value
Aresult
11
00
1398 1 ▶ my $prog = $cmd[0] // '';
Condition50%1/2
$cmd[0] // ""
l!l
10
MC/DC0%0/1
$cmd[0] // ""
$cmd[0]
Truth table50%1/2
A
A= $cmd[0]
Aresult
11
00
1399 1 ▶ return (0, 'no command given') unless length $prog;
Branch: 1 branch
BranchTrueFalseTotal
unless length $prog 0 1 1
1400 1 ▶ return (1, join ' ', @cmd) if $prog =~ m{/} && -x $prog;
Branch: 1 branch
BranchTrueFalseTotal
if $prog =~ m[/] and -x $prog 0 1 1
Condition33%1/3
$prog =~ m[/] and -x $prog
!ll&&!rl&&r
100
MC/DC0%0/2
$prog =~ m[/] and -x $prog
$prog =~ m[/] -x $prog
Truth table33%1/3
A and B
A= $prog =~ m[/]B= -x $prog
ABresult
0X0
100
111
1401 1 ▶ for my $d (split /:/, ($ENV{PATH} // '')) {
Condition50%1/2
$ENV{"PATH"} // ""
l!l
10
MC/DC0%0/1
$ENV{"PATH"} // ""
$ENV{"PATH"}
Truth table50%1/2
A
A= $ENV{"PATH"}
Aresult
11
00
1402 10 ▶ return (1, join ' ', @cmd) if -x File::Spec->catfile($d, $prog);
Branch: 1 branch
BranchTrueFalseTotal
if -x "File::Spec"->catfile($d, $prog) 0 10 10
1403 }
1404 1 return (0, "$prog is not on PATH");
1405 }
1406 0 return (0, 'unknown resolver');
1407 }
1408  
1409 # ---- api sync helpers --------------------------------------------------------
1410  
1411 # Which operationIds already have a sub, by reading the controllers rather than
1412 # loading them: a half-written controller should not stop the command that is
1413 # meant to help you finish it.
1414 4 ▶sub _implemented_ops {
Subroutine _implemented_ops: called CC=12 SCAR=26.8
1415 4 my ($dir, %o) = @_;
1416 4 my %seen;
1417 4 ▶ return %seen unless -d $dir;
Branch: 1 branch
BranchTrueFalseTotal
unless -d $dir 0 4 4
1418 4 ▶ opendir(my $dh, $dir) or return %seen;
Branch: 1 branch
BranchTrueFalseTotal
opendir my $dh, $dir or return %seen 4 0 4
1419 4 my @files = grep { /\.pm\z/ } readdir $dh;
1420 4 closedir $dh;
1421 4 for my $f (@files) {
1422 4 ▶ next if $o{only} && $f !~ $o{only};
Branch: 1 branch
BranchTrueFalseTotal
if $o{"only"} and not $f =~ /$o{"only"}/ 0 4 4
Condition33%1/3
$o{"only"} and not $f =~ /$o{"only"}/
!ll&&!rl&&r
400
MC/DC0%0/2
$o{"only"} and not $f =~ /$o{"only"}/
$o{"only"} not $f =~ /$o{"only"}/
Truth table33%1/3
A and not(B)
A= $o{"only"}B= not $f =~ /$o{"only"}/
ABresult
0X0
100
111
1423 4 ▶ next if $o{skip} && $f =~ $o{skip};
Branch: 1 branch
BranchTrueFalseTotal
if $o{"skip"} and $f =~ /$o{"skip"}/ 0 4 4
Condition33%1/3
$o{"skip"} and $f =~ /$o{"skip"}/
!ll&&!rl&&r
400
MC/DC0%0/2
$o{"skip"} and $f =~ /$o{"skip"}/
$o{"skip"} $f =~ /$o{"skip"}/
Truth table33%1/3
A and B
A= $o{"skip"}B= $f =~ /$o{"skip"}/
ABresult
0X0
100
111
1424 4 ▶ open my $fh, '<', File::Spec->catfile($dir, $f) or next;
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", "File::Spec"->catfile($dir, $f) or next 4 0 4
1425 4 ▶ while (my $l = <$fh>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $l = readline $fh)) 179 0 179
1426 179 ▶ last if $l =~ /\A__END__/;
Branch: 1 branch
BranchTrueFalseTotal
if $l =~ /\A__END__/ 4 175 179
1427 175 ▶ $seen{$1} = $f if $l =~ /\A\s*sub\s+([A-Za-z_]\w*)\s*\{/;
Branch: 1 branch
BranchTrueFalseTotal
if $l =~ /\A\s*sub\s+([A-Za-z_]\w*)\s*\{/ 13 162 175
1428 }
1429 4 close $fh;
1430 }
1431 4 return %seen;
1432 }
1433  
1434 # Splice new stubs in before the closing 1; of an existing controller.
1435 2 ▶sub _insert_stubs {
Subroutine _insert_stubs: called CC=6 SCAR=18.2
1436 2 my ($file, $ops, $dry) = @_;
1437 2 ▶ return if $dry;
Branch: 1 branch
BranchTrueFalseTotal
if $dry 1 1 2
1438 1 ▶ open my $fh, '<', $file or Carp::croak("punk api: cannot read $file: $!");
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $file or Carp::croak("punk api: cannot read ${file}: $!") 1 0 1
1439 1 local $/;
1440 1 my $src = <$fh>;
1441 1 close $fh;
1442  
1443 1 require Punk::Generate;
1444 1 Punk::Generate::_op_id($_->{id}) for @$ops;
1445 my $stubs = join '', map {
1446 1 Punk::Generate->render_skel('api_stub.tmpl', { op => $_ })
1447 } @$ops;
1448  
1449 1 ▶ if ($src =~ /\n1;\s*\n/) { $src =~ s/\n1;\s*\n/\n$stubs\n1;\n/ }
Branch: 1 branch
BranchTrueFalseTotal
if ($src =~ /\n1;\s*\n/) { } 1 0 1
1450 0 else { $src .= "\n$stubs" }
1451  
1452 1 ▶ open my $out, '>', $file or Carp::croak("punk api: cannot write $file: $!");
Branch: 1 branch
BranchTrueFalseTotal
open my $out, ">", $file or Carp::croak("punk api: cannot write ${file}: $!") 1 0 1
1453 1 print $out $src;
1454 1 close $out;
1455 1 return;
1456 }
1457  
1458 # ---- console helpers ---------------------------------------------------------
1459  
1460 1 ▶sub _console_context {
Subroutine _console_context: called CC=2 SCAR=7.0
1461 1 my ($app) = @_;
1462 1 return eval {
1463 1 require Punk::Context;
1464 1 my $class = $app->{class} . '::_Context';
1465 1 ▶ $class = 'Punk::Context' unless $class->can('req');
Branch: 1 branch
BranchTrueFalseTotal
unless $class->can("req") 0 1 1
1466 $class->_build({ REQUEST_METHOD => 'GET', PATH_INFO => '/',
1467 QUERY_STRING => '', 'psgi.url_scheme' => 'http',
1468 HTTP_HOST => 'localhost', SERVER_NAME => 'localhost',
1469 SERVER_PORT => 80 },
1470 1 $app->{registrar}, {});
1471 };
1472 }
1473  
1474 1 ▶sub _console_dump {
Subroutine _console_dump: called CC=1 SCAR=0.0
1475 1 my (@out) = @_;
1476 1 require Data::Dumper;
1477 1 my $d = Data::Dumper->new(\@out);
1478 1 $d->Sortkeys(1)->Indent(1)->Terse(1);
1479 1 return $d->Dump;
1480 }
1481  
1482 1 ▶sub _console_wrap {
Subroutine _console_wrap: called CC=1 SCAR=0.0
1483 1 my ($line) = @_;
1484 1 return "package main; my \$app = \$Punk::Command::app_;"
1485 . " my \$psgi = \$Punk::Command::psgi_;"
1486 . " my \$c = \$Punk::Command::ctx_; $line";
1487 }
1488  
1489 # ---- dev helpers -------------------------------------------------------------
1490  
1491 0 ▶sub _mtimes {
Subroutine _mtimes: not called CC=2 SCAR=17.9
1492 0 my (@dirs) = @_;
1493 0 my %m;
1494 0 require File::Find;
1495 0 ▶ File::Find::find({ no_chdir => 1, wanted => sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
1496 0 ▶ return unless -f $File::Find::name;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $File::Find::name 0 0 0
1497 0 ▶ return if $File::Find::name =~ m{/\.};
Branch: 1 branch
BranchTrueFalseTotal
if $File::Find::name =~ m[/\.] 0 0 0
1498 0 $m{$File::Find::name} = (stat _)[9];
1499 0 ▶ } }, @dirs) if @dirs;
Branch: 1 branch
BranchTrueFalseTotal
if @dirs 0 0 0
1500 0 return %m;
1501 }
1502  
1503 0 ▶sub _same {
Subroutine _same: not called CC=5 SCAR=34.0
1504 0 my ($a, $b) = @_;
1505 0 ▶ return 0 if keys %$a != keys %$b;
Branch: 1 branch
BranchTrueFalseTotal
if keys %$a != keys %$b 0 0 0
1506 0 ▶ for (keys %$a) { return 0 if !exists $b->{$_} || $a->{$_} != $b->{$_} }
Branch: 1 branch
BranchTrueFalseTotal
if not exists $b->{$_} or $a->{$_} != $b->{$_} 0 0 0
Condition0%0/3
not exists $b->{$_} or $a->{$_} != $b->{$_}
l!l&&r!l&&!r
000
MC/DC0%0/2
not exists $b->{$_} or $a->{$_} != $b->{$_}
not exists $b->{$_} $a->{$_} != $b->{$_}
Truth table0%0/3
not(A) or B
A= not exists $b->{$_}B= $a->{$_} != $b->{$_}
ABresult
1X1
011
000
1507 0 return 1;
1508 }
1509  
1510 # ---- punk new ----------------------------------------------------------------
1511 # The one command that does not need an existing application. The work lives
1512 # in Punk::Generate; this is argument shape and the next-steps note.
1513  
1514 # The kit seam, the command seam's twin: `--kit diy` loads Punk::Kit::Diy and
1515 # generates through it. Same name shape and same transform as _probe, so a
1516 # distribution shipping both a kit and a subcommand spells them alike.
1517 7 ▶sub _kit_name_ok { return $_[0] =~ /\A[a-z][a-z0-9_-]*\z/ }
Subroutine _kit_name_ok: called CC=1 SCAR=0.0
1518  
1519 5 ▶sub _kit_class {
Subroutine _kit_class: called CC=4 SCAR=14.2
1520 5 my ($kit) = @_;
1521 5 (my $mod = ucfirst $kit) =~ s/[-_](\w)/\U$1/g;
1522 5 my $class = "Punk::Kit::$mod";
1523 5 (my $file = "$class.pm") =~ s{::}{/}g;
1524 5 ▶ unless (eval { require $file; 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (eval { do { require $file; 1 } }) 2 3 5
1525 2 my $err = $@;
1526 # Two different problems with two different answers: one is a cpanm
1527 # away, the other is a bug in something already installed.
1528 2 ▶ die "kit '$kit' is not installed (no $class on \@INC)\n"
Branch: 1 branch
BranchTrueFalseTotal
if $err =~ /\ACan't locate \Q$file\E in \@INC/ 2 0 2
1529 if $err =~ /\ACan't locate \Q$file\E in \@INC/;
1530 0 $err =~ s/\s+\z//;
1531 0 die "kit '$kit' failed to load: $err\n";
1532 }
1533 3 ▶ die "$class is not a kit: a kit subclasses Punk::Generate and overrides "
Branch: 1 branch
BranchTrueFalseTotal
unless $class->isa("Punk::Generate") 0 3 3
1534 . "run\n" unless $class->isa('Punk::Generate');
1535 3 return $class;
1536 }
1537  
1538 # --kit's value, read out of argv before Getopt has run, so the kit's own
1539 # options can be added to the ones being parsed. Takes both spellings and only
1540 # the first: a second --kit is Getopt's to complain about, not this.
1541 9 ▶sub _kit_from_argv {
Subroutine _kit_from_argv: called CC=5 SCAR=16.1
1542 9 my (@argv) = @_;
1543 9 for my $i (0 .. $#argv) {
1544 21 ▶ return $1 if $argv[$i] =~ /\A--kit=(.*)\z/s;
Branch: 1 branch
BranchTrueFalseTotal
if $argv[$i] =~ /\A--kit=(.*)\z/s 1 20 21
1545 20 ▶ return $argv[$i + 1] if $argv[$i] eq '--kit' && $i < $#argv;
Branch: 1 branch
BranchTrueFalseTotal
if $argv[$i] eq "--kit" and $i < $#argv 4 16 20
Condition66%2/3
$argv[$i] eq "--kit" and $i < $#argv
!ll&&!rl&&r
1604
MC/DC50%1/2
$argv[$i] eq "--kit" and $i < $#argv
$argv[$i] eq "--kit" $i < $#argv
Truth table66%2/3
A and B
A= $argv[$i] eq "--kit"B= $i < $#argv
ABresult
0X0
100
111
1546 }
1547 4 return;
1548 }
1549  
1550 5 ▶sub _cmd_new {
Subroutine _cmd_new: called CC=17 SCAR=30.5
1551 5 my ($opt, @args) = @_;
1552 5 my $name = shift @args;
1553 5 ▶ die { usage_error => 'an application name is required' }
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and length $name 1 4 5
Condition66%2/3
defined $name and length $name
!ll&&!rl&&r
104
MC/DC50%1/2
defined $name and length $name
defined $name length $name
Truth table66%2/3
A and B
A= defined $nameB= length $name
ABresult
0X0
100
111
1554 unless defined $name && length $name;
1555 4 ▶ die { usage_error => "unexpected argument '$args[0]'" } if @args;
Branch: 1 branch
BranchTrueFalseTotal
if @args 0 4 4
1556 # --sqitch's engine is checked before anything is written
1557 die { usage_error => "--sqitch needs an engine: sqlite, pg or mysql, not '$opt->{sqitch}'" }
1558 4 ▶ if defined $opt->{sqitch} && $opt->{sqitch} !~ /\A(?:sqlite|pg|mysql)\z/;
Branch: 1 branch
BranchTrueFalseTotal
if defined $opt->{"sqitch"} and not $opt->{"sqitch"} =~ /\A(?:sqlite|pg|mysql)\z/ 1 3 4
Condition100%3/3
defined $opt->{"sqitch"} and not $opt->{"sqitch"} =~ /\A(?:sqlite|pg|mysql)\z/
!ll&&!rl&&r
211
MC/DC100%2/2
defined $opt->{"sqitch"} and not $opt->{"sqitch"} =~ /\A(?:sqlite|pg|mysql)\z/
defined $opt->{"sqitch"} not $opt->{"sqitch"} =~ /\A(?:sqlite|pg|mysql)\z/
Truth table100%3/3
A and not(B)
A= defined $opt->{"sqitch"}B= not $opt->{"sqitch"} =~ /\A(?:sqlite|pg|mysql)\z/
ABresult
0X0
100
111
1559 die { usage_error => "--kit takes a name like 'diy' ([a-z][a-z0-9_-]*), "
1560 . "not '$opt->{kit}'" }
1561 3 ▶ if defined $opt->{kit} && !_kit_name_ok($opt->{kit});
Branch: 1 branch
BranchTrueFalseTotal
if defined $opt->{"kit"} and not _kit_name_ok($opt->{"kit"}) 1 2 3
Condition100%3/3
defined $opt->{"kit"} and not _kit_name_ok($opt->{"kit"})
!ll&&!rl&&r
111
MC/DC100%2/2
defined $opt->{"kit"} and not _kit_name_ok($opt->{"kit"})
defined $opt->{"kit"} not _kit_name_ok($opt->{"kit"})
Truth table100%3/3
A and not(B)
A= defined $opt->{"kit"}B= not _kit_name_ok($opt->{"kit"})
ABresult
0X0
100
111
1562  
1563 2 require Punk::Generate;
1564 2 ▶ my $class = defined $opt->{kit} ? _kit_class($opt->{kit}) : 'Punk::Generate';
Branch: 1 branch
BranchTrueFalseTotal
defined $opt->{'kit'} ? : 1 1 2
1565  
1566 # Every option goes to the constructor: Punk::Generate ignores the keys it
1567 # does not know, so a kit reads its own out of the same hash rather than
1568 # needing this to know what it takes.
1569 my $gen = $class->new(
1570 %$opt,
1571 name => $name,
1572 (defined $opt->{dir} ? (dir => $opt->{dir}) : ()),
1573 (defined $opt->{api} ? (api => $opt->{api}) : ()),
1574 force => $opt->{force},
1575 1 ▶ );
Branch: 2 branches
BranchTrueFalseTotal
defined $opt->{'dir'} ? : 1 0 1
defined $opt->{'api'} ? : 0 1 1
1576 1 my @files = $gen->run;
1577 1 my $dir = $gen->dir;
1578 1 print "Created $name in $dir\n\n";
1579 1 print " $_\n" for @files;
1580  
1581 # --sqitch ENGINE: a Sqitch project for the schema, through Punk-Sqitch.
1582 # The engine is asked for rather than read, because the generated
1583 # punk.yml ships its database block commented out. The application is
1584 # already written by now, so a missing Punk-Sqitch is reported with the
1585 # command to run once it is installed, not as a failed `new`.
1586 1 my $sq = 0;
1587 1 ▶ if (defined $opt->{sqitch}
Branch: 2 branches
BranchTrueFalseTotal
if (defined $opt->{'sqitch'} and -f 'File::Spec'->catfile($dir, 'sqitch.plan')) { } 0 1 1
elsif (defined $opt->{'sqitch'}) { } 1 0 1
Condition33%1/3
defined $opt->{"sqitch"} and -f "File::Spec"->catfile($dir, "sqitch.plan")
!ll&&!rl&&r
010
MC/DC0%0/2
defined $opt->{"sqitch"} and -f "File::Spec"->catfile($dir, "sqitch.plan")
defined $opt->{"sqitch"} -f "File::Spec"->catfile($dir, "sqitch.plan")
Truth table33%1/3
A and B
A= defined $opt->{"sqitch"}B= -f "File::Spec"->catfile($dir, "sqitch.plan")
ABresult
0X0
100
111
1588 && -f File::Spec->catfile($dir, 'sqitch.plan')) {
1589 # A kit that manages its own schema has already written the project.
1590 # Sqitch's own init is a silent no-op on one, so running it here would
1591 # end a successful generation with a confusing message about a project
1592 # that is exactly as it should be.
1593 0 print "\npunk new: the kit wrote the Sqitch project; skipping init\n";
1594 }
1595 elsif (defined $opt->{sqitch}) {
1596 1 my $engine = $opt->{sqitch};
1597 0 ▶ if (eval { require Punk::Command::Sqitch; 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
if (eval { do { require Punk::Command::Sqitch; 1 } }) { } 0 1 1
1598 0 print "\n";
1599 0 $sq = Punk::Command::Sqitch::main('--dir', $dir, 'init', '--engine', $engine);
1600 }
1601 else {
1602 1 print STDERR "\npunk new: --sqitch needs Punk-Sqitch, which is not installed; "
1603 . "once it is, run\n\n punk sqitch init --engine $engine\n\n"
1604 . "inside $dir\n";
1605 1 $sq = 1;
1606 }
1607 }
1608 # A kit knows what its application needs before it will serve - a schema
1609 # deployed, a secret set - so it gets to say so instead of this.
1610 1 ▶ if ($gen->can('next_steps')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($gen->can('next_steps')) { } 0 1 1
1611 0 print $gen->next_steps;
1612 }
1613 else {
1614 1 print <<"NEXT";
1615  
1616 cd $dir
1617 plackup app.psgi
1618  
1619 Then open http://localhost:5000/
1620 NEXT
1621 }
1622 1 return $sq;
1623 }
1624  
1625 # ---- punk generate -----------------------------------------------------------
1626 # Into an EXISTING application - `new` scaffolds once; these add to it. The
1627 # class comes from app.psgi by the same scrape _load_app uses, but without
1628 # executing anything - a broken controller cannot stop you generating the fix.
1629  
1630 10 ▶sub _cmd_generate {
Subroutine _cmd_generate: called CC=13 SCAR=25.7
1631 10 my ($kind, $opt, @args) = @_;
1632 10 my $name = shift @args;
1633 10 ▶ die { usage_error => "a $kind name is required" }
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and length $name 1 9 10
Condition66%2/3
defined $name and length $name
!ll&&!rl&&r
109
MC/DC50%1/2
defined $name and length $name
defined $name length $name
Truth table66%2/3
A and B
A= defined $nameB= length $name
ABresult
0X0
100
111
1634 unless defined $name && length $name;
1635 9 ▶ die { usage_error => "unexpected argument '$args[0]'" } if @args;
Branch: 1 branch
BranchTrueFalseTotal
if @args 0 9 9
1636 9 ▶ die { usage_error => "'$name' is not a valid package name" }
Branch: 1 branch
BranchTrueFalseTotal
unless $name =~ /^[A-Z]\w*(?:::[A-Z]\w*)*$/ 1 8 9
1637 unless $name =~ /^[A-Z]\w*(?:::[A-Z]\w*)*$/;
1638  
1639 my $root = _find_root($opt->{dir})
1640 8 ▶ or die "no application found (run inside one, or pass --dir)\n";
Branch: 1 branch
BranchTrueFalseTotal
my $root = _find_root($opt->{"dir"}) or die "no application found (run inside one, or pass --dir)\n" 7 1 8
1641 7 ▶ my $class = _class_of($root)
Branch: 1 branch
BranchTrueFalseTotal
my $class = _class_of($root) or die "could not read the application class from app.psgi\n" 7 0 7
1642 or die "could not read the application class from app.psgi\n";
1643  
1644 7 my @segs = split /::/, $name;
1645 7 my ($tmpl, $rel, %vars);
1646 7 ▶ if ($kind eq 'controller') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq 'controller') { } 5 2 7
1647 5 ▶ my $ns = $opt->{api} ? 'API' : 'Web';
Branch: 1 branch
BranchTrueFalseTotal
$opt->{'api'} ? : 1 4 5
1648 5 $rel = join('/', 'lib', (split /::/, $class),
1649 'Controller', $ns, @segs) . '.pm';
1650 5 $tmpl = 'controller_gen.tmpl';
1651 %vars = (app => $class, ns => $ns, name => join('::', @segs),
1652 5 ▶ route => lc(join '/', @segs), api => $opt->{api} ? 1 : 0);
Branch: 1 branch
BranchTrueFalseTotal
$opt->{'api'} ? : 1 4 5
1653 }
1654 else {
1655 2 $rel = join('/', 'lib', (split /::/, $class), 'Model', @segs) . '.pm';
1656 2 $tmpl = 'model_gen.tmpl';
1657 %vars = (app => $class, name => join('::', @segs),
1658 2 ▶ table => $opt->{table} // lc($segs[-1]) . 's');
Condition100%2/2
$opt->{"table"} // lc($segs[-1]) . 's'
l!l
11
MC/DC100%1/1
$opt->{"table"} // lc($segs[-1]) . 's'
$opt->{"table"}
Truth table100%2/2
A
A= $opt->{"table"}
Aresult
11
00
1659 }
1660 7 my $abs = File::Spec->catfile($root, split m{/}, $rel);
1661 7 ▶ die "$rel already exists\n" if -e $abs && !$opt->{force};
Branch: 1 branch
BranchTrueFalseTotal
if -e $abs and not $opt->{"force"} 1 6 7
Condition100%3/3
-e $abs and not $opt->{"force"}
!ll&&!rl&&r
511
MC/DC100%2/2
-e $abs and not $opt->{"force"}
-e $abs not $opt->{"force"}
Truth table100%3/3
A and not(B)
A= -e $absB= not $opt->{"force"}
ABresult
0X0
100
111
1662  
1663 6 require Punk::Generate;
1664 6 Punk::Generate->write_skel($tmpl, $abs, \%vars);
1665 6 print "wrote $rel\n";
1666 6 return 0;
1667 }
1668  
1669 # ---- punk test ---------------------------------------------------------------
1670  
1671 0 ▶sub _cmd_test {
Subroutine _cmd_test: not called CC=7 SCAR=40.3
1672 0 my ($opt, @args) = @_;
1673 0 ▶ my $root = _find_root($opt->{dir}) or do {
Branch: 1 branch
BranchTrueFalseTotal
my $root = _find_root($opt->{"dir"}) or do { print STDERR "punk test: no application found\n"; return 2 } 0 0 0
1674 0 print STDERR "punk test: no application found\n";
1675 0 return 2;
1676 };
1677 0 require App::Prove; # ships with Test::Harness
1678 0 ▶ local $ENV{PUNK_ENV} = $opt->{env} if defined $opt->{env};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opt->{"env"} 0 0 0
1679 0 my $cwd = Cwd::getcwd();
1680 0 ▶ chdir $root or die "cannot chdir to $root: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
chdir $root or die "cannot chdir to ${root}: $!\n" 0 0 0
1681 0 my $prove = App::Prove->new;
1682 0 ▶ $prove->process_args('-l', '-r', (@args ? @args : 't'));
Branch: 1 branch
BranchTrueFalseTotal
@args ? : 0 0 0
1683 0 my $ok = eval { $prove->run };
1684 0 my $err = $@;
1685 0 chdir $cwd;
1686 0 ▶ die $err if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 0 0 0
1687 0 ▶ return $ok ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
$ok ? : 0 0 0
1688 }
1689  
1690 # ---- punk secret -------------------------------------------------------------
1691  
1692 4 ▶sub _random_bytes {
Subroutine _random_bytes: called CC=4 SCAR=14.3
1693 4 my ($n) = @_;
1694 4 ▶ open my $ur, '<:raw', '/dev/urandom'
Branch: 1 branch
BranchTrueFalseTotal
open my $ur, "<:raw", "/dev/urandom" or die "cannot open /dev/urandom: $!\n" 4 0 4
1695 or die "cannot open /dev/urandom: $!\n";
1696 4 my $bytes;
1697 4 my $got = read($ur, $bytes, $n);
1698 4 close $ur;
1699 4 ▶ die "short read from /dev/urandom\n" unless ($got // 0) == $n;
Branch: 1 branch
BranchTrueFalseTotal
unless ($got // 0) == $n 0 4 4
Condition50%1/2
$got // 0
l!l
40
MC/DC0%0/1
$got // 0
$got
Truth table50%1/2
A
A= $got
Aresult
11
00
1700 4 return $bytes;
1701 }
1702  
1703 5 ▶sub _cmd_secret {
Subroutine _cmd_secret: called CC=5 SCAR=16.1
1704 5 my ($opt) = @_;
1705 5 my $n = $opt->{bytes};
1706 5 ▶ die { usage_error => 'bytes must be between 16 and 256' }
Branch: 1 branch
BranchTrueFalseTotal
if not $n or $n < 16 or $n > 256 1 4 5
Condition66%4/6
not $n or $n < 16 or $n > 256
l!l&&r!l&&!r
104
not $n or $n < 16
l!l&&r!l&&!r
014
MC/DC33%1/3
not $n or $n < 16 or $n > 256
not $n $n < 16 $n > 256
Truth table50%2/4
not(A) or B or C
A= not $nB= $n < 16C= $n > 256
ABCresult
1XX1
01X1
0011
0000
1707 if !$n || $n < 16 || $n > 256;
1708 4 my $raw = _random_bytes($n);
1709 4 ▶ if ($opt->{hex}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt->{'hex'}) { } 1 3 4
1710 1 print unpack('H*', $raw), "\n";
1711 }
1712 else {
1713 3 require MIME::Base64;
1714 3 my $t = MIME::Base64::encode_base64($raw, '');
1715 3 $t =~ tr{+/=}{-_}d; # url-safe, no padding
1716 3 print "$t\n";
1717 }
1718 4 return 0;
1719 }
1720  
1721 # ---- the core registrations --------------------------------------------------
1722 # Registration order is the order `punk` lists them in.
1723  
1724 __PACKAGE__->register(new => {
1725 abstract => 'generate a new application',
1726 display => 'new <AppName>',
1727 usage => '<AppName> [options]',
1728 desc => 'Generate a running Punk application: routes, a controller, '
1729 . "Stencil views,\nconfig/punk.yml, a psgi entry point and a "
1730 . 'test.',
1731 options => [
1732 { spec => 'dir=s', arg => 'PATH',
1733 doc => 'where to write it (default: the name, :: replaced by -)' },
1734 { spec => 'api=s', arg => 'SPEC',
1735 doc => 'an OpenAPI 3.1 document to mount under /api, generating '
1736 . 'one controller of operation stubs per tag' },
1737 { spec => 'force',
1738 doc => 'write into a directory that is not empty' },
1739 { spec => 'sqitch=s', arg => 'ENGINE',
1740 doc => 'also initialise a Sqitch project for the schema (sqlite, pg '
1741 . 'or mysql); needs Punk-Sqitch' },
1742 { spec => 'kit=s', arg => 'NAME',
1743 doc => 'generate from an installed kit (Punk::Kit::<Name>) instead '
1744 . 'of the basic skeleton; `punk new --kit NAME --help` lists '
1745 . 'what it takes' },
1746 ],
1747 # The kit named in argv brings its own options, so they parse and appear
1748 # in help like any other rather than being scraped out of a leftover argv.
1749 9 ▶ extra_options => sub {
Subroutine __ANON__: called CC=5 SCAR=16.1
1750 9 my (@argv) = @_;
1751 9 my $kit = _kit_from_argv(@argv);
1752 9 ▶ return unless defined $kit && _kit_name_ok($kit);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $kit and _kit_name_ok($kit) 5 4 9
Condition100%3/3
defined $kit and _kit_name_ok($kit)
!ll&&!rl&&r
414
MC/DC100%2/2
defined $kit and _kit_name_ok($kit)
defined $kit _kit_name_ok($kit)
Truth table100%3/3
A and B
A= defined $kitB= _kit_name_ok($kit)
ABresult
0X0
100
111
1753 4 ▶ my $class = eval { _kit_class($kit) } or return; # the body reports it
Branch: 1 branch
BranchTrueFalseTotal
my $class = eval { do { _kit_class($kit) } } or return 3 1 4
1754 3 ▶ return unless $class->can('options');
Branch: 1 branch
BranchTrueFalseTotal
unless $class->can("options") 0 3 3
1755 3 return map { { %$_, owner => $class, section => "kit options ($kit)" } }
1756 $class->options;
1757 },
1758 51 examples => [
1759 'punk new MyApp',
1760 'punk new MyApp --dir ~/code/myapp',
1761 'punk new MyApp --api ./openapi.json',
1762 'punk new MyApp --sqitch pg',
1763 'punk new MyApp --kit diy',
1764 ],
1765 hints => [ [ qr/is not empty/, 'use --force to write into it anyway' ],
1766 [ qr/kit '.*' is not installed/,
1767 'kits ship in their own distributions; the diy kit is '
1768 . 'Punk-DIY' ] ],
1769 code => \&_cmd_new,
1770 });
1771  
1772 __PACKAGE__->register(generate => {
1773 abstract => 'add a controller or model to an existing application',
1774 display => 'generate <what>',
1775 commands => {
1776 controller => {
1777 abstract => 'a controller class',
1778 usage => '<Name> [options]',
1779 desc => 'Write lib/<App>/Controller/Web/<Name>.pm (or '
1780 . "Controller/API with --api) into\nthe application, "
1781 . 'ready to be named as a route target.',
1782 options => [
1783 { spec => 'api',
1784 doc => 'under Controller::API, answering JSON' },
1785 { spec => 'force', doc => 'overwrite an existing file' },
1786 ],
1787 8 ▶ code => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1788 8 my ($opt, @a) = @_;
1789 8 return _cmd_generate(controller => $opt, @a);
1790 },
1791 },
1792 model => {
1793 abstract => 'a Punk::Model class',
1794 usage => '<Name> [options]',
1795 desc => 'Write lib/<App>/Model/<Name>.pm with a table and a '
1796 . "field stub - auto-discovered\nby a bare `model;`, or "
1797 . "registered with model '<Name>'.",
1798 options => [
1799 { spec => 'table=s', arg => 'NAME',
1800 doc => 'the table (default: the lowercased name, '
1801 . 'pluralised)' },
1802 { spec => 'force', doc => 'overwrite an existing file' },
1803 ],
1804 2 ▶ code => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1805 2 my ($opt, @a) = @_;
1806 2 return _cmd_generate(model => $opt, @a);
1807 },
1808 },
1809 },
1810 51 });
1811  
1812 __PACKAGE__->register(routes => {
1813 abstract => 'the compiled routing table',
1814 desc => 'Print the compiled routing table: every route, API '
1815 . "operation, websocket\nroute and mounted application, with "
1816 . 'what it resolved to.',
1817 options => [
1818 { spec => 'sort',
1819 doc => 'order by path rather than by declaration' },
1820 { spec => 'method=s', arg => 'NAME',
1821 doc => 'only this HTTP method (or WS / ANY)' },
1822 { spec => 'path=s', arg => 'GLOB',
1823 doc => 'only paths matching the glob (* within a segment, '
1824 . '** across)' },
1825 { spec => 'kind=s', arg => 'KIND',
1826 doc => 'only route, api, ws, markdown or mount rows' },
1827 { spec => 'name=s', arg => 'NAME',
1828 doc => 'only the route with this name (exact)' },
1829 { spec => 'json',
1830 doc => 'machine output: a JSON array of row objects' },
1831 ],
1832 9 ▶ code => sub { my ($opt) = @_; return routes(%$opt) },
Subroutine __ANON__: called CC=1 SCAR=0.0
1833 51 });
1834  
1835 __PACKAGE__->register(api => {
1836 abstract => 'add stubs for operations added to the spec',
1837 display => 'api sync',
1838 commands => {
1839 sync => {
1840 abstract => 'add stubs for new operations',
1841 desc => 'Add a stub for every operation openapi.json declares '
1842 . "that the controllers\ndo not implement. Methods with "
1843 . "no matching operation are reported, never\nremoved, "
1844 . 'and an implemented operation is never touched.',
1845 options => [
1846 { spec => 'spec=s', arg => 'PATH',
1847 doc => 'the document (default: openapi.json in the '
1848 . 'application root)' },
1849 { spec => 'dry-run',
1850 doc => 'report what would change, write nothing' },
1851 ],
1852 5 ▶ code => sub { my ($opt) = @_; return api_sync(%$opt) },
Subroutine __ANON__: called CC=1 SCAR=0.0
1853 },
1854 },
1855 51 });
1856  
1857 __PACKAGE__->register(config => {
1858 abstract => 'resolve the configuration and every secret it references',
1859 display => 'config check',
1860 commands => {
1861 check => {
1862 abstract => 'resolve the configuration',
1863 desc => 'Resolve config/punk.yml and report every $env, '
1864 . "\$file and \$exec reference\nindependently, so one "
1865 . "missing secret does not hide the rest. Exits\n"
1866 . 'non-zero when anything failed - usable as a '
1867 . 'deployment gate.',
1868 options => [
1869 { spec => 'file=s', arg => 'PATH',
1870 doc => 'the config file (default: config/punk.yml)' },
1871 { spec => 'env=s', arg => 'NAME',
1872 doc => 'the environment layer (default: $PUNK_ENV or '
1873 . 'production)' },
1874 { spec => 'secrets=s', arg => 'MODE',
1875 doc => 'strict, warn or off, for the plaintext-secret '
1876 . 'guardrail' },
1877 { spec => 'dump',
1878 doc => 'print the resolved structure, secrets redacted' },
1879 ],
1880 5 ▶ code => sub { my ($opt) = @_; return config_check(%$opt) },
Subroutine __ANON__: called CC=1 SCAR=0.0
1881 },
1882 },
1883 51 });
1884  
1885 __PACKAGE__->register(doctor => {
1886 abstract => 'versions, C ABIs and application health',
1887 desc => 'Report versions, which C ABI tables resolved and at what '
1888 . "version, and -\nwhen run inside an application - its routes "
1889 . 'and configuration.',
1890 4 ▶ code => sub { my ($opt) = @_; return doctor(%$opt) },
Subroutine __ANON__: called CC=1 SCAR=0.0
1891 51 });
1892  
1893 __PACKAGE__->register(console => {
1894 abstract => 'a REPL with the application compiled',
1895 desc => 'A REPL with the application compiled: $app is the '
1896 . "registrar, \$psgi the\ncompiled coderef, \$c a throwaway "
1897 . 'context for $c->model and friends.',
1898 options => [
1899 { spec => 'eval=s', arg => 'CODE',
1900 doc => 'evaluate one expression, print its dump, exit' },
1901 ],
1902 1 ▶ code => sub { my ($opt) = @_; return console(%$opt) },
Subroutine __ANON__: called CC=1 SCAR=0.0
1903 51 });
1904  
1905 51 __PACKAGE__->register(test => {
1906 abstract => 'run the application test suite',
1907 usage => '[prove arguments]',
1908 desc => 'Run prove -lr in the application root. Extra arguments go '
1909 . "to prove\nverbatim (a file, -v, -j4).",
1910 options => [
1911 { spec => 'env=s', arg => 'NAME', doc => 'PUNK_ENV for the run' },
1912 ],
1913 code => \&_cmd_test,
1914 });
1915  
1916 51 __PACKAGE__->register(secret => {
1917 abstract => 'random key material for a session secret',
1918 desc => 'Print one line of random key material - what punk.yml\'s '
1919 . "session secret\nwants behind its \$env reference. Nothing "
1920 . 'else goes to stdout, so it pipes.',
1921 options => [
1922 { spec => 'bytes=i', arg => 'N', doc => 'how much entropy',
1923 default => 32 },
1924 { spec => 'hex', doc => 'hex instead of url-safe base64' },
1925 ],
1926 code => \&_cmd_secret,
1927 });
1928  
1929 __PACKAGE__->register(dev => {
1930 abstract => 'run under Hyperman, restarting when files change',
1931 desc => 'Run the application under Hyperman, restarting it when '
1932 . "anything under\nlib/, config/ or root/templates/ changes.",
1933 options => [
1934 { spec => 'port=i', arg => 'N', doc => 'listen port',
1935 default => 5000 },
1936 { spec => 'host=s', arg => 'ADDR', doc => 'listen address',
1937 default => '127.0.0.1' },
1938 { spec => 'workers=i', arg => 'N', doc => 'worker processes',
1939 default => 1 },
1940 { spec => 'watch=s@', arg => 'DIR',
1941 doc => 'watch this directory, repeatable (default: lib, config, '
1942 . 'root/templates)' },
1943 { spec => 'env=s', arg => 'NAME',
1944 doc => 'PUNK_ENV for the server (default: development)' },
1945 { spec => 'no-reload', doc => 'do not watch for changes' },
1946 ],
1947 0 ▶ code => sub { my ($opt) = @_; return dev(%$opt) },
Subroutine __ANON__: not called CC=1 SCAR=6.9
1948 51 });
1949  
1950 51 __PACKAGE__->register(serve => {
1951 abstract => 'serve a directory of files over HTTP',
1952 display => 'serve [DIR]',
1953 usage => '[DIR] [options]',
1954 desc => "Serve a directory of files under Hyperman. There is no "
1955 . "application involved -\nno app.psgi, no configuration, "
1956 . "nothing to generate. A directory resolves to\nits "
1957 . 'index.html, and --list renders one for a directory that '
1958 . 'has none.',
1959 options => [
1960 # displaces the shared --dir, which is about finding an application
1961 { spec => 'dir=s', arg => 'PATH',
1962 doc => 'the directory to serve, if not given as an argument',
1963 default => '.' },
1964 { spec => 'port=i', arg => 'N', doc => 'listen port',
1965 default => 8000 },
1966 { spec => 'host=s', arg => 'ADDR', doc => 'listen address',
1967 default => '127.0.0.1' },
1968 { spec => 'workers=i', arg => 'N', doc => 'worker processes',
1969 default => 1 },
1970 { spec => 'index=s', arg => 'NAME',
1971 doc => 'the file a directory resolves to', default => 'index.html' },
1972 { spec => 'no-index',
1973 doc => 'leave a directory as a 404 instead' },
1974 { spec => 'list',
1975 doc => 'render a listing for a directory with no index file' },
1976 { spec => 'max-age=i', arg => 'N',
1977 doc => 'Cache-Control freshness in seconds (default: revalidate '
1978 . 'every time)' },
1979 { spec => 'quiet', doc => 'no access log' },
1980 ],
1981 examples => [
1982 'punk serve',
1983 'punk serve ./public --port 3000',
1984 'punk serve --host 0.0.0.0 --list',
1985 ],
1986 hints => [ [ qr/Hyperman is not installed/,
1987 'cpanm Hyperman' ] ],
1988 code => \&_cmd_serve,
1989 });
1990  
1991 __PACKAGE__->register(version => {
1992 abstract => 'print the version',
1993 hidden => 1, # the list already shows punk --version
1994 1 ▶ code => sub { print "punk $Punk::VERSION\n"; return 0 },
Subroutine __ANON__: called CC=1 SCAR=0.0
1995 51 });
1996  
1997 51 1;
1998  
1999 __END__
↑ Summary blib/lib/Punk/DevError.pm »