lib/IO/K8s/CRD/Emitter.pm

filter: Statementstmt 97.4% 311 / 319 Branchbran 81.2% 169 / 208 Conditioncond 69.5% 57 / 82 MC/DCmcdc 51.0% 25 / 49 Subroutinesub 97.2% 35 / 36 Podpod 100% 2 / 2 totaltotal 86.0% 599 / 696 CC 138 SCAR 28.7
CC
138
Cov
88%
_type_source
47.3
_render_class
27.2
_literal
10.5
CRAP 17.6
« blib/lib/IO/K8s/Role/APIObject.pm ↑ Summary lib/IO/K8s/Role/Routable.pm »
1 package IO::K8s::CRD::Emitter;
2 # ABSTRACT: Render generated IO::K8s classes as house-style Perl source
3 15 our $VERSION = '1.112';
4 15 ▶use v5.10;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 15 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 15 ▶use Carp qw( croak );
Subroutine BEGIN: called CC=1 SCAR=0.0
7 # Deliberate exception to the "no Data::Dumper in shipped code" house rule:
8 # _scalar_literal below renders a single scalar as a Perl literal via Dumper,
9 # to reproduce its number-vs-string quoting byte-for-byte. Codegen, not debug.
10 15 ▶use Data::Dumper ();
Subroutine BEGIN: called CC=1 SCAR=0.0
11 15 ▶use Digest::SHA qw( sha1_hex );
Subroutine BEGIN: called CC=1 SCAR=0.0
12 15 ▶use re ();
Subroutine BEGIN: called CC=1 SCAR=0.0
13 15 ▶use Types::Standard qw( Bool Str HashRef );
Subroutine BEGIN: called CC=1 SCAR=0.0
14 15 ▶use IO::K8s::AutoGen ();
Subroutine BEGIN: called CC=1 SCAR=0.0
15 15 ▶use IO::K8s::Resource ();
Subroutine BEGIN: called CC=1 SCAR=0.0
16 15 ▶use IO::K8s::Role::Resource ();
Subroutine BEGIN: called CC=1 SCAR=0.0
17  
18  
19  
20 15 has base => (is => 'ro', isa => Str, required => 1);
21 20 ▶has names => (is => 'ro', isa => HashRef, default => sub { {} });
Subroutine __ANON__: called CC=1 SCAR=0.0
22 25 ▶has overlay => (is => 'ro', isa => HashRef, default => sub { {} });
Subroutine __ANON__: called CC=1 SCAR=0.0
23 27 ▶has version => (is => 'ro', isa => Str, default => sub { $VERSION });
Subroutine __ANON__: called CC=1 SCAR=0.0
24 15 has subresources => (is => 'ro', isa => Bool, default => 1);
25  
26 # The reverse of IO::K8s::Resource's class-prefix map (full namespace ->
27 # short prefix), longest full namespace first so a more specific prefix
28 # ('IO::K8s::Api::Core') is tried before a shorter one that would also
29 # match as a '::'-bounded prefix. Built once per emitter instance -- the
30 # map itself never changes mid-render.
31 15 has _prefix_pairs => (is => 'lazy', init_arg => undef);
32  
33 7 ▶sub _build__prefix_pairs {
Subroutine _build__prefix_pairs: called CC=1 SCAR=0.0
34 7 my $prefixes = IO::K8s::Resource::class_prefixes();
35 return [
36 900 sort { length($b->[1]) <=> length($a->[1]) }
37 7 map { [ $_, $prefixes->{$_} ] } keys %$prefixes
38 ];
39 }
40  
41  
42 # Bounds only the suffix this method appends below `base` -- AutoGen's own
43 # $MAX_CLASS_NAME bounds the full namespace-qualified name IT generates,
44 # which this has no control over and does not need to duplicate.
45 15 my $MAX_PACKAGE_SUFFIX = 200;
46  
47 # A filesystem path component -- and much tooling that shells out to a file
48 # name -- tops out around 255 bytes. A long `base` plus an otherwise-short
49 # suffix can still cross that even when the suffix alone passes the check
50 # above, so the joined package name as a whole is capped too.
51 15 my $MAX_PACKAGE_LENGTH = 255;
52  
53 475 ▶sub package_for {
Subroutine package_for: called CC=10 SCAR=23.0
Pod documented
54 475 my ($self, $class) = @_;
55 475 ▶ my $root = $self->{_root} // croak 'package_for needs a render() first';
Condition50%1/2
$self->{"_root"} // croak("package_for needs a render() first")
l!l
4750
MC/DC0%0/1
$self->{"_root"} // croak("package_for needs a render() first")
$self->{"_root"}
Truth table50%1/2
A
A= $self->{"_root"}
Aresult
11
00
56 475 ▶ return $self->base . '::' . $self->names->{$class} if $self->names->{$class};
Branch: 1 branch
BranchTrueFalseTotal
if $self->names->{$class} 62 413 475
57 413 my $kind = (split /::/, $root)[-1];
58  
59 # The field path, independent of whatever (possibly hash-shortened)
60 # Perl name AutoGen gave the class -- see the POD above.
61 413 my $path = IO::K8s::AutoGen::class_path($class);
62 413 ▶ unless (defined $path) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $path) 70 343 413
63 70 ($path = $class) =~ s/^\Q$root\E(?:::)?//;
64 }
65  
66 # overlay.names is keyed by that same logical path, not by $class --
67 # unlike L</names>, an overlay is written once per Kind against the
68 # upstream Go types and has no way to know what (possibly shortened)
69 # Perl name AutoGen happened to give a class this run.
70 413 ▶ if (length $path and my $overlay_names = $self->overlay->{names}) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $path and my $overlay_names = $self->overlay->{"names"}) 116 297 413
Condition100%3/3
length $path and my $overlay_names = $self->overlay->{"names"}
!ll&&!rl&&r
70227116
MC/DC100%2/2
length $path and my $overlay_names = $self->overlay->{"names"}
length $path my $overlay_names = $self->overlay->{"names"}
Truth table100%3/3
A and B
A= length $pathB= my $overlay_names = $self->overlay->{"names"}
ABresult
0X0
100
111
71 116 ▶ if (my $name = $overlay_names->{$path}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $name = $overlay_names->{$path}) 66 50 116
72 # k120: an overlay name carrying '::' (or a leading '+') is an
73 # ABSOLUTE target -- a fully-qualified package under another
74 # version directory of this same provider (ExternalSecrets'
75 # v1alpha1 generators reuse the v1 Auth types) or any other
76 # checked-in class. It is used verbatim rather than joined below
77 # $base, and _is_external_ref treats it as a bare reference that
78 # this render does not itself emit a file for. A bare name (no
79 # '::') is a package under $base as before.
80 66 $name =~ s/^\+//;
81 66 ▶ return $name =~ /::/ ? $name : $self->base . '::' . $name;
Branch: 1 branch
BranchTrueFalseTotal
$name =~ /::/ ? : 6 60 66
82 }
83 }
84  
85 347 my $joined = join '', $kind, split /::/, $path;
86 347 my $full = $self->base . '::' . $joined;
87 347 ▶ if (length($joined) > $MAX_PACKAGE_SUFFIX || length($full) > $MAX_PACKAGE_LENGTH) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $joined > $MAX_PACKAGE_SUFFIX or length $full > $MAX_PACKAGE_LENGTH) 16 331 347
Condition66%2/3
length $joined > $MAX_PACKAGE_SUFFIX or length $full > $MAX_PACKAGE_LENGTH
l!l&&r!l&&!r
160331
MC/DC50%1/2
length $joined > $MAX_PACKAGE_SUFFIX or length $full > $MAX_PACKAGE_LENGTH
length $joined > $MAX_PACKAGE_SUFFIX length $full > $MAX_PACKAGE_LENGTH
Truth table66%2/3
A or B
A= length $joined > $MAX_PACKAGE_SUFFIXB= length $full > $MAX_PACKAGE_LENGTH
ABresult
1X1
011
000
88 16 $joined = $kind . '_' . substr(sha1_hex($path), 0, 10);
89 16 $full = $self->base . '::' . $joined;
90 }
91 347 return $full;
92 }
93  
94  
95 35 ▶sub render {
Subroutine render: called CC=5 SCAR=16.1
Pod documented
96 35 my ($self, $root) = @_;
97 35 $self->{_root} = $root; # kept after render() so package_for() stays usable
98 35 my %files;
99 my %functional;
100 35 my %origins;
101 35 my @todo = ($root);
102 35 my %seen;
103 35 ▶ while (my $class = shift @todo) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $class = shift @todo) 114 33 147
104 114 ▶ next if $seen{$class}++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen{$class}++ 0 114 114
105 114 my ($source, @nested) = $self->_render_class($class);
106 114 my $functional = $self->_functional_source($source);
107 114 (my $path = $self->package_for($class)) =~ s{::}{/}g;
108 114 $path .= '.pm';
109 114 ▶ if (exists $files{$path}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $files{$path}) 4 110 114
110 croak 'IO::K8s::CRD::Emitter: target ' . $path
111 . ' has non-identical generated classes ' . $origins{$path}
112 . ' and ' . $class
113 4 ▶ if $functional{$path} ne $functional;
Branch: 1 branch
BranchTrueFalseTotal
if $functional{$path} ne $functional 2 2 4
114 }
115 # Deliberately retain the last equivalent source, matching the
116 # overwrite selection render() made before collision detection.
117 112 $files{$path} = $source;
118 112 $functional{$path} = $functional;
119 112 $origins{$path} = $class;
120 112 push @todo, @nested;
121 }
122 33 return \%files;
123 }
124  
125 # The collision identity is the generated class's executable declaration
126 # surface. Contextual # ABSTRACT and POD text describe the same wire class
127 # differently across upstream GVKs; they must not turn that alias into a
128 # rejected collision. `use utf8` is equally documentation-only when no
129 # remaining executable source needs it, because _render_class adds it for
130 # non-ASCII POD too.
131 138 ▶sub _functional_source {
Subroutine _functional_source: called CC=2 SCAR=7.0
132 138 my ($self, $source) = @_;
133 138 (my $functional = $source) =~ s/\n\n(?:=encoding UTF-8\n\n=cut\n\n)?=attr\b.*\z//s;
134 138 $functional =~ s/^# ABSTRACT:.*\n//m;
135 138 my $without_utf8 = $functional;
136 138 $without_utf8 =~ s/^use utf8;\n//m;
137 138 ▶ $functional = $without_utf8 unless $without_utf8 =~ /[^\x00-\x7F]/;
Branch: 1 branch
BranchTrueFalseTotal
unless $without_utf8 =~ /[^\x00-\x7F]/ 138 0 138
138 138 return $functional;
139 }
140  
141 # A generated class is one this emitter renders; anything else is stock.
142 # IO::K8s::AutoGen::class_root is authoritative when it knows the class --
143 # it is exactly the bookkeeping _nested_class itself relies on, so it is
144 # never fooled by a name merely looking related. Fall back to the string
145 # prefix test for anything AutoGen has no record of (a stock class, or a
146 # class from a namespace this emitter never generated) -- a plain
147 # index()==0 test on its own would also match a sibling whose name merely
148 # starts with the same string -- root ...::V1::Knob would wrongly claim
149 # ...::V1::KnobExtra as its own -- so the fallback still requires the '::'
150 # boundary (or an exact match on the root itself).
151 340 ▶sub _is_generated {
Subroutine _is_generated: called CC=3 SCAR=11.3
152 340 my ($self, $class) = @_;
153 340 my $root = $self->{_root};
154 340 ▶ return 1 if IO::K8s::AutoGen::class_root($class) eq $root;
Branch: 1 branch
BranchTrueFalseTotal
if IO::K8s::AutoGen::class_root($class) eq $root 322 18 340
155 18 ▶ return $class eq $root || index($class, "$root\::") == 0;
Condition33%1/3
$class eq $root || index($class, "${root}::") == 0
l!l&&r!l&&!r
0018
MC/DC0%0/2
$class eq $root || index($class, "${root}::") == 0
$class eq $root index($class, "${root}::") == 0
Truth table33%1/3
A || B
A= $class eq $rootB= index($class, "${root}::") == 0
ABresult
1X1
011
000
156 }
157  
158 # k120: a generated class an overlay `names` entry redirects to an ABSOLUTE
159 # package outside this render's own `base` -- a cross-version reference to a
160 # type another version directory already ships. It is still referenced
161 # (_class_ref emits '+<that package>' via package_for, exactly as a
162 # hand-written class writes it), but this render neither recurses into it nor
163 # writes a file for it: the version directory that owns the target renders it.
164 # A normal generated class resolves under `base::...` and is not external.
165 168 ▶sub _is_external_ref {
Subroutine _is_external_ref: called CC=2 SCAR=6.9
166 168 my ($self, $class) = @_;
167 168 ▶ return 0 unless $self->_is_generated($class);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_is_generated($class) 6 162 168
168 162 return index($self->package_for($class), $self->base . '::') != 0;
169 }
170  
171 # The full package name of a registry class, for the one DSL form that takes
172 # it unexpanded: HashRef[ArrayRef[InstanceOf['...']]] (k194).
173 0 ▶sub _full_class {
Subroutine _full_class: not called CC=2 SCAR=17.9
174 0 my ($self, $class) = @_;
175 0 ▶ return $self->_is_generated($class) ? $self->package_for($class) : $class;
Branch: 1 branch
BranchTrueFalseTotal
$self->_is_generated($class) ? : 0 0 0
176 }
177  
178 87 ▶sub _class_ref {
Subroutine _class_ref: called CC=7 SCAR=19.8
179 87 my ($self, $class) = @_;
180  
181 # k120: an overlay redirect to an absolute package outside this render
182 # (a cross-version provider type, or a core class the reuse heuristic
183 # would not pick on its own -- a single-key {name} that stays
184 # Core::V1::LocalObjectReference). Reference the TARGET package exactly
185 # as a hand-written class does: a core/apimachinery type by its short
186 # prefix (Core::V1::X, Meta::V1::X), any other package -- a cross-version
187 # provider type -- kept in the full '+IO::K8s::...' form. class_prefixes()
188 # also carries provider prefixes (for the DSL's own expansion), so
189 # restricting the shortening to the core groups here is what keeps a
190 # provider cross-ref from collapsing to 'ExternalSecrets::V1::X' where
191 # lib writes '+IO::K8s::ExternalSecrets::V1::X'.
192 87 ▶ if ($self->_is_external_ref($class)) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->_is_external_ref($class)) { } 2 85 87
elsif ($self->_is_generated($class)) { } 79 6 85
193 2 my $target = $self->package_for($class);
194 2 ▶ return "'+$target'" unless $target =~ /^IO::K8s::(?:Api|Apimachinery)::/;
Branch: 1 branch
BranchTrueFalseTotal
unless $target =~ /^IO::K8s::(?:Api|Apimachinery)::/ 1 1 2
195 1 $class = $target;
196 }
197 elsif ($self->_is_generated($class)) {
198 79 return "'+" . $self->package_for($class) . "'";
199 }
200  
201 # IO::K8s::Resource::class_prefixes(), longest full namespace first --
202 # see _build__prefix_pairs.
203 7 for my $pair (@{ $self->_prefix_pairs }) {
204 85 my ($short, $full) = @$pair;
205 85 ▶ next unless index($class, "$full\::") == 0;
Branch: 1 branch
BranchTrueFalseTotal
unless index($class, "${full}::") == 0 78 7 85
206 7 return "'$short\::" . substr($class, length($full) + 2) . "'";
207 }
208  
209 # class_prefixes() only carries the groups with their own entry
210 # (Core, Apps, Meta, ...); a shipped IO::K8s::Api::<X> subgroup with no
211 # entry of its own (e.g. Apiserverinternal) still renders the short way
212 # a hand-written class under it would, by dropping just the common
213 # IO::K8s::Api:: prefix -- the same fallback the old @SHORT_PREFIXES
214 # catch-all gave it.
215 0 ▶ return "'" . substr($class, length('IO::K8s::Api::')) . "'"
Branch: 1 branch
BranchTrueFalseTotal
if index($class, "IO::K8s::Api::") == 0 0 0 0
216 if index($class, 'IO::K8s::Api::') == 0;
217  
218 0 return "'+$class'";
219 }
220  
221 # The apimachinery Quantity pattern carried by the affected CRD schemas.
222 # It is an exact wire contract, so a merely similar pattern must not select
223 # Quantity during rendering.
224 15 my $CANONICAL_QUANTITY_PATTERN = q{^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$};
225  
226 # `u` is the implicit UTF-8 artifact and `p` does not affect matching, the
227 # same two flags _pattern_literal ignores. Every other flag changes the
228 # contract and keeps the field as IntOrStr.
229 12 ▶sub _is_canonical_quantity_pattern {
Subroutine _is_canonical_quantity_pattern: called CC=6 SCAR=19.6
230 12 my ($value) = @_;
231 12 ▶ return defined($value) && $value eq $CANONICAL_QUANTITY_PATTERN unless ref $value;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value 0 12 12
Condition0%0/3
defined $value && $value eq $CANONICAL_QUANTITY_PATTERN
!ll&&!rl&&r
000
MC/DC0%0/2
defined $value && $value eq $CANONICAL_QUANTITY_PATTERN
defined $value $value eq $CANONICAL_QUANTITY_PATTERN
Truth table0%0/3
A && B
A= defined $valueB= $value eq $CANONICAL_QUANTITY_PATTERN
ABresult
0X0
100
111
232 12 ▶ return 0 unless ref $value eq 'Regexp';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value eq "Regexp" 0 12 12
233  
234 12 my ($pattern, $flags) = re::regexp_pattern($value);
235 12 ▶ $flags = '' unless defined $flags;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $flags 0 12 12
236 12 $flags =~ s/[up]//g;
237 12 ▶ return $pattern eq $CANONICAL_QUANTITY_PATTERN && !length $flags;
Condition100%3/3
$pattern eq $CANONICAL_QUANTITY_PATTERN && !length($flags)
!ll&&!rl&&r
426
MC/DC100%2/2
$pattern eq $CANONICAL_QUANTITY_PATTERN && !length($flags)
$pattern eq $CANONICAL_QUANTITY_PATTERN !length($flags)
Truth table100%3/3
A && not(B)
A= $pattern eq $CANONICAL_QUANTITY_PATTERNB= !length($flags)
ABresult
0X0
100
111
238 }
239  
240 184 ▶sub _is_quantity_entry {
Subroutine _is_quantity_entry: called CC=4 SCAR=13.9
241 184 my ($info) = @_;
242 184 ▶ return unless $info->{is_int_or_string};
Branch: 1 branch
BranchTrueFalseTotal
unless $info->{"is_int_or_string"} 164 20 184
243 20 my $opts = $info->{options};
244 20 ▶ return unless $opts && exists $opts->{pattern};
Branch: 1 branch
BranchTrueFalseTotal
unless $opts and exists $opts->{"pattern"} 8 12 20
Condition100%3/3
$opts and exists $opts->{"pattern"}
!ll&&!rl&&r
6212
MC/DC100%2/2
$opts and exists $opts->{"pattern"}
$opts exists $opts->{"pattern"}
Truth table100%3/3
A and B
A= $optsB= exists $opts->{"pattern"}
ABresult
0X0
100
111
245 12 return _is_canonical_quantity_pattern($opts->{pattern});
246 }
247  
248 # The DSL type spec for one registry entry, as source. Returns
249 # ($source, $nested_class_or_undef). $class/$key are diagnostic context
250 # only, for the croak below -- the caller already has both.
251 174 ▶sub _type_source {
Subroutine _type_source: called CC=36 SCAR=38.6
252 174 my ($self, $info, $class, $key) = @_;
253 my $nested = $info->{class} && $self->_is_generated($info->{class})
254 174 ▶ && !$self->_is_external_ref($info->{class}) ? $info->{class} : undef;
Branch: 1 branch
BranchTrueFalseTotal
$info->{'class'} && $self->_is_generated($info->{'class'}) && !$self->_is_external_ref($info->{'class'}) ? : 79 95 174
Condition100%6/6
$info->{"class"} and $self->_is_generated($info->{"class"}) and not $self->_is_external_ref($info->{"class"})
!ll&&!rl&&r
93279
$info->{"class"} and $self->_is_generated($info->{"class"})
!ll&&!rl&&r
87681
MC/DC100%3/3
$info->{"class"} and $self->_is_generated($info->{"class"}) and not $self->_is_external_ref($info->{"class"})
$info->{"class"} $self->_is_generated($info->{"class"}) not $self->_is_external_ref($info->{"class"})
Truth table100%4/4
A and B and not(C)
A= $info->{"class"}B= $self->_is_generated($info->{"class"})C= not $self->_is_external_ref($info->{"class"})
ABCresult
0XX0
10X0
1100
1111
255 174 ▶ return ($self->_class_ref($info->{class}), $nested) if $info->{is_object};
Branch: 1 branch
BranchTrueFalseTotal
if $info->{"is_object"} 83 91 174
256 91 ▶ return ('[' . $self->_class_ref($info->{class}) . ']', $nested) if $info->{is_array_of_objects};
Branch: 1 branch
BranchTrueFalseTotal
if $info->{"is_array_of_objects"} 4 87 91
257 87 ▶ return ('{ ' . $self->_class_ref($info->{class}) . ' => 1 }', $nested) if $info->{is_hash_of_objects};
Branch: 1 branch
BranchTrueFalseTotal
if $info->{"is_hash_of_objects"} 0 87 87
258 87 ▶ return ('HashRef[ArrayRef[Str]]') if $info->{is_hash_of_str_arrays};
Branch: 1 branch
BranchTrueFalseTotal
if $info->{"is_hash_of_str_arrays"} 0 87 87
259 return ("HashRef[ArrayRef[InstanceOf['" . $self->_full_class($info->{class}) . "']]]", $nested)
260 87 ▶ if $info->{is_hash_of_object_arrays};
Branch: 1 branch
BranchTrueFalseTotal
if $info->{"is_hash_of_object_arrays"} 0 87 87
261 87 ▶ return ('[Str]') if $info->{is_array_of_str};
Branch: 1 branch
BranchTrueFalseTotal
if $info->{"is_array_of_str"} 0 87 87
262 87 ▶ return ('[Int]') if $info->{is_array_of_int};
Branch: 1 branch
BranchTrueFalseTotal
if $info->{"is_array_of_int"} 0 87 87
263 87 ▶ return ('[Bool]') if $info->{is_array_of_bool};
Branch: 1 branch
BranchTrueFalseTotal
if $info->{"is_array_of_bool"} 0 87 87
264 87 ▶ return ('[Num]') if $info->{is_array_of_num};
Branch: 1 branch
BranchTrueFalseTotal
if $info->{"is_array_of_num"} 2 85 87
265 85 ▶ return ('[IntOrStr]') if $info->{is_array_of_int_or_string};
Branch: 1 branch
BranchTrueFalseTotal
if $info->{"is_array_of_int_or_string"} 2 83 85
266 83 ▶ return ('[Quantity]') if $info->{is_array_of_quantity};
Branch: 1 branch
BranchTrueFalseTotal
if $info->{"is_array_of_quantity"} 1 82 83
267 82 ▶ return ('[Time]') if $info->{is_array_of_time};
Branch: 1 branch
BranchTrueFalseTotal
if $info->{"is_array_of_time"} 2 80 82
268 80 ▶ return ('[ {} ]') if $info->{is_array_of_hash};
Branch: 1 branch
BranchTrueFalseTotal
if $info->{"is_array_of_hash"} 0 80 80
269 80 ▶ return ('[ [] ]') if $info->{is_array_of_array};
Branch: 1 branch
BranchTrueFalseTotal
if $info->{"is_array_of_array"} 0 80 80
270 # The string map in the spelling that reads back as itself (k191): the
271 # lenient legacy form only where the registry says lenient, a strict
272 # one -- AutoGen's additionalProperties {type: string} -- as
273 # HashRef[Str]. The free map is Opaque.
274 80 ▶ return ('{ Str => 1 }') if $info->{is_hash_of_str} && $info->{is_hash_of_str_lenient};
Branch: 1 branch
BranchTrueFalseTotal
if $info->{"is_hash_of_str"} and $info->{"is_hash_of_str_lenient"} 1 79 80
Condition100%3/3
$info->{"is_hash_of_str"} and $info->{"is_hash_of_str_lenient"}
!ll&&!rl&&r
7811
MC/DC100%2/2
$info->{"is_hash_of_str"} and $info->{"is_hash_of_str_lenient"}
$info->{"is_hash_of_str"} $info->{"is_hash_of_str_lenient"}
Truth table100%3/3
A and B
A= $info->{"is_hash_of_str"}B= $info->{"is_hash_of_str_lenient"}
ABresult
0X0
100
111
275 79 ▶ return ('HashRef[Str]') if $info->{is_hash_of_str};
Branch: 1 branch
BranchTrueFalseTotal
if $info->{"is_hash_of_str"} 1 78 79
276 78 ▶ return ('Opaque') if $info->{is_hash_opaque};
Branch: 1 branch
BranchTrueFalseTotal
if $info->{"is_hash_opaque"} 4 74 78
277 74 ▶ return ('HashRef[Int]') if $info->{is_hash_of_int};
Branch: 1 branch
BranchTrueFalseTotal
if $info->{"is_hash_of_int"} 1 73 74
278 73 ▶ return ('HashRef[Num]') if $info->{is_hash_of_num};
Branch: 1 branch
BranchTrueFalseTotal
if $info->{"is_hash_of_num"} 0 73 73
279 73 ▶ return ('HashRef[Bool]') if $info->{is_hash_of_bool};
Branch: 1 branch
BranchTrueFalseTotal
if $info->{"is_hash_of_bool"} 0 73 73
280 73 ▶ return ('HashRef[Quantity]') if $info->{is_hash_of_quantity};
Branch: 1 branch
BranchTrueFalseTotal
if $info->{"is_hash_of_quantity"} 0 73 73
281 73 ▶ return ('HashRef[Time]') if $info->{is_hash_of_time};
Branch: 1 branch
BranchTrueFalseTotal
if $info->{"is_hash_of_time"} 0 73 73
282 73 ▶ return ('HashRef[IntOrStr]') if $info->{is_hash_of_int_or_string};
Branch: 1 branch
BranchTrueFalseTotal
if $info->{"is_hash_of_int_or_string"} 0 73 73
283 73 ▶ return ('Str') if $info->{is_str};
Branch: 1 branch
BranchTrueFalseTotal
if $info->{"is_str"} 42 31 73
284 31 ▶ return ('Int') if $info->{is_int};
Branch: 1 branch
BranchTrueFalseTotal
if $info->{"is_int"} 18 13 31
285 13 ▶ return ('Num') if $info->{is_num};
Branch: 1 branch
BranchTrueFalseTotal
if $info->{"is_num"} 0 13 13
286 13 ▶ return ('Bool') if $info->{is_bool};
Branch: 1 branch
BranchTrueFalseTotal
if $info->{"is_bool"} 3 10 13
287 10 ▶ return ('Quantity') if _is_quantity_entry($info);
Branch: 1 branch
BranchTrueFalseTotal
if _is_quantity_entry($info) 3 7 10
288 7 ▶ return ('IntOrStr') if $info->{is_int_or_string};
Branch: 1 branch
BranchTrueFalseTotal
if $info->{"is_int_or_string"} 7 0 7
289 0 ▶ return ('Quantity') if $info->{is_quantity};
Branch: 1 branch
BranchTrueFalseTotal
if $info->{"is_quantity"} 0 0 0
290 0 ▶ return ('Time') if $info->{is_time};
Branch: 1 branch
BranchTrueFalseTotal
if $info->{"is_time"} 0 0 0
291 0 croak "IO::K8s::CRD::Emitter: registry entry with no recognizable type for field '$key' of $class";
292 }
293  
294 # A pattern string re-quoted into `qr/.../ ` source is interpolated by Perl
295 # just like a double-quoted string: an unescaped '@' tries to interpolate an
296 # array -- '^[a-z]+@example\.com$' would die "Global symbol '@example'
297 # requires explicit package name" at compile time -- and an unescaped '$'
298 # not already meaning "end of string/group/alternative" tries to
299 # interpolate a scalar. '@' is always escaped, unconditionally: '\@' means
300 # a literal '@' in a regex no matter what follows it, so escaping it can
301 # never change what the pattern matches, and it is the only way to rule out
302 # every '@'-led interpolation form at once -- '@name', '@{...}', and
303 # '@$name'/'@$' (an array deref through a scalar, including the
304 # punctuation variable $) or $| that '@$' immediately before a bare ')' or
305 # '|' would reach for). A narrower rule that only escaped '@' before a word
306 # character or '{' missed exactly that last form: '(a@$)' left both the
307 # '@' (not followed by \w/{) and the '$' (immediately before ')') bare,
308 # and '@$)' interpolated away to nothing, silently turning the pattern
309 # into '(a)'. '$' cannot be escaped unconditionally the same way -- unlike
310 # '@', a bare '$' is meaningful in a regex (the end-of-string/line anchor),
311 # so it is only escaped when it is NOT in one of the anchor positions
312 # ("...$", "(...$)", "...$|...") a schema pattern realistically uses;
313 # escaping it there would turn the anchor into a literal '$' character
314 # instead of leaving it as an anchor -- wrong regex, not just wrong Perl.
315 # Walks the pattern one (possibly backslash-escaped) unit at a time so an
316 # already-escaped character -- notably a pattern that came in as
317 # '\/api\/v1' -- is left exactly as it was instead of gaining a second
318 # backslash.
319 #
320 # Since k114 only the '/' branch normally reaches a rendered file: an escape
321 # this adds that Perl would still be carrying in the compiled pattern makes
322 # _pattern_literal reject the qr// form altogether and emit a plain string
323 # instead, so the '@'/'$'/non-ASCII branches now mostly serve the round-trip
324 # probe that decides that. They are not dead either way -- a '@' left bare
325 # would interpolate the candidate away and the probe would then compare
326 # against a different pattern, which is the same bug one step earlier.
327 606 ▶sub _escape_pattern_body {
Subroutine _escape_pattern_body: called CC=9 SCAR=22.0
328 606 my ($pattern) = @_;
329 606 my $out = '';
330 606 ▶ while ($pattern =~ /\G(?:(\\.)|(.))/gs) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pattern =~ /\G(?:(\\.)|(.))/gs) 54702 606 55308
331 54702 ▶ if (defined $1) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $1) 1435 53267 54702
332 1435 $out .= $1;
333 1435 next;
334 }
335 53267 my $c = $2;
336 53267 ▶ if ($c eq '/') {
Branch: 4 branches
BranchTrueFalseTotal
if ($c eq '/') { } 214 53053 53267
elsif ($c eq '@') { } 5 53048 53053
elsif ($c eq '$') { } 679 52369 53048
elsif (ord $c > 127) { } 2 52367 52369
337 214 $out .= '\\/';
338 }
339 elsif ($c eq '@') {
340 5 $out .= '\\@';
341 }
342 elsif ($c eq '$') {
343 679 my $rest = substr($pattern, pos($pattern));
344 679 ▶ $out .= ($rest eq '' || $rest =~ /\A[)|]/) ? '$' : '\\$';
Branch: 1 branch
BranchTrueFalseTotal
$rest eq '' || $rest =~ /\A[)|]/ ? : 678 1 679
Condition100%3/3
$rest eq "" or $rest =~ /\A[)|]/
l!l&&r!l&&!r
581971
MC/DC100%2/2
$rest eq "" or $rest =~ /\A[)|]/
$rest eq "" $rest =~ /\A[)|]/
Truth table100%3/3
A or B
A= $rest eq ""B= $rest =~ /\A[)|]/
ABresult
1X1
011
000
345 }
346 elsif (ord($c) > 0x7F) {
347 # A codepoint above ASCII, interpolated raw into 'qr/.../ ',
348 # only round-trips through this emitted .pm file when it is
349 # BOTH saved to disk as UTF-8 bytes AND compiled under 'use
350 # utf8' -- neither of which this method controls once the
351 # caller has the rendered source in hand. \x{HEX} means the
352 # same codepoint either way: a schema pattern like
353 # '^[0-9]+\x{b5}s$' matches '100\x{b5}s' (100, MICRO SIGN, s)
354 # exactly like the generated class does, independent of that
355 # pragma. See render()'s own use-utf8/=encoding decision for
356 # the one place non-ASCII text still goes into the file
357 # unescaped: a schema's free-form 'description', in POD.
358 2 $out .= sprintf('\x{%x}', ord($c));
359 }
360 else {
361 52367 $out .= $c;
362 }
363 }
364 606 return $out;
365 }
366  
367 # A double-quoted Perl string literal that stays ASCII-only regardless of
368 # what $str holds: '\', '"', '$' and '@' are escaped so the double-quoted
369 # form -- unlike Data::Dumper's default single-quoted style, this one DOES
370 # interpolate -- carries nothing but the literal value, and every character
371 # above ASCII becomes \x{HEX}, the same escape and the same reason as
372 # _escape_pattern_body above. Single-quoted Perl strings cannot carry a
373 # \x{...} escape at all (only \\ and \' mean anything inside them), which is
374 # why a value that needs this can't just be tacked onto Data::Dumper's
375 # normal single-quoted output.
376 19 ▶sub _quote_utf8_string {
Subroutine _quote_utf8_string: called CC=2 SCAR=6.9
377 19 my ($str) = @_;
378 19 (my $escaped = $str) =~ s{ ([\\"\$\@]) | ([^\x00-\x7F]) }{
379 37 ▶ defined $1 ? "\\$1" : sprintf('\x{%x}', ord($2))
Branch: 1 branch
BranchTrueFalseTotal
defined $1 ? : 18 19 37
380 }gex;
381 19 return qq{"$escaped"};
382 }
383  
384 # One scalar option value (an enum member, or `default`), rendered via
385 # Data::Dumper's own single-quoted style for anything ASCII -- byte-for-byte
386 # what every rendered file already produced -- or, for anything that is
387 # not, via _quote_utf8_string above.
388 101 ▶sub _scalar_literal {
Subroutine _scalar_literal: called CC=4 SCAR=14.1
389 101 my ($value) = @_;
390 101 ▶ return _quote_utf8_string($value)
Branch: 1 branch
BranchTrueFalseTotal
if not ref $value and defined $value and $value =~ /[^\x00-\x7F]/ 19 82 101
Condition50%3/6
not ref $value and defined $value and $value =~ /[^\x00-\x7F]/
!ll&&!rl&&r
08219
not ref $value and defined $value
!ll&&!rl&&r
00101
MC/DC33%1/3
not ref $value and defined $value and $value =~ /[^\x00-\x7F]/
not ref $value defined $value $value =~ /[^\x00-\x7F]/
Truth table50%2/4
not(A) and B and C
A= not ref $valueB= defined $valueC= $value =~ /[^\x00-\x7F]/
ABCresult
0XX0
10X0
1100
1111
391 if !ref($value) && defined($value) && $value =~ /[^\x00-\x7F]/;
392 82 local $Data::Dumper::Terse = 1;
393 82 local $Data::Dumper::Indent = 0;
394 82 local $Data::Dumper::Sortkeys = 1;
395 82 local $Data::Dumper::Useqq = 0;
396 82 my $dumped = Data::Dumper::Dumper($value);
397 82 $dumped =~ s/^\s+|\s+$//g;
398 82 return $dumped;
399 }
400  
401 # A Perl literal for an option value. A Regexp is rendered as qr/.../, read
402 # back out via re::regexp_pattern in LIST context -- the scalar-context form
403 # returns the whole "(?^:PATTERN)" wrapper, which is not what a hand-written
404 # `k8s x => Str, { pattern => qr/.../ };` line looks like anywhere else in
405 # this distribution. 'u' is dropped from the flags before they are appended:
406 # every pattern IO::K8s::CRD compiles starts life as a UTF8-flagged string
407 # out of YAML::PP, and interpolating one into qr/$p/ tags the result with an
408 # implicit 'u' that reflects nothing the CRD schema's `pattern` asked for --
409 # rendering it back would forge a modifier into the source. A real modifier
410 # a pattern did ask for (i, m, s, x) still comes through.
411 378 ▶sub _literal {
Subroutine _literal: called CC=10 SCAR=23.5
412 378 my ($value) = @_;
413 378 ▶ if (ref $value eq 'Regexp') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $value eq "Regexp") 298 80 378
414 298 my ($pattern, $flags) = re::regexp_pattern($value);
415 298 my $body = _escape_pattern_body($pattern);
416 298 ▶ $flags =~ s/u//g if defined $flags;
Branch: 1 branch
BranchTrueFalseTotal
if defined $flags 298 0 298
417 298 ▶ return "qr/$body/" . ($flags // '');
Condition50%1/2
$flags // ""
l!l
2980
MC/DC0%0/1
$flags // ""
$flags
Truth table50%1/2
A
A= $flags
Aresult
11
00
418 }
419 80 ▶ if (ref $value eq 'ARRAY' && @$value) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $value eq "ARRAY" and @$value) 5 75 80
Condition66%2/3
ref $value eq "ARRAY" and @$value
!ll&&!rl&&r
7505
MC/DC50%1/2
ref $value eq "ARRAY" and @$value
ref $value eq "ARRAY" @$value
Truth table66%2/3
A and B
A= ref $value eq "ARRAY"B= @$value
ABresult
0X0
100
111
420 # The qw() shorthand only for a list of genuinely bareword-safe
421 # values (D6-friendly enum members like Always/IfNotPresent): word
422 # characters, dots, colons, dashes and slashes -- ASCII only, never
423 # empty. An enum entry that is the empty string -- a real, if
424 # unusual, upstream value -- would otherwise vanish: 'qw( Always
425 # IfNotPresent)' from ('', 'Always', 'IfNotPresent') silently drops
426 # the '', and the emitted class would then reject a value the
427 # generated one accepts. A non-ASCII entry is excluded the same
428 # way even though Perl's \w matches a Unicode letter like 'µ' when
429 # the string carries the UTF8 flag (as one loaded from a CRD
430 # manifest does) -- qw() has no escape syntax at all, so a raw
431 # non-ASCII byte inside it would be exactly the bug this emitter
432 # exists to avoid.
433 5 ▶ my $qw_safe = !grep { ref $_ || !defined $_ || $_ !~ /\A[\w.:\/-]+\z/ || $_ =~ /[^\x00-\x7F]/ } @$value;
Condition66%6/9
ref $_ || !defined($_) || !($_ =~ m[\A[\w.:/-]+\z]) || $_ =~ /[^\x00-\x7F]/
l!l&&r!l&&!r
119
ref $_ or not defined $_ or not $_ =~ m[\A[\w.:/-]+\z]
l!l&&r!l&&!r
0110
ref $_ or not defined $_
l!l&&r!l&&!r
0011
MC/DC50%2/4
ref $_ || !defined($_) || !($_ =~ m[\A[\w.:/-]+\z]) || $_ =~ /[^\x00-\x7F]/
ref $_ not defined $_ not $_ =~ m[\A[\w.:/-]+\z] $_ =~ /[^\x00-\x7F]/
Truth table60%3/5
A or not(B) or not(C) || D
A= ref $_B= not defined $_C= not $_ =~ m[\A[\w.:/-]+\z]D= $_ =~ /[^\x00-\x7F]/
ABCDresult
1XXX1
01XX1
001X1
00011
00000
434 5 ▶ return '[qw(' . join(' ', @$value) . ')]' if $qw_safe;
Branch: 1 branch
BranchTrueFalseTotal
if $qw_safe 3 2 5
435 # Not qw()-safe: render element by element rather than handing the
436 # whole arrayref to Data::Dumper, so a non-ASCII element can switch
437 # to the double-quoted \x{HEX} form on its own while its ASCII
438 # siblings keep Dumper's ordinary single-quoted style -- Dumper has
439 # no way to quote just one element of a list differently.
440 2 return '[' . join(',', map { _scalar_literal($_) } @$value) . ']';
441 }
442 75 return _scalar_literal($value);
443 }
444  
445 # A `pattern` option specifically (k110, k114). Everything else still goes
446 # through _literal above.
447 #
448 # The qr/.../ form stays the default: it is what every hand-written class in
449 # this distribution writes, and IO::K8s::CRD translates one back into the
450 # ECMA262 text a CRD's openAPIV3Schema.pattern is specified in.
451 #
452 # What it cannot translate is a regex FLAG. A CRD pattern is a bare string
453 # with nowhere to carry one, so IO::K8s::CRD croaks on a flagged qr// rather
454 # than dropping the flag and emitting a pattern that means something else.
455 # Rendering `qr/.../i` would therefore hand the caller a class that compiles,
456 # validates correctly in Perl, and then cannot be turned back into a CRD --
457 # which is how IO::K8s::PrometheusOperator::V1::RuleGroup came to carry one
458 # (upstream's own `^(?i)(abort|warn)?$` picked up an 'i' flag on the way
459 # through AutoGen's qr/$p/, and this method wrote it back out).
460 #
461 # So a flagged pattern is folded back into the pattern TEXT as an inline
462 # (?flags) group -- the spelling upstream uses anyway, and one Go's regexp
463 # engine takes -- and rendered as a plain string. That is the escape hatch
464 # IO::K8s::CRD passes through untouched: whatever upstream put in its CRD
465 # goes back out unchanged, because upstream knows what its apiserver
466 # accepts. Perl-side validation is unaffected either way -- Resource.pm
467 # compiles a string pattern with qr/$p/, and an inline (?i) sets exactly
468 # what the /i modifier set.
469 #
470 # The other thing a qr// cannot always carry is the pattern's own BYTES
471 # (k114). Rendering one means writing the text back as `qr/.../` SOURCE, and
472 # _escape_pattern_body has to escape whatever Perl would otherwise
473 # interpolate -- an '@', a '$' that is not in an anchor position -- and to
474 # spell a non-ASCII codepoint as \x{HEX} so the file needs no `use utf8`.
475 # Perl keeps those backslashes in the compiled pattern: only the delimiter's
476 # own '\/' is stripped again by the tokenizer. So they survive into the
477 # registry and out through IO::K8s::CRD, and upstream's
478 # '^.*@.*\.iam\.gserviceaccount\.com$' goes back to a cluster as
479 # '^.*\@.*...', Traefik's '^([0-9]+(ns|us|µs|ms|s|m|h)?)+$' as
480 # '...\x{b5}s...'. Neither breaks the Go/RE2 engine the apiserver actually
481 # validates with -- '\@' is not even a valid ECMA262 identity escape and
482 # '\x{...}' is no ECMA262 at all -- but both are IO::K8s' own Perl artifacts
483 # sitting in a text that is supposed to be upstream's, which is the thing
484 # k110 set out to stop rather than a different problem.
485 #
486 # So the qr// form ships only where it is byte-exact: the candidate source is
487 # compiled and its text read back, and a pattern that does not come out
488 # identical takes the same plain-string path a flagged one does. That also
489 # catches the loss in the other direction -- a '\/' upstream wrote itself
490 # ('^\/api\/v1$') passes through _escape_pattern_body untouched, but the
491 # tokenizer then strips that backslash, so the qr// form would hand back
492 # '^/api/v1$', again not the bytes upstream wrote.
493 #
494 # Perl-side validation is unaffected either way: Resource.pm compiles a
495 # string pattern with qr/$p/, where '\@' and '@', '\$' and a '$' inside a
496 # character class, and '\x{b5}' and a literal MICRO SIGN are each the same
497 # regex as the other.
498 358 ▶sub _pattern_literal {
Subroutine _pattern_literal: called CC=5 SCAR=16.1
499 358 my ($value) = @_;
500 358 ▶ return _literal($value) unless ref $value eq 'Regexp';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value eq "Regexp" 44 314 358
501  
502 314 my ($pattern, $flags) = re::regexp_pattern($value);
503 314 ▶ $flags = '' unless defined $flags;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $flags 0 314 314
504 # 'u' for the same reason _literal drops it (an artifact of the
505 # UTF8-flagged string the pattern was compiled from, not something the
506 # schema asked for); 'p' never changes what a pattern matches.
507 314 $flags =~ s/[up]//g;
508 314 ▶ return _scalar_literal(_fold_pattern_flags($pattern, $flags)) if length $flags;
Branch: 1 branch
BranchTrueFalseTotal
if length $flags 6 308 314
509  
510 308 ▶ return _literal($value) if _qr_round_trips($pattern);
Branch: 1 branch
BranchTrueFalseTotal
if _qr_round_trips($pattern) 298 10 308
511 10 return _scalar_literal($pattern);
512 }
513  
514 # Whether `qr/BODY/` -- BODY as _escape_pattern_body renders it, which is
515 # literally the source _literal is about to emit -- compiles back to exactly
516 # $pattern, carrying no flag it was not given.
517 #
518 # Verified by compiling that source, the same discipline _fold_pattern_flags
519 # uses, and here the only faithful one: `qr/$body/` with $body INTERPOLATED
520 # is a different thing from the literal the rendered file carries, because
521 # delimiter unescaping ('\/' -> '/') happens in the tokenizer and never
522 # touches an interpolated string. A candidate that will not compile at all
523 # (a pattern ending in a lone backslash, say) fails the check too, which is
524 # the right answer: that source would not have compiled in the rendered file
525 # either, and the string form carries it without a delimiter to escape.
526 308 ▶sub _qr_round_trips {
Subroutine _qr_round_trips: called CC=4 SCAR=14.2
527 308 my ($pattern) = @_;
528 308 my $re = eval 'qr/' . _escape_pattern_body($pattern) . '/';
529 308 ▶ return 0 unless ref $re eq 'Regexp';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $re eq "Regexp" 0 308 308
530 308 my ($text, $flags) = re::regexp_pattern($re);
531 308 ▶ $flags = '' unless defined $flags;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $flags 0 308 308
532 308 $flags =~ s/[up]//g;
533 308 ▶ return $text eq $pattern && $flags eq '';
Condition66%2/3
$text eq $pattern && $flags eq ''
!ll&&!rl&&r
100298
MC/DC50%1/2
$text eq $pattern && $flags eq ''
$text eq $pattern $flags eq ''
Truth table66%2/3
A && B
A= $text eq $patternB= $flags eq ''
ABresult
0X0
100
111
534 }
535  
536 # The fold is verified rather than assumed: the candidate text is compiled
537 # and its own (text, flags) read back, so the result only ships when Perl
538 # agrees it carries the same modifiers. Two candidates, in order:
539 #
540 # * the text unchanged -- Perl hoists a leading (?i) INTO the flags while
541 # leaving it in the text, so a pattern upstream already wrote that way
542 # needs no prefix and must not get a duplicate one;
543 # * the text with '(?flags)' prefixed.
544 #
545 # Neither verifying is a croak, not a silent flag drop.
546 7 ▶sub _fold_pattern_flags {
Subroutine _fold_pattern_flags: called CC=6 SCAR=18.0
547 7 my ($pattern, $flags) = @_;
548 7 my $want = join '', sort split //, $flags;
549 7 for my $candidate ($pattern, '(?' . $flags . ')' . $pattern) {
550 11 ▶ my $re = eval { qr/$candidate/ } or next;
Branch: 1 branch
BranchTrueFalseTotal
my $re = eval { do { qr/$candidate/ } } or next 10 1 11
551 10 my ($text, $got) = re::regexp_pattern($re);
552 10 ▶ $got = '' unless defined $got;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $got 0 10 10
553 10 $got =~ s/[up]//g;
554 10 ▶ return $candidate
Branch: 1 branch
BranchTrueFalseTotal
if $text eq $candidate and join("", sort(split(//, $got, 0))) eq $want 6 4 10
Condition66%2/3
$text eq $candidate and join("", sort(split(//, $got, 0))) eq $want
!ll&&!rl&&r
046
MC/DC50%1/2
$text eq $candidate and join("", sort(split(//, $got, 0))) eq $want
$text eq $candidate join("", sort(split(//, $got, 0))) eq $want
Truth table66%2/3
A and B
A= $text eq $candidateB= join("", sort(split(//, $got, 0))) eq $want
ABresult
0X0
100
111
555 if $text eq $candidate && join('', sort split //, $got) eq $want;
556 }
557 1 croak "IO::K8s::CRD::Emitter: the /$flags flags on qr/$pattern/ cannot be"
558 . ' folded into the pattern text, and a CRD pattern has nowhere to'
559 . ' carry a flag';
560 }
561  
562 15 my @OPTION_ORDER = qw( required enum minimum maximum pattern default nullable preserve_unknown );
563  
564 # `required` is rendered as `required => 'schema'`: recorded for the CRD
565 # schema, never enforced at construction -- the same policy AutoGen applies,
566 # because a cluster returns `status: {}` for a fresh object whatever the
567 # status schema requires. A hand-written class that wants enforcement
568 # writes `'required'` itself.
569 174 ▶sub _options_source {
Subroutine _options_source: called CC=6 SCAR=17.9
570 174 my ($info) = @_;
571 174 ▶ my %opts = %{ $info->{options} // {} };
Condition100%2/2
$info->{"options"} // {}
l!l
9678
MC/DC100%1/1
$info->{"options"} // {}
$info->{"options"}
Truth table100%2/2
A
A= $info->{"options"}
Aresult
11
00
572 174 delete $opts{description}; # goes to POD
573 174 ▶ delete $opts{pattern} if _is_quantity_entry($info);
Branch: 1 branch
BranchTrueFalseTotal
if _is_quantity_entry($info) 3 171 174
574 174 ▶ $opts{required} = 'schema' if $info->{required};
Branch: 1 branch
BranchTrueFalseTotal
if $info->{"required"} 9 165 174
575 174 ▶ return '' unless %opts;
Branch: 1 branch
BranchTrueFalseTotal
unless %opts 131 43 174
576 54 ▶ my @parts = map { "$_ => " . ($_ eq 'pattern' ? _pattern_literal($opts{$_}) : _literal($opts{$_})) }
Branch: 1 branch
BranchTrueFalseTotal
$_ eq 'pattern' ? : 18 36 54
577 43 grep { exists $opts{$_} } @OPTION_ORDER;
578 43 return ', { ' . join(', ', @parts) . ' }';
579 }
580  
581 # The class-level ABSTRACT text from a schema's `description`: every run of
582 # whitespace (a multi-line description included -- a literal newline in a
583 # `# ABSTRACT:` comment would not compile) collapsed to one space, then the
584 # first sentence of that (up to the first '. ' or the end), the same way a
585 # hand-written class's # ABSTRACT line is one line, not the whole paragraph.
586 # Returns undef -- never an empty string -- for a missing or whitespace-only
587 # description, so the caller's fallback triggers on truthiness.
588 114 ▶sub _first_sentence {
Subroutine _first_sentence: called CC=4 SCAR=14.0
589 114 my ($text) = @_;
590 114 ▶ return undef unless defined $text;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $text 92 22 114
591 22 (my $flat = $text) =~ s/\s+/ /g;
592 22 $flat =~ s/\A\s+|\s+\z//g;
593 22 ▶ return undef unless length $flat;
Branch: 1 branch
BranchTrueFalseTotal
unless length $flat 0 22 22
594 22 my ($first) = $flat =~ /\A(.*?\.)(?:\s|\z)/;
595 22 ▶ return $first // $flat;
Condition66%2/3
$first // $flat
l!l&&r!l&&!r
2110
MC/DC0%0/2
$first // $flat
$first $flat
Truth table66%2/3
A // B
A= $firstB= $flat
ABresult
1X1
011
000
596 }
597  
598 # A schema's free-form description lands in POD (the =attr block). Guard
599 # against it breaking the surrounding document: a line starting with '='
600 # would open a bogus POD command instead of just being text -- E<61> is the
601 # POD escape for a literal '=' (ASCII 61) -- and a run of blank lines would
602 # split the paragraph into several, an artifact of however the upstream
603 # text happened to be wrapped rather than anything meaningful.
604 174 ▶sub _pod_safe {
Subroutine _pod_safe: called CC=2 SCAR=6.9
605 174 my ($text) = @_;
606 174 ▶ return $text unless defined $text;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $text 128 46 174
607 46 $text =~ s/^[ \t]+$//gm;
608 46 $text =~ s/\n{3,}/\n\n/g;
609 46 $text =~ s/^=/E<61>/gm;
610 46 return $text;
611 }
612  
613 # The value of the subresources import parameter (k158), as source in the
614 # column of the `use IO::K8s::APIObject` parameter it follows. status alone
615 # fits on the line; scale, with its three paths, gets one line per key,
616 # keys sorted and => aligned like the k8s lines, no trailing commas.
617 7 ▶sub _subresources_source {
Subroutine _subresources_source: called CC=4 SCAR=13.9
618 7 my ($subresources) = @_;
619 7 ▶ return '{}' unless %$subresources;
Branch: 1 branch
BranchTrueFalseTotal
unless %$subresources 1 6 7
620 6 ▶ return '{ status => {} }' unless $subresources->{scale};
Branch: 1 branch
BranchTrueFalseTotal
unless $subresources->{"scale"} 4 2 6
621 2 my $scale = $subresources->{scale};
622 2 my ($kw) = sort { $b <=> $a } map { length } keys %$scale;
623 my %value = (
624 scale => "{\n"
625 2 . join(",\n", map { sprintf(' %-*s => %s', $kw, $_, _scalar_literal($scale->{$_})) }
626 sort keys %$scale)
627 . "\n }"
628 );
629 2 ▶ $value{status} = '{}' if exists $subresources->{status};
Branch: 1 branch
BranchTrueFalseTotal
if exists $subresources->{"status"} 1 1 2
630 2 my ($sw) = sort { $b <=> $a } map { length } keys %value;
631 return "{\n"
632 2 . join(",\n", map { sprintf(' %-*s => %s', $sw, $_, $value{$_}) } sort keys %value)
633 . "\n }";
634 }
635  
636 114 ▶sub _render_class {
Subroutine _render_class: called CC=26 SCAR=33.0
637 114 my ($self, $class) = @_;
638 114 my $info = $class->_k8s_attr_info;
639 114 my $attrs = $class->_k8s_attributes;
640 114 ▶ my $is_top = $class->can('_is_resource') ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$class->can('_is_resource') ? : 32 82 114
641 114 my $package = $self->package_for($class);
642  
643 # `metadata` is registered in the generated class's own registry (D10's
644 # AutoGen adds it via the k8s DSL so _inflate_struct knows its type),
645 # but no hand-written top-level class ever declares it explicitly --
646 # `use IO::K8s::APIObject ...;` already does, the same way this
647 # rendered source will. Emitting it again would be a harmless but
648 # un-idiomatic duplicate line no template class carries.
649 114 ▶ my %skip = $is_top ? (metadata => 1) : ();
Branch: 1 branch
BranchTrueFalseTotal
$is_top ? : 32 82 114
650  
651 # The printed field name -- quoted when it is not a bareword-safe Perl
652 # identifier -- is what actually lines up in the source, so the column
653 # width is measured on it, not on the (possibly shorter, unquoted) raw
654 # JSON key.
655 my %name = map {
656 174 ▶ my $key = $info->{$_}{json_key} // $_;
Condition33%1/3
$info->{$_}{"json_key"} // $_
l!l&&r!l&&!r
01740
MC/DC0%0/2
$info->{$_}{"json_key"} // $_
$info->{$_}{"json_key"} $_
Truth table33%1/3
A // B
A= $info->{$_}{"json_key"}B= $_
ABresult
1X1
011
000
657 174 ▶ ($_ => ($key =~ /^[A-Za-z_]\w*$/ ? $key : "'$key'"));
Branch: 1 branch
BranchTrueFalseTotal
$key =~ /^[A-Za-z_]\w*$/ ? : 174 0 174
658 114 } grep { !$skip{$_} } @$attrs;
659  
660 114 my @nested;
661 114 my (@lines, @pod);
662 114 my $width = 0;
663 114 for my $attr (@$attrs) {
664 206 ▶ next if $skip{$attr};
Branch: 1 branch
BranchTrueFalseTotal
if $skip{$attr} 32 174 206
665 174 ▶ $width = length $name{$attr} if length $name{$attr} > $width;
Branch: 1 branch
BranchTrueFalseTotal
if length $name{$attr} > $width 142 32 174
666 }
667 114 for my $attr (@$attrs) {
668 206 ▶ next if $skip{$attr};
Branch: 1 branch
BranchTrueFalseTotal
if $skip{$attr} 32 174 206
669 174 my $i = $info->{$attr};
670 174 ▶ my $key = $i->{json_key} // $attr;
Condition33%1/3
$i->{"json_key"} // $attr
l!l&&r!l&&!r
01740
MC/DC0%0/2
$i->{"json_key"} // $attr
$i->{"json_key"} $attr
Truth table33%1/3
A // B
A= $i->{"json_key"}B= $attr
ABresult
1X1
011
000
671 174 my ($type, $nested) = $self->_type_source($i, $class, $key);
672 174 ▶ push @nested, $nested if $nested;
Branch: 1 branch
BranchTrueFalseTotal
if $nested 79 95 174
673 174 push @lines, sprintf("k8s %-*s => %s%s;", $width, $name{$attr}, $type, _options_source($i));
674 174 ▶ my $desc = _pod_safe($i->{options}{description}) // 'No description in the upstream schema.';
Condition100%2/2
_pod_safe($i->{"options"}{"description"}) // "No description in the upstream schema."
l!l
46128
MC/DC100%1/1
_pod_safe($i->{"options"}{"description"}) // "No description in the upstream schema."
_pod_safe($i->{"options"}{"description"})
Truth table100%2/2
A
A= _pod_safe($i->{"options"}{"description"})
Aresult
11
00
675 174 push @pod, "=attr $key\n\n$desc\n\n=cut\n";
676 }
677  
678 114 ▶ my $abstract = _first_sentence(IO::K8s::AutoGen::class_description($class))
Branch: 1 branch
BranchTrueFalseTotal
$is_top ? : 31 61 92
Condition66%2/3
_first_sentence(IO::K8s::AutoGen::class_description($class)) || ($is_top ? $class->kind : (split(/::/, $package, 0))[-1])
l!l&&r!l&&!r
22920
MC/DC0%0/2
_first_sentence(IO::K8s::AutoGen::class_description($class)) || ($is_top ? $class->kind : (split(/::/, $package, 0))[-1])
_first_sentence(IO::K8s::AutoGen::class_description($class)) ($is_top ? $class->kind : (split(/::/, $package, 0))[-1])
Truth table66%2/3
A || B
A= _first_sentence(IO::K8s::AutoGen::class_description($class))B= ($is_top ? $class->kind : (split(/::/, $package, 0))[-1])
ABresult
1X1
011
000
679 || ($is_top ? $class->kind : (split /::/, $package)[-1]);
680 114 my $header = join "\n",
681 "package $package;",
682 "# ABSTRACT: $abstract",
683 "our \$VERSION = '" . $self->version . "';";
684 114 my $use;
685 114 ▶ if ($is_top) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_top) { } 32 82 114
686 32 my $plural = $class->resource_plural;
687 32 my @params = ([ api_version => "'" . $class->api_version . "'" ]);
688 32 ▶ push @params, [ resource_plural => "'$plural'" ] if defined $plural && length $plural;
Branch: 1 branch
BranchTrueFalseTotal
if defined $plural and length $plural 32 0 32
Condition33%1/3
defined $plural and length $plural
!ll&&!rl&&r
0032
MC/DC0%0/2
defined $plural and length $plural
defined $plural length $plural
Truth table33%1/3
A and B
A= defined $pluralB= length $plural
ABresult
0X0
100
111
689 32 ▶ push @params, [ subresources => _subresources_source($class->subresources) ]
Branch: 1 branch
BranchTrueFalseTotal
if $self->subresources and $class->can("subresources") 7 25 32
Condition100%3/3
$self->subresources and $class->can("subresources")
!ll&&!rl&&r
1247
MC/DC100%2/2
$self->subresources and $class->can("subresources")
$self->subresources $class->can("subresources")
Truth table100%3/3
A and B
A= $self->subresourcesB= $class->can("subresources")
ABresult
0X0
100
111
690 if $self->subresources && $class->can('subresources');
691 32 my @use_lines;
692 32 ▶ if (@params == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@params == 1) { } 0 32 32
693 0 @use_lines = ("use IO::K8s::APIObject $params[0][0] => $params[0][1];");
694 } else {
695 32 my ($width) = sort { $b <=> $a } map { length $_->[0] } @params;
696 @use_lines = ('use IO::K8s::APIObject',
697 32 join(",\n", map { sprintf(' %-*s => %s', $width, @$_) } @params) . ';');
698 }
699  
700 # overlay: with/extra, for the root Kind only. 'with' defaults to
701 # Namespaced when the class composes it and to no roles otherwise
702 # -- an overlay entry (including an explicit empty list) always
703 # wins over that default.
704 32 my $with = $self->overlay->{with};
705 32 ▶ $with = [ $class->does('IO::K8s::Role::Namespaced') ? 'IO::K8s::Role::Namespaced' : () ]
Branch: 2 branches
BranchTrueFalseTotal
unless defined $with 31 1 32
$class->does('IO::K8s::Role::Namespaced') ? : 31 0 31
706 unless defined $with;
707 32 ▶ push @use_lines, "with " . join(', ', map { "'$_'" } @$with) . ';' if @$with;
Branch: 1 branch
BranchTrueFalseTotal
if @$with 32 0 32
708 32 ▶ push @use_lines, @{ $self->overlay->{extra} // [] };
Condition100%2/2
$self->overlay->{"extra"} // []
l!l
131
MC/DC100%1/1
$self->overlay->{"extra"} // []
$self->overlay->{"extra"}
Truth table100%2/2
A
A= $self->overlay->{"extra"}
Aresult
11
00
709  
710 32 $use = join "\n", @use_lines;
711 }
712 else {
713 82 $use = 'use IO::K8s::Resource;';
714 }
715  
716 # Every value that could carry non-ASCII text -- a pattern, an enum
717 # member, a default -- is already rendered ASCII-only above (\x{HEX}
718 # escapes; see _escape_pattern_body / _quote_utf8_string). The one place
719 # non-ASCII text still reaches this file unescaped is a schema's
720 # free-form 'description', left verbatim in POD (the # ABSTRACT comment
721 # above, or an =attr block) by design -- descriptions are documentation,
722 # not data a client-side check runs against, so there is nothing to
723 # protect by mangling them. 'use utf8' and '=encoding UTF-8' are added
724 # together, only when that happens: the former is Perl's own rule for a
725 # literal non-ASCII byte anywhere in a file it compiles (POD included),
726 # the latter is what a POD viewer needs to decode that text correctly.
727 # An all-ASCII file -- the overwhelming majority -- carries neither.
728 114 ▶ if (grep { /[^\x00-\x7F]/ } ($header, $use, @lines, @pod)) {
Branch: 1 branch
BranchTrueFalseTotal
if (grep {/[^\x00-\x7F]/;} $header, $use, @lines, @pod) 3 111 114
729 3 $header .= "\nuse utf8;";
730 3 unshift @pod, "=encoding UTF-8\n\n=cut\n";
731 }
732  
733 114 my $source = join "\n", $header, $use, '', @lines, '', @pod, '1;', '';
734 114 return ($source, @nested);
735 }
736  
737 15 1;
738  
739 __END__
« blib/lib/IO/K8s/Role/APIObject.pm ↑ Summary lib/IO/K8s/Role/Routable.pm »