blib/lib/IO/K8s/AutoGen.pm

filter: Statementstmt 93.5% 624 / 667 Branchbran 80.8% 354 / 438 Conditioncond 65.3% 192 / 294 MC/DCmcdc 41.8% 69 / 165 Subroutinesub 98.5% 69 / 70 Podpod 100% 10 / 10 totaltotal 80.1% 1318 / 1644 CC 350 SCAR 33.6
CC
350
Cov
84%
_field_options
73.0
_schema_to_type_spec
62.1
_object_compatible
49.3
CRAP 28.9
« blib/lib/IO/K8s/Resource.pm ↑ Summary blib/lib/IO/K8s/Role/APIObject.pm »
1 package IO::K8s::AutoGen;
2 # ABSTRACT: Dynamically generate IO::K8s classes from OpenAPI schema
3 148 our $VERSION = '1.110';
4 148 ▶use v5.10;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 148 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 148 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 148 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 148 ▶use Digest::SHA qw( sha1_hex );
Subroutine BEGIN: called CC=1 SCAR=0.0
9 148 ▶use Module::Runtime qw( use_module );
Subroutine BEGIN: called CC=1 SCAR=0.0
10 148 ▶use Package::Stash;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 148 ▶use Scalar::Util qw(blessed reftype refaddr looks_like_number);
Subroutine BEGIN: called CC=1 SCAR=0.0
12 148 ▶use Types::Standard qw( Bool HashRef Int Num Str );
Subroutine BEGIN: called CC=1 SCAR=0.0
13 # Type::Tiny object for the [IntOrStr] array items (k167); see the array
14 # branch of _schema_to_type_spec for why a bareword does not do. [Time]
15 # items go through $GENERATED_TIME instead (k178), so Time is not imported.
16 # Opaque is the free map a schemaless object becomes (k191).
17 148 ▶use IO::K8s::Types qw( IntOrStr Opaque );
Subroutine BEGIN: called CC=1 SCAR=0.0
18 # The empty list matters: IO::K8s::APIObject's import would make this
19 # package a Moo class. Loaded for its subresources check (k158).
20 148 ▶use IO::K8s::APIObject ();
Subroutine BEGIN: called CC=1 SCAR=0.0
21 148 our @CARP_NOT = ('IO::K8s'); # errors via an openapi_spec instance name its caller (k175)
22  
23 # Cache of generated classes -- only classes whose generation run completed
24 # (see "Generation runs" below). generated_classes() lists exactly these.
25 148 my %_generated;
26  
27 # ---------------------------------------------------------------------------
28 # Generation runs (k149)
29 #
30 # A root get_or_generate call is one small transaction, a "run". Every class
31 # first begun during it -- the root, each $ref'd definition generated on the
32 # way, each nested class -- stays pending until the whole run, identity
33 # methods and roles included, has succeeded; only then do they all become
34 # complete together. A class is marked begun early, before its own fields
35 # exist, because a recursive type (A.child => A, A => B => A) must be able to
36 # name it; a pending class is only ever handed back to that same run's
37 # recursion, never as a public cache hit.
38 #
39 # If the run dies, every class it began is recorded as failed, keyed by
40 # class name (so per namespace), with the run's original error -- including
41 # a dependency whose own fields finished cleanly, since it may well point
42 # back at the class that died. Nothing is rolled back: the packages, the Moo
43 # internals and the attribute registry keep whatever the run built. Any
44 # later request that would hand out one of those classes, directly or as a
45 # dependency, rethrows that original error instead. Classes that were
46 # already complete before the run are untouched. The failure record is never
47 # cleared, not even by clear_cache(), which would otherwise revive a
48 # half-built package; a repaired schema is generated into a fresh namespace
49 # (a fresh IO::K8s instance gets one).
50 # ---------------------------------------------------------------------------
51  
52 # class name -> the original error of the run that began it and died
53 my %_failed;
54  
55 # The classes begun by the generation run in progress, as a { $class => 1 }
56 # hashref; undef between runs. Only _in_generation_run sets or clears it.
57 148 my $_run;
58  
59 # Perl's own limit on a fully qualified identifier is 251 characters. A
60 # path-derived nested class name (see _nested_class below) is kept while it
61 # fits under this, lower threshold -- the headroom accounts for a
62 # '::_Spec'-style segment a caller might append to an already-long name, and
63 # for the shortened '::_<hash>' form itself, which must never in turn need
64 # shortening.
65 148 my $MAX_CLASS_NAME = 200;
66  
67 # Class-level schema description, keyed by generated class name. AutoGen
68 # itself never reads this -- it exists for IO::K8s::CRD::Emitter, which has
69 # no other way to recover a schema's `description` once the class is built
70 # (the k8s DSL only records per-field descriptions, not one for the class
71 # as a whole).
72 148 my %_descriptions;
73  
74 # Default namespace for auto-generated classes
75 148 our $DEFAULT_NAMESPACE = 'IO::K8s::_AUTOGEN';
76  
77 # Sanitize one or more strings into safe Perl package-name segments: every
78 # character outside [A-Za-z0-9_] becomes '_', and a segment that would
79 # start with a digit gets a leading '_' (a bareword identifier can't start
80 # with one). Each argument becomes exactly one output segment -- splitting
81 # a def_name or an api_version into segments is the caller's job (see
82 # def_to_class and _class_name_for below); _class_segment passes a whole
83 # JSON key through as a single segment on purpose, since a key containing
84 # '.' or '/' is one field name, not a request for sub-packages.
85 #
86 # A hyphenated API group ('cert-manager.io') is the case this exists for:
87 # left alone, 'acme.cert-manager.io' becomes the package segment
88 # 'cert-manager', which Perl parses as a subtraction ('cert' MINUS
89 # 'manager'), not an identifier -- def_to_class died building the package,
90 # not on anything IO::K8s::CRD did wrong.
91 726 ▶sub _class_segments {
Subroutine _class_segments: called CC=2 SCAR=7.0
92 return map {
93 726 my $s = $_;
94 1455 $s =~ s/[^A-Za-z0-9_]/_/g;
95 1455 ▶ $s = "_$s" if $s =~ /^[0-9]/;
Branch: 1 branch
BranchTrueFalseTotal
if $s =~ /^[0-9]/ 0 1455 1455
96 1455 $s;
97 } @_;
98 }
99  
100 # Convert OpenAPI definition name to Perl class name
101 # With namespace 'MyProject::K8s':
102 # helm.cattle.io.v1.HelmChart -> MyProject::K8s::helm::cattle::io::v1::HelmChart
103 215 ▶sub def_to_class {
Subroutine def_to_class: called CC=2 SCAR=7.0
Pod documented
104 215 my ($def_name, $namespace) = @_;
105 215 ▶ $namespace //= $DEFAULT_NAMESPACE;
Condition66%2/3
$namespace //= $IO::K8s::AutoGen::DEFAULT_NAMESPACE
l!l&&r!l&&!r
21410
MC/DC0%0/2
$namespace //= $IO::K8s::AutoGen::DEFAULT_NAMESPACE
$namespace $IO::K8s::AutoGen::DEFAULT_NAMESPACE
Truth table66%2/3
A //= B
A= $namespaceB= $IO::K8s::AutoGen::DEFAULT_NAMESPACE
ABresult
1X1
011
000
106 215 return join('::', $namespace, _class_segments(split /\./, $def_name));
107 }
108  
109 # Convert Perl class name back to OpenAPI definition name. Lossy on
110 # purpose: def_to_class/_class_segments sanitize each package segment (a
111 # hyphen becomes '_', among other substitutions), and that cannot be
112 # undone here. Used only for diagnostics and to build a nested class's
113 # synthetic def_name (_nested_class) -- never to look a definition back up
114 # in $all_defs.
115 225 ▶sub class_to_def {
Subroutine class_to_def: called CC=1 SCAR=0.0
Pod documented
116 225 my ($class) = @_;
117 # Strip any _AUTOGEN namespace prefix
118 225 $class =~ s/^IO::K8s::_AUTOGEN_[^:]+:://;
119 225 $class =~ s/^IO::K8s::_AUTOGEN:://;
120 225 $class =~ s/::/./g;
121 225 return $class;
122 }
123  
124 # Check if a class was auto-generated
125 8 ▶sub is_autogen {
Subroutine is_autogen: called CC=1 SCAR=0.0
Pod documented
126 8 my ($class) = @_;
127 8 return $class =~ /^IO::K8s::_AUTOGEN/;
128 }
129  
130 # Get or generate a class from schema
131 # Options hash can include:
132 # api_version => 'stable.example.com/v1'
133 # kind => 'StaticWebSite'
134 # resource_plural => 'staticwebsites'
135 # is_namespaced => 1
136 # subresources => { status => {}, scale => {...} } -- a CRD
137 # version's subresources, installed as the fixed
138 # identity method `subresources` on a top-level class
139 # (k158); checked like the IO::K8s::APIObject import
140 # parameter, before the class is begun.
141 # reuse_core => 0|1 (default 1) -- type a nested object/items/
142 # additionalProperties schema as a shipped core class
143 # instead of a nested class when its shape matches
144 # one (D5); see _core_class_for.
145 # reuse_core_except => { 'Spec::Foo' => 1, ... } -- with reuse_core on,
146 # the logical nested-class paths (root-relative,
147 # class_path's key space) at which reuse is suppressed
148 # so a provider's own named type is generated even
149 # though its shape matches a core class (k120).
150 197 ▶sub get_or_generate {
Subroutine get_or_generate: called CC=2 SCAR=6.9
Pod documented
151 197 my ($def_name, $schema, $all_defs, $namespace, %opts) = @_;
152  
153 197 my $class = _class_name_for($def_name, $schema, $namespace, $opts{api_version});
154 197 ▶ return $class if _class_usable($class);
Branch: 1 branch
BranchTrueFalseTotal
if _class_usable($class) 8 181 189
155  
156 181 ▶ _in_generation_run(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
157 181 _generate_class($class, $def_name, $schema, $all_defs, $namespace, %opts);
158 181 });
159 154 return $class;
160 }
161  
162 # Run $code as a generation run (see "Generation runs" above). A request made
163 # while a run is already in progress -- a $ref reached from inside the
164 # property loop -- joins that run instead of opening its own, so the root
165 # call's run is the one unit that commits or fails.
166 181 ▶sub _in_generation_run {
Subroutine _in_generation_run: called CC=6 SCAR=17.9
167 181 my ($code) = @_;
168 181 ▶ return $code->() if $_run;
Branch: 1 branch
BranchTrueFalseTotal
if $_run 8 173 181
169  
170 173 $_run = {};
171 173 my $ok = eval { $code->(); 1 };
172 173 ▶ my $err = $@ || 'IO::K8s::AutoGen: class generation died without an error message';
Condition100%2/2
$@ || 'IO::K8s::AutoGen: class generation died without an error message'
l!l
27146
MC/DC100%1/1
$@ || 'IO::K8s::AutoGen: class generation died without an error message'
$@
Truth table100%2/2
A
A= $@
Aresult
11
00
173 173 my @begun = keys %$_run;
174 173 undef $_run;
175  
176 173 ▶ if ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ok) 146 27 173
177 146 $_generated{$_} = 1 for @begun;
178 146 return;
179 }
180 27 $_failed{$_} = $err for @begun;
181 27 die $err; # rethrow unchanged: croak would restamp it with our caller
182 }
183  
184 # Rethrow the original error of the failed run that began $class, if any.
185 # The first failure reaches the caller unchanged (_in_generation_run); a
186 # later request gets it again behind a prefix saying it is a remembered
187 # failure -- otherwise a dependency asked for directly would die naming
188 # another class's field and the first call's line. The original message is
189 # kept whole. An exception object is rethrown as it is, never stringified.
190 601 ▶sub _rethrow_failed {
Subroutine _rethrow_failed: called CC=3 SCAR=11.0
191 601 my ($class) = @_;
192 601 ▶ return unless exists $_failed{$class};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $_failed{$class} 593 8 601
193 8 my $err = $_failed{$class};
194 8 ▶ die $err if ref $err;
Branch: 1 branch
BranchTrueFalseTotal
if ref $err 0 8 8
195 8 chomp $err;
196 8 croak 'IO::K8s::AutoGen: '.$class.' failed to generate earlier in this namespace '
197 .'and stays failed; load a repaired schema into a fresh IO::K8s instance. '
198 .'Original error: '.$err;
199 }
200  
201 # True when $class can be handed out as it is: complete, or begun earlier in
202 # the run in progress (recursion). Rethrows instead when its run failed.
203 601 ▶sub _class_usable {
Subroutine _class_usable: called CC=3 SCAR=11.0
204 601 my ($class) = @_;
205 601 _rethrow_failed($class);
206 593 ▶ return $_generated{$class} || ($_run && $_run->{$class});
Condition100%6/6
$_generated{$class} || $_run && $_run->{$class}
l!l&&r!l&&!r
53585
$_run and $_run->{$class}
!ll&&!rl&&r
1734123
MC/DC100%3/3
$_generated{$class} || $_run && $_run->{$class}
$_generated{$class} $_run $_run->{$class}
Truth table100%4/4
A || B and C
A= $_generated{$class}B= $_runC= $_run->{$class}
ABCresult
1XX1
0111
00X0
0100
207 }
208  
209 # Class identity for a definition. A definition whose
210 # x-kubernetes-group-version-kind lists several entries serves more than
211 # one apiVersion from one schema; requesting one of them must produce a
212 # package specific to that GVK, otherwise the second version would silently
213 # reuse the first version's class (and its api_version method). The
214 # versionless generation keeps the plain def_to_class name as the
215 # deterministic compatibility default.
216 197 ▶sub _class_name_for {
Subroutine _class_name_for: called CC=4 SCAR=13.9
217 197 my ($def_name, $schema, $namespace, $api_version) = @_;
218 197 my $class = def_to_class($def_name, $namespace);
219 197 ▶ return $class unless defined $api_version;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $api_version 54 143 197
220  
221 143 my $gvk = $schema->{'x-kubernetes-group-version-kind'};
222 143 ▶ return $class unless ref($gvk) eq 'ARRAY' && @$gvk > 1;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $gvk eq "ARRAY" and @$gvk > 1 140 3 143
Condition100%3/3
ref $gvk eq "ARRAY" and @$gvk > 1
!ll&&!rl&&r
131273
MC/DC100%2/2
ref $gvk eq "ARRAY" and @$gvk > 1
ref $gvk eq "ARRAY" @$gvk > 1
Truth table100%3/3
A and B
A= ref $gvk eq "ARRAY"B= @$gvk > 1
ABresult
0X0
100
111
223  
224 # / and . are not valid in a package name, and every segment must be a
225 # bare identifier; map group/version to sanitized ::-separated segments
226 # the same way def_to_class maps def_names (see _class_segments) -- a
227 # hyphenated group in the api_version needs the same treatment here.
228 3 my @segments = _class_segments(split m{[./]}, $api_version);
229 3 return "${class}::" . join('::', @segments);
230 }
231  
232 # Wire apiVersion a GVK entry represents: group/version, or bare version
233 # when the group is empty (core group).
234 123 ▶sub _gvk_api_version {
Subroutine _gvk_api_version: called CC=4 SCAR=14.9
235 123 my ($entry) = @_;
236 123 ▶ my $group = $entry->{group} // '';
Condition50%1/2
$entry->{"group"} // ""
l!l
1230
MC/DC0%0/1
$entry->{"group"} // ""
$entry->{"group"}
Truth table50%1/2
A
A= $entry->{"group"}
Aresult
11
00
237 123 ▶ my $version = $entry->{version} // '';
Condition50%1/2
$entry->{"version"} // ""
l!l
1230
MC/DC0%0/1
$entry->{"version"} // ""
$entry->{"version"}
Truth table50%1/2
A
A= $entry->{"version"}
Aresult
11
00
238 123 ▶ return $group ? "$group/$version" : $version;
Branch: 1 branch
BranchTrueFalseTotal
$group ? : 123 0 123
239 }
240  
241 # Deterministic ordering key for a GVK entry.
242 4 ▶sub _gvk_sort_key {
Subroutine _gvk_sort_key: called CC=4 SCAR=15.8
243 4 my ($entry) = @_;
244 return join '/',
245 ($entry->{group} // ''),
246 ($entry->{version} // ''),
247 4 ▶ ($entry->{kind} // '');
Condition50%3/6
$entry->{"group"} // ""
l!l
40
$entry->{"version"} // ""
l!l
40
$entry->{"kind"} // ""
l!l
40
MC/DC0%0/1
$entry->{"group"} // ""
$entry->{"group"}
MC/DC0%0/1
$entry->{"version"} // ""
$entry->{"version"}
MC/DC0%0/1
$entry->{"kind"} // ""
$entry->{"kind"}
Truth table50%1/2
A
A= $entry->{"group"}
Aresult
11
00
Truth table50%1/2
A
A= $entry->{"version"}
Aresult
11
00
Truth table50%1/2
A
A= $entry->{"kind"}
Aresult
11
00
248 }
249  
250 # Pick the GVK entry a class should be built from.
251 #
252 # With an $api_version the request is exact: the entry whose group/version
253 # matches is returned; several matches are an ambiguity error, none is a
254 # fail-closed error. It never silently takes the first entry.
255 #
256 # Without an $api_version the entries are sorted and the first is returned
257 # -- deterministic regardless of array order.
258 131 ▶sub _select_gvk_entry {
Subroutine _select_gvk_entry: called CC=5 SCAR=16.8
259 131 my ($gvk, $api_version, $def_name) = @_;
260  
261 131 ▶ return $gvk unless ref($gvk) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $gvk eq "ARRAY" 0 131 131
262  
263 131 ▶ if (defined $api_version) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $api_version) 120 11 131
264 120 my @matches = grep { _gvk_api_version($_) eq $api_version } @$gvk;
265 120 ▶ if (@matches > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@matches > 1) 0 120 120
266 0 croak "GVK ambiguity in definition '$def_name': "
267 . scalar(@matches)
268 . " x-kubernetes-group-version-kind entries match api_version '$api_version'";
269 }
270 120 ▶ if (@matches == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@matches == 1) 120 0 120
271 120 return $matches[0];
272 }
273 0 croak "No x-kubernetes-group-version-kind entry in definition '$def_name' "
274 . "matches api_version '$api_version'";
275 }
276  
277 11 return (sort { _gvk_sort_key($a) cmp _gvk_sort_key($b) } @$gvk)[0];
278 }
279  
280 # Generate a class from OpenAPI schema using IO::K8s::Resource
281 405 ▶sub _generate_class {
Subroutine _generate_class: called CC=29 SCAR=33.9
282 405 my ($class, $def_name, $schema, $all_defs, $namespace, %opts) = @_;
283  
284 # Determine api_version/kind from schema or explicit options. This has
285 # to happen before the class is marked begun: a fail-closed error here
286 # (ambiguous or non-matching api_version) builds nothing, so it must not
287 # record the class as failed either -- a retry with a matching
288 # api_version resolves to the same class name and has to work.
289 405 my ($api_ver, $kind_val, $res_plural, $is_namespaced);
290 405 ▶ if (my $gvk = $schema->{'x-kubernetes-group-version-kind'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $gvk = $schema->{"x-kubernetes-group-version-kind"}) 131 274 405
291 131 my $entry = _select_gvk_entry($gvk, $opts{api_version}, $def_name);
292 131 ▶ my $group = $entry->{group} // '';
Condition50%1/2
$entry->{"group"} // ""
l!l
1310
MC/DC0%0/1
$entry->{"group"} // ""
$entry->{"group"}
Truth table50%1/2
A
A= $entry->{"group"}
Aresult
11
00
293 131 ▶ my $version = $entry->{version} // '';
Condition50%1/2
$entry->{"version"} // ""
l!l
1310
MC/DC0%0/1
$entry->{"version"} // ""
$entry->{"version"}
Truth table50%1/2
A
A= $entry->{"version"}
Aresult
11
00
294 131 ▶ $kind_val = $entry->{kind} // '';
Condition50%1/2
$entry->{"kind"} // ""
l!l
1310
MC/DC0%0/1
$entry->{"kind"} // ""
$entry->{"kind"}
Truth table50%1/2
A
A= $entry->{"kind"}
Aresult
11
00
295 131 ▶ $api_ver = $group ? "$group/$version" : $version;
Branch: 1 branch
BranchTrueFalseTotal
$group ? : 131 0 131
296 }
297  
298 # Explicit options override schema-derived values. Hoisted above the
299 # property loop because whether this class ends up with GVK class
300 # methods decides which properties must not become attributes.
301 405 ▶ $api_ver = $opts{api_version} if exists $opts{api_version};
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts{"api_version"} 133 272 405
302 405 ▶ $kind_val = $opts{kind} if exists $opts{kind};
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts{"kind"} 112 293 405
303 405 ▶ $res_plural = $opts{resource_plural} if exists $opts{resource_plural};
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts{"resource_plural"} 102 303 405
304 405 ▶ $is_namespaced = $opts{is_namespaced} if exists $opts{is_namespaced};
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts{"is_namespaced"} 83 322 405
305  
306 # A CRD version's subresources (k158), checked here for the same reason
307 # as the GVK selection above: a malformed section builds nothing and
308 # marks nothing failed, so the repaired manifest works on a retry.
309 405 my $subresources;
310 $subresources = IO::K8s::APIObject::_checked_subresources($class, $opts{subresources})
311 405 ▶ if exists $opts{subresources};
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts{"subresources"} 22 383 405
312  
313 404 ▶ return if _class_usable($class);
Branch: 1 branch
BranchTrueFalseTotal
if _class_usable($class) 0 404 404
314 404 ▶ croak "IO::K8s::AutoGen: $class generated outside a generation run" unless $_run;
Branch: 1 branch
BranchTrueFalseTotal
unless $_run 0 404 404
315 404 $_run->{$class} = 1; # Mark begun early to allow recursion; pending until the run commits
316 404 ▶ $_descriptions{$class} = $schema->{description} if defined $schema->{description};
Branch: 1 branch
BranchTrueFalseTotal
if defined $schema->{"description"} 31 373 404
317  
318 # Ensure parent packages exist
319 404 _ensure_package_exists($class);
320  
321 # Set up the class using IO::K8s::Resource's shared setup method
322 {
323 148 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
324 404 @{"${class}::ISA"} = ();
325 }
326  
327 404 require IO::K8s::Resource;
328 404 IO::K8s::Resource->_setup_class($class);
329  
330 # Get the k8s function for this class
331 404 ▶ my $k8s = $class->can('k8s')
Branch: 1 branch
BranchTrueFalseTotal
my $k8s = $class->can("k8s") or croak("Failed to set up k8s DSL for $class") 404 0 404
332 or croak "Failed to set up k8s DSL for $class";
333  
334 # A top-level class -- one with a GVK -- gets its identity methods and
335 # IO::K8s::Role::APIObject (and with it IO::K8s::Role::SpecBuilder)
336 # BEFORE any property is declared: the order `use IO::K8s::APIObject`
337 # gives a hand-written class (k150). The other way round, Role::Tiny's
338 # "class wins" let a property whose accessor has the name of a role
339 # method (label, save, is_ready, spec_get, ...) silently replace that
340 # method. Now the k144 declaration preflight in IO::K8s::Resource sees
341 # the role method and refuses the property, naming the class, the
342 # property and the method, which fails the whole generation run (k149).
343 # There is no renaming: the property would have to change its accessor
344 # name, and with it what the class looks like, to get past a clash its
345 # schema cannot know about. conditions keeps its k144 exception -- the
346 # role helper yields to a declared field of that name.
347 #
348 # The identity methods still go in before the role, so the role sees
349 # them and does not install its own class-name-derived api_version, kind
350 # and resource_plural -- the same reason IO::K8s::APIObject::import
351 # installs a CRD's before it composes the role.
352 404 ▶ my $is_top = defined $api_ver && defined $kind_val;
Condition66%2/3
defined $api_ver && defined $kind_val
!ll&&!rl&&r
2610143
MC/DC50%1/2
defined $api_ver && defined $kind_val
defined $api_ver defined $kind_val
Truth table66%2/3
A && B
A= defined $api_verB= defined $kind_val
ABresult
0X0
100
111
353 404 ▶ if ($is_top) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_top) 143 261 404
354 143 my $stash = Package::Stash->new($class);
355  
356 # These are fixed identity methods, not writable fields. A caller
357 # passing an argument believes they retargeted the object; fail closed
358 # rather than swallow the write (k67, the house line of k37/k39).
359 260 ▶ $stash->add_symbol('&api_version', sub {
Subroutine __ANON__: called CC=2 SCAR=7.2
360 260 ▶ croak 'api_version is fixed for this class and cannot be set' if @_ > 1;
Branch: 1 branch
BranchTrueFalseTotal
if @_ > 1 0 260 260
361 260 $api_ver;
362 143 });
363 220 ▶ $stash->add_symbol('&kind', sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
364 220 ▶ croak 'kind is fixed for this class and cannot be set' if @_ > 1;
Branch: 1 branch
BranchTrueFalseTotal
if @_ > 1 2 218 220
365 218 $kind_val;
366 143 });
367 46 ▶ $stash->add_symbol('&resource_plural', sub {
Subroutine __ANON__: called CC=2 SCAR=7.2
368 46 ▶ croak 'resource_plural is fixed for this class and cannot be set' if @_ > 1;
Branch: 1 branch
BranchTrueFalseTotal
if @_ > 1 0 46 46
369 46 $res_plural;
370 143 });
371 # The same identity method `use IO::K8s::APIObject subresources =>`
372 # installs, so to_crd writes them back (k112 symmetry, k158).
373 143 ▶ IO::K8s::APIObject::_install_subresources($class, $subresources)
Branch: 1 branch
BranchTrueFalseTotal
if $subresources 21 122 143
374 if $subresources;
375  
376 # Apply Role::APIObject for metadata, to_yaml, save, etc.
377 143 require Moo::Role;
378 143 require IO::K8s::Role::APIObject;
379 143 Moo::Role->apply_roles_to_package($class, 'IO::K8s::Role::APIObject');
380  
381 # Register the role's metadata attribute so _inflate_struct knows the
382 # type -- adopted, the same way IO::K8s::APIObject::import does it
383 # for hand-written classes (k144)
384 143 IO::K8s::Resource->_k8s_adopt($class, 'metadata', 'Meta::V1::ObjectMeta');
385  
386 # Apply Namespaced role if requested or schema suggests it
387 143 ▶ if ($is_namespaced) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_namespaced) 80 63 143
388 80 require IO::K8s::Role::Namespaced;
389 80 Moo::Role->apply_roles_to_package($class, 'IO::K8s::Role::Namespaced');
390 }
391 }
392  
393 404 ▶ my $properties = $schema->{properties} // {};
Condition50%1/2
$schema->{"properties"} // {}
l!l
4040
MC/DC0%0/1
$schema->{"properties"} // {}
$schema->{"properties"}
Truth table50%1/2
A
A= $schema->{"properties"}
Aresult
11
00
394  
395 # The block above gave a top-level class apiVersion, kind and metadata
396 # -- exactly the three properties IO::K8s::Role::Resource::compare_to_schema
397 # already excuses a top-level object for not declaring, and the line
398 # k45 drew for the hand-written template classes. A schema that lists
399 # them as properties as well is skipped for each of them:
400 #
401 # kind: the fixed identity method is already there, so the k144
402 # preflight would refuse the property as a collision. Back
403 # when properties came first, the identity method was
404 # installed over the generated accessor afterwards and
405 # $obj->kind('Other') was a silent no-op (k60).
406 # apiVersion: no method of that name, which is worse -- it would become
407 # a writable attribute and TO_JSON would emit it over the
408 # apiVersion the class actually is.
409 # metadata: the role's own attribute, adopted above; declaring it
410 # again from the schema could only conflict with that, and
411 # would generate a throwaway ObjectMeta class on the way. It is
412 # skipped here so that a schema referencing the standard
413 # ObjectMeta without carrying its definition (a very common
414 # way to hand in a single CRD schema) does not trip the
415 # unresolved-$ref refusal below over a field the role
416 # supplies anyway.
417 404 ▶ my %role_supplied = $is_top ? (apiVersion => 1, kind => 1, metadata => 1) : ();
Branch: 1 branch
BranchTrueFalseTotal
$is_top ? : 143 261 404
418  
419 # D5: reuse a shipped core class for a nested object/items/
420 # additionalProperties schema of exactly its shape, default on.
421 404 ▶ my $reuse_core = exists $opts{reuse_core} ? ($opts{reuse_core} ? 1 : 0) : 1;
Branch: 2 branches
BranchTrueFalseTotal
exists $opts{'reuse_core'} ? : 241 163 404
$opts{'reuse_core'} ? : 228 13 241
422  
423 # k120: a set of logical nested-class paths (root-relative,
424 # '::'-joined -- the same key space class_path/the render overlay use)
425 # at which core reuse is suppressed even with reuse_core on, so a
426 # provider's own named type is generated where its shape happens to
427 # match a core class (PrometheusOperator's Argument matches
428 # Core::V1::HTTPHeader). Empty/absent -> reuse behaves exactly as before.
429 404 ▶ my $reuse_core_except = $opts{reuse_core_except} || {};
Condition100%2/2
$opts{'reuse_core_except'} || {}
l!l
234170
MC/DC100%1/1
$opts{'reuse_core_except'} || {}
$opts{'reuse_core_except'}
Truth table100%2/2
A
A= $opts{'reuse_core_except'}
Aresult
11
00
430  
431 # Generate attributes using k8s DSL
432 # Property names with special characters ($ref, x-kubernetes-*) are
433 # automatically sanitized to valid Perl identifiers by _k8s(), with
434 # init_arg mapping so constructors still accept the original JSON keys.
435 404 ▶ my %required = map { $_ => 1 } @{ $schema->{required} // [] };
Condition100%2/2
$schema->{"required"} // []
l!l
57347
MC/DC100%1/1
$schema->{"required"} // []
$schema->{"required"}
Truth table100%2/2
A
A= $schema->{"required"}
Aresult
11
00
436 404 for my $prop (sort keys %$properties) {
437 847 ▶ next if $role_supplied{$prop};
Branch: 1 branch
BranchTrueFalseTotal
if $role_supplied{$prop} 87 760 847
438 760 my $prop_schema = $properties->{$prop};
439 760 my $type_spec = _schema_to_type_spec($prop_schema, $all_defs, $namespace, $prop, $class, $reuse_core, $reuse_core_except);
440 742 ▶ next unless defined $type_spec; # Skip unsupported types
Branch: 1 branch
BranchTrueFalseTotal
unless defined $type_spec 0 742 742
441  
442 742 my $opts = _field_options($prop_schema, $type_spec, $required{$prop});
443 742 ▶ $k8s->($prop, $type_spec, ($opts ? $opts : ()));
Branch: 1 branch
BranchTrueFalseTotal
$opts ? : 212 530 742
444 }
445  
446 375 return $class;
447 }
448  
449 # Opaque type definitions that should be the free map (Opaque), not object
450 # references
451 148 my %OPAQUE_TYPES = map { $_ => 1 } qw(
452 io.k8s.apimachinery.pkg.apis.meta.v1.FieldsV1
453 io.k8s.apimachinery.pkg.runtime.RawExtension
454 );
455  
456 # The apiextensions union types (k152). Upstream's swagger.json describes
457 # each of them with a description and nothing else, since none is a JSON
458 # object: v1.JSON is any JSON value, JSONSchemaPropsOrArray a schema or an
459 # array of schemas, JSONSchemaPropsOrBool a schema or a boolean,
460 # JSONSchemaPropsOrStringArray a schema or a string array. Generated from
461 # such a definition, a class has no fields and no FROM_STRUCT and cannot
462 # hold `default: "foo"`. IO::K8s ships a hand-written class for each of the
463 # four, inflated through FROM_STRUCT, and a $ref to one of the names is
464 # typed as that class -- by name, whether the spec carries the definition
465 # or not, like the apimachinery scalars and %OPAQUE_TYPES above. reuse_core
466 # has no say: this is the type itself, not a shape that happens to match.
467 #
468 # IO::K8s ships no v1beta1 apiextensions classes. The v1beta1 names -- in a
469 # spec from a cluster older than 1.22, which removed that API -- are carried
470 # by the v1 JSON class instead, which holds any JSON value as it came and
471 # writes it back unchanged: opaque, never a field-less class that loses the
472 # value.
473 148 my $APIEXT_DEF = 'io.k8s.apiextensions-apiserver.pkg.apis.apiextensions.';
474 148 my $APIEXT_CLASS = 'IO::K8s::ApiextensionsApiserver::Pkg::Apis::Apiextensions::V1::';
475 my %UNION_TYPES = map {
476 148 ( $APIEXT_DEF.'v1.'.$_ => $APIEXT_CLASS.$_,
477 $APIEXT_DEF.'v1beta1.'.$_ => $APIEXT_CLASS.'JSON' )
478 } qw( JSON JSONSchemaPropsOrArray JSONSchemaPropsOrBool JSONSchemaPropsOrStringArray );
479  
480 # The shipped class a union $ref stands for, loaded, or nothing.
481 53 ▶sub _union_class {
Subroutine _union_class: called CC=2 SCAR=6.9
482 53 my ($ref) = @_;
483 53 ▶ my $class = $UNION_TYPES{$ref} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $class = $UNION_TYPES{$ref} or return 30 23 53
484 30 return use_module($class);
485 }
486  
487 # A $ref pointing at a definition the caller never supplied.
488 #
489 # Refusing is the fail-closed choice (k56). The property used to be
490 # skipped outright: the generated class simply had no such attribute, Moo
491 # dropped the constructor argument for it without a word, and TO_JSON never
492 # emitted the data again -- an inflate/serialize round-trip that quietly
493 # lost whatever sat under that key.
494 #
495 # The alternative considered was an opaque { Str => 1 } attribute. It was
496 # rejected for two reasons. It cannot be applied at all three call sites:
497 # the k8s DSL has no array-of-hash form, so `items: { $ref: <missing> }`
498 # would have to become ArrayRef[Str] and then reject the very hashrefs the
499 # field carries -- the k57 failure, reintroduced. And it guesses a
500 # shape: a missing definition may just as well be a string or array alias,
501 # in which case the Maybe[HashRef] attribute fails its type constraint
502 # without ever naming the unresolved $ref that caused it. %OPAQUE_TYPES
503 # above is a decision taken per named type, not a default for anything
504 # unresolvable.
505 12 ▶sub _croak_unresolved_ref {
Subroutine _croak_unresolved_ref: called CC=1 SCAR=0.0
506 12 my ($ref, $where) = @_;
507 12 croak "Cannot resolve the \$ref '$ref' for $where: no such definition in "
508 . "the OpenAPI spec. Supply the definition or drop the property -- "
509 . "generating the class without it would silently drop that field on "
510 . "every round-trip";
511 }
512  
513 # The class segment for a nested class: the whole JSON key sanitized into
514 # one package-identifier segment (see _class_segments above), then
515 # ucfirst'd. `x-extra` -> `X_extra`, `$ref` -> `_ref`, `x.y/z` -> `X_y_z`
516 # -- unlike def_to_class/_class_name_for the key is never split on '.' or
517 # '/' first: it is one field name, not a request for sub-packages, and a
518 # key containing either used to reach package creation unsanitized and die
519 # there with a message that named neither the field nor the class.
520 508 ▶sub _class_segment {
Subroutine _class_segment: called CC=1 SCAR=0.0
521 508 my ($json_key) = @_;
522 508 return ucfirst((_class_segments($json_key))[0]);
523 }
524  
525 # The field name that generated a given nested class name. Needed to fail
526 # closed on a name collision: two schema keys can sanitize + ucfirst to the
527 # same class segment -- an array-of-objects field `routes` (its items get
528 # an `Item` suffix) and a sibling plain-object field `routesItem` both
529 # produce `...::RoutesItem`; so would a `weights` map (`Value` suffix)
530 # alongside a sibling `weightsValue`, or `x-extra` next to `x_extra`, or
531 # `Foo` next to `foo`. The class name already encodes the suffix, so the
532 # bare field name is enough to tell two different owners apart -- and it
533 # has to be the bare name, not "$field_name$suffix", because that compound
534 # form is itself ambiguous: `routes` + the `Item` suffix and the plain
535 # field `routesItem` concatenate to the identical string, which would defeat
536 # the very check meant to catch that exact pair. Without this, the `unless
537 # ($_generated{$class})` guard below would silently keep the FIRST field's
538 # class for the SECOND -- the second field ends up typed as the first
539 # field's class, and inflating real data for it drops the field on every
540 # round-trip in the default non-strict mode. Never generate a class that
541 # silently drops a field -- the same rule _croak_unresolved_ref enforces for
542 # an unresolved $ref (k56), reached here from a name collision instead.
543 #
544 # Keyed on the FULL logical name (root + the whole '::'-joined path below
545 # it), never on a class's own (possibly hash-shortened) Perl name: two
546 # different long paths must never be treated as "the same nested class"
547 # just because a name collision detector happened to look at the shortened
548 # form, which -- being a 40-bit truncated hash -- is a much smaller space
549 # than the paths it stands in for.
550 148 my %_nested_origin;
551  
552 # Every nested class AutoGen has generated, keyed by its actual (possibly
553 # shortened) Perl class name:
554 # %_root_of -> the top-level generated class (the Kind class) the
555 # nesting started from. A root has no entry here;
556 # class_root() falls back to the class itself.
557 # %_class_path -> the '::'-joined path below that root
558 # ('Spec::Acme::SolversItem::...'), recorded regardless of
559 # whether the class name itself had to be shortened. A
560 # root, or a class AutoGen did not generate as nested, has
561 # no entry; class_path() returns undef for those.
562 my %_root_of;
563 148 my %_class_path;
564  
565 # The Perl class name for a nested class at logical path $path below $root:
566 # the path-derived name (identical to what pre-1.109 AutoGen always used)
567 # while it fits under $MAX_CLASS_NAME, otherwise <root>::_<10 hex chars>
568 # from a SHA-1 of the full logical name -- deterministic, so the same
569 # (root, path) always yields the same class, and short enough that it can
570 # never itself need shortening (root plus a fixed 13-character suffix).
571 224 ▶sub _class_for_path {
Subroutine _class_for_path: called CC=2 SCAR=6.9
572 224 my ($root, $path) = @_;
573 224 my $logical_name = "$root\::$path";
574 224 ▶ return $logical_name if length($logical_name) <= $MAX_CLASS_NAME;
Branch: 1 branch
BranchTrueFalseTotal
if length $logical_name <= $MAX_CLASS_NAME 209 15 224
575 15 return $root . '::_' . substr(sha1_hex($logical_name), 0, 10);
576 }
577  
578 # An inline `type: object` with its own properties becomes a nested class
579 # named after its place in the parent -- <Parent>::<Prop>, plus an Item /
580 # Value suffix for array items and map values -- generated in the parent's
581 # namespace and cached like every other generated class. Before 1.108 such
582 # an object was an opaque hash, so a CRD's spec, which every CRD schema
583 # inlines, carried no typing below the top level (k94). Hash-style access on
584 # the result keeps working: a Moo object is a blessed hash keyed by
585 # attribute name. Property-less objects and additionalProperties-only maps
586 # are not touched here; they stay opaque (k55).
587 #
588 # A schema nested deep enough (cert-manager's CRDs inline a full
589 # PodTemplateSpec under a solver, itself several levels into a Challenge)
590 # makes the path-derived name run past Perl's 251-character identifier
591 # limit; see $MAX_CLASS_NAME and _class_for_path above.
592 #
593 # $reuse_core carries forward unchanged (D5): a schema only reaches here
594 # because its own shape did NOT match a shipped core class, but its
595 # properties still get the same reuse_core treatment when this new class's
596 # own fields are, in turn, typed.
597 225 ▶sub _nested_class {
Subroutine _nested_class: called CC=7 SCAR=19.8
598 225 my ($parent_class, $field_name, $suffix, $schema, $all_defs, $namespace, $reuse_core, $reuse_core_except) = @_;
599 225 ▶ $reuse_core = 1 unless defined $reuse_core;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $reuse_core 0 225 225
600  
601 225 ▶ my $root = $_root_of{$parent_class} // $parent_class;
Condition66%2/3
$_root_of{$parent_class} // $parent_class
l!l&&r!l&&!r
1021230
MC/DC0%0/2
$_root_of{$parent_class} // $parent_class
$_root_of{$parent_class} $parent_class
Truth table66%2/3
A // B
A= $_root_of{$parent_class}B= $parent_class
ABresult
1X1
011
000
602 225 my $parent_path = $_class_path{$parent_class};
603 225 ▶ my $segment = _class_segment($field_name) . ($suffix // '');
Condition100%2/2
$suffix // ""
l!l
24201
MC/DC100%1/1
$suffix // ""
$suffix
Truth table100%2/2
A
A= $suffix
Aresult
11
00
604 225 ▶ my $path = defined($parent_path) ? "$parent_path\::$segment" : $segment;
Branch: 1 branch
BranchTrueFalseTotal
defined $parent_path ? : 102 123 225
605 225 my $logical_name = "$root\::$path";
606  
607 225 ▶ if (exists $_nested_origin{$logical_name}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $_nested_origin{$logical_name}) 1 224 225
608 1 my $existing = $_nested_origin{$logical_name};
609 1 ▶ if ($existing ne $field_name) {
Branch: 1 branch
BranchTrueFalseTotal
if ($existing ne $field_name) 1 0 1
610 1 croak "Cannot generate a nested class for field '$field_name' of $parent_class: "
611 . "its class name $logical_name is already taken by field '$existing' "
612 . "-- two schema keys collapse to the same class segment; rename one of them";
613 }
614 0 my $existing_class = _class_for_path($root, $path);
615 0 _rethrow_failed($existing_class);
616 0 return $existing_class;
617 }
618 224 $_nested_origin{$logical_name} = $field_name;
619  
620 224 my $class = _class_for_path($root, $path);
621 224 $_root_of{$class} = $root;
622 224 $_class_path{$class} = $path;
623  
624 224 my $def_name = class_to_def($parent_class) . '.' . $segment;
625 224 _generate_class($class, $def_name, $schema, $all_defs, $namespace,
626 reuse_core => $reuse_core, reuse_core_except => $reuse_core_except);
627 221 return $class;
628 }
629  
630 # The logical path a nested class for ($parent_class, $field_name, $suffix)
631 # WOULD be generated at, computed the same way _nested_class does above --
632 # but without generating anything, so the reuse decision in
633 # _schema_to_type_spec can consult reuse_core_except before it calls
634 # _core_class_for (k120).
635 283 ▶sub _prospective_nested_path {
Subroutine _prospective_nested_path: called CC=3 SCAR=11.0
636 283 my ($parent_class, $field_name, $suffix) = @_;
637 283 my $parent_path = $_class_path{$parent_class};
638 283 ▶ my $segment = _class_segment($field_name) . ($suffix // '');
Condition100%2/2
$suffix // ""
l!l
71212
MC/DC100%1/1
$suffix // ""
$suffix
Truth table100%2/2
A
A= $suffix
Aresult
11
00
639 283 ▶ return defined($parent_path) ? "$parent_path\::$segment" : $segment;
Branch: 1 branch
BranchTrueFalseTotal
defined $parent_path ? : 117 166 283
640 }
641  
642 884 ▶sub _has_properties {
Subroutine _has_properties: called CC=5 SCAR=16.1
643 884 my ($schema) = @_;
644 return ref $schema eq 'HASH'
645 && ($schema->{type} // '') eq 'object'
646 && ref $schema->{properties} eq 'HASH'
647 884 ▶ && %{ $schema->{properties} };
Condition90%10/11
ref $schema eq 'HASH' && ($schema->{'type'} // '') eq 'object' && ref $schema->{'properties'} eq 'HASH' && %{$schema->{'properties'};}
!ll&&!rl&&r
2361647
ref $schema eq "HASH" and ($schema->{"type"} // "") eq "object" and ref $schema->{"properties"} eq "HASH"
!ll&&!rl&&r
125111648
ref $schema eq "HASH" and ($schema->{"type"} // "") eq "object"
!ll&&!rl&&r
0125759
$schema->{"type"} // ""
l!l
85826
MC/DC75%3/4
ref $schema eq 'HASH' && ($schema->{'type'} // '') eq 'object' && ref $schema->{'properties'} eq 'HASH' && %{$schema->{'properties'};}
ref $schema eq "HASH" $schema->{"type"} ref $schema->{"properties"} eq "HASH" %{$schema->{'properties'};}
Truth table80%4/5
A and B and C && D
A= ref $schema eq "HASH"B= $schema->{"type"}C= ref $schema->{"properties"} eq "HASH"D= %{$schema->{'properties'};}
ABCDresult
0XXX0
10XX0
110X0
11100
11111
648 }
649  
650 # ---------------------------------------------------------------------------
651 # reuse_core (D5): a nested object whose property set is exactly the key set
652 # of a shipped core / apimachinery class is typed as that class. CRD schemas
653 # inline the types they embed (a LabelSelector, a PodTemplateSpec), and
654 # modeling them again would give every provider its own copy of PodSpec.
655 #
656 # The index is built once from the shipped class files, keyed by JSON key
657 # NAME only -- core_class_for_shape lists every candidate a key set could
658 # mean, without regard to type. _core_class_for below is the actual reuse
659 # decision, and needs more than a name match to be safe:
660 #
661 # 1. A schema shape under two keys is never reused. A single shared key
662 # name ({value}, {name}, ...) is common enough by accident that
663 # requiring at least two narrows out most of it for free.
664 #
665 # 2. Every remaining candidate must be TYPE-compatible with the schema,
666 # key by key (see %_TYPE_COMPAT below) -- a schema string field can't
667 # reuse a class that declares the same-named field as an array, for
668 # instance. This is checked before anything else, since a name match
669 # alone says nothing about the wire shape. It is coarse for arrays and
670 # maps (any array, any map); step 4 settles what they hold.
671 #
672 # 3. Every remaining candidate must not OVER-CONSTRAIN the schema (k136,
673 # see _overrequires): a candidate that marks some shared key
674 # `required` (plain Moo-enforced or registry-only `required =>
675 # 'schema'`) which the schema's own `required` list leaves optional is
676 # dropped. Reusing it would reject or silently drop a real cluster
677 # object that (validly, per the CRD) omits that key -- the metav1.
678 # Condition shape reused for a CRD condition that requires only
679 # [type,status] is the case this exists for (k135/k137): message,
680 # reason and lastTransitionTime are required on Condition but not on
681 # the CRD, so a message-less live condition failed to inflate. Only
682 # this direction is checked -- a schema requiring MORE than the
683 # candidate leaves the reused class merely looser than the schema
684 # promises, never lossy.
685 #
686 # 4. Every remaining candidate must hold the schema all the way down
687 # (k148, see _field_compatible): an array's elements, a map's values
688 # and every nested object's fields, recursively. A candidate that does
689 # not -- an array of objects against a class whose same-named field is
690 # an array of strings, which is what LabelSelectorRequirement was reused
691 # for before -- is dropped here. k148 first ran this as a gate on the
692 # class steps 5/6 had already picked, so it could only WITHDRAW a reuse;
693 # k156 moved it ahead of the tie-break, where dropping the
694 # recursively-incompatible candidates can leave a single survivor and so
695 # DECIDE a reuse that a name/type match alone left ambiguous: a
696 # {metadata,spec} matches every *TemplateSpec by name and type, but only
697 # PodTemplateSpec's spec holds a PodSpec and only
698 # PersistentVolumeClaimTemplate's a PVC spec, so the mismatched
699 # candidates fall away and the one that fits is reused (AgentSandbox's
700 # podTemplate and volumeClaimTemplates, PrometheusOperator's ephemeral
701 # volumeClaimTemplate). Wire-identical candidates share their verdict
702 # here (same flags, same classes per key), so they survive or fall
703 # together and step 6 still sees the same wire-identical set.
704 #
705 # 5. Exactly one candidate survives every filter -> reuse it.
706 #
707 # 6. Several do -- reused only when they are wire-identical: the same
708 # type flags (NOT required-ness -- a field being optional on one
709 # shipped class and mandatory on another doesn't change what value it
710 # holds) and the same referenced class per key, where a key has one.
711 # {name,value} matches HTTPHeader, PodDNSConfigOption and Sysctl --
712 # three unrelated Core::V1 leaf structs, wire-identical (two required
713 # Str fields on two of them, two optional Str fields on the third, but
714 # Str either way) -- reused as the preferred one (Meta::V1, then
715 # Core::V1, then alphabetical: HTTPHeader). {key,operator,values}
716 # matches LabelSelectorRequirement, FieldSelectorRequirement (both
717 # Meta::V1) and NodeSelectorRequirement (Core::V1) -- also
718 # wire-identical despite spanning two API areas -- reused as
719 # LabelSelectorRequirement, by a wide margin the most common shape a
720 # provider CRD's inline schema turns out to match (138 LabelSelector
721 # copies, 162 of this bare triple, per the step-4 drift measurement).
722 # A shape still matched by several NON-wire-identical candidates after
723 # the step-4 filter (an optional field naming a different type, a
724 # different value type under the same key that both nonetheless hold the
725 # schema) stays a nested class rather than guess.
726 #
727 # A class's own `metadata` is part of its shape only for an embedded type
728 # (PodTemplateSpec: {metadata,spec}, a real schema-visible field) -- never
729 # for a top-level Kind (Pod: {spec,status}), whose `metadata` is supplied
730 # by IO::K8s::Role::APIObject outside the schema's own properties (see
731 # _generate_class's %role_supplied) and so never appears in a CRD's own
732 # inline schema for that Kind.
733 # ---------------------------------------------------------------------------
734  
735 148 my %_core_shapes; # "k1,k2,..." -> [ classes, preference-ordered ]
736 148 my %_core_shape_loaded; # shape -> 1 once that shape's candidates are loaded
737 148 my $_core_indexed = 0;
738  
739 # The checked-in, precomputed form of %_core_shapes (k104). Building the
740 # index live costs ~6.5s in a fresh process -- >99% of it Module::Runtime
741 # loading all 839 classes under the two trees, the File::Find walk and the
742 # registry reads being ~15ms together -- and reuse_core is default on, so
743 # every first add_crd / generate / CRD inflate paid it. The precomputed
744 # module carries the finished shape -> classes map (no DSL semantics: the
745 # type-aware half of the reuse decision in _core_class_for loads the few
746 # candidate classes it actually looks at, see core_class_for_shape) and
747 # loads in ~2ms.
748 #
749 # It is a maint-maintained artifact in the sense of
750 # maint/spec-drift-exceptions.yaml, NOT a codegen step -- nothing under
751 # lib/IO/K8s/Api* is generated. maint/core-shape-index-gen.pl writes it by
752 # calling _scan_core_shapes below, and t/85_core_shape_index.t fails when
753 # the checked-in copy no longer matches what that same function produces,
754 # which is what keeps adding, removing or renaming a class honest.
755 148 our $CORE_SHAPE_INDEX = 'IO::K8s::AutoGen::CoreShapes';
756  
757 # Preference order for core_class_for_shape's listing and for picking among
758 # several wire-identical candidates: LabelSelector / LabelSelectorRequirement
759 # first (see above), then the rest of apimachinery's Meta::V1, then
760 # core/v1, then everything else alphabetically.
761 148 my @CORE_PREFERENCE = (
762 'IO::K8s::Apimachinery::Pkg::Apis::Meta::V1::LabelSelector',
763 'IO::K8s::Apimachinery::Pkg::Apis::Meta::V1::',
764 'IO::K8s::Api::Core::V1::',
765 );
766  
767 1176 ▶sub _core_rank {
Subroutine _core_rank: called CC=3 SCAR=11.0
768 1176 my ($class) = @_;
769 1176 for my $i (0 .. $#CORE_PREFERENCE) {
770 3503 ▶ return $i if index($class, $CORE_PREFERENCE[$i]) == 0;
Branch: 1 branch
BranchTrueFalseTotal
if index($class, $CORE_PREFERENCE[$i]) == 0 151 3352 3503
771 }
772 1025 return scalar @CORE_PREFERENCE;
773 }
774  
775 119 ▶sub _index_core_shapes {
Subroutine _index_core_shapes: called CC=3 SCAR=11.0
776 119 ▶ return if $_core_indexed++;
Branch: 1 branch
BranchTrueFalseTotal
if $_core_indexed++ 99 20 119
777 20 my $precomputed = eval { use_module($CORE_SHAPE_INDEX)->shapes };
778 # A copy of the top level only: the arrayrefs stay shared with the
779 # index module, so core_class_for_shape replaces a shape's entry
780 # rather than sorting or splicing one in place.
781 20 ▶ %_core_shapes = %{ $precomputed || _scan_core_shapes() };
Condition66%2/3
$precomputed || _scan_core_shapes()
l!l&&r!l&&!r
1910
MC/DC0%0/2
$precomputed || _scan_core_shapes()
$precomputed _scan_core_shapes()
Truth table66%2/3
A || B
A= $precomputedB= _scan_core_shapes()
ABresult
1X1
011
000
782 }
783  
784 # Build the shape index by loading every shipped class under the two trees
785 # and reading its attribute registry -- the slow path the precomputed
786 # index above exists to avoid. Called as the fallback when that module is
787 # missing, and, deliberately, as the ONE implementation both
788 # maint/core-shape-index-gen.pl and t/85_core_shape_index.t call: the
789 # artifact cannot encode a different metadata rule or a different
790 # preference order than the live path produces, because it IS this
791 # function's output. Returns a fresh hashref and touches no module state,
792 # so the drift test can scan without disturbing a lookup already served.
793 1 ▶sub _scan_core_shapes {
Subroutine _scan_core_shapes: called CC=8 SCAR=20.9
794 1 require File::Find;
795 1 require IO::K8s::Role::Resource;
796 1 (my $lib = $INC{'IO/K8s/AutoGen.pm'}) =~ s{/IO/K8s/AutoGen\.pm\z}{};
797 1 my @files;
798 912 ▶ File::Find::find(sub { push @files, $File::Find::name if /\.pm\z/ },
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
if /\.pm\z/ 839 73 912
799 1 "$lib/IO/K8s/Api", "$lib/IO/K8s/Apimachinery");
800 1 my %shapes;
801 1 for my $file (sort @files) {
802 839 (my $class = $file) =~ s{^\Q$lib\E/}{};
803 839 $class =~ s{/}{::}g;
804 839 $class =~ s/\.pm\z//;
805 839 ▶ eval { use_module($class); 1 } or next;
Branch: 1 branch
BranchTrueFalseTotal
eval { do { &use_module($class); 1 } } or next 839 0 839
806 839 my $info = IO::K8s::Role::Resource::_k8s_attr_info($class);
807 # See the block comment above: metadata is part of the shape for an
808 # embedded type, not for a top-level Kind (Role::APIObject supplies
809 # it outside the schema there).
810 839 ▶ my @attrs = $class->can('_is_resource') ? grep { $_ ne 'metadata' } keys %$info : keys %$info;
Branch: 1 branch
BranchTrueFalseTotal
$class->can('_is_resource') ? : 122 717 839
811 839 ▶ my @keys = sort map { $info->{$_}{json_key} // $_ } @attrs;
Condition33%1/3
$info->{$_}{"json_key"} // $_
l!l&&r!l&&!r
028770
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
812 839 ▶ next unless @keys;
Branch: 1 branch
BranchTrueFalseTotal
unless @keys 17 822 839
813 822 push @{ $shapes{ join ',', @keys } }, $class;
814 }
815 1 for my $shape (keys %shapes) {
816 453 ▶ @{ $shapes{$shape} } = sort { _core_rank($a) <=> _core_rank($b) || $a cmp $b } @{ $shapes{$shape} };
Condition66%2/3
_core_rank($a) <=> _core_rank($b) || $a cmp $b
l!l&&r!l&&!r
635030
MC/DC0%0/2
_core_rank($a) <=> _core_rank($b) || $a cmp $b
_core_rank($a) <=> _core_rank($b) $a cmp $b
Truth table66%2/3
A || B
A= _core_rank($a) <=> _core_rank($b)B= $a cmp $b
ABresult
1X1
011
000
817 }
818 1 return \%shapes;
819 }
820  
821 # Every shipped class whose key set is exactly \@json_keys, preference
822 # ordered. Diagnostic / listing use as well as the reuse decision below;
823 # building the class-name-only class from a plain ARRAY (JSON key names,
824 # not schema fragments) keeps it usable without a schema in hand. Name
825 # match only -- see _core_class_for for the type-aware reuse decision.
826 119 ▶sub core_class_for_shape {
Subroutine core_class_for_shape: called CC=3 SCAR=11.0
Pod documented
827 119 my ($keys) = @_;
828 119 _index_core_shapes();
829 119 my $shape = join ',', sort @$keys;
830 119 ▶ my $classes = $_core_shapes{$shape} or return ();
Branch: 1 branch
BranchTrueFalseTotal
my $classes = $_core_shapes{$shape} or return () 48 71 119
831 # The precomputed index names classes without loading them, while
832 # every caller -- _core_class_for's type check first among them --
833 # reads the candidate's attribute registry, which is empty until the
834 # class is loaded. Handing out an unloaded name would not raise: the
835 # type filter would simply find no compatible candidate and silently
836 # stop reusing anything, which is the worst shape this optimisation
837 # could fail in. So a shape's candidates are loaded the first time
838 # that shape is asked for: a handful of classes per lookup instead of
839 # all 839 up front. A class that will not load is dropped and stays
840 # dropped, matching the live scan, which never indexes one.
841 48 ▶ unless ($_core_shape_loaded{$shape}++) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($_core_shape_loaded{$shape}++) 27 21 48
842 27 $classes = [ grep { eval { use_module($_); 1 } } @$classes ];
843 27 $_core_shapes{$shape} = $classes;
844 }
845 48 return @$classes;
846 }
847  
848 # The JSON-schema "kind" a property's type dispatches on for reuse-safety
849 # purposes -- string / int-or-string / time / quantity / integer / number /
850 # boolean / array / object. Mirrors _schema_to_type_spec's own dispatch
851 # (including its x-kubernetes-int-or-string, `format: int-or-string` and
852 # `format: date-time` checks and its Str fallback for anything unmodeled)
853 # without generating anything, since _core_class_for needs this for a schema
854 # fragment it may end up NOT typing as an object at all.
855 #
856 # The string family splits into four kinds (k181, k185), not one, because a
857 # reused class imposes its own wire type on the field and the wrong one
858 # corrupts the value:
859 # * int-or-string (k181) -- x-kubernetes-int-or-string, or `type: string`
860 # with `format: int-or-string`, or a $ref to intstr.IntOrString
861 # (_scalar_ref_kind). Matches an IntOrStr field and a Quantity one:
862 # controller-gen renders a resource.Quantity as x-kubernetes-int-or-string
863 # with the quantity pattern (the emitter reads that back as Quantity,
864 # k125), so a CRD embedding a pod template or a ResourceList still reuses
865 # the core class that holds it.
866 # * time -- `format: date-time`, or a $ref to meta.v1.(Micro)Time
867 # (_scalar_ref_kind). Matches a Time field: the value IS an RFC 3339
868 # timestamp, which is exactly what a Time field holds and emits.
869 # * quantity -- a $ref to resource.Quantity (_scalar_ref_kind). Matches a
870 # Quantity field: the value IS a quantity.
871 # * string -- a plain `type: string` (no format, no scalar $ref), '', and
872 # anything unmodeled. Matches a Str field only (k185). It must NOT reuse
873 # an IntOrStr, Quantity or Time class: an IntOrStr turns the schema's
874 # "8080" into the number 8080 (a Str goes out quoted since k145), a strict
875 # Quantity rejects a "big", a strict Time rejects any non-RFC 3339 string.
876 # Reading a plain string as any of those was the k185 bug -- the mirror of
877 # the k181 one that read int-or-string as 'string'.
878 # time and quantity also match a Str field: a timestamp or quantity string is
879 # a lossless fit for one, the same direction the reuse check accepts elsewhere.
880 630 ▶sub _schema_type_kind {
Subroutine _schema_type_kind: called CC=14 SCAR=26.4
881 630 my ($schema) = @_;
882 630 ▶ return 'int-or-string' if eval { IO::K8s::Resource::_normalize_bool($schema->{'x-kubernetes-int-or-string'}) };
Branch: 1 branch
BranchTrueFalseTotal
if eval { do { IO::K8s::Resource::_normalize_bool($schema->{"x-kubernetes-int-or-string"}) } } 22 608 630
883 608 ▶ my $type = $schema->{type} // '';
Condition100%2/2
$schema->{"type"} // ""
l!l
6053
MC/DC100%1/1
$schema->{"type"} // ""
$schema->{"type"}
Truth table100%2/2
A
A= $schema->{"type"}
Aresult
11
00
884 608 ▶ return 'int-or-string' if $type eq 'string' && ($schema->{format} // '') eq 'int-or-string';
Branch: 1 branch
BranchTrueFalseTotal
if $type eq "string" and ($schema->{"format"} // "") eq "int-or-string" 3 605 608
Condition100%5/5
$type eq "string" and ($schema->{"format"} // "") eq "int-or-string"
!ll&&!rl&&r
2373683
$schema->{"format"} // ""
l!l
37334
MC/DC100%2/2
$type eq "string" and ($schema->{"format"} // "") eq "int-or-string"
$type eq "string" $schema->{"format"}
Truth table100%3/3
A and B
A= $type eq "string"B= $schema->{"format"}
ABresult
0X0
100
111
885 605 ▶ return 'time' if $type eq 'string' && ($schema->{format} // '') eq 'date-time';
Branch: 1 branch
BranchTrueFalseTotal
if $type eq "string" and ($schema->{"format"} // "") eq "date-time" 34 571 605
Condition100%5/5
$type eq "string" and ($schema->{"format"} // "") eq "date-time"
!ll&&!rl&&r
23733434
$schema->{"format"} // ""
l!l
34334
MC/DC100%2/2
$type eq "string" and ($schema->{"format"} // "") eq "date-time"
$type eq "string" $schema->{"format"}
Truth table100%3/3
A and B
A= $type eq "string"B= $schema->{"format"}
ABresult
0X0
100
111
886 571 ▶ return 'integer' if $type eq 'integer';
Branch: 1 branch
BranchTrueFalseTotal
if $type eq "integer" 31 540 571
887 540 ▶ return 'number' if $type eq 'number';
Branch: 1 branch
BranchTrueFalseTotal
if $type eq "number" 0 540 540
888 540 ▶ return 'boolean' if $type eq 'boolean';
Branch: 1 branch
BranchTrueFalseTotal
if $type eq "boolean" 0 540 540
889 540 ▶ return 'array' if $type eq 'array';
Branch: 1 branch
BranchTrueFalseTotal
if $type eq "array" 63 477 540
890 477 ▶ return 'object' if $type eq 'object';
Branch: 1 branch
BranchTrueFalseTotal
if $type eq "object" 140 337 477
891 337 return 'string'; # 'string', '', and anything unmodeled alike (k42's own Str fallback)
892 }
893  
894 # The value type of a map whose additionalProperties is a scalar schema
895 # (k191) -- the DSL kind name Str, Int, Num, Bool, IntOrStr or Time -- or
896 # undef when the generator types the map as the free Opaque instead: an
897 # object or array value, or a value schema that names no type at all.
898 # Unlike _schema_type_kind, a missing type is not read as a string here: a
899 # string map stringifies every value on the wire, and `{}` promises no
900 # strings. Shared by _schema_to_type_spec and the reuse check
901 # (_object_compatible), so both read a map the same way.
902 19 ▶sub _map_value_kind {
Subroutine _map_value_kind: called CC=10 SCAR=25.9
903 19 my ($addl) = @_;
904 19 ▶ return 'IntOrStr' if eval { IO::K8s::Resource::_normalize_bool($addl->{'x-kubernetes-int-or-string'}) };
Branch: 1 branch
BranchTrueFalseTotal
if eval { do { IO::K8s::Resource::_normalize_bool($addl->{"x-kubernetes-int-or-string"}) } } 5 14 19
905 14 ▶ my $type = $addl->{type} // '';
Condition50%1/2
$addl->{"type"} // ""
l!l
140
MC/DC0%0/1
$addl->{"type"} // ""
$addl->{"type"}
Truth table50%1/2
A
A= $addl->{"type"}
Aresult
11
00
906 14 ▶ if ($type eq 'string') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "string") 13 1 14
907 13 ▶ my $format = $addl->{format} // '';
Condition100%2/2
$addl->{"format"} // ""
l!l
112
MC/DC100%1/1
$addl->{"format"} // ""
$addl->{"format"}
Truth table100%2/2
A
A= $addl->{"format"}
Aresult
11
00
908 13 ▶ return 'IntOrStr' if $format eq 'int-or-string';
Branch: 1 branch
BranchTrueFalseTotal
if $format eq "int-or-string" 0 13 13
909 13 ▶ return 'Time' if $format eq 'date-time';
Branch: 1 branch
BranchTrueFalseTotal
if $format eq "date-time" 1 12 13
910 12 return 'Str';
911 }
912 1 ▶ return 'Int' if $type eq 'integer';
Branch: 1 branch
BranchTrueFalseTotal
if $type eq "integer" 1 0 1
913 0 ▶ return 'Num' if $type eq 'number';
Branch: 1 branch
BranchTrueFalseTotal
if $type eq "number" 0 0 0
914 0 ▶ return 'Bool' if $type eq 'boolean';
Branch: 1 branch
BranchTrueFalseTotal
if $type eq "boolean" 0 0 0
915 0 return undef;
916 }
917  
918 # Registry type flags compatible with each schema kind (rule 2 above). The
919 # string family (string / int-or-string / time / quantity) and why each is a
920 # kind of its own is explained on _schema_type_kind above.
921 # 'array'/'object' match by prefix/membership rather than an exhaustive
922 # list -- see _flag_compatible. That coarse array/object match is only the
923 # pre-selection the tie-break works on; what the array holds and what the
924 # map's values are is decided by _field_compatible below (k148), which asks
925 # _flag_compatible about scalar kinds only.
926 my %_TYPE_COMPAT = (
927 string => { is_str => 1 },
928 296 quantity => { map { $_ => 1 } qw( is_quantity is_str ) },
929 296 time => { map { $_ => 1 } qw( is_time is_str ) },
930 296 'int-or-string' => { map { $_ => 1 } qw( is_int_or_string is_quantity ) },
931 296 integer => { map { $_ => 1 } qw( is_int is_int_or_string ) },
932 148 number => { map { $_ => 1 } qw( is_num ) },
933 148 boolean => { map { $_ => 1 } qw( is_bool ) },
934 );
935  
936 545 ▶sub _flag_compatible {
Subroutine _flag_compatible: called CC=9 SCAR=23.1
937 545 my ($kind, $flag) = @_;
938 545 ▶ return 1 if $kind eq 'array' && $flag =~ /^is_array_of_/;
Branch: 1 branch
BranchTrueFalseTotal
if $kind eq "array" and $flag =~ /^is_array_of_/ 24 521 545
Condition66%2/3
$kind eq "array" and $flag =~ /^is_array_of_/
!ll&&!rl&&r
521024
MC/DC50%1/2
$kind eq "array" and $flag =~ /^is_array_of_/
$kind eq "array" $flag =~ /^is_array_of_/
Truth table66%2/3
A and B
A= $kind eq "array"B= $flag =~ /^is_array_of_/
ABresult
0X0
100
111
939 521 ▶ return 1 if $kind eq 'object' && ($flag eq 'is_object' || $flag eq 'is_inline_struct'
Branch: 1 branch
BranchTrueFalseTotal
if $kind eq "object" and $flag eq "is_object" || $flag eq "is_inline_struct" || $flag eq "is_hash_opaque" || $flag =~ /^is_hash_of_/ 82 439 521
Condition66%8/12
$kind eq "object" and $flag eq "is_object" || $flag eq "is_inline_struct" || $flag eq "is_hash_opaque" || $flag =~ /^is_hash_of_/
!ll&&!rl&&r
439082
$flag eq "is_object" or $flag eq "is_inline_struct" or $flag eq "is_hash_opaque" or $flag =~ /^is_hash_of_/
l!l&&r!l&&!r
70120
$flag eq "is_object" or $flag eq "is_inline_struct" or $flag eq "is_hash_opaque"
l!l&&r!l&&!r
70012
$flag eq "is_object" or $flag eq "is_inline_struct"
l!l&&r!l&&!r
70012
MC/DC20%1/5
$kind eq "object" and $flag eq "is_object" || $flag eq "is_inline_struct" || $flag eq "is_hash_opaque" || $flag =~ /^is_hash_of_/
$kind eq "object" $flag eq "is_object" $flag eq "is_inline_struct" $flag eq "is_hash_opaque" $flag =~ /^is_hash_of_/
Truth table50%3/6
A and B or C or D or E
A= $kind eq "object"B= $flag eq "is_object"C= $flag eq "is_inline_struct"D= $flag eq "is_hash_opaque"E= $flag =~ /^is_hash_of_/
ABCDEresult
0XXXX0
100000
11XXX1
101XX1
1001X1
100011
940 || $flag eq 'is_hash_opaque' || $flag =~ /^is_hash_of_/);
941 439 ▶ return $_TYPE_COMPAT{$kind} ? !!$_TYPE_COMPAT{$kind}{$flag} : 0;
Branch: 1 branch
BranchTrueFalseTotal
$_TYPE_COMPAT{$kind} ? : 439 0 439
942 }
943  
944 # Does $registry_entry (one candidate's _k8s_attr_info entry for a key)
945 # hold a type flag compatible with $kind? Every k8s()-registered attribute
946 # carries exactly one "is_*" classifying flag (is_object plus
947 # is_inline_struct together for an inline struct -- either one matches
948 # 'object'), so one match is enough.
949 507 ▶sub _entry_compatible {
Subroutine _entry_compatible: called CC=3 SCAR=11.0
950 507 my ($entry, $kind) = @_;
951 507 ▶ return !!grep { /^is_/ && $entry->{$_} && _flag_compatible($kind, $_) } keys %$entry;
Condition83%5/6
/^is_/ && $entry->{$_} && _flag_compatible($kind, $_)
!ll&&!rl&&r
33321489
/^is_/ and $entry->{$_}
!ll&&!rl&&r
3330510
MC/DC66%2/3
/^is_/ && $entry->{$_} && _flag_compatible($kind, $_)
/^is_/ $entry->{$_} _flag_compatible($kind, $_)
Truth table75%3/4
A and B && C
A= /^is_/B= $entry->{$_}C= _flag_compatible($kind, $_)
ABCresult
0XX0
10X0
1100
1111
952 }
953  
954 # ---------------------------------------------------------------------------
955 # Container compatibility (k148)
956 #
957 # A flag alone cannot tell whether a candidate's array or map field holds
958 # what the schema says: "an array" matched every is_array_of_* and "an
959 # object" every is_object / is_hash_of_*, so LabelSelectorRequirement
960 # ({key,operator,values}, values [Str]) was reused for a schema whose values
961 # are an array of objects, and the schema's own valid data then failed to
962 # inflate. _field_compatible instead compares the candidate's field with
963 # the type _schema_to_type_spec WOULD give the schema fragment -- read off
964 # the schema the same way that function dispatches on it, without
965 # generating anything -- and recurses into element, value and nested
966 # object shapes:
967 #
968 # scalar -> the scalar rules above, unchanged
969 # array -> items decide: a scalar item kind needs the matching
970 # is_array_of_<scalar> (the scalar rules one level
971 # down); items with properties need is_array_of_objects
972 # whose class matches them (_class_compatible); bare
973 # `type: object` / `type: array` items need
974 # is_array_of_hash / is_array_of_array, what the
975 # generator types them as
976 # object + props -> is_object whose class matches them
977 # object + map -> additionalProperties with properties needs
978 # is_hash_of_objects whose class matches it; a scalar
979 # value kind a typed scalar map (is_hash_of_quantity,
980 # ...) by the scalar rules -- the string map
981 # (is_hash_of_str, labels, annotations) among them, a
982 # `type: string` value needing is_hash_of_str (k191)
983 # opaque object -> see below
984 #
985 # The opaque map, Opaque / is_hash_opaque (arbitrary JSON, fieldsV1,
986 # RawExtension), is its own case: it matches exactly the schema fragments
987 # the generator itself types as Opaque -- an object with neither properties
988 # nor a scalar-valued additionalProperties (an object, array or typeless
989 # value schema, a boolean one, or none; a $ref to %OPAQUE_TYPES; see
990 # _map_value_kind). Reusing it there changes nothing about the field. It
991 # does not match a map of structured objects, a string or typed map, a
992 # structured object, an array or a scalar, however permissive a plain
993 # HashRef is: that would reuse a class that loses the schema's typing, and
994 # a match that cannot be shown is not one. Nor does an opaque schema match
995 # a string map, a typed map or a structured class -- the schema allows
996 # values those reject or would rewrite (a string map puts a number out as
997 # a string) -- with the one exception of ObjectMeta ($OBJECT_META below).
998 # Until k191 the opaque map was spelled { Str => 1 }, and is_hash_of_str
999 # was matched here in its place.
1000 #
1001 # A $ref is resolved read-only against the definitions _core_class_for was
1002 # handed, the way _schema_to_type_spec resolves it: the apimachinery scalars
1003 # are values -- IntOrString the int-or-string kind (k181), Quantity the
1004 # quantity kind and Time the time kind (k185) -- as a property, as items and
1005 # as map values alike (k178, see _scalar_ref_kind), %OPAQUE_TYPES is the
1006 # opaque map, an apiextensions union name is its shipped class
1007 # (%UNION_TYPES), anything else is the object its definition describes. A
1008 # $ref that does not resolve cannot be shown compatible.
1009 #
1010 # Nested classes: every schema property must be declared by the class and
1011 # hold a compatible value (an undeclared one would end in the unknown-field
1012 # bag, or die under strict), the class must not require a key the schema
1013 # lacks, and _overrequires applies as it does one level up -- a nested
1014 # class the nested decision would refuse must not come in through its
1015 # parent. Keys only the class declares are fine otherwise: the reused class
1016 # is looser than the schema there, never lossy (the same direction
1017 # _overrequires accepts).
1018 #
1019 # Recursion: a (class, schema) pair met again while it is still being
1020 # checked further up (a recursive $ref'd definition against a recursive
1021 # class) counts as compatible at the repeat -- that pair's every other field
1022 # is being checked by the frame that entered it, so nothing unchecked is
1023 # waved through, and any finite value of the schema is held by the class.
1024 # The set is path-scoped, like IO::K8s::CRD's own, so a pair that recurs as
1025 # an unrelated sibling is checked again rather than taken on trust.
1026 # ---------------------------------------------------------------------------
1027  
1028 # The one structured class an unstructured object schema stands for. Below
1029 # the root, controller-gen renders an embedded metav1.ObjectMeta as a bare
1030 # `type: object` (the apiserver owns its shape) -- a PVC template's metadata
1031 # inside core Volume's ephemeral source, for one -- so there the schema IS
1032 # ObjectMeta, not some other opaque value, and ObjectMeta holds it, with any
1033 # key it does not declare kept in the unknown-field bag. Refusing it would
1034 # refuse the whole core Volume for every pod template a CRD embeds.
1035 148 my $OBJECT_META = 'IO::K8s::Apimachinery::Pkg::Apis::Meta::V1::ObjectMeta';
1036  
1037 302 ▶sub _field_compatible {
Subroutine _field_compatible: called CC=13 SCAR=35.3
1038 302 my ($entry, $schema, $ctx) = @_;
1039 302 ▶ return 0 unless ref $entry eq 'HASH' && ref $schema eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $entry eq "HASH" and ref $schema eq "HASH" 18 284 302
Condition66%2/3
ref $entry eq "HASH" and ref $schema eq "HASH"
!ll&&!rl&&r
180284
MC/DC50%1/2
ref $entry eq "HASH" and ref $schema eq "HASH"
ref $entry eq "HASH" ref $schema eq "HASH"
Truth table66%2/3
A and B
A= ref $entry eq "HASH"B= ref $schema eq "HASH"
ABresult
0X0
100
111
1040 284 ▶ if (defined(my $ref = $schema->{'$ref'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $ref = $schema->{"\$ref"})) 7 277 284
1041 7 $ref =~ s{^#/definitions/}{};
1042 7 ▶ if (my $kind = _scalar_ref_kind($ref)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $kind = _scalar_ref_kind($ref)) 7 0 7
1043 7 return _entry_compatible($entry, $kind);
1044 }
1045 0 ▶ return !!$entry->{is_hash_opaque} if $OPAQUE_TYPES{$ref};
Branch: 1 branch
BranchTrueFalseTotal
if $OPAQUE_TYPES{$ref} 0 0 0
1046 0 ▶ if (my $union = _union_class($ref)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $union = _union_class($ref)) 0 0 0
1047 0 ▶ return $entry->{is_object} && ($entry->{class} // '') eq $union;
Condition0%0/5
$entry->{'is_object'} && ($entry->{'class'} // '') eq $union
!ll&&!rl&&r
000
$entry->{"class"} // ""
l!l
00
MC/DC0%0/2
$entry->{'is_object'} && ($entry->{'class'} // '') eq $union
$entry->{'is_object'} $entry->{"class"}
Truth table0%0/3
A && B
A= $entry->{'is_object'}B= $entry->{"class"}
ABresult
0X0
100
111
1048 }
1049 0 ▶ my $def = _ref_definition($ref, $ctx) or return 0;
Branch: 1 branch
BranchTrueFalseTotal
my $def = _ref_definition($ref, $ctx) or return 0 0 0 0
1050 0 ▶ return $entry->{is_object} && _class_compatible($entry->{class}, $def, $ctx);
Condition0%0/3
$entry->{'is_object'} && _class_compatible($entry->{'class'}, $def, $ctx)
!ll&&!rl&&r
000
MC/DC0%0/2
$entry->{'is_object'} && _class_compatible($entry->{'class'}, $def, $ctx)
$entry->{'is_object'} _class_compatible($entry->{'class'}, $def, $ctx)
Truth table0%0/3
A && B
A= $entry->{'is_object'}B= _class_compatible($entry->{'class'}, $def, $ctx)
ABresult
0X0
100
111
1051 }
1052 277 my $kind = _schema_type_kind($schema);
1053 277 ▶ return _array_compatible($entry, $schema, $ctx) if $kind eq 'array';
Branch: 1 branch
BranchTrueFalseTotal
if $kind eq "array" 36 241 277
1054 241 ▶ return _object_compatible($entry, $schema, $ctx) if $kind eq 'object';
Branch: 1 branch
BranchTrueFalseTotal
if $kind eq "object" 61 180 241
1055 180 return _entry_compatible($entry, $kind);
1056 }
1057  
1058 36 ▶sub _array_compatible {
Subroutine _array_compatible: called CC=14 SCAR=35.2
1059 36 my ($entry, $schema, $ctx) = @_;
1060 36 ▶ my $items = $schema->{items} // {};
Condition50%1/2
$schema->{"items"} // {}
l!l
360
MC/DC0%0/1
$schema->{"items"} // {}
$schema->{"items"}
Truth table50%1/2
A
A= $schema->{"items"}
Aresult
11
00
1061 36 ▶ return 0 unless ref $items eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $items eq "HASH" 0 36 36
1062 # items with a $ref: an array of the scalar an apimachinery $ref stands
1063 # for, as the generator's items branch types it (k178), else an array of
1064 # the definition's class
1065 36 ▶ if (defined(my $ref = $items->{'$ref'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $ref = $items->{"\$ref"})) 3 33 36
1066 3 $ref =~ s{^#/definitions/}{};
1067 3 ▶ if (my $kind = _scalar_ref_kind($ref)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $kind = _scalar_ref_kind($ref)) 3 0 3
1068 3 return _element_compatible($entry, 'is_array_of_', $kind);
1069 }
1070 0 ▶ if (my $union = _union_class($ref)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $union = _union_class($ref)) 0 0 0
1071 0 ▶ return $entry->{is_array_of_objects} && ($entry->{class} // '') eq $union;
Condition0%0/5
$entry->{'is_array_of_objects'} && ($entry->{'class'} // '') eq $union
!ll&&!rl&&r
000
$entry->{"class"} // ""
l!l
00
MC/DC0%0/2
$entry->{'is_array_of_objects'} && ($entry->{'class'} // '') eq $union
$entry->{'is_array_of_objects'} $entry->{"class"}
Truth table0%0/3
A && B
A= $entry->{'is_array_of_objects'}B= $entry->{"class"}
ABresult
0X0
100
111
1072 }
1073 0 ▶ my $def = _ref_definition($ref, $ctx) or return 0;
Branch: 1 branch
BranchTrueFalseTotal
my $def = _ref_definition($ref, $ctx) or return 0 0 0 0
1074 0 ▶ return $entry->{is_array_of_objects} && _class_compatible($entry->{class}, $def, $ctx);
Condition0%0/3
$entry->{'is_array_of_objects'} && _class_compatible($entry->{'class'}, $def, $ctx)
!ll&&!rl&&r
000
MC/DC0%0/2
$entry->{'is_array_of_objects'} && _class_compatible($entry->{'class'}, $def, $ctx)
$entry->{'is_array_of_objects'} _class_compatible($entry->{'class'}, $def, $ctx)
Truth table0%0/3
A && B
A= $entry->{'is_array_of_objects'}B= _class_compatible($entry->{'class'}, $def, $ctx)
ABresult
0X0
100
111
1075 }
1076 33 ▶ return $entry->{is_array_of_objects} && _class_compatible($entry->{class}, $items, $ctx)
Branch: 1 branch
BranchTrueFalseTotal
if _has_properties($items) 8 25 33
Condition66%2/3
$entry->{'is_array_of_objects'} && _class_compatible($entry->{'class'}, $items, $ctx)
!ll&&!rl&&r
305
MC/DC50%1/2
$entry->{'is_array_of_objects'} && _class_compatible($entry->{'class'}, $items, $ctx)
$entry->{'is_array_of_objects'} _class_compatible($entry->{'class'}, $items, $ctx)
Truth table66%2/3
A && B
A= $entry->{'is_array_of_objects'}B= _class_compatible($entry->{'class'}, $items, $ctx)
ABresult
0X0
100
111
1077 if _has_properties($items);
1078 25 my $kind = _schema_type_kind($items);
1079 25 ▶ return !!$entry->{is_array_of_hash} if $kind eq 'object';
Branch: 1 branch
BranchTrueFalseTotal
if $kind eq "object" 0 25 25
1080 25 ▶ return !!$entry->{is_array_of_array} if $kind eq 'array';
Branch: 1 branch
BranchTrueFalseTotal
if $kind eq "array" 3 22 25
1081 22 return _element_compatible($entry, 'is_array_of_', $kind);
1082 }
1083  
1084 61 ▶sub _object_compatible {
Subroutine _object_compatible: called CC=17 SCAR=39.0
1085 61 my ($entry, $schema, $ctx) = @_;
1086 61 ▶ return $entry->{is_object} && _class_compatible($entry->{class}, $schema, $ctx)
Branch: 1 branch
BranchTrueFalseTotal
if _has_properties($schema) 21 40 61
Condition66%2/3
$entry->{'is_object'} && _class_compatible($entry->{'class'}, $schema, $ctx)
!ll&&!rl&&r
0183
MC/DC50%1/2
$entry->{'is_object'} && _class_compatible($entry->{'class'}, $schema, $ctx)
$entry->{'is_object'} _class_compatible($entry->{'class'}, $schema, $ctx)
Truth table66%2/3
A && B
A= $entry->{'is_object'}B= _class_compatible($entry->{'class'}, $schema, $ctx)
ABresult
0X0
100
111
1087 if _has_properties($schema);
1088 40 my $addl = $schema->{additionalProperties};
1089 # a boolean additionalProperties, or none: the opaque map -- or an
1090 # embedded ObjectMeta (see $OBJECT_META)
1091 40 ▶ unless (ref $addl eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $addl eq "HASH") 30 10 40
1092 30 ▶ return 1 if $entry->{is_hash_opaque};
Branch: 1 branch
BranchTrueFalseTotal
if $entry->{"is_hash_opaque"} 0 30 30
1093 30 ▶ return $entry->{is_object} && ($entry->{class} // '') eq $OBJECT_META;
Condition60%3/5
$entry->{'is_object'} && ($entry->{'class'} // '') eq $OBJECT_META
!ll&&!rl&&r
01416
$entry->{"class"} // ""
l!l
300
MC/DC0%0/2
$entry->{'is_object'} && ($entry->{'class'} // '') eq $OBJECT_META
$entry->{'is_object'} $entry->{"class"}
Truth table33%1/3
A && B
A= $entry->{'is_object'}B= $entry->{"class"}
ABresult
0X0
100
111
1094 }
1095 10 ▶ if (defined(my $ref = $addl->{'$ref'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $ref = $addl->{"\$ref"})) 2 8 10
1096 2 $ref =~ s{^#/definitions/}{};
1097 # the typed map the generator makes of an apimachinery scalar (k178)
1098 2 ▶ if (my $kind = _scalar_ref_kind($ref)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $kind = _scalar_ref_kind($ref)) 2 0 2
1099 2 return _element_compatible($entry, 'is_hash_of_', $kind);
1100 }
1101 0 ▶ if (my $union = _union_class($ref)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $union = _union_class($ref)) 0 0 0
1102 0 ▶ return $entry->{is_hash_of_objects} && ($entry->{class} // '') eq $union;
Condition0%0/5
$entry->{'is_hash_of_objects'} && ($entry->{'class'} // '') eq $union
!ll&&!rl&&r
000
$entry->{"class"} // ""
l!l
00
MC/DC0%0/2
$entry->{'is_hash_of_objects'} && ($entry->{'class'} // '') eq $union
$entry->{'is_hash_of_objects'} $entry->{"class"}
Truth table0%0/3
A && B
A= $entry->{'is_hash_of_objects'}B= $entry->{"class"}
ABresult
0X0
100
111
1103 }
1104 0 ▶ my $def = _ref_definition($ref, $ctx) or return 0;
Branch: 1 branch
BranchTrueFalseTotal
my $def = _ref_definition($ref, $ctx) or return 0 0 0 0
1105 0 ▶ return $entry->{is_hash_of_objects} && _class_compatible($entry->{class}, $def, $ctx);
Condition0%0/3
$entry->{'is_hash_of_objects'} && _class_compatible($entry->{'class'}, $def, $ctx)
!ll&&!rl&&r
000
MC/DC0%0/2
$entry->{'is_hash_of_objects'} && _class_compatible($entry->{'class'}, $def, $ctx)
$entry->{'is_hash_of_objects'} _class_compatible($entry->{'class'}, $def, $ctx)
Truth table0%0/3
A && B
A= $entry->{'is_hash_of_objects'}B= _class_compatible($entry->{'class'}, $def, $ctx)
ABresult
0X0
100
111
1106 }
1107 8 ▶ return $entry->{is_hash_of_objects} && _class_compatible($entry->{class}, $addl, $ctx)
Branch: 1 branch
BranchTrueFalseTotal
if _has_properties($addl) 0 8 8
Condition0%0/3
$entry->{'is_hash_of_objects'} && _class_compatible($entry->{'class'}, $addl, $ctx)
!ll&&!rl&&r
000
MC/DC0%0/2
$entry->{'is_hash_of_objects'} && _class_compatible($entry->{'class'}, $addl, $ctx)
$entry->{'is_hash_of_objects'} _class_compatible($entry->{'class'}, $addl, $ctx)
Truth table0%0/3
A && B
A= $entry->{'is_hash_of_objects'}B= _class_compatible($entry->{'class'}, $addl, $ctx)
ABresult
0X0
100
111
1108 if _has_properties($addl);
1109 # a scalar value schema is the string or typed map the generator makes
1110 # of it, by the scalar rules; anything else it types as the opaque map
1111 8 ▶ return !!$entry->{is_hash_opaque} unless _map_value_kind($addl);
Branch: 1 branch
BranchTrueFalseTotal
unless _map_value_kind($addl) 0 8 8
1112 8 return _element_compatible($entry, 'is_hash_of_', _schema_type_kind($addl));
1113 }
1114  
1115 # Does $entry carry a scalar-element container flag ($prefix plus a scalar
1116 # name: is_array_of_int, is_hash_of_quantity, ...) whose scalar is
1117 # compatible with $kind under the scalar rules? Since k191 is_hash_of_str
1118 # is the string map and counts like is_array_of_str; the opaque map has a
1119 # flag of its own (is_hash_opaque) that never matches a prefix here.
1120 35 ▶sub _element_compatible {
Subroutine _element_compatible: called CC=4 SCAR=13.9
1121 35 my ($entry, $prefix, $kind) = @_;
1122 35 for my $flag (grep { $entry->{$_} } keys %$entry) {
1123 35 ▶ next unless $flag =~ /^\Q$prefix\E(.+)\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $flag =~ /^\Q$prefix\E(.+)\z/ 0 35 35
1124 35 ▶ return 1 if _flag_compatible($kind, 'is_' . $1);
Branch: 1 branch
BranchTrueFalseTotal
if _flag_compatible($kind, 'is_' . $1) 27 8 35
1125 }
1126 8 return 0;
1127 }
1128  
1129 # Does $class hold every value the object schema $schema describes? See
1130 # the block comment above for the rules and the recursion guard.
1131 128 ▶sub _class_compatible {
Subroutine _class_compatible: called CC=13 SCAR=26.8
1132 128 my ($class, $schema, $ctx) = @_;
1133 128 ▶ return 0 unless defined $class && _has_properties($schema);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $class and _has_properties($schema) 0 128 128
Condition33%1/3
defined $class and _has_properties($schema)
!ll&&!rl&&r
00128
MC/DC0%0/2
defined $class and _has_properties($schema)
defined $class _has_properties($schema)
Truth table33%1/3
A and B
A= defined $classB= _has_properties($schema)
ABresult
0X0
100
111
1134 128 my $pair = $class . '|' . refaddr($schema);
1135 128 ▶ return 1 if $ctx->{active}{$pair};
Branch: 1 branch
BranchTrueFalseTotal
if $ctx->{"active"}{$pair} 0 128 128
1136 128 ▶ return 0 unless $class->can('_k8s_attr_info') || eval { use_module($class); 1 };
Branch: 1 branch
BranchTrueFalseTotal
unless $class->can("_k8s_attr_info") or eval { do { &use_module($class); 1 } } 0 128 128
Condition66%2/3
$class->can("_k8s_attr_info") or eval { do { &use_module($class); 1 } }
l!l&&r!l&&!r
11990
MC/DC0%0/2
$class->can("_k8s_attr_info") or eval { do { &use_module($class); 1 } }
$class->can("_k8s_attr_info") eval { do { &use_module($class); 1 } }
Truth table66%2/3
A or B
A= $class->can("_k8s_attr_info")B= eval { do { &use_module($class); 1 } }
ABresult
1X1
011
000
1137 128 local $ctx->{active}{$pair} = 1;
1138  
1139 128 my $by_json = _attrs_by_json_key($class);
1140 128 my $props = $schema->{properties};
1141 128 for my $key (keys %$props) {
1142 276 ▶ return 0 unless _field_compatible($by_json->{$key}, $props->{$key}, $ctx);
Branch: 1 branch
BranchTrueFalseTotal
unless _field_compatible($by_json->{$key}, $props->{$key}, $ctx) 63 213 276
1143 }
1144 65 for my $key (keys %$by_json) {
1145 322 ▶ return 0 if $by_json->{$key}{required} && !exists $props->{$key};
Branch: 1 branch
BranchTrueFalseTotal
if $by_json->{$key}{"required"} and not exists $props->{$key} 0 322 322
Condition66%2/3
$by_json->{$key}{"required"} and not exists $props->{$key}
!ll&&!rl&&r
233890
MC/DC0%0/2
$by_json->{$key}{"required"} and not exists $props->{$key}
$by_json->{$key}{"required"} not exists $props->{$key}
Truth table66%2/3
A and not(B)
A= $by_json->{$key}{"required"}B= not exists $props->{$key}
ABresult
0X0
100
111
1146 }
1147 65 ▶ if (defined $schema->{required}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $schema->{"required"}) 12 53 65
1148 12 my %schema_required = map { $_ => 1 } @{ $schema->{required} };
1149 12 ▶ return 0 if _overrequires([ keys %$props ], \%schema_required, $class);
Branch: 1 branch
BranchTrueFalseTotal
if _overrequires([keys %$props], \%schema_required, $class) 0 12 12
1150 }
1151 65 return 1;
1152 }
1153  
1154 # The definition a $ref names, from the definitions handed to
1155 # _core_class_for, or undef.
1156 0 ▶sub _ref_definition {
Subroutine _ref_definition: not called CC=3 SCAR=24.8
1157 0 my ($ref, $ctx) = @_;
1158 0 ▶ my $def = $ctx->{defs} && $ctx->{defs}{$ref};
Condition0%0/3
$ctx->{'defs'} && $ctx->{'defs'}{$ref}
!ll&&!rl&&r
000
MC/DC0%0/2
$ctx->{'defs'} && $ctx->{'defs'}{$ref}
$ctx->{'defs'} $ctx->{'defs'}{$ref}
Truth table0%0/3
A && B
A= $ctx->{'defs'}B= $ctx->{'defs'}{$ref}
ABresult
0X0
100
111
1159 0 ▶ return ref $def eq 'HASH' ? $def : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $def eq 'HASH' ? : 0 0 0
1160 }
1161  
1162 # $class's registry entries keyed by JSON key rather than attribute name.
1163 128 ▶sub _attrs_by_json_key {
Subroutine _attrs_by_json_key: called CC=3 SCAR=11.4
1164 128 my ($class) = @_;
1165 128 my $info = IO::K8s::Role::Resource::_k8s_attr_info($class);
1166 128 my %by_json;
1167 128 ▶ $by_json{ $info->{$_}{json_key} // $_ } = $info->{$_} for keys %$info;
Condition33%1/3
$info->{$_}{"json_key"} // $_
l!l&&r!l&&!r
05480
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
1168 128 return \%by_json;
1169 }
1170  
1171 # Do every one of @candidates agree, key by key, on type flags (ignoring
1172 # required-ness) and on the referenced class where a key has one? Assumes
1173 # @candidates already share the identical JSON key set (core_class_for_shape
1174 # guarantees that) -- compared by JSON key, not by each candidate's own
1175 # (possibly differently-sanitized) Perl attribute name.
1176 11 ▶sub _wire_identical {
Subroutine _wire_identical: called CC=10 SCAR=24.2
1177 11 my ($keys, @candidates) = @_;
1178 11 ▶ return 1 if @candidates <= 1;
Branch: 1 branch
BranchTrueFalseTotal
if @candidates <= 1 0 11 11
1179 my @by_json = map {
1180 11 my $info = IO::K8s::Role::Resource::_k8s_attr_info($_);
1181 38 ▶ my %j; $j{ $info->{$_}{json_key} // $_ } = $info->{$_} for keys %$info;
Condition33%1/3
$info->{$_}{"json_key"} // $_
l!l&&r!l&&!r
01290
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
1182 38 \%j;
1183 } @candidates;
1184 11 for my $key (@$keys) {
1185 34 my %sig;
1186 34 for my $j (@by_json) {
1187 129 ▶ my $e = $j->{$key} // {};
Condition50%1/2
$j->{$key} // {}
l!l
1290
MC/DC0%0/1
$j->{$key} // {}
$j->{$key}
Truth table50%1/2
A
A= $j->{$key}
Aresult
11
00
1188 129 ▶ my @flags = sort grep { /^is_/ && $e->{$_} } keys %$e;
Condition66%2/3
/^is_/ && $e->{$_}
!ll&&!rl&&r
670129
MC/DC50%1/2
/^is_/ && $e->{$_}
/^is_/ $e->{$_}
Truth table66%2/3
A && B
A= /^is_/B= $e->{$_}
ABresult
0X0
100
111
1189 129 ▶ $sig{ join('|', @flags) . '#' . ($e->{class} // '') } = 1;
Condition50%1/2
$e->{"class"} // ""
l!l
0129
MC/DC0%0/1
$e->{"class"} // ""
$e->{"class"}
Truth table50%1/2
A
A= $e->{"class"}
Aresult
11
00
1190 }
1191 34 ▶ return 0 if keys %sig > 1;
Branch: 1 branch
BranchTrueFalseTotal
if keys %sig > 1 0 34 34
1192 }
1193 11 return 1;
1194 }
1195  
1196 # Does $candidate mark some shared key `required` (Moo-enforced plain
1197 # `required => 1`, or registry-only `required => 'schema'` -- both are
1198 # recorded as `required => 1` in _k8s_attr_info, see IO::K8s::Resource's
1199 # k8s()) that $schema_required does NOT list? One direction only (k136): a
1200 # candidate requiring MORE than the schema is unsafe to reuse -- a real
1201 # cluster object that omits that key would fail ->new() (plain required) or
1202 # be silently dropped on inflate (required => 'schema'), even though the
1203 # schema never promised the field. A schema requiring MORE than the
1204 # candidate is the opposite, harmless direction -- the reused class is
1205 # merely looser than the schema, never lossy -- and is not checked here.
1206 #
1207 # Only called (see _core_class_for) when $schema itself carries a `required`
1208 # key at all -- a schema fragment that omits `required` entirely is treated
1209 # as making no required-ness claim one way or the other, not as an explicit
1210 # "nothing required" (which, strictly, is what JSON Schema says an absent
1211 # `required` means). Every upstream CRD schema actually seen to embed one of
1212 # these reused shapes (LabelSelector's {key,operator,values}, {name,value},
1213 # ...) does carry an explicit `required` list matching the reused class, so
1214 # this distinction changes nothing for real schemas; what it avoids is
1215 # treating a schema fragment that simply never bothered to state `required`
1216 # (as this function's own test fixtures do, and as a hand-written or
1217 # less careful third-party CRD might) as if it had positively declared every
1218 # field optional, which would fall back dozens of well-established, safe
1219 # reuses (LabelSelectorRequirement, HTTPHeader, ...) to nested classes for no
1220 # safety gain.
1221 36 ▶sub _overrequires {
Subroutine _overrequires: called CC=6 SCAR=18.1
1222 36 my ($keys, $schema_required, $candidate) = @_;
1223 36 my $info = IO::K8s::Role::Resource::_k8s_attr_info($candidate);
1224 36 ▶ my %by_json; $by_json{ $info->{$_}{json_key} // $_ } = $info->{$_} for keys %$info;
Condition33%1/3
$info->{$_}{"json_key"} // $_
l!l&&r!l&&!r
01620
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
1225 36 for my $key (@$keys) {
1226 145 ▶ return 1 if $by_json{$key}{required} && !$schema_required->{$key};
Branch: 1 branch
BranchTrueFalseTotal
if $by_json{$key}{"required"} and not $schema_required->{$key} 4 141 145
Condition100%3/3
$by_json{$key}{"required"} and not $schema_required->{$key}
!ll&&!rl&&r
88534
MC/DC100%2/2
$by_json{$key}{"required"} and not $schema_required->{$key}
$by_json{$key}{"required"} not $schema_required->{$key}
Truth table100%3/3
A and not(B)
A= $by_json{$key}{"required"}B= not $schema_required->{$key}
ABresult
0X0
100
111
1227 }
1228 32 return 0;
1229 }
1230  
1231 # The class to reuse for a nested object schema, or undef. $all_defs, the
1232 # definitions the schema's $refs resolve against, is only read (k148).
1233 293 ▶sub _core_class_for {
Subroutine _core_class_for: called CC=14 SCAR=26.5
1234 293 my ($schema, $all_defs) = @_;
1235 293 ▶ return undef unless _has_properties($schema);
Branch: 1 branch
BranchTrueFalseTotal
unless _has_properties($schema) 47 246 293
1236 246 my @keys = sort keys %{ $schema->{properties} };
1237 246 ▶ return undef if @keys < 2; # a single shared key name is too common to trust
Branch: 1 branch
BranchTrueFalseTotal
if @keys < 2 132 114 246
1238 114 my @candidates = core_class_for_shape(\@keys);
1239 114 ▶ return undef unless @candidates;
Branch: 1 branch
BranchTrueFalseTotal
unless @candidates 71 43 114
1240  
1241 # Type-compatibility filter: drop any candidate that types some key
1242 # incompatibly with what the schema itself says that key is.
1243 @candidates = grep {
1244 43 my $info = IO::K8s::Role::Resource::_k8s_attr_info($_);
1245 116 ▶ my %by_json; $by_json{ $info->{$_}{json_key} // $_ } = $info->{$_} for keys %$info;
Condition33%1/3
$info->{$_}{"json_key"} // $_
l!l&&r!l&&!r
03200
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
1246 116 !grep { !_entry_compatible($by_json{$_}, _schema_type_kind($schema->{properties}{$_})) } @keys;
1247 } @candidates;
1248 43 ▶ return undef unless @candidates;
Branch: 1 branch
BranchTrueFalseTotal
unless @candidates 4 39 43
1249  
1250 # Required-compatibility filter (k136): drop any candidate that
1251 # over-constrains the schema -- see _overrequires. Only applied when the
1252 # schema itself declares a `required` list (see that function's comment
1253 # for why an absent one is not treated as an explicit "nothing
1254 # required"). Checked before the single-candidate shortcut and the
1255 # wire-identical tie-break alike, so an over-constrained candidate can
1256 # never be "the one" reuse picks, whether it was alone or one of several
1257 # wire-identical options.
1258 39 ▶ if (defined $schema->{required}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $schema->{"required"}) 6 33 39
1259 6 my %schema_required = map { $_ => 1 } @{ $schema->{required} };
1260  
1261 # k139: remember the shared-vocab candidates (Meta::V1 / Core::V1,
1262 # _core_rank below @CORE_PREFERENCE) that ENTER the required filter,
1263 # to catch the specific fallback the check just below rejects.
1264 6 my @shared_vocab_before = grep { _core_rank($_) < scalar @CORE_PREFERENCE } @candidates;
1265  
1266 6 @candidates = grep { !_overrequires(\@keys, \%schema_required, $_) } @candidates;
1267 6 ▶ return undef unless @candidates;
Branch: 1 branch
BranchTrueFalseTotal
unless @candidates 0 6 6
1268  
1269 # k139: a shared-vocab candidate matched this shape but the required
1270 # filter above eliminated every one of them, leaving only a
1271 # domain-foreign candidate (_core_rank == @CORE_PREFERENCE) to reuse.
1272 # That is the k135/k137 condition case: metav1.Condition matches a
1273 # CRD condition's {lastTransitionTime,message,observedGeneration,
1274 # reason,status,type} shape but over-requires (message/reason/
1275 # lastTransitionTime) relative to a CRD that requires only
1276 # [status,type], so k136 drops it -- and reuse would otherwise fall
1277 # back to an unrelated class that merely shares the shape and the
1278 # narrower required set (Autoscaling::V2::HorizontalPodAutoscaler-
1279 # Condition for a cert-manager IssuerCondition). Return undef so the
1280 # provider's own nested class is generated instead of reusing a
1281 # foreign one. This fires ONLY once a shared-vocab candidate has been
1282 # removed HERE: a shape whose candidates were always domain-specific
1283 # (no Meta/Core member ever) is a genuine sole-family reuse of the
1284 # one real embedded upstream type (NetworkPolicyPort,
1285 # CrossVersionObjectReference, ParamKind, ...) and is left untouched,
1286 # as is a shape where a shared-vocab candidate still survives the
1287 # required filter (Core::V1::NamespaceCondition for the 5-key
1288 # CertificateRequest condition, which requires only [status,type]).
1289 return undef
1290 if @shared_vocab_before
1291 6 ▶ && !grep { _core_rank($_) < scalar @CORE_PREFERENCE } @candidates;
Branch: 1 branch
BranchTrueFalseTotal
if @shared_vocab_before and not grep({_core_rank($_) < scalar @CORE_PREFERENCE;} @candidates) 2 4 6
Condition66%2/3
@shared_vocab_before and not grep({_core_rank($_) < scalar @CORE_PREFERENCE;} @candidates)
!ll&&!rl&&r
042
MC/DC50%1/2
@shared_vocab_before and not grep({_core_rank($_) < scalar @CORE_PREFERENCE;} @candidates)
@shared_vocab_before not grep({_core_rank($_) < scalar @CORE_PREFERENCE;} @candidates)
Truth table66%2/3
A and not(B)
A= @shared_vocab_beforeB= not grep({_core_rank($_) < scalar @CORE_PREFERENCE;} @candidates)
ABresult
0X0
100
111
1292 }
1293 # Recursive-compatibility filter (k148 check, k156 placement): every
1294 # remaining candidate must hold what the schema describes all the way
1295 # down -- array elements, map values, nested objects (see
1296 # _field_compatible / _class_compatible) -- or it is dropped here, ahead
1297 # of the tie-break below. k148 first ran this as a gate on the
1298 # already-picked class (it could only WITHDRAW a reuse); k156 moves it
1299 # ahead of the tie-break so it can also DECIDE one: a shape several
1300 # candidates match by name and type alone (a {metadata,spec} that fits
1301 # every *TemplateSpec) narrows to the single candidate whose deep shape
1302 # holds the schema (only PodTemplateSpec's spec holds a PodSpec, only
1303 # PersistentVolumeClaimTemplate's a PVC spec), and that one is reused
1304 # where before the non-wire-identical tie-break refused them all.
1305 # Wire-identical candidates share their verdict here (same flags, same
1306 # classes per key), so they survive or fall together and the tie-break
1307 # below still sees the same wire-identical set.
1308 @candidates = grep {
1309 37 _class_compatible($_, $schema, { defs => $all_defs, active => {} })
1310 } @candidates;
1311 37 ▶ return undef unless @candidates;
Branch: 1 branch
BranchTrueFalseTotal
unless @candidates 7 30 37
1312  
1313 # Several type-, required- and recursively-compatible candidates: reuse
1314 # the preferred one only if they are wire-identical (already
1315 # preference-sorted by core_class_for_shape, and every filter above
1316 # preserves that order). A single survivor is reused outright.
1317 30 ▶ return @candidates == 1 ? $candidates[0]
Branch: 2 branches
BranchTrueFalseTotal
@candidates == 1 ? : 19 11 30
_wire_identical(\@keys, @candidates) ? : 11 0 11
1318 : _wire_identical(\@keys, @candidates) ? $candidates[0]
1319 : undef;
1320 }
1321  
1322 # The scalar type a $ref to one of the special apimachinery types stands for
1323 # (they are values, not object references), or undef -- as a property, as
1324 # an array's items and as a map's additionalProperties alike (k178).
1325 # Shared by _schema_to_type_spec and the reuse check (_field_compatible), so
1326 # the two read a $ref the same way.
1327 88 ▶sub _scalar_ref_type {
Subroutine _scalar_ref_type: called CC=4 SCAR=13.9
1328 88 my ($ref) = @_;
1329 88 ▶ return 'IntOrStr' if $ref =~ /intstr\.IntOrString$/;
Branch: 1 branch
BranchTrueFalseTotal
if $ref =~ /intstr\.IntOrString$/ 9 79 88
1330 79 ▶ return 'Quantity' if $ref =~ /resource\.Quantity$/;
Branch: 1 branch
BranchTrueFalseTotal
if $ref =~ /resource\.Quantity$/ 16 63 79
1331 63 ▶ return 'Time' if $ref =~ /meta\.v1\.(Micro)?Time$/;
Branch: 1 branch
BranchTrueFalseTotal
if $ref =~ /meta\.v1\.(Micro)?Time$/ 10 53 63
1332 53 return undef;
1333 }
1334  
1335 # The reuse-check kind (see _schema_type_kind) of such a $ref, or undef:
1336 # IntOrString is the int-or-string kind (k181), Quantity the quantity kind
1337 # and Time the time kind (k185) -- each distinct from a plain string, which a
1338 # scalar $ref never is.
1339 12 ▶sub _scalar_ref_kind {
Subroutine _scalar_ref_kind: called CC=4 SCAR=13.9
1340 12 my ($ref) = @_;
1341 12 ▶ my $scalar = _scalar_ref_type($ref) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $scalar = _scalar_ref_type($ref) or return undef 12 0 12
1342 12 ▶ return 'int-or-string' if $scalar eq 'IntOrStr';
Branch: 1 branch
BranchTrueFalseTotal
if $scalar eq "IntOrStr" 5 7 12
1343 7 ▶ return 'quantity' if $scalar eq 'Quantity';
Branch: 1 branch
BranchTrueFalseTotal
if $scalar eq "Quantity" 5 2 7
1344 2 return 'time'; # Time / MicroTime
1345 }
1346  
1347 # The element types of a generated class's scalar arrays (k178). The scalar
1348 # fields of a generated class are the barewords 'Quantity' and 'Time', which
1349 # the DSL builds on Str: any string, so a value the API server stores as
1350 # written -- a custom resource's date-time with a lowercase 't' or 'z' is
1351 # valid RFC 3339 -- never fails to inflate. An array element has to follow
1352 # the same rule, but inside an arrayref the DSL reads a bareword as a class
1353 # name, and the library's Time and Quantity carry the strict regexes a
1354 # hand-written class keeps. So each is Str under the kind's name: the DSL
1355 # and _scalar_kind classify a Type::Tiny element by its name, which is what
1356 # gives it the is_array_of_time / is_array_of_quantity registry flag and
1357 # with that its TO_JSON rule, its to_crd schema and its emitter spelling. A
1358 # Type::Library cannot hold a second Time, so these stay private here
1359 # rather than becoming an export of IO::K8s::Types. IntOrStr is Str in the
1360 # library already.
1361 148 my $GENERATED_TIME = Str->create_child_type(name => 'Time');
1362 148 my $GENERATED_QUANTITY = Str->create_child_type(name => 'Quantity');
1363 148 my %GENERATED_ITEM_TYPE = (
1364 IntOrStr => IntOrStr,
1365 Quantity => $GENERATED_QUANTITY,
1366 Time => $GENERATED_TIME,
1367 );
1368  
1369 # The value types of a generated scalar map, HashRef[X] (k191), by the kind
1370 # _map_value_kind reads off additionalProperties. Time is the lenient
1371 # $GENERATED_TIME for the reason the array element above is.
1372 148 my %GENERATED_MAP_VALUE_TYPE = (
1373 Str => Str,
1374 Int => Int,
1375 Num => Num,
1376 Bool => Bool,
1377 IntOrStr => IntOrStr,
1378 Time => $GENERATED_TIME,
1379 );
1380  
1381 # Convert OpenAPI schema to k8s() type spec
1382 #
1383 # $field_name and $class are diagnostic context only: everything this
1384 # function refuses has to name the class being generated and the field it
1385 # choked on, because the caller sees neither (the k42 diagnostic line).
1386 #
1387 # $reuse_core (D5, default 1) turns the object / array-items /
1388 # additionalProperties reuse check on or off (see _core_class_for).
1389 760 ▶sub _schema_to_type_spec {
Subroutine _schema_to_type_spec: called CC=57 SCAR=41.3
1390 760 my ($schema, $all_defs, $namespace, $field_name, $class, $reuse_core, $reuse_core_except) = @_;
1391 760 ▶ $reuse_core = 1 unless defined $reuse_core;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $reuse_core 0 760 760
1392 760 ▶ $reuse_core_except ||= {};
Condition50%1/2
$reuse_core_except ||= {}
l!l
7600
MC/DC0%0/1
$reuse_core_except ||= {}
$reuse_core_except
Truth table50%1/2
A
A= $reuse_core_except
Aresult
11
00
1393  
1394 # k120: reuse core here unless this field's would-be nested class sits
1395 # at a path the caller marked for suppression (see reuse_core_except in
1396 # _generate_class). $suffix matches the _nested_class call in the same
1397 # branch: 'Item' for array items, undef for a plain object, 'Value' for
1398 # additionalProperties.
1399 297 ▶ my $may_reuse = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1400 297 my ($suffix) = @_;
1401 297 ▶ return 0 unless $reuse_core;
Branch: 1 branch
BranchTrueFalseTotal
unless $reuse_core 14 283 297
1402 283 return !$reuse_core_except->{ _prospective_nested_path($class, $field_name, $suffix) };
1403 760 };
1404  
1405 760 my $where = "field '" . $field_name . "' of " . $class;
1406  
1407 # Handle $ref
1408 760 ▶ if (my $ref = $schema->{'$ref'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ref = $schema->{"\$ref"}) 45 715 760
1409 45 $ref =~ s{^#/definitions/}{};
1410  
1411 # Special apimachinery types - not object references
1412 45 ▶ if (my $scalar = _scalar_ref_type($ref)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $scalar = _scalar_ref_type($ref)) 9 36 45
1413 9 return $scalar;
1414 }
1415  
1416 # apiextensions union types: the shipped FROM_STRUCT class (k152)
1417 36 ▶ if (my $union = _union_class($ref)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $union = _union_class($ref)) 15 21 36
1418 15 return "+$union";
1419 }
1420  
1421 # Opaque types should be the free map, not object references
1422 21 ▶ if ($OPAQUE_TYPES{$ref}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($OPAQUE_TYPES{$ref}) 0 21 21
1423 0 return Opaque;
1424 }
1425  
1426 # Generate referenced class if needed
1427 21 ▶ if ($all_defs && $all_defs->{$ref}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($all_defs and $all_defs->{$ref}) 11 10 21
Condition66%2/3
$all_defs and $all_defs->{$ref}
!ll&&!rl&&r
01011
MC/DC50%1/2
$all_defs and $all_defs->{$ref}
$all_defs $all_defs->{$ref}
Truth table66%2/3
A and B
A= $all_defsB= $all_defs->{$ref}
ABresult
0X0
100
111
1428 11 my $ref_class = get_or_generate($ref, $all_defs->{$ref}, $all_defs, $namespace);
1429 11 return "+$ref_class"; # + prefix for full class name
1430 }
1431 10 _croak_unresolved_ref($ref, $where);
1432 }
1433  
1434 # A structural CRD schema marks Kubernetes' IntOrString union type with
1435 # this extension, almost always instead of `type` rather than alongside
1436 # it (the pruning rules for x-kubernetes-int-or-string require either no
1437 # `type` or an `anyOf`) -- checked before the type dispatch below, which
1438 # would otherwise read the type-less shape as "unknown type" and fall
1439 # back to Str. Found via IO::K8s::CRD::Emitter's stronger assertion on
1440 # the registry type flag (t/74_crd_emitter.t): t/73_add_crd.t's own
1441 # same-named subtest passed regardless, since a Str-typed attribute
1442 # holds a plain IntOrString value like '10Gi' exactly as well as an
1443 # IntOrStr-typed one does. The swagger v2 `format: int-or-string`
1444 # convention below still works for a schema that keeps `type: string`.
1445 #
1446 # Unlike the nullable/preserve_unknown checks in _field_options (Minor 6
1447 # of the k93 review, deliberately left unwrapped: a schema property is
1448 # always a plain scalar or JSON boolean there), this call sits ahead of
1449 # the type dispatch below rather than after it -- a malformed value here
1450 # must not abort class generation outright, so it is wrapped in eval and
1451 # treated as false, falling through to the ordinary `type`-based
1452 # dispatch instead.
1453 return 'IntOrStr'
1454 715 ▶ if eval { IO::K8s::Resource::_normalize_bool($schema->{'x-kubernetes-int-or-string'}) };
Branch: 1 branch
BranchTrueFalseTotal
if eval { do { IO::K8s::Resource::_normalize_bool($schema->{"x-kubernetes-int-or-string"}) } } 21 694 715
1455  
1456 694 ▶ my $type = $schema->{type} // '';
Condition50%1/2
$schema->{"type"} // ""
l!l
6940
MC/DC0%0/1
$schema->{"type"} // ""
$schema->{"type"}
Truth table50%1/2
A
A= $schema->{"type"}
Aresult
11
00
1457  
1458 694 ▶ if ($type eq 'string') {
Branch: 6 branches
BranchTrueFalseTotal
if ($type eq 'string') { } 214 480 694
elsif ($type eq 'integer') { } 86 394 480
elsif ($type eq 'number') { } 3 391 394
elsif ($type eq 'boolean') { } 28 363 391
elsif ($type eq 'array') { } 77 286 363
elsif ($type eq 'object') { } 286 0 286
1459 214 ▶ my $format = $schema->{format} // '';
Condition100%2/2
$schema->{"format"} // ""
l!l
5209
MC/DC100%1/1
$schema->{"format"} // ""
$schema->{"format"}
Truth table100%2/2
A
A= $schema->{"format"}
Aresult
11
00
1460 214 ▶ return 'IntOrStr' if $format eq 'int-or-string';
Branch: 1 branch
BranchTrueFalseTotal
if $format eq "int-or-string" 2 212 214
1461 212 ▶ return 'Time' if $format eq 'date-time';
Branch: 1 branch
BranchTrueFalseTotal
if $format eq "date-time" 3 209 212
1462 209 return 'Str';
1463 }
1464 elsif ($type eq 'integer') {
1465 86 return 'Int';
1466 }
1467 elsif ($type eq 'number') {
1468 3 return 'Num'; # A genuine JSON number -- unquoted on the wire (k68)
1469 }
1470 elsif ($type eq 'boolean') {
1471 28 return 'Bool';
1472 }
1473 elsif ($type eq 'array') {
1474 77 ▶ my $items = $schema->{items} // {};
Condition50%1/2
$schema->{"items"} // {}
l!l
770
MC/DC0%0/1
$schema->{"items"} // {}
$schema->{"items"}
Truth table50%1/2
A
A= $schema->{"items"}
Aresult
11
00
1475 77 ▶ if (my $ref = $items->{'$ref'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ref = $items->{"\$ref"}) 12 65 77
1476 12 $ref =~ s{^#/definitions/}{};
1477 # The apimachinery scalars are values here too (k178): generated
1478 # from their definitions -- a bare `type: string` -- they used to
1479 # become an empty class no element could inflate into.
1480 12 ▶ if (my $scalar = _scalar_ref_type($ref)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $scalar = _scalar_ref_type($ref)) 6 6 12
1481 6 return [ $GENERATED_ITEM_TYPE{$scalar} ];
1482 }
1483 6 ▶ if (my $union = _union_class($ref)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $union = _union_class($ref)) 5 1 6
1484 5 return ["+$union"];
1485 }
1486 1 ▶ if ($all_defs && $all_defs->{$ref}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($all_defs and $all_defs->{$ref}) 0 1 1
Condition33%1/3
$all_defs and $all_defs->{$ref}
!ll&&!rl&&r
010
MC/DC0%0/2
$all_defs and $all_defs->{$ref}
$all_defs $all_defs->{$ref}
Truth table33%1/3
A and B
A= $all_defsB= $all_defs->{$ref}
ABresult
0X0
100
111
1487 0 my $ref_class = get_or_generate($ref, $all_defs->{$ref}, $all_defs, $namespace);
1488 0 return ["+$ref_class"];
1489 }
1490 1 _croak_unresolved_ref($ref, "the items of $where");
1491 }
1492 65 ▶ if ($may_reuse->('Item') and my $core = _core_class_for($items, $all_defs)) {
Branch: 1 branch
BranchTrueFalseTotal
if (&$may_reuse("Item") and my $core = _core_class_for($items, $all_defs)) 2 63 65
Condition100%3/3
&$may_reuse("Item") and my $core = _core_class_for($items, $all_defs)
!ll&&!rl&&r
6572
MC/DC100%2/2
&$may_reuse("Item") and my $core = _core_class_for($items, $all_defs)
&$may_reuse("Item") my $core = _core_class_for($items, $all_defs)
Truth table100%3/3
A and B
A= &$may_reuse("Item")B= my $core = _core_class_for($items, $all_defs)
ABresult
0X0
100
111
1493 2 return [ "+$core" ];
1494 }
1495 63 ▶ if (_has_properties($items)) {
Branch: 1 branch
BranchTrueFalseTotal
if (_has_properties($items)) 23 40 63
1496 23 return [ '+' . _nested_class($class, $field_name, 'Item', $items, $all_defs, $namespace, $reuse_core, $reuse_core_except) ];
1497 }
1498 # Type::Tiny objects rather than the barewords: inside an arrayref
1499 # the DSL reads a plain string as a class name for everything except
1500 # 'Str' and 'Int', so ['Bool'] would ask for an array of
1501 # IO::K8s::Api::Bool objects. [Bool] is the form that reaches the
1502 # is_array_of_bool branch and its per-element normalization, which is
1503 # what an array of schema-true JSON booleans needs (k57). Number
1504 # items get [Num], the array form of the scalar number case (k68):
1505 # they used to fall through to [ Str ] below, and a [Str] element
1506 # goes out as a JSON string since k145 (k155). int-or-string and
1507 # date-time items are the same gap for the scalar IntOrStr / Time
1508 # cases above (k167), read off the items exactly as those read the
1509 # property: the extension first, a format only with `type: string`.
1510 # [IntOrStr] keeps an element 8080 a number on the wire; a [Time]
1511 # element accepts what the scalar Time of a generated class accepts
1512 # (k178, see %GENERATED_ITEM_TYPE).
1513 return [ IntOrStr ]
1514 40 ▶ if eval { IO::K8s::Resource::_normalize_bool($items->{'x-kubernetes-int-or-string'}) };
Branch: 1 branch
BranchTrueFalseTotal
if eval { do { IO::K8s::Resource::_normalize_bool($items->{"x-kubernetes-int-or-string"}) } } 6 34 40
1515 34 ▶ if (($items->{type} // '') eq 'string') {
Branch: 1 branch
BranchTrueFalseTotal
if (($items->{"type"} // "") eq "string") 18 16 34
Condition100%2/2
$items->{"type"} // ""
l!l
331
MC/DC100%1/1
$items->{"type"} // ""
$items->{"type"}
Truth table100%2/2
A
A= $items->{"type"}
Aresult
11
00
1516 18 ▶ my $format = $items->{format} // '';
Condition100%2/2
$items->{"format"} // ""
l!l
108
MC/DC100%1/1
$items->{"format"} // ""
$items->{"format"}
Truth table100%2/2
A
A= $items->{"format"}
Aresult
11
00
1517 18 ▶ return [ IntOrStr ] if $format eq 'int-or-string';
Branch: 1 branch
BranchTrueFalseTotal
if $format eq "int-or-string" 1 17 18
1518 17 ▶ return [ $GENERATED_TIME ] if $format eq 'date-time';
Branch: 1 branch
BranchTrueFalseTotal
if $format eq "date-time" 9 8 17
1519 }
1520 24 ▶ my $item_type = $items->{type} // 'string';
Condition100%2/2
$items->{"type"} // "string"
l!l
231
MC/DC100%1/1
$items->{"type"} // "string"
$items->{"type"}
Truth table100%2/2
A
A= $items->{"type"}
Aresult
11
00
1521 24 ▶ return [ Int ] if $item_type eq 'integer';
Branch: 1 branch
BranchTrueFalseTotal
if $item_type eq "integer" 3 21 24
1522 21 ▶ return [ Num ] if $item_type eq 'number';
Branch: 1 branch
BranchTrueFalseTotal
if $item_type eq "number" 4 17 21
1523 17 ▶ return [ Bool ] if $item_type eq 'boolean';
Branch: 1 branch
BranchTrueFalseTotal
if $item_type eq "boolean" 3 14 17
1524 # items: object / array with no further structure -> an array of
1525 # opaque hashes / opaque arrays. Before k66 both fell through to
1526 # [ Str ] below and rejected the very hashrefs/arrayrefs the schema
1527 # describes.
1528 14 ▶ return [ {} ] if $item_type eq 'object';
Branch: 1 branch
BranchTrueFalseTotal
if $item_type eq "object" 3 11 14
1529 11 ▶ return [ [] ] if $item_type eq 'array';
Branch: 1 branch
BranchTrueFalseTotal
if $item_type eq "array" 2 9 11
1530 9 return [ Str ]; # string, and the default for anything unmodelled
1531 }
1532 elsif ($type eq 'object') {
1533 286 ▶ if (_has_properties($schema)) {
Branch: 1 branch
BranchTrueFalseTotal
if (_has_properties($schema)) 220 66 286
1534 220 ▶ if ($may_reuse->(undef) and my $core = _core_class_for($schema, $all_defs)) {
Branch: 1 branch
BranchTrueFalseTotal
if (&$may_reuse(undef) and my $core = _core_class_for($schema, $all_defs)) 19 201 220
Condition100%3/3
&$may_reuse(undef) and my $core = _core_class_for($schema, $all_defs)
!ll&&!rl&&r
819319
MC/DC100%2/2
&$may_reuse(undef) and my $core = _core_class_for($schema, $all_defs)
&$may_reuse(undef) my $core = _core_class_for($schema, $all_defs)
Truth table100%3/3
A and B
A= &$may_reuse(undef)B= my $core = _core_class_for($schema, $all_defs)
ABresult
0X0
100
111
1535 19 return "+$core";
1536 }
1537 201 return '+' . _nested_class($class, $field_name, undef, $schema, $all_defs, $namespace, $reuse_core, $reuse_core_except);
1538 }
1539 66 my $addl = $schema->{additionalProperties};
1540 66 ▶ if (ref $addl eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $addl eq "HASH") 31 35 66
1541 31 ▶ if (my $ref = $addl->{'$ref'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ref = $addl->{"\$ref"}) 19 12 31
1542 19 $ref =~ s{^#/definitions/}{};
1543 # The DSL's typed map of the scalar (k178), as for items
1544 # above: { Quantity => 1 } is what a ResourceList is. It is
1545 # the DSL's one typed map, so its values are checked against
1546 # the library types -- for Quantity and Time the strict
1547 # form a hand-written map carries. A $ref only comes from a
1548 # swagger definition (a CRD schema has none), and the API
1549 # server writes both of those scalars in canonical form.
1550 19 ▶ if (my $scalar = _scalar_ref_type($ref)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $scalar = _scalar_ref_type($ref)) 8 11 19
1551 8 return { $scalar => 1 };
1552 }
1553 11 ▶ if (my $union = _union_class($ref)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $union = _union_class($ref)) 10 1 11
1554 10 return { "+$union" => 1 };
1555 }
1556 1 ▶ if ($all_defs && $all_defs->{$ref}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($all_defs and $all_defs->{$ref}) 0 1 1
Condition33%1/3
$all_defs and $all_defs->{$ref}
!ll&&!rl&&r
010
MC/DC0%0/2
$all_defs and $all_defs->{$ref}
$all_defs $all_defs->{$ref}
Truth table33%1/3
A and B
A= $all_defsB= $all_defs->{$ref}
ABresult
0X0
100
111
1557 0 my $ref_class = get_or_generate($ref, $all_defs->{$ref}, $all_defs, $namespace);
1558 0 return { "+$ref_class" => 1 };
1559 }
1560 1 _croak_unresolved_ref($ref, "the additionalProperties of $where");
1561 }
1562 12 ▶ if ($may_reuse->('Value') and my $core = _core_class_for($addl, $all_defs)) {
Branch: 1 branch
BranchTrueFalseTotal
if (&$may_reuse("Value") and my $core = _core_class_for($addl, $all_defs)) 0 12 12
Condition66%2/3
&$may_reuse("Value") and my $core = _core_class_for($addl, $all_defs)
!ll&&!rl&&r
2100
MC/DC0%0/2
&$may_reuse("Value") and my $core = _core_class_for($addl, $all_defs)
&$may_reuse("Value") my $core = _core_class_for($addl, $all_defs)
Truth table66%2/3
A and B
A= &$may_reuse("Value")B= my $core = _core_class_for($addl, $all_defs)
ABresult
0X0
100
111
1563 0 return { "+$core" => 1 };
1564 }
1565 12 ▶ if (_has_properties($addl)) {
Branch: 1 branch
BranchTrueFalseTotal
if (_has_properties($addl)) 1 11 12
1566 1 return { '+' . _nested_class($class, $field_name, 'Value', $addl, $all_defs, $namespace, $reuse_core, $reuse_core_except) => 1 };
1567 }
1568 # A scalar value schema is the string map HashRef[Str] or the
1569 # typed map of its kind; anything else -- object or array
1570 # values, a value schema without a type -- the free map (k191).
1571 # Before k191 every one of them became the then-opaque
1572 # { Str => 1 }.
1573 11 my $value_kind = _map_value_kind($addl);
1574 11 ▶ return $value_kind ? HashRef[ $GENERATED_MAP_VALUE_TYPE{$value_kind} ] : Opaque;
Branch: 1 branch
BranchTrueFalseTotal
$value_kind ? : 11 0 11
1575 }
1576 # additionalProperties is allowed to be a JSON boolean instead of a
1577 # schema -- true: any extra property, false: none. A JSON::PP::Boolean
1578 # is a blessed scalar ref, so the $ref lookup above used to die "Not a
1579 # HASH reference" naming neither class nor field (k55). Neither
1580 # boolean says anything about the value types, so the field stays the
1581 # same free map (Opaque) a schemaless object gets.
1582 35 ▶ if (defined $addl) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $addl) 4 31 35
1583 4 my $reftype = reftype($addl);
1584 4 ▶ croak "additionalProperties of $where is a " . $reftype
Branch: 1 branch
BranchTrueFalseTotal
if defined $reftype and $reftype ne "SCALAR" 2 2 4
Condition66%2/3
defined $reftype and $reftype ne "SCALAR"
!ll&&!rl&&r
022
MC/DC50%1/2
defined $reftype and $reftype ne "SCALAR"
defined $reftype $reftype ne "SCALAR"
Truth table66%2/3
A and B
A= defined $reftypeB= $reftype ne "SCALAR"
ABresult
0X0
100
111
1585 . " reference; expected a schema object or a boolean"
1586 if defined $reftype && $reftype ne 'SCALAR';
1587 }
1588 33 return Opaque; # Generic object -> the free map (k191)
1589 }
1590  
1591 # Unknown type
1592 0 return 'Str';
1593 }
1594  
1595 # The scalar type a DSL type spec is built on -- Str, Int, Num, Bool,
1596 # IntOrStr, Quantity, Time -- or undef for objects, structs and the opaque
1597 # container forms. Value constraints (enum, minimum, maximum, pattern) only
1598 # make sense on the former; passing one to the DSL for the latter would
1599 # croak at class generation.
1600 148 my %SCALAR_KIND = map { $_ => 1 } qw( Str Int Num Bool IntOrStr Quantity Time );
1601  
1602 742 ▶sub _scalar_kind {
Subroutine _scalar_kind: called CC=17 SCAR=28.9
1603 742 my ($type_spec) = @_;
1604 742 ▶ if (!ref $type_spec) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $type_spec) 603 139 742
1605 603 ▶ return $SCALAR_KIND{$type_spec} ? $type_spec : undef;
Branch: 1 branch
BranchTrueFalseTotal
$SCALAR_KIND{$type_spec} ? : 361 242 603
1606 }
1607 139 ▶ if (ref $type_spec eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $type_spec eq "ARRAY") 76 63 139
1608 76 my $elem = $type_spec->[0];
1609 76 ▶ return undef if ref $elem eq 'HASH' || ref $elem eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $elem eq "HASH" or ref $elem eq "ARRAY" 5 71 76
Condition100%3/3
ref $elem eq "HASH" or ref $elem eq "ARRAY"
l!l&&r!l&&!r
3271
MC/DC100%2/2
ref $elem eq "HASH" or ref $elem eq "ARRAY"
ref $elem eq "HASH" ref $elem eq "ARRAY"
Truth table100%3/3
A or B
A= ref $elem eq "HASH"B= ref $elem eq "ARRAY"
ABresult
1X1
011
000
1610 # Mirror _k8s's own array-element handling exactly (Important 4 of
1611 # the k93 review): a Type::Tiny element is a scalar kind only when
1612 # its name is one of the seven the DSL knows, and a bareword
1613 # string element is a scalar kind only for 'Str' and 'Int' -- _k8s
1614 # treats every other bareword (including the kind names 'Num',
1615 # 'Bool', 'Quantity', 'Time', 'IntOrStr' spelled as plain strings)
1616 # as a class name and hands it to _expand_class.
1617 71 ▶ if (blessed($elem) && $elem->isa('Type::Tiny')) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($elem) and $elem->isa("Type::Tiny")) 41 30 71
Condition66%2/3
builtin::blessed($elem) and $elem->isa("Type::Tiny")
!ll&&!rl&&r
30041
MC/DC50%1/2
builtin::blessed($elem) and $elem->isa("Type::Tiny")
builtin::blessed($elem) $elem->isa("Type::Tiny")
Truth table66%2/3
A and B
A= builtin::blessed($elem)B= $elem->isa("Type::Tiny")
ABresult
0X0
100
111
1618 41 ▶ return $SCALAR_KIND{$elem->name} ? $elem->name : undef;
Branch: 1 branch
BranchTrueFalseTotal
$SCALAR_KIND{$elem->name} ? : 41 0 41
1619 }
1620 30 ▶ return undef if ref $elem;
Branch: 1 branch
BranchTrueFalseTotal
if ref $elem 0 30 30
1621 30 ▶ return ($elem eq 'Str' || $elem eq 'Int') ? $elem : undef;
Branch: 1 branch
BranchTrueFalseTotal
$elem eq 'Str' || $elem eq 'Int' ? : 0 30 30
Condition33%1/3
$elem eq "Str" or $elem eq "Int"
l!l&&r!l&&!r
0030
MC/DC0%0/2
$elem eq "Str" or $elem eq "Int"
$elem eq "Str" $elem eq "Int"
Truth table33%1/3
A or B
A= $elem eq "Str"B= $elem eq "Int"
ABresult
1X1
011
000
1622 }
1623 63 ▶ if (ref $type_spec eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $type_spec eq "HASH") 19 44 63
1624 19 my ($k) = keys %$type_spec;
1625 # { Str => 1 } is the lenient string map, which takes no value
1626 # option (IO::K8s::Resource); typed maps carry their value kind.
1627 19 ▶ return undef if $k eq 'Str';
Branch: 1 branch
BranchTrueFalseTotal
if $k eq "Str" 0 19 19
1628 19 ▶ return $SCALAR_KIND{$k} ? $k : undef;
Branch: 1 branch
BranchTrueFalseTotal
$SCALAR_KIND{$k} ? : 8 11 19
1629 }
1630 # HashRef[X] (k191): the value type's kind, Str included -- the strict
1631 # string map takes value options; Opaque none.
1632 44 ▶ if (my $value_type = _map_value_type($type_spec)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $value_type = _map_value_type($type_spec)) 11 33 44
1633 11 ▶ return $SCALAR_KIND{ $value_type->name } ? $value_type->name : undef;
Branch: 1 branch
BranchTrueFalseTotal
$SCALAR_KIND{$value_type->name} ? : 11 0 11
1634 }
1635 33 return undef;
1636 }
1637  
1638 # The value type of a HashRef[X] type spec, or undef for anything else.
1639 447 ▶sub _map_value_type {
Subroutine _map_value_type: called CC=5 SCAR=16.2
1640 447 my ($type_spec) = @_;
1641 447 ▶ return undef unless blessed($type_spec) && $type_spec->isa('Type::Tiny')
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($type_spec) and $type_spec->isa("Type::Tiny") and $type_spec->is_parameterized and $type_spec->parameterized_from->name eq "HashRef" 425 22 447
Condition77%7/9
builtin::blessed($type_spec) and $type_spec->isa("Type::Tiny") and $type_spec->is_parameterized and $type_spec->parameterized_from->name eq "HashRef"
!ll&&!rl&&r
425022
builtin::blessed($type_spec) and $type_spec->isa("Type::Tiny") and $type_spec->is_parameterized
!ll&&!rl&&r
3923322
builtin::blessed($type_spec) and $type_spec->isa("Type::Tiny")
!ll&&!rl&&r
392055
MC/DC50%2/4
builtin::blessed($type_spec) and $type_spec->isa("Type::Tiny") and $type_spec->is_parameterized and $type_spec->parameterized_from->name eq "HashRef"
builtin::blessed($type_spec) $type_spec->isa("Type::Tiny") $type_spec->is_parameterized $type_spec->parameterized_from->name eq "HashRef"
Truth table60%3/5
A and B and C and D
A= builtin::blessed($type_spec)B= $type_spec->isa("Type::Tiny")C= $type_spec->is_parameterizedD= $type_spec->parameterized_from->name eq "HashRef"
ABCDresult
0XXX0
10XX0
110X0
11100
11111
1642 && $type_spec->is_parameterized
1643 && $type_spec->parameterized_from->name eq 'HashRef';
1644 22 return $type_spec->type_parameter;
1645 }
1646  
1647 # A typed map of either spelling: { X => 1 } or HashRef[X].
1648 385 ▶sub _is_map_spec {
Subroutine _is_map_spec: called CC=3 SCAR=11.0
1649 385 my ($type_spec) = @_;
1650 385 ▶ return ref $type_spec eq 'HASH' || _map_value_type($type_spec) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
ref $type_spec eq 'HASH' || _map_value_type($type_spec) ? : 22 363 385
Condition100%3/3
ref $type_spec eq "HASH" or _map_value_type($type_spec)
l!l&&r!l&&!r
1111363
MC/DC100%2/2
ref $type_spec eq "HASH" or _map_value_type($type_spec)
ref $type_spec eq "HASH" _map_value_type($type_spec)
Truth table100%3/3
A or B
A= ref $type_spec eq "HASH"B= _map_value_type($type_spec)
ABresult
1X1
011
000
1651 }
1652  
1653 # Field options for one property (D3). Schema-only facts (description,
1654 # default, nullable, x-kubernetes-preserve-unknown-fields) travel for every
1655 # field; the value constraints only where the DSL can enforce them. For an
1656 # array the constraints sit on `items` and apply per element.
1657 #
1658 # required => 'schema' (not 1): the schema's required list is a fact for
1659 # to_crd, not a client-side guarantee. A cluster document can validly omit
1660 # a field the schema requires -- a server-side default, or an object still
1661 # short of that field (an empty status right after creation) -- and
1662 # rejecting inflate over that would reject real cluster data. required =>
1663 # 1 would enforce it at construction; see IO::K8s::Resource/k8s (Critical
1664 # 1 of the k93 review).
1665 #
1666 # A pattern is an ECMA 262 regex on the wire. Perl compiles nearly all of
1667 # them; one it cannot is dropped rather than failing the whole class -- the
1668 # client-side check is a convenience, the API server validates regardless,
1669 # and no data is lost (the k56 line is about data, not about checks). An
1670 # empty enum, a duplicate enum, or an enum containing a JSON null is
1671 # dropped the same way; minimum/maximum are dropped (individually, if only
1672 # one bound is bad, or both together when minimum exceeds maximum) when
1673 # either fails to parse as a number; and a default the field cannot hold --
1674 # wrong type, or outside its own enum/range -- is dropped rather than
1675 # refused at generation time the way a hand-written k8s declaration would
1676 # refuse it (Important 2 of the k93 review).
1677 #
1678 # `default: null` in a schema (common on a `nullable: true` field) decodes
1679 # to undef; that is treated as no default at all, not as a default of
1680 # undef, since the DSL's own field-option check refuses an undef value for
1681 # any option, and a null default carries no information for the
1682 # client-side check anyway.
1683 742 ▶sub _field_options {
Subroutine _field_options: called CC=57 SCAR=42.9
1684 742 my ($prop_schema, $type_spec, $is_required) = @_;
1685 742 my %opts;
1686 742 ▶ $opts{required} = 'schema' if $is_required;
Branch: 1 branch
BranchTrueFalseTotal
if $is_required 63 679 742
1687 742 ▶ $opts{description} = $prop_schema->{description} if defined $prop_schema->{description};
Branch: 1 branch
BranchTrueFalseTotal
if defined $prop_schema->{"description"} 66 676 742
1688 742 ▶ $opts{default} = $prop_schema->{default} if defined $prop_schema->{default};
Branch: 1 branch
BranchTrueFalseTotal
if defined $prop_schema->{"default"} 36 706 742
1689 # nullable and x-kubernetes-preserve-unknown-fields are JSON booleans on
1690 # the wire and so need the same normalization every other Bool value in
1691 # the distribution gets (plain Perl truthiness would treat the string
1692 # 'false' as true). _normalize_bool only dies on a value that cannot
1693 # mean true or false at all (a non-scalar reference); a schema property
1694 # is always a plain scalar or JSON boolean here, so there is nothing for
1695 # an eval to usefully swallow (Minor 6 of the k93 review).
1696 $opts{nullable} = 1
1697 742 ▶ if IO::K8s::Resource::_normalize_bool($prop_schema->{nullable});
Branch: 1 branch
BranchTrueFalseTotal
if IO::K8s::Resource::_normalize_bool($prop_schema->{"nullable"}) 8 734 742
1698 $opts{preserve_unknown} = 1
1699 742 ▶ if IO::K8s::Resource::_normalize_bool($prop_schema->{'x-kubernetes-preserve-unknown-fields'});
Branch: 1 branch
BranchTrueFalseTotal
if IO::K8s::Resource::_normalize_bool($prop_schema->{"x-kubernetes-preserve-unknown-fields"}) 17 725 742
1700  
1701 742 my $kind = _scalar_kind($type_spec);
1702 # A schema decoded from JSON carries a boolean default as a
1703 # JSON::PP::Boolean (or similar) blessed scalar ref, which fails the
1704 # field's own Bool constraint at class-generation time (_k8s's own
1705 # default-vs-type check). Normalize it the one way the distribution
1706 # normalizes every other Bool value rather than duplicating that rule
1707 # here (IO::K8s::Resource::_normalize_bool's own comment: "The one
1708 # boolean normalization in the distribution"). $kind is 'Bool' for both
1709 # the scalar Bool field and the [Bool] array field (_scalar_kind reads
1710 # through the array wrapper), but the default's own shape differs: a
1711 # [Bool] default is itself an arrayref of JSON booleans, and
1712 # _normalize_bool only accepts a scalar or scalar ref -- handing it the
1713 # arrayref whole would die and kill class generation over an entirely
1714 # legal default. Normalize per element instead, and drop the default
1715 # (rather than refuse generation) if any element cannot mean true/false,
1716 # the same "malformed default is dropped" rule every other option here
1717 # follows (carried over from the step-2 final re-review).
1718 742 ▶ if ($kind && $kind eq 'Bool' && exists $opts{default}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind and $kind eq "Bool" and exists $opts{"default"}) 4 738 742
Condition100%6/6
$kind and $kind eq "Bool" and exists $opts{"default"}
!ll&&!rl&&r
711274
$kind and $kind eq "Bool"
!ll&&!rl&&r
32139031
MC/DC100%3/3
$kind and $kind eq "Bool" and exists $opts{"default"}
$kind $kind eq "Bool" exists $opts{"default"}
Truth table100%4/4
A and B and C
A= $kindB= $kind eq "Bool"C= exists $opts{"default"}
ABCresult
0XX0
10X0
1100
1111
1719 4 ▶ if (_is_map_spec($type_spec)) {
Branch: 2 branches
BranchTrueFalseTotal
if (_is_map_spec($type_spec)) { } 0 4 4
elsif (ref $type_spec eq 'ARRAY') { } 2 2 4
1720 # A map of Bool (k191): the default is a hash, normalized value
1721 # by value and dropped when a value cannot mean true/false, as
1722 # the array case below does per element.
1723 0 my %normalized;
1724 0 ▶ if (ref $opts{default} eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $opts{"default"} eq "HASH") 0 0 0
1725 0 for my $key (keys %{ $opts{default} }) {
1726 0 my $n = eval { IO::K8s::Resource::_normalize_bool($opts{default}{$key}) };
1727 0 ▶ last if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
1728 0 $normalized{$key} = $n;
1729 }
1730 }
1731 0 ▶ if (ref $opts{default} eq 'HASH' && keys %normalized == keys %{ $opts{default} }) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $opts{'default'} eq 'HASH' and keys %normalized == keys %{$opts{'default'};}) { } 0 0 0
Condition0%0/3
ref $opts{"default"} eq "HASH" and keys %normalized == keys %{$opts{"default"};}
!ll&&!rl&&r
000
MC/DC0%0/2
ref $opts{"default"} eq "HASH" and keys %normalized == keys %{$opts{"default"};}
ref $opts{"default"} eq "HASH" keys %normalized == keys %{$opts{"default"};}
Truth table0%0/3
A and B
A= ref $opts{"default"} eq "HASH"B= keys %normalized == keys %{$opts{"default"};}
ABresult
0X0
100
111
1732 0 $opts{default} = \%normalized;
1733 } else {
1734 0 delete $opts{default};
1735 }
1736 } elsif (ref $type_spec eq 'ARRAY') {
1737 2 my @normalized;
1738 2 ▶ if (ref $opts{default} eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $opts{"default"} eq "ARRAY") 2 0 2
1739 2 for my $elem (@{ $opts{default} }) {
1740 4 my $n = eval { IO::K8s::Resource::_normalize_bool($elem) };
1741 4 ▶ last if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 1 3 4
1742 3 push @normalized, $n;
1743 }
1744 }
1745 2 ▶ if (ref $opts{default} eq 'ARRAY' && @normalized == @{ $opts{default} }) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $opts{'default'} eq 'ARRAY' and @normalized == @{$opts{'default'};}) { } 1 1 2
Condition66%2/3
ref $opts{"default"} eq "ARRAY" and @normalized == @{$opts{"default"};}
!ll&&!rl&&r
011
MC/DC50%1/2
ref $opts{"default"} eq "ARRAY" and @normalized == @{$opts{"default"};}
ref $opts{"default"} eq "ARRAY" @normalized == @{$opts{"default"};}
Truth table66%2/3
A and B
A= ref $opts{"default"} eq "ARRAY"B= @normalized == @{$opts{"default"};}
ABresult
0X0
100
111
1746 1 $opts{default} = \@normalized;
1747 } else {
1748 1 delete $opts{default};
1749 }
1750 } else {
1751 2 $opts{default} = IO::K8s::Resource::_normalize_bool($opts{default});
1752 }
1753 }
1754 742 ▶ if ($kind && $kind ne 'Bool') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind and $kind ne "Bool") 390 352 742
Condition100%3/3
$kind and $kind ne "Bool"
!ll&&!rl&&r
32131390
MC/DC100%2/2
$kind and $kind ne "Bool"
$kind $kind ne "Bool"
Truth table100%3/3
A and B
A= $kindB= $kind ne "Bool"
ABresult
0X0
100
111
1755 # A typed map (k178) constrains each value, as an array each
1756 # element: its constraints sit on additionalProperties.
1757 my $src = ($prop_schema->{type} // '') eq 'array' ? ($prop_schema->{items} // {})
1758 : _is_map_spec($type_spec) ? $prop_schema->{additionalProperties}
1759 390 ▶ : $prop_schema;
Branch: 2 branches
BranchTrueFalseTotal
($prop_schema->{'type'} // '') eq 'array' ? : 38 352 390
_is_map_spec($type_spec) ? : 19 333 352
Condition75%3/4
$prop_schema->{"type"} // ""
l!l
36426
$prop_schema->{"items"} // {}
l!l
380
MC/DC100%1/1
$prop_schema->{"type"} // ""
$prop_schema->{"type"}
MC/DC0%0/1
$prop_schema->{"items"} // {}
$prop_schema->{"items"}
Truth table100%2/2
A
A= $prop_schema->{"type"}
Aresult
11
00
Truth table50%1/2
A
A= $prop_schema->{"items"}
Aresult
11
00
1760 390 ▶ if (ref $src->{enum} eq 'ARRAY' && @{ $src->{enum} } && !grep { !defined } @{ $src->{enum} }) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $src->{"enum"} eq "ARRAY" and @{$src->{"enum"};} and not grep({not defined $_;} @{$$src{"enum"};})) 24 366 390
Condition83%5/6
ref $src->{"enum"} eq "ARRAY" and @{$src->{"enum"};} and not grep({not defined $_;} @{$$src{"enum"};})
!ll&&!rl&&r
365124
ref $src->{"enum"} eq "ARRAY" and @{$src->{"enum"};}
!ll&&!rl&&r
365025
MC/DC66%2/3
ref $src->{"enum"} eq "ARRAY" and @{$src->{"enum"};} and not grep({not defined $_;} @{$$src{"enum"};})
ref $src->{"enum"} eq "ARRAY" @{$src->{"enum"};} not grep({not defined $_;} @{$$src{"enum"};})
Truth table75%3/4
A and B and not(C)
A= ref $src->{"enum"} eq "ARRAY"B= @{$src->{"enum"};}C= not grep({not defined $_;} @{$$src{"enum"};})
ABCresult
0XX0
10X0
1100
1111
1761 24 my %seen;
1762 24 $seen{$_}++ for @{ $src->{enum} };
1763 24 ▶ $opts{enum} = $src->{enum} if keys %seen == @{ $src->{enum} };
Branch: 1 branch
BranchTrueFalseTotal
if keys %seen == @{$src->{"enum"};} 24 0 24
1764 }
1765 390 ▶ if ($kind eq 'Int' || $kind eq 'Num') {
Branch: 2 branches
BranchTrueFalseTotal
if ($kind eq 'Int' or $kind eq 'Num') { } 97 293 390
elsif (defined $src->{'pattern'}) { } 34 259 293
Condition100%3/3
$kind eq "Int" or $kind eq "Num"
l!l&&r!l&&!r
907293
MC/DC100%2/2
$kind eq "Int" or $kind eq "Num"
$kind eq "Int" $kind eq "Num"
Truth table100%3/3
A or B
A= $kind eq "Int"B= $kind eq "Num"
ABresult
1X1
011
000
1766 97 my ($min, $max) = @{$src}{qw(minimum maximum)};
1767 97 ▶ $min = undef if defined $min && !looks_like_number($min);
Branch: 1 branch
BranchTrueFalseTotal
if defined $min and not &looks_like_number($min) 2 95 97
Condition100%3/3
defined $min and not &looks_like_number($min)
!ll&&!rl&&r
57382
MC/DC100%2/2
defined $min and not &looks_like_number($min)
defined $min not &looks_like_number($min)
Truth table100%3/3
A and not(B)
A= defined $minB= not &looks_like_number($min)
ABresult
0X0
100
111
1768 97 ▶ $max = undef if defined $max && !looks_like_number($max);
Branch: 1 branch
BranchTrueFalseTotal
if defined $max and not &looks_like_number($max) 0 97 97
Condition66%2/3
defined $max and not &looks_like_number($max)
!ll&&!rl&&r
77200
MC/DC0%0/2
defined $max and not &looks_like_number($max)
defined $max not &looks_like_number($max)
Truth table66%2/3
A and not(B)
A= defined $maxB= not &looks_like_number($max)
ABresult
0X0
100
111
1769 97 ▶ if (defined $min && defined $max && $min > $max) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $min and defined $max and $min > $max) 2 95 97
Condition100%6/6
defined $min and defined $max and $min > $max
!ll&&!rl&&r
79162
defined $min and defined $max
!ll&&!rl&&r
592018
MC/DC100%3/3
defined $min and defined $max and $min > $max
defined $min defined $max $min > $max
Truth table100%4/4
A and B and C
A= defined $minB= defined $maxC= $min > $max
ABCresult
0XX0
10X0
1100
1111
1770 2 $min = $max = undef;
1771 }
1772 97 ▶ $opts{minimum} = $min if defined $min;
Branch: 1 branch
BranchTrueFalseTotal
if defined $min 36 61 97
1773 97 ▶ $opts{maximum} = $max if defined $max;
Branch: 1 branch
BranchTrueFalseTotal
if defined $max 18 79 97
1774 } elsif (defined $src->{pattern}) {
1775 34 my $re = eval { my $p = $src->{pattern}; qr/$p/ };
1776 34 ▶ $opts{pattern} = $re if $re;
Branch: 1 branch
BranchTrueFalseTotal
if $re 32 2 34
1777 }
1778 }
1779  
1780 # A default the field cannot hold kills class generation via _k8s's own
1781 # default-vs-type check unless it is dropped here first. Built from the
1782 # same (already-filtered) enum/minimum/maximum/pattern collected above
1783 # so the check matches what _k8s itself would enforce. Object-bearing
1784 # and opaque fields ($kind undef) keep the default as given -- there is
1785 # no scalar Type::Tiny check to run there, and to_crd validates it
1786 # against the schema instead (Important 3 of the k93 review; _k8s's own
1787 # default check now skips those fields too).
1788 742 ▶ if (exists $opts{default} && $kind) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $opts{"default"} and $kind) 35 707 742
Condition66%2/3
exists $opts{"default"} and $kind
!ll&&!rl&&r
707035
MC/DC50%1/2
exists $opts{"default"} and $kind
exists $opts{"default"} $kind
Truth table66%2/3
A and B
A= exists $opts{"default"}B= $kind
ABresult
0X0
100
111
1789 # An array's element type is the Type::Tiny object in the spec (k167);
1790 # a typed map's value type is the library type of that name, the one
1791 # IO::K8s::Resource's { X => 1 } form checks each value against --
1792 # the strict Quantity and Time among them (k178). A default that is
1793 # a hash, for a map, is checked value by value.
1794 35 ▶ my $base = ref $type_spec eq 'ARRAY' && blessed($type_spec->[0]) ? $type_spec->[0]
Branch: 3 branches
BranchTrueFalseTotal
ref $type_spec eq 'ARRAY' && builtin::blessed($type_spec->[0]) ? : 6 29 35
_map_value_type($type_spec) ? : 0 29 29
ref $type_spec eq 'HASH' ? : 3 26 29
Condition66%2/3
ref $type_spec eq "ARRAY" and builtin::blessed($type_spec->[0])
!ll&&!rl&&r
2906
MC/DC50%1/2
ref $type_spec eq "ARRAY" and builtin::blessed($type_spec->[0])
ref $type_spec eq "ARRAY" builtin::blessed($type_spec->[0])
Truth table66%2/3
A and B
A= ref $type_spec eq "ARRAY"B= builtin::blessed($type_spec->[0])
ABresult
0X0
100
111
1795 : _map_value_type($type_spec) ? _map_value_type($type_spec)
1796 : ref $type_spec eq 'HASH' ? IO::K8s::Types->get_type($kind)
1797 : IO::K8s::Resource::_scalar_base_for($kind);
1798 35 my %check_opts = map { $_ => $opts{$_} } grep { exists $opts{$_} } qw(enum minimum maximum pattern);
1799 35 my $constrained = IO::K8s::Resource::_constrain($base, $kind, \%check_opts, 'AutoGen default check');
1800 my $default_ok = ref $type_spec eq 'ARRAY'
1801 8 ▶ ? (ref $opts{default} eq 'ARRAY' && !grep { !$constrained->check($_) } @{ $opts{default} })
Branch: 1 branch
BranchTrueFalseTotal
_is_map_spec($type_spec) ? : 3 26 29
Condition100%3/3
ref $opts{"default"} eq "HASH" and not grep({not $constrained->check($_);} values %{$opts{"default"};})
!ll&&!rl&&r
111
MC/DC100%2/2
ref $opts{"default"} eq "HASH" and not grep({not $constrained->check($_);} values %{$opts{"default"};})
ref $opts{"default"} eq "HASH" not grep({not $constrained->check($_);} values %{$opts{"default"};})
Truth table100%3/3
A and not(B)
A= ref $opts{"default"} eq "HASH"B= not grep({not $constrained->check($_);} values %{$opts{"default"};})
ABresult
0X0
100
111
1802 : _is_map_spec($type_spec)
1803 3 ? (ref $opts{default} eq 'HASH' && !grep { !$constrained->check($_) } values %{ $opts{default} })
1804 35 ▶ : $constrained->check($opts{default});
Branch: 1 branch
BranchTrueFalseTotal
ref $type_spec eq 'ARRAY' ? : 6 29 35
Condition66%2/3
ref $opts{"default"} eq "ARRAY" and not grep({not $constrained->check($_);} @{$opts{"default"};})
!ll&&!rl&&r
024
MC/DC50%1/2
ref $opts{"default"} eq "ARRAY" and not grep({not $constrained->check($_);} @{$opts{"default"};})
ref $opts{"default"} eq "ARRAY" not grep({not $constrained->check($_);} @{$opts{"default"};})
Truth table66%2/3
A and not(B)
A= ref $opts{"default"} eq "ARRAY"B= not grep({not $constrained->check($_);} @{$opts{"default"};})
ABresult
0X0
100
111
1805 35 ▶ delete $opts{default} unless $default_ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $default_ok 8 27 35
1806 }
1807  
1808 742 ▶ return %opts ? \%opts : undef;
Branch: 1 branch
BranchTrueFalseTotal
%opts ? : 212 530 742
1809 }
1810  
1811 # Ensure parent packages exist
1812 404 ▶sub _ensure_package_exists {
Subroutine _ensure_package_exists: called CC=5 SCAR=16.1
1813 404 my ($class) = @_;
1814 404 my @parts = split /::/, $class;
1815 404 pop @parts; # Remove the final class name
1816  
1817 404 my $current = '';
1818 404 for my $part (@parts) {
1819 3183 ▶ $current .= '::' if $current;
Branch: 1 branch
BranchTrueFalseTotal
if $current 2779 404 3183
1820 3183 $current .= $part;
1821 148 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
1822 3183 ▶ unless (%{"${current}::"}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (%{"${current}::";}) 695 2488 3183
1823 # Create empty package
1824 695 ▶ eval "package $current; 1;" or warn "Could not create package $current: $@";
Branch: 1 branch
BranchTrueFalseTotal
eval "package $current; 1;" or warn "Could not create package ${current}: $@" 695 0 695
1825 }
1826 }
1827 }
1828  
1829 # Clear generated class cache (mainly for testing). %_failed is left alone on
1830 # purpose: forgetting a failure would let the next request return the
1831 # half-built package that failed run left behind (k149).
1832 32 ▶sub clear_cache {
Subroutine clear_cache: called CC=1 SCAR=0.0
Pod documented
1833 32 %_generated = ();
1834 32 %_nested_origin = ();
1835 32 %_descriptions = ();
1836 32 %_root_of = ();
1837 32 %_class_path = ();
1838 }
1839  
1840 # The schema `description` a generated class was built from, or undef when
1841 # the schema had none. See IO::K8s::CRD::Emitter, the only consumer.
1842 114 ▶sub class_description {
Subroutine class_description: called CC=1 SCAR=0.0
Pod documented
1843 114 my ($class) = @_;
1844 114 return $_descriptions{$class};
1845 }
1846  
1847 # The top-level generated class (the Kind class) a nested class's naming
1848 # started from, or $class itself when it already is one -- a root is never
1849 # recorded in %_root_of, so this always falls back correctly. See
1850 # IO::K8s::CRD::Emitter, which needs the true root to decide whether a
1851 # reachable class belongs to the tree it is currently rendering.
1852 342 ▶sub class_root {
Subroutine class_root: called CC=2 SCAR=7.1
Pod documented
1853 342 my ($class) = @_;
1854 342 ▶ return $_root_of{$class} // $class;
Condition66%2/3
$_root_of{$class} // $class
l!l&&r!l&&!r
323190
MC/DC0%0/2
$_root_of{$class} // $class
$_root_of{$class} $class
Truth table66%2/3
A // B
A= $_root_of{$class}B= $class
ABresult
1X1
011
000
1855 }
1856  
1857 # The '::'-joined path a nested class sits at below its root
1858 # ('Spec::Acme::SolversItem::...'), recorded even when the class's own Perl
1859 # name had to be shortened (see $MAX_CLASS_NAME). undef for a root class, or
1860 # for any class AutoGen did not generate through _nested_class.
1861 418 ▶sub class_path {
Subroutine class_path: called CC=1 SCAR=0.0
Pod documented
1862 418 my ($class) = @_;
1863 418 return $_class_path{$class};
1864 }
1865  
1866 # List all generated classes -- complete ones only; a class begun by a run
1867 # that failed is never listed (k149)
1868 5 ▶sub generated_classes {
Subroutine generated_classes: called CC=1 SCAR=0.0
Pod documented
1869 5 return keys %_generated;
1870 }
1871  
1872 148 1;
1873  
1874 __END__
« blib/lib/IO/K8s/Resource.pm ↑ Summary blib/lib/IO/K8s/Role/APIObject.pm »