Xrepo/Build.pm

filter: Statementstmt 80.0% 8 / 10 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 4 / 4 Podpod n/a totaltotal 85.7% 12 / 14 CC 1 SCAR 2.2
CC
1
Cov
80%
BEGIN
2.0
BEGIN
1.0
BEGIN
1.0
CRAP 1.2
« Xrepo.pm ↑ Summary Xrepo/MM.pm »
1 2 ▶use v5.40;
Subroutine BEGIN: called CC=1 SCAR=0.0
2 2 ▶use feature 'class';
Subroutine BEGIN: called CC=1 SCAR=0.0
3 2 ▶no warnings 'experimental::class';
Subroutine BEGIN: called CC=1 SCAR=0.0
4 #
5 class Alien::Xrepo::Build v1.0.10 {
6 0 ▶ use Alien::Xrepo;
Subroutine BEGIN: called CC=1 SCAR=6.9
7 use Alien::Xrepo::Build::Recipe;
8 use Path::Tiny;
9 use JSON::PP qw[encode_json decode_json];
10 use Config ();
11 #
12 my @STAGES = qw[configure probe install gather export test];
13 #
14 field $recipe : param; # Recipe object (or path/dir, normalized in ADJUST)
15 field $root : param //= undef; # xrepo store root (XMAKE_PKG_INSTALLDIR)
16 field $verbose : param //= 0;
17 field $diagnosis : param //= 0; # forward the engine's -D to xmake require for install failures
18 field $cache : param //= 1; # forward the engine's warm-start cache to Alien::Xrepo
19 field $repo : param //= undef; # injectable engine (spy-able)
20 field $checkpoint : param //= undef; # state file path; enables resume
21 field $snapshot : param //= undef; # write gathered runtime data as JSON here
22 field $export_dir : param //= undef; # also xrepo-export each package into this dir
23 field $share_dir : param //= undef; # shallow-install packages into <share_dir>/<pkg> (self-contained dist)
24 field $probe_policy : param //= 'skip'; # skip|always|off
25 field $resume : param //= 0;
26 field $update_repo : param //= 0; # on install failure, `xrepo update-repo` once, then retry once
27  
28 #
29 field $loaded_hooks = {}; # recipe hook modules already registered
30  
31 #
32 field $hooks = {}; # stage => [ coderef, ... ]
33 field $meta_prop : reader = {};
34 field $install_prop : reader = {};
35 field $runtime_prop : reader = {};
36 field $stage_done : reader = {};
37 field $install_type : reader = 'system';
38 field $r : reader(engine) = undef; # resolved Alien::Xrepo engine
39  
40 #
41 method packages () { return $recipe->packages }
42 method package_defs () { return $recipe->package_defs }
43 #
44 ADJUST {
45 if ( ref $recipe eq 'HASH' ) {
46 $recipe = Alien::Xrepo::Build::Recipe->new(%$recipe);
47 }
48 elsif ( !ref $recipe ) {
49 $recipe = Alien::Xrepo::Build::Recipe->new( defined $recipe && -d $recipe ? ( dir => $recipe ) : ( file => $recipe ), );
50 }
51 die "probe_policy must be skip|always|off" unless $probe_policy =~ /^(?:skip|always|off)$/;
52 $r = $repo // Alien::Xrepo->new( root => $root, verbose => $verbose, diagnosis => $diagnosis, cache => $cache );
53 if ($resume) {
54 $self->_load_checkpoint;
55 $self->configure( resume => 1 ) unless $stage_done->{configure};
56 }
57 }
58  
59 # Hooks. A hook is invoked with ($self) immediately before its stage body.
60 method register_hook ( $stage, $hook ) {
61 die "Unknown stage '$stage'. Stages: @STAGES" unless grep { $_ eq $stage } @STAGES;
62 die 'hook must be a coderef' unless ref $hook eq 'CODE';
63 push @{ $hooks->{$stage} //= [] }, $hook;
64 return;
65 }
66 method has_hook ($stage) { return $hooks->{$stage} && @{ $hooks->{$stage} } ? 1 : 0 }
67  
68 method run_hooks ($stage) {
69 $_->($self) for @{ $hooks->{$stage} // [] };
70 return;
71 }
72  
73 method run (%opts) {
74 $self->configure(%opts);
75 $self->probe;
76 $self->install;
77 $self->gather;
78 $self->export;
79 $self->test;
80 $self;
81 }
82  
83 method assert_installed () {
84 my $errors = $runtime_prop->{errors} // {};
85 return $self unless %$errors;
86 if ( defined $snapshot && length $snapshot ) {
87 my $file = path($snapshot);
88 $file->remove if -e $file;
89 }
90 my @failed = sort keys %$errors;
91 my $fatal = grep { $errors->{$_}{fatal} // 0 } @failed;
92 my $line
93 = 'Alien::Xrepo: failed to install ' .
94 join( ', ', @failed ) . ":\n" .
95 join( "\n", map { " $_: " . ( ref $errors->{$_} eq 'HASH' ? $errors->{$_}{error} : $errors->{$_} ) } @failed ) . "\n";
96 $fatal ? die $line : warn $line;
97 $self; # In case it's non-fatal...
98 }
99  
100 method configure (%opts) {
101 $self->_load_recipe_hooks;
102 return if $stage_done->{configure};
103 $self->run_hooks('configure');
104 $meta_prop = {
105 name => $recipe->name,
106 packages => [ $recipe->packages ],
107 package_defs => $recipe->package_defs,
108 defaults => $recipe->defaults,
109 pkg_roots => $recipe->pkg_roots,
110 local_repos => [ @{ $recipe->local_repos } ],
111 hooks => [ @{ $recipe->hooks } ]
112 };
113 my %profile = ( %{ $recipe->defaults }, %opts );
114 $profile{configs} = { %{ $recipe->defaults->{configs} // {} }, %{ $opts{configs} // {} } }
115 if ref $recipe->defaults->{configs} eq 'HASH' || ref $opts{configs} eq 'HASH';
116 my $store;
117 eval { $store = $r->_store_dir( installdir => $root ) };
118 $store //= $root;
119 $install_prop = { root => $root, profile => \%profile, probed => {}, store => $store, share_dir => $share_dir, };
120  
121 for my $repo_def ( @{ $recipe->local_repos } ) {
122 my $dir = path($repo_def)->absolute;
123 my $nm = 'alien-' . $dir->basename;
124 next unless $dir->child('packages')->is_dir;
125 say "[xrepo] registering local recipe repo $nm from $dir..." if $verbose;
126 eval { $r->add_repo( $nm, $dir->stringify ) };
127 }
128 $install_type = 'system';
129 $stage_done->{configure} = 1;
130 $self->_checkpoint;
131 $self;
132 }
133  
134 method probe () {
135 return if $stage_done->{probe};
136 $self->run_hooks('probe');
137 $install_prop->{probed} ||= {};
138 if ( $probe_policy ne 'off' ) {
139 for my $name ( $recipe->packages ) {
140 if ( my $root = $self->_pkg_root($name) ) {
141 $install_prop->{probed}{$name} = { version => undef, satisfied => 1, root => $root };
142 next;
143 }
144 my %opts = $recipe->opts_for( $name, %{ $install_prop->{profile} // {} } );
145 my $inst = $self->_pkg_installdir($name);
146 $opts{installdir} = $inst if defined $inst;
147 my $expected = $recipe->version_for($name);
148 my $found;
149 eval {
150 my $info = $r->info( $name, format => 'json', %opts );
151 $found = ref $info eq 'HASH' ? ( $info->{version} // $info->{package}{version} // undef ) : undef;
152 };
153 $install_prop->{probed}{$name} = { version => $found, satisfied => $self->_probe_satisfied( $found, $expected ) };
154 }
155 }
156 $stage_done->{probe} = 1;
157 $self->_checkpoint;
158 $self;
159 }
160  
161 method install () {
162 return if $stage_done->{install};
163 $self->run_hooks('install');
164 $runtime_prop->{packages} ||= {};
165 $runtime_prop->{errors} ||= {};
166 my $profile = $install_prop->{profile} // {};
167 for my $name ( $self->_install_order ) {
168 if ( my $root = $self->_pkg_root($name) ) {
169 $runtime_prop->{packages}{$name} = $self->_root_entry($root);
170 say "[xrepo] $name satisfied by " . $recipe->pkg_roots->{$name} . "=$root; skipping install" if $verbose;
171 next;
172 }
173 my %opts = $recipe->opts_for( $name, %$profile );
174 my $inst = $self->_pkg_installdir($name);
175 $opts{installdir} = $inst if defined $inst;
176 if ( $self->_can_skip_install($name) ) {
177 say "[xrepo] $name already satisfied by the store; skipping install" if $verbose;
178 next;
179 }
180 my $version = $recipe->version_for($name);
181 say "Installing $name" . ( defined $version && length $version ? " $version" : '' ) . '...' if $verbose;
182 my %env = $self->_manager_tool_env($name);
183 local @ENV{ keys %env } = values %env if %env;
184 my $info;
185 while (1) {
186 $info = eval { $r->install( $name, $version, %opts ) };
187 last if $info || !$@;
188  
189 # Bounded recovery: one refresh-and-retry per package per build tree.
190 # The count lives in runtime_prop, which _checkpoint persists, so a
191 # resumed Build cannot start the cycle over for the same package --
192 # without that, every run of an install the registry cannot satisfy
193 # repeats the refresh and the retry never terminates.
194 if ( $update_repo && !$runtime_prop->{retries}{$name} ) {
195 $runtime_prop->{retries}{$name} = 1;
196 $self->_checkpoint;
197 say "[xrepo] $name install failed; refreshing repositories to retry once..." if $verbose;
198 eval { $r->update_repo };
199 next;
200 }
201 warn "[!] $name failed to install: $@\n";
202 $runtime_prop->{errors}{$name} //= { name => $name, error => "$@", fatal => $recipe->required($name) };
203 last;
204 }
205 if ( ref $info eq 'Alien::Xrepo::PackageInfo' ) {
206 my $data = $info->_data_printer(undef);
207 $self->_attach_runtime_deps( $name, $data, %opts );
208 $runtime_prop->{packages}{$name} = $data;
209 $install_type = 'share';
210 }
211 }
212 $stage_done->{install} = 1;
213 $self->_checkpoint;
214 $self;
215 }
216  
217 method gather () {
218 return if $stage_done->{gather};
219 $self->run_hooks('gather');
220 $runtime_prop->{packages} ||= {};
221 my $profile = $install_prop->{profile} // {};
222 for my $name ( $recipe->packages ) {
223 next if exists $runtime_prop->{packages}{$name} || exists $runtime_prop->{errors}{$name};
224 if ( my $root = $self->_pkg_root($name) ) {
225 $runtime_prop->{packages}{$name} = $self->_root_entry($root);
226 next;
227 }
228 my %opts = $recipe->opts_for( $name, %$profile );
229 my $inst = $self->_pkg_installdir($name);
230 $opts{installdir} = $inst if defined $inst;
231 my %env = $self->_manager_tool_env($name);
232 local @ENV{ keys %env } = values %env if %env;
233 my $info;
234 eval { $info = $r->fetch( $name, $recipe->version_for($name), %opts ); };
235  
236 if ($@) {
237 warn "[!] $name could not be gathered: $@\n";
238 $runtime_prop->{errors}{$name} //= { name => $name, error => "$@", fatal => $recipe->required($name) };
239 next;
240 }
241 if ( ref $info eq 'Alien::Xrepo::PackageInfo' ) {
242 my $data = $info->_data_printer(undef);
243 $self->_attach_runtime_deps( $name, $data, %opts );
244 $runtime_prop->{packages}{$name} = $data;
245 $install_type = 'share';
246 }
247 }
248 $stage_done->{gather} = 1;
249 $self->_checkpoint;
250 $self;
251 }
252  
253 # Post-install diagnostic: once a package is installed/gathered, ask the engine which shared libraries its
254 # FFI library needs at dlopen time and record them on the package data. They then ride into the snapshot and
255 # out through Alien::Xrepo::Runtime::package_info, so a consumer learns what else must be loadable instead of
256 # hitting an opaque loader error later. Guarded on engine capability, so spy engines are left untouched.
257 method _attach_runtime_deps ( $name, $data, %opts ) {
258 return unless $r->can('runtime_deps') && $r->can('fetch_closure');
259 my $libpath = $data->{libpath};
260 return unless defined $libpath && length $libpath && -f $libpath;
261  
262 # Resolve against the package closure (transitive providers such as freetype behind libsdl3_ttf), not the
263 # shallow <share>/<pkg> dir, so clear installdir and fall back to the engine's store root.
264 my %fetch_opts = %opts;
265 delete $fetch_opts{installdir};
266 my @entries = eval { $r->fetch_closure( $name, $recipe->version_for($name), %fetch_opts ) };
267 my ( $search, $store ) = $r->can('dep_search_dirs') ? $r->dep_search_dirs( \@entries ) : ( [], [] );
268 my %seen = map { $_ => 1 } @$search;
269 my $add = sub { my $d = shift; return unless defined $d && length $d; push @$search, $d unless $seen{$d}++ };
270  
271 # Everything already recorded in this run is also fair game to resolve against.
272 for my $other ( values %{ $runtime_prop->{packages} // {} } ) {
273 my $id = $other->{installdir};
274 if ( defined $id && length $id ) {
275 push @$store, $id;
276 $add->( path($id)->child($_)->stringify ) for qw[bin lib];
277 }
278 $add->($_) for @{ $other->{linkdirs} // [] }, @{ $other->{bindirs} // [] };
279 }
280 $add->( path($libpath)->parent->stringify );
281 push @$store, $data->{installdir} if defined $data->{installdir} && length $data->{installdir};
282 my $deps = eval { $r->runtime_deps( $libpath, search_dirs => $search, store_dirs => $store ) };
283 return unless ref $deps eq 'ARRAY';
284 $data->{runtime_deps} = $deps;
285 my @missing = grep { ( $_->{scope} // '' ) eq 'unresolved' } @$deps;
286 warn "[!] $name: unresolved runtime dependencies (not found in the store or system paths): " .
287 join( ', ', map { $_->{name} } @missing ) . "\n"
288 if @missing;
289 return;
290 }
291  
292 method export () {
293 return if $stage_done->{export};
294 $self->run_hooks('export');
295 if ( my $dir = $export_dir ) {
296 for my $name ( $recipe->packages ) {
297 next if exists $runtime_prop->{errors}{$name};
298 say "Exporting $name into $dir..." if $verbose;
299 eval { $r->export( $name, $recipe->version_for($name), packagedir => path($dir)->child($name)->absolute ); };
300 warn "[!] $name could not be exported: $@\n" if $@;
301 }
302 }
303 if ($snapshot) {
304 my $packages = $runtime_prop->{packages} // {};
305 if ( defined $share_dir ) {
306 my %rebased;
307 for my $name ( keys %$packages ) {
308 my %data = %{ $packages->{$name} // {} };
309 $self->_share_rebase( $name, \%data );
310 $rebased{$name} = \%data;
311 }
312 $packages = \%rebased;
313 }
314 my $data = {
315 dist_name => $recipe->name,
316 install_type => $install_type,
317 pkg_roots => $recipe->pkg_roots,
318 packages => $packages,
319 errors => $runtime_prop->{errors} // {},
320 digest => $self->_config_digest
321 };
322 path($snapshot)->parent->mkpath if defined $snapshot;
323 path($snapshot)->spew_utf8( encode_json($data) . "\n" );
324 say "Wrote runtime snapshot $snapshot" if $verbose;
325 }
326 $stage_done->{export} = 1;
327 $self->_checkpoint;
328 $self;
329 }
330  
331 method test () {
332 return if $stage_done->{test};
333 $self->run_hooks('test');
334 $stage_done->{test} = 1;
335 $self;
336 }
337 method _version_for_pkg ($name) { $recipe->version_for($name) }
338 method _opts_for_pkg ( $name, %opts ) { $recipe->opts_for( $name, %opts ) }
339  
340 method _config_digest () {
341 require Digest::SHA;
342 my @parts;
343 for my $name ( $recipe->packages ) {
344 my $version = $recipe->version_for($name);
345 my %opts = $recipe->opts_for( $name, %{ $install_prop->{profile} // {} } );
346 push @parts, $name, ( defined $version ? $version : '' );
347 push @parts, map { $_ . '=' . ( defined $opts{$_} ? $opts{$_} : '' ) } sort keys %opts;
348 }
349 Digest::SHA::sha256_hex( join "\x1f", @parts );
350 }
351  
352 method _probe_satisfied ( $found, $expected ) {
353 return 0 unless defined $found && length $found;
354 return 1 unless defined $expected && length $expected;
355 return $found eq $expected;
356 }
357  
358 # Recipe hook modules are loaded once per engine and invited to register their own stage hooks the same way code
359 # can: module->register_hooks($self).
360 method _load_recipe_hooks () {
361 for my $mod ( @{ $recipe->hooks || [] } ) {
362 next if $loaded_hooks->{$mod};
363 my $file = $mod;
364 $file =~ s{::}{/}g;
365 $file .= '.pm';
366 require $file;
367 my $register = $mod->can('register_hooks');
368 die "Alien::Xrepo::Build: recipe hook module '$mod' must expose register_hooks(\$build), got '$mod'" unless $register;
369 $register->($self);
370 $loaded_hooks->{$mod} = 1;
371 }
372 return;
373 }
374  
375 # pkg_roots mirror Alien::Build's: name => environment variable whose value holds the package root. When the
376 # variable is set and points at an existing directory the package is treated as system-provided there and xrepo is
377 # never consulted (probe reports it satisfied; install/gather record it directly).
378 method _pkg_root ($name) {
379 my $pr = $recipe->pkg_roots->{$name};
380 return () unless defined $pr && length $pr;
381 my $dir = $ENV{$pr};
382 return () unless defined $dir && length $dir && -d $dir;
383 return path($dir)->absolute->stringify;
384 }
385  
386 method _root_entry ($root) {
387 my @inc = -d path($root)->child('include') ? ( path($root)->child('include')->stringify ) : ();
388 my @lib = -d path($root)->child('lib') ? ( path($root)->child('lib')->stringify ) : ();
389 my @bin = -d path($root)->child('bin') ? ( path($root)->child('bin')->stringify ) : ();
390 { includedirs => \@inc,
391 libfiles => [],
392 license => undef,
393 linkdirs => \@lib,
394 links => [],
395 shared => 1,
396 static => 0,
397 version => undef,
398 libpath => undef,
399 bindirs => \@bin,
400 installdir => $root,
401 kind => 'system'
402 };
403 }
404  
405 method _can_skip_install ($name) {
406 return 0 unless $probe_policy eq 'skip';
407 my $probe = $install_prop->{probed}{$name} // {};
408 return 0 unless $probe->{satisfied};
409 my %opts = $self->_opts_for_pkg( $name, %{ $install_prop->{profile} // {} } );
410 !$opts{force};
411 }
412  
413 method _install_order () {
414 my @pkgs = $recipe->packages;
415 my %ns;
416 for my $name (@pkgs) {
417 $ns{$1} = 1 if $name =~ /^([^:]+)::/;
418 }
419 my @tools = grep { $ns{$_} } @pkgs;
420 my @rest = grep { !$ns{$_} } @pkgs;
421 return ( @tools, @rest );
422 }
423  
424 method _manager_tool_env ($name) {
425 return () unless $name =~ /^([^:]+)::/;
426 my $ns = $1;
427 my $rec = $runtime_prop->{packages}{$ns} // {};
428 return () unless ref $rec eq 'HASH';
429 my $dir = $rec->{installdir};
430 return () unless defined $dir && length $dir;
431 my $sep = $Config::Config{path_sep} // ( $^O eq 'MSWin32' ? ';' : ':' );
432 my %env = ( PATH => join( $sep, $dir, ( $ENV{PATH} // () ) ) );
433 $env{VCPKG_ROOT} = $dir if $ns eq 'vcpkg';
434 return %env;
435 }
436  
437 # Shallow share install: when a share_dir is set, every package is installed
438 # into <share_dir>/<pkg> (its own little store) so the dist ships its own copy
439 # of the libraries and never depends on the xmake cache at runtime. The
440 # snapshot records those paths share-relative (see export/_share_rebase).
441 method _pkg_installdir ($name) {
442 return () unless defined $share_dir && length $share_dir;
443 return () if $name =~ /::/;
444 return path($share_dir)->absolute->child($name)->stringify;
445 }
446  
447 # Rewrite an installed package's recorded paths to be relative to share_dir
448 # (so they survive `./Build install` relocating the share dir). Only paths
449 # that actually live under the share dir are made relative.
450 method _share_rebase ( $name, $data ) {
451 my $share = path($share_dir)->absolute->stringify;
452 for my $k (qw[includedirs libfiles linkdirs bindirs]) {
453 next unless ref $data->{$k} eq 'ARRAY';
454 $data->{$k} = [ map { $self->_under_share( $share, $_ ) } @{ $data->{$k} } ];
455 }
456 for my $k (qw[libpath installdir]) {
457 $data->{$k} = $self->_under_share( $share, $data->{$k} ) if defined $data->{$k};
458 }
459 if ( ref $data->{runtime_deps} eq 'ARRAY' ) {
460 for my $dep ( @{ $data->{runtime_deps} } ) {
461 next unless ref $dep eq 'HASH';
462 for my $k (qw[path dir]) {
463 $dep->{$k} = $self->_under_share( $share, $dep->{$k} ) if defined $dep->{$k};
464 }
465 }
466 }
467 return $data;
468 }
469  
470 method _under_share ( $share, $p ) {
471 return $p unless defined $p && length $p;
472 my ( $s, $n ) = map { ( $_ // '' ) =~ s{\\}{/}gr } ( $share, $p );
473 $s =~ s{/$}{};
474 $s = lc($s) if $^O eq 'MSWin32';
475 $n = lc($n) if $^O eq 'MSWin32';
476 return $p unless index( $n, "$s/" ) == 0;
477 return substr( $p, length($share) + 1 );
478 }
479  
480 # Callers mark the stage done *before* checkpointing. The file has to record the
481 # stage that just finished, or a resumed Build re-enters work that is already
482 # complete -- on a long stage such as install, repeating it in full.
483 method _checkpoint () {
484 return unless defined $checkpoint;
485 path($checkpoint)->parent->mkpath;
486 my $data = {
487 install_type => $install_type,
488 stage_done => $stage_done,
489 meta_prop => $meta_prop,
490 install_prop => $install_prop,
491 runtime_prop => $runtime_prop
492 };
493 path($checkpoint)->spew_utf8( encode_json($data) . "\n" );
494 return;
495 }
496 #
497 method _load_checkpoint () {
498 return 0 unless defined $checkpoint && -e $checkpoint;
499 my $data = eval { decode_json( path($checkpoint)->slurp_utf8 ) };
500 return 0 unless ref $data eq 'HASH';
501 $install_type = $data->{install_type} // 'system';
502 $stage_done = $data->{stage_done} // {};
503 $meta_prop = $data->{meta_prop} // {};
504 $install_prop = $data->{install_prop} // {};
505 $runtime_prop = $data->{runtime_prop} // {};
506 return 1;
507 }
508 };
509 #
510 1;
511 __END__
« Xrepo.pm ↑ Summary Xrepo/MM.pm »