Alien-Xrepo

 view release on metacpan or  search on metacpan

lib/Alien/Xrepo.pm  view on Meta::CPAN

            my $str = ref $c eq 'HASH' ? join( ',', map { "$_=" . Alien::Xmake::_bool_str( $c->{$_} ) } sort keys %$c ) : "$c";
            push @parts, $str;
        }
        sha1_hex( join( "\0", @parts ) );
    }

    method _cache_load (%opts) {
        my $dir  = $self->_cache_dir(%opts) or return ();
        my $file = $dir->child('cache.json');
        return () unless -f $file;
        my $raw = eval { $file->slurp_utf8 };
        return () unless defined $raw && length $raw;
        my $meta = eval { decode_json($raw) };
        return () unless ref $meta eq 'HASH' && ref $meta->{order} eq 'ARRAY' && ref $meta->{entries} eq 'HASH';
        $meta;
    }

    method _cache_save ( $meta, %opts ) {
        my $dir = $self->_cache_dir(%opts) or return;
        my ( @order, %keep );
        for my $k ( @{ $meta->{order} // [] } ) {
            my $e = $meta->{entries}{$k} or next;
            next unless $self->_entry_alive($e);
            push @order, $k;
            $keep{$k} = $e;
        }
        while ( @order > _CACHE_MAX() ) { delete $keep{ pop @order }; }
        $dir->mkpath;
        my $file = $dir->child('cache.json');
        my $tmp  = $dir->child('cache.json.tmp');
        $tmp->remove if $tmp->exists;    # clear a tmp stranded by an interrupted save
        $tmp->spew_utf8( encode_json( { version => 1, order => \@order, entries => \%keep } ) );
        $file->remove if $^O eq 'MSWin32' && $file->exists;
        move( "$tmp", "$file" );
    }

    method _entry_alive ($e) {
        return () unless ref $e eq 'HASH';
        return -f $e->{libpath} if defined $e->{libpath} && length $e->{libpath};
        defined $e->{installdir} && length $e->{installdir} && -d $e->{installdir};
    }

lib/Alien/Xrepo.pm  view on Meta::CPAN

        # rather than building from source when none is found), while leaving it unset means "prefer the system,
        # fall back to building". Only the latter can restore add_extsources() without turning a source fallback
        # into a hard failure, so a bare add_requires() is what we want here.
        my @lines = ( 'add_requires(' . $self->_lua_str($full_spec) . ')' );
        push @lines,
            'add_requireconfs(' .
            $self->_lua_str($name) .
            ', {configs = {' .
            join( ',', map { $self->_lua_key($_) . ' = ' . $self->_lua_value( $configs{$_} ) } sort keys %configs ) . '}})'
            if %configs;
        $file->spew_utf8( join( "\n", @lines ) . "\n" );
        say '[*] xrepo: system packages requested, driving install via a package file...' if $verbose;
        return $file->stringify;
    }

    # Lua string literal for a package spec or name.
    method _lua_str ($s) {
        my $q = $s;
        $q =~ s{(["\\])}{\\$1}g;
        return qq{"$q"};
    }

lib/Alien/Xrepo/Build.pm  view on Meta::CPAN

            }
            my $data = {
                dist_name    => $recipe->name,
                install_type => $install_type,
                pkg_roots    => $recipe->pkg_roots,
                packages     => $packages,
                errors       => $runtime_prop->{errors} // {},
                digest       => $self->_config_digest
            };
            path($snapshot)->parent->mkpath if defined $snapshot;
            path($snapshot)->spew_utf8( encode_json($data) . "\n" );
            say "Wrote runtime snapshot $snapshot" if $verbose;
        }
        $stage_done->{export} = 1;
        $self->_checkpoint;
        $self;
    }

    method test () {
        return if $stage_done->{test};
        $self->run_hooks('test');

lib/Alien/Xrepo/Build.pm  view on Meta::CPAN

    method _checkpoint () {
        return unless defined $checkpoint;
        path($checkpoint)->parent->mkpath;
        my $data = {
            install_type => $install_type,
            stage_done   => $stage_done,
            meta_prop    => $meta_prop,
            install_prop => $install_prop,
            runtime_prop => $runtime_prop
        };
        path($checkpoint)->spew_utf8( encode_json($data) . "\n" );
        return;
    }
    #
    method _load_checkpoint () {
        return 0 unless defined $checkpoint && -e $checkpoint;
        my $data = eval { decode_json( path($checkpoint)->slurp_utf8 ) };
        return 0 unless ref $data eq 'HASH';
        $install_type = $data->{install_type} // 'system';
        $stage_done   = $data->{stage_done}   // {};
        $meta_prop    = $data->{meta_prop}    // {};
        $install_prop = $data->{install_prop} // {};
        $runtime_prop = $data->{runtime_prop} // {};
        return 1;
    }
};
#

lib/Alien/Xrepo/Build/Recipe.pm  view on Meta::CPAN

    field @order : reader(packages);    # package names in recipe order (first = primary)
    field %defs;                        # package name => normalized per-package hashref def
    method package_defs { \%defs }
    #
    ADJUST {
        if ( defined $file || defined $dir ) {
            die 'Recipe: pass exactly one of file / dir / inline data'       if defined $file && defined $dir;
            die q[Recipe: inline 'packages' is ignored when a file is given] if defined $packages;
            my $path = $file // path($dir)->child('xrepo.json');    # Used during testing
            die 'Recipe file not found: ' . $path unless -e $path;
            my $data = eval { decode_json( path($path)->slurp_utf8 ) };
            die "Recipe '$path' is not valid JSON: $@" if !defined $data || ref $data ne 'HASH';
            $name        //= $data->{name};
            $packages    //= $data->{packages};
            $defaults    //= $data->{defaults};
            $pkg_roots   //= $data->{pkg_roots};
            $local_repos //= $data->{local_repos} // [];
            $hooks       //= $data->{hooks}       // [];
        }
        die 'Recipe: packages is required' unless defined $packages;
        @order = ( $self->_normalize_defs($packages) );

lib/Alien/Xrepo/MM.pm  view on Meta::CPAN


    # Generate the Makefile. The config below is written first so the pure_all hook the recipe emits has something to read when `make` runs.
    sub Write ($self) {
        my $base = path( $self->{base_dir} );
        $base->mkpath unless -d $base;
        my $cwd = getcwd();
        chdir $base or die "Alien::Xrepo::MM: chdir $base: $!";
        my $dist     = $self->_dist;
        my $snapshot = path( defined $self->{xrepo_snapshot} ? $self->{xrepo_snapshot} : $dist->snapshot_path )->absolute;
        my $share    = defined $self->{xrepo_share_dir} ? path( $self->{xrepo_share_dir} )->absolute : $snapshot->parent;
        $base->child($CONFIG)->spew_utf8(
            encode_json(
                {   module_name => $self->{module_name},
                    snapshot    => $snapshot->stringify,
                    share_dir   => $share->stringify,
                    cache       => $self->{xrepo_cache},
                    update_repo => $self->{xrepo_update_repo},
                    verbose     => $self->{xrepo_verbose},
                    diagnosis   => $self->{xrepo_diagnosis}
                }
            )

lib/Alien/Xrepo/MM.pm  view on Meta::CPAN

        );
        return %wm;
    }

# What `make` executes on the xrepo target: re-read the config written by Write(), rebuild the snapshot when stale, and do nothing (successfully) when the file is absent so a dist that merely loaded us but never used Write is unharmed.
    sub run ( $config //= $CONFIG ) {
        my $cfg = path($config);
        $cfg = $cfg->absolute unless $cfg->is_absolute;
        my $dist_root = $cfg->parent;
        return !print "Alien::Xrepo::MM: no $config found; skipping xrepo build\n" unless -e $cfg;
        my $data = decode_json( $cfg->slurp_utf8 );
        my $dist = Alien::Xrepo::Build::Dist->new( base_dir => $dist_root->stringify, module_name => $data->{module_name}, script => 'Makefile.PL' );
        my $snapshot = path( $data->{snapshot} );
        $snapshot = $dist_root->child( $data->{snapshot} ) unless $snapshot->is_absolute;
        return !print "=> xrepo: $snapshot is up to date\n" unless $dist->snapshot_stale( $snapshot, _engine_mods() );
        my $share = ( defined $data->{share_dir} && $data->{share_dir} ne '' ) ? path( $data->{share_dir} ) : $snapshot->parent;
        $share->mkpath;
        print "=> xrepo: writing $snapshot\n";
        my $build = Alien::Xrepo::Build->new(
            recipe      => $dist->recipe,
            snapshot    => $snapshot,

lib/Alien/Xrepo/Runtime.pm  view on Meta::CPAN

    #
    # Hermetic mode: a snapshot file wins entirely (no xrepo subprocess).
    method _load_snapshot () {
        my $file = $snapshot;
        if ( !defined $file && $autodetect_snapshot ) {
            for my $cand ( __PACKAGE__->_snapshot_candidates_for( ref $self ) ) {
                if ( -e $cand ) { $file = $cand; last; }
            }
        }
        return unless defined $file && -e $file;
        my $data = eval { decode_json( path($file)->slurp_utf8 ) };
        return unless ref $data eq 'HASH';
        $snap              = $data->{packages} // {};
        $snap_install_type = $data->{install_type};
        $snap_file         = "$file";
        $snap_errors       = $data->{errors} // {};
        my $base = path($file)->parent;

        for my $name ( keys %$snap ) {
            my %pkg = %{ $snap->{$name} };
            $self->_rebase_relative( $base, \%pkg );

t/002_argv.t  view on Meta::CPAN

subtest '_package_file is only generated for a system install' => sub {

    # Without `system`, an install must stay on the bare-spec path: xrepo's shim forces
    # system=false there, which is what keeps an isolated/pinned install inside its own store.
    ok !scalar $repo->_package_file( 'zlib', {} ), 'no package file without system';

    # With it, the install is driven through a package file so our own add_requires decides system.
    my $file = $repo->_package_file( 'libsdl3_ttf 3.2.2', { system => 1, kind => 'shared' } );
    ok defined $file && -f $file, 'package file is created';
    like $file, qr/xrepo\.lua$/, 'package file has a .lua name (the shim keys off the suffix)';
    my $body = path($file)->slurp_utf8;
    like $body, qr/^add_requires\("libsdl3_ttf 3\.2\.2"\)$/m,                              'add_requires carries the versioned spec verbatim';
    like $body, qr/^add_requireconfs\("libsdl3_ttf", \{configs = \{shared = true\}\}\)$/m, 'kind folds into configs';

    # The whole point: no `system` option. `system = true` means system-only in xmake and would
    # fail outright instead of falling back to a source build; leaving it unset means "prefer the
    # system, else build", which is what makes add_extsources() reachable again.
    unlike $body, qr/system/, 'no system option at all: prefer-system-then-build, not system-only';

    # configs and kind both land in add_requireconfs rather than --configs, which the shim ignores
    # once it has a package file.
    my $f2 = $repo->_package_file( 'zlib', { system => 1, kind => 'shared', configs => { vs_runtime => 'MD', wsa => false, plain => 1 }, } );
    my $b2 = path($f2)->slurp_utf8;
    like $b2, qr/shared = true/,     'shared from kind';
    like $b2, qr/vs_runtime = "MD"/, 'string config is quoted as a Lua string';
    like $b2, qr/wsa = false/,       'built-in false renders as Lua false';
    like $b2, qr/plain = 1/,         'numeric 1 config renders as a Lua number, like --configs does';
    my $f3 = $repo->_package_file( 'zlib', { system => 1, kind => 'static' } );
    like path($f3)->slurp_utf8, qr/shared = false/, 'kind => static pins shared = false';

    # no_kind suppresses the shared choice, as it does for -k.
    my $f4 = $repo->_package_file( 'zlib', { system => 1, kind => 'shared', no_kind => 1 } );
    unlike path($f4)->slurp_utf8, qr/shared/, 'no_kind omits the shared config entirely';
};
subtest '_cache_key separates system from private installs' => sub {
    my $plain = $repo->_cache_key( 'zlib', { kind => 'shared' } );
    my $sys   = $repo->_cache_key( 'zlib', { kind => 'shared', system => 1 } );
    isnt $sys,                                                         $plain, 'a system install never reuses a private-install entry';
    is $repo->_cache_key( 'zlib', { kind => 'shared', system => 0 } ), $plain, 'system => 0 stays on the private identity';
};
subtest '_build_args includes uses the OS path separator' => sub {

    # xrepo's install.lua splits `--includes` with path.splitenv and rejoins with

t/050_recipe.t  view on Meta::CPAN

    my %zstd   = $recipe->opts_for( 'zstd', kind => 'static', configs => { wayland => 0 } );
    is $zstd{kind},             'static', 'plain entry keeps ambient kind';
    is $zstd{configs}{wayland}, 0,        'plain entry keeps ambient configs';
    my %sdl = $recipe->opts_for( 'libsdl3', kind => 'static', configs => { zlib => 0, wayland => 0 } );
    is $sdl{kind},             'shared', 'def kind overrides ambient';
    is $sdl{configs}{zlib},    0,        'ambient configs preserved';
    is $sdl{configs}{wayland}, 1,        'def config wins per-key';
};
subtest 'file round-trip (xrepo.json)' => sub {
    my $file = path($dir)->child('xrepo.json');
    $file->spew_utf8(
        encode_json(
            {   name        => 'Exotic-Zstandard',
                packages    => [ { name => 'zstd', version => '1.5.6', kind => 'shared' } ],
                defaults    => { mode => 'release', configs => { legacy => 1 } },
                pkg_roots   => { ZSTD => '$ZSTD' },
                local_repos => ['vendor/recipes'],
                hooks       => ['Exotic::Zstandard::Hooks']
            }
        )
    );

t/051_engine.t  view on Meta::CPAN

    my $b   = build( ['raylib'], repo => $spy, probe_policy => 'off', checkpoint => $cp, update_repo => 1 );
    $b->run;
    my (@updates)  = grep { $_->{action} eq 'update_repo' } @{ $spy->calls };
    my (@installs) = grep { $_->{action} eq 'install' } @{ $spy->calls };
    is scalar @updates,  1, 'first run refreshed the registry once';
    is scalar @installs, 2, 'first run attempted the install twice';

    # Model a build that died inside the install stage: the checkpoint it wrote
    # mid-stage is where the retry count is persisted, but the stage never
    # completed, so a resume re-enters install() for the same package.
    my $state = decode_json( $cp->slurp_utf8 );
    delete $state->{stage_done}{install};
    $cp->spew_utf8( encode_json($state) . "\n" );
    my $spy2 = Alien::Xrepo::Build::TestSpy->new( fail => { raylib => 1 } );
    my $b2   = build( ['raylib'], repo => $spy2, probe_policy => 'off', checkpoint => $cp, update_repo => 1, resume => 1 );
    $b2->run;
    my (@updates2)  = grep { $_->{action} eq 'update_repo' } @{ $spy2->calls };
    my (@installs2) = grep { $_->{action} eq 'install' } @{ $spy2->calls };
    is scalar @updates2,  0, 'the resumed run does not refresh the registry again';
    is scalar @installs2, 1, 'the resumed run makes one attempt and no retry';
    like $b2->runtime_prop->{errors}{raylib}{error}, qr/boom/, 'the failure is still recorded on the resumed run';
};
subtest 'gather fetches anything the install did not produce' => sub {

t/051_engine.t  view on Meta::CPAN

    $b2->gather;
    my (@f2) = grep { $_->{action} eq 'fetch' } @{ $spy2->calls };
    is scalar @f2, 1, 'gather fetches when install never ran';
};
subtest 'export writes the runtime snapshot' => sub {
    my $snap = path($dir)->child('snapshot.json');
    my $spy  = Alien::Xrepo::Build::TestSpy->new;
    my $b    = build( [ { name => 'zstd', version => '1.5.6' } ], repo => $spy, probe_policy => 'off', snapshot => $snap );
    $b->run;
    ok -e $snap, 'snapshot file written';
    my $data = decode_json( $snap->slurp_utf8 );
    is $data->{install_type},               'share',           'snapshot records install_type';
    is $data->{packages}{zstd}{version},    '1.5.6',           'snapshot records runtime data';
    is $data->{packages}{zstd}{installdir}, '/tmp/store/zstd', 'snapshot records installdir';
};
subtest 'assert_installed fails a dist and drops a snapshot that records errors' => sub {
    my $snap = path($dir)->child('failed.json');
    my $spy  = Alien::Xrepo::Build::TestSpy->new( fail => { libsdl3 => 1 } );
    my $b    = build( [ 'zstd', 'libsdl3' ], repo => $spy, probe_policy => 'off', snapshot => $snap );
    $b->run;
    ok -e $snap, 'a failed run still writes its snapshot';

t/051_engine.t  view on Meta::CPAN

    };
    is $warn, D(), 'assert_installed emitted a warning instead of dying';
    like $warn, qr[optpkg], 'warning identifies the optional package that failed';
    is $ret, $b, 'assert_installed returns $self on non-fatal failure';
};
subtest 'a checkpoint records the stage it just finished' => sub {
    my $cp  = path($dir)->child('stage-state.json');
    my $spy = Alien::Xrepo::Build::TestSpy->new;
    my $b   = build( ['zstd'], repo => $spy, probe_policy => 'off', checkpoint => $cp );
    $b->configure;
    my $state = decode_json( $cp->slurp_utf8 );
    is $state->{stage_done}{configure}, 1, 'configure is recorded as done as soon as it finishes';
    my $spy2 = Alien::Xrepo::Build::TestSpy->new;
    my $b2   = build( ['zstd'], repo => $spy2, probe_policy => 'off', checkpoint => $cp, resume => 1 );
    my @hooks;
    $b2->register_hook( configure => sub { push @hooks, 1 } );
    $b2->run;
    is scalar @hooks,                0, 'a resumed build does not re-run the configure stage';
    is $b2->stage_done->{configure}, 1, 'the resumed build knows configure completed';
};
subtest 'checkpoint/resume skips completed work' => sub {

t/051_engine.t  view on Meta::CPAN

    ok !$b->has_hook('probe'),  'unregistered stage has no hooks';
    like dies {
        $b->register_hook( bogus => sub { } )
    }, qr/Unknown stage/, 'bad stage dies';
    $b->run;
    is \@ran, [qw[install gather]], 'hooks fired in stage order';
};
our @HOOK_RAN;
subtest 'recipe hooks load once and register stage callbacks' => sub {
    my $hdir = Path::Tiny->tempdir;
    $hdir->child('RecipeHooksDemo.pm')->spew_utf8(<<~'END');
        package RecipeHooksDemo {
            sub register_hooks {
                my ($build) = @_;
                push @main::HOOK_RAN, 'register';
                $build->register_hook( install => sub { push @main::HOOK_RAN, 'install' } );
            }
        };
        1;
        END
    local @INC = ( @INC, $hdir->stringify );

t/051_engine.t  view on Meta::CPAN

    is \@main::HOOK_RAN,        ['register'], 'recipe hook module saw register_hooks';
    is $b->has_hook('install'), 1,            'recipe hook attached a stage hook';
    @main::HOOK_RAN = ();
    $b->configure;
    is scalar @main::HOOK_RAN, 0, 'recipe hooks load once even if configure repeats';
    $b->install;
    is \@main::HOOK_RAN, ['install'], 'recipe-registered hook fired at its stage';
};
subtest 'recipe hooks die clearly when the module lacks register_hooks' => sub {
    my $hdir = Path::Tiny->tempdir;
    $hdir->child('RecipeHooksBad.pm')->spew_utf8("package RecipeHooksBad;\n1;\n");
    local @INC = ( @INC, $hdir->stringify );
    my $spy = Alien::Xrepo::Build::TestSpy->new;
    my $b   = build( ['zstd'], repo => $spy, recipe_extra => { hooks => ['RecipeHooksBad'] } );
    like dies { $b->configure }, qr/register_hooks/, 'missing register_hooks dies at configure';
};
subtest 'pkg_roots resolve a package from a system root' => sub {
    my $root = Path::Tiny->tempdir;
    $root->child('include')->mkpath;
    $root->child('lib')->mkpath;
    $root->child( 'include', 'zstd.h' )->spew_utf8('#define ZSTD 1');
    $root->child( 'lib',     'libzstd.a' )->spew_utf8('');
    local $ENV{ZSTD_ROOT} = $root->stringify;
    my $spy = Alien::Xrepo::Build::TestSpy->new;
    my $b   = build( ['zstd'], repo => $spy, recipe_extra => { pkg_roots => { zstd => 'ZSTD_ROOT' } } );
    $b->run;
    my (@infos)    = grep { $_->{action} eq 'info' } @{ $spy->calls };
    my (@installs) = grep { $_->{action} eq 'install' } @{ $spy->calls };
    my (@fetches)  = grep { $_->{action} eq 'fetch' } @{ $spy->calls };
    is scalar @infos,                                      0,                'probe never consults xrepo for a root-resolved package';
    is scalar @installs,                                   0,                'install never consults xrepo for a root-resolved package';
    is scalar @fetches,                                    0,                'gather never consults xrepo for a root-resolved package';

t/051_engine.t  view on Meta::CPAN

        snapshot     => $snap,
        probe_policy => 'off'
    );
    $b->run;
    my (@installs) = grep { $_->{action} eq 'install' } @{ $spy->calls };
    is scalar @installs,               2,                                         'both packages installed';
    is $installs[0]{opts}{installdir}, path($share)->child('zstd')->stringify,    'zstd installation goes into the sharedir';
    is $installs[1]{opts}{installdir}, path($share)->child('libsdl3')->stringify, 'libsdl3 installation goes into the sharedir';
    my (@fetches) = grep { $_->{action} eq 'fetch' } @{ $spy->calls };
    is scalar @fetches, 0, 'gather reuses install data (no extra fetch)';
    my $data = decode_json( $snap->slurp_utf8 );
    is $data->{packages}{zstd}{installdir}, 'zstd', 'snapshot installdir is share-relative';
    like $data->{packages}{zstd}{includedirs}[0], qr/^zstd[\\\/]include$/, 'snapshot includedirs are share-relative';
    is $data->{install_type},         'share',           'share install recorded';
    is $b->install_prop->{share_dir}, $share->stringify, 'share_dir recorded in install_prop';
};
#
done_testing;

t/052_runtime.t  view on Meta::CPAN

    my $spy2 = Alien::Xrepo::Runtime::TestSpy->new;
    my $alt  = Alien::Xrepo::Runtime->new( pkg_name => [ 'zstd', 'ninja' ], repo => $spy2 )->alt('ninja');
    {
        local $ENV{PATH} = 'C:/original';
        $alt->prepend_to_path;
        is $ENV{PATH}, join( $Config::Config{path_sep}, 'C:/store/ninja/bin', 'C:/original' ), 'alt view prepends the pinned package bindir';
    }
};
subtest 'hermetic snapshot: no xrepo call at all' => sub {
    my $snap = path($dir)->child('snapshot.json');
    $snap->spew_utf8(
        encode_json(
            {   dist_name    => 'Exotic-Zstandard',
                install_type => 'share',
                packages     => {
                    zstd => {
                        includedirs => ['C:/snap/zstd/include'],
                        libfiles    => ['C:/snap/zstd/bin/zstd.dll'],
                        license     => undef,
                        linkdirs    => ['C:/snap/zstd/lib'],
                        links       => ['zstd'],

t/052_runtime.t  view on Meta::CPAN

    my $spy = Alien::Xrepo::Runtime::TestSpy->new;
    my $a   = Alien::Xrepo::Runtime->new( pkg_name => 'zstd', snapshot => $snap, repo => $spy, autodetect_snapshot => 0 );
    is $a->version, '1.5.6', 'snapshot version served';
    like $a->cflags,  qr[C:/snap/zstd/include$],       'snapshot cflags served';
    like $a->libpath, qr[C:/snap/zstd/bin/zstd\.dll$], 'snapshot libpath served';
    is $a->install_type, 'share', 'snapshot install_type served';
    is $spy->calls,      0,       'no xrepo subprocess in hermetic mode';
};
subtest 'snapshot state is exposed for built-vs-cold test guards' => sub {
    my $snap = path($dir)->child('stateful.json');
    $snap->spew_utf8(
        encode_json(
            {   dist_name    => 'Exotic-Zstandard',
                install_type => 'share',
                packages     => {
                    zstd => {
                        includedirs => ['C:/snap/zstd/include'],
                        libfiles    => [],
                        linkdirs    => ['C:/snap/zstd/lib'],
                        links       => ['zstd'],
                        license     => undef,

t/052_runtime.t  view on Meta::CPAN

subtest 'constructor accepts an Alien::Xrepo::Build::Recipe object' => sub {
    my $rec = Alien::Xrepo::Build::Recipe->new( packages => ['zstd'] );
    my $spy = Alien::Xrepo::Runtime::TestSpy->new;
    my $a   = Alien::Xrepo::Runtime->new( recipe => $rec, repo => $spy );
    is [ $a->package_names ], ['zstd'], 'Recipe object honored';
};
subtest 'hermetic snapshot rebases share-relative paths against its own dir' => sub {
    my $share = path($dir)->child('share');
    $share->child('zstd')->mkpath;
    my $snap = $share->child('xrepo-snapshot.json');
    $snap->spew_utf8(
        encode_json(
            {   dist_name    => 'Exotic-Zstandard',
                install_type => 'share',
                packages     => {
                    zstd => {
                        includedirs => ['zstd/include'],
                        libfiles    => [],
                        license     => undef,
                        linkdirs    => ['zstd/lib'],
                        links       => ['zstd'],

t/053_install_cache.t  view on Meta::CPAN

subtest 'cache save replaces existing/read-only cache and clears a stale tmp' => sub {
    my $store = Path::Tiny->tempdir;
    my $live  = $store->child( 'pkgs', 'z', 'bin' );
    $live->mkpath;
    my $meta = { order => [], entries => {} };
    $repo->_cache_put( 'z', $meta, { installdir => "$live", last_used => time }, 10 );
    $repo->_cache_save( $meta, installdir => "$store" );
    my $cache = $store->child( '.alien-xmake', 'cache.json' );
    ok $cache->exists, 'first save writes cache.json';
    my $stale = $store->child( '.alien-xmake', 'cache.json.tmp' );
    $stale->spew_utf8('{"stale":true}');
    $cache->spew_utf8('{"old":true}');    # existing dest a Windows rename would refuse
    $repo->_cache_save( $meta, installdir => "$store" );
    ok !$stale->exists, 'stale tmp cleared before save';
    my $loaded = $repo->_cache_load( installdir => "$store" );
    is [ @{ $loaded->{order} } ], ['z'], 'existing cache.json replaced on save';

    if ( $^O eq 'MSWin32' ) {
        $cache->chmod(0444);
        ok !-w $cache, 'dest is read-only for the edge case';
        $repo->_cache_save( $meta, installdir => "$store" );
        ok $cache->exists,                                                         'read-only dest replaced without dying';

t/054_mb.t  view on Meta::CPAN

use Test2::Util::Importer 'Test2::Tools::Subtest' => ( subtest_streamed => { -as => 'subtest' } );
use File::Temp qw[tempdir];
use Path::Tiny;
use Alien::Xrepo::MB;
#
my $dir = tempdir( CLEANUP => 1 );

sub make_mini_dist {
    my $root = path($dir)->child('Exotic-Foo');
    $root->child( 'lib', 'Exotic' )->mkpath;
    $root->child('Build.PL')->spew_utf8("use Alien::Xrepo::MB;\n");
    $root->child( 'lib', 'Exotic', 'Foo.pm' )->spew_utf8(<<'PM');
use v5.40;
use feature 'class';
no warnings 'experimental::class';
use Alien::Xrepo::Runtime;
class Exotic::Foo : isa(Alien::Xrepo::Runtime) {
    method recipe { return { name => 'Exotic-Foo', packages => ['zstd'] }; }
}
1;
PM
    return $root;

t/054_mb.t  view on Meta::CPAN

subtest 'staleness keys on the dist recipe inputs and engine modules' => sub {
    my $root  = make_mini_dist();
    my $b     = make_builder( root => $root );
    my @input = $b->_xrepo_inputs;
    like join( ' ', @input ), qr/Build\.PL/,                            'Build.PL is an input';
    like join( ' ', @input ), qr/Foo\.pm/,                              'module file is an input';
    like join( ' ', @input ), qr/Alien[\\\/]Xrepo[\\\/](MB|Build)\.pm/, 'engine modules are inputs';
    my $snap = path( $b->_xrepo_snapshot );
    ok $b->_snapshot_stale($snap), 'stale when the snapshot is missing';
    $snap->parent->mkpath;
    $snap->spew_utf8('{}');
    my $t = time;
    utime( $t + 100, $t + 100, $snap );
    ok !$b->_snapshot_stale($snap), 'fresh when newer than the inputs';
};
subtest '_recipe loads lib/<class>.pm and forwards recipe()' => sub {
    my $root = make_mini_dist();
    my $b    = make_builder( root => $root );
    is $b->_recipe, { name => 'Exotic-Foo', packages => ['zstd'] }, 'recipe hashref from the class';
};
#

t/055_mm.t  view on Meta::CPAN

use File::Temp qw[tempdir];
use Path::Tiny;
use JSON::PP;
use Alien::Xrepo::MM;
my $dir = tempdir( CLEANUP => 1 );
my $n   = 0;

sub make_mini_dist {
    my $root = path($dir)->child( 'Exotic-Foo-' . ++$n );
    $root->child( 'lib', 'Exotic' )->mkpath;
    $root->child('Makefile.PL')->spew_utf8("use Alien::Xrepo::MM;\n");
    $root->child( 'lib', 'Exotic', 'Foo.pm' )->spew_utf8(<<'PM');
use v5.40;
use feature 'class';
no warnings 'experimental::class';
use Alien::Xrepo::Runtime;
class Exotic::Foo : isa(Alien::Xrepo::Runtime) {
    method recipe { return { name => 'Exotic-Foo', packages => [] }; }
}
1;
PM
    return $root;

t/055_mm.t  view on Meta::CPAN

};
subtest 'Write emits the Makefile and the config' => sub {
    my $root = make_mini_dist();
    my $orig = Cwd::getcwd();
    chdir $root->stringify or die "chdir failed";
    my $mm = Alien::Xrepo::MM->new( module_name => 'Exotic::Foo', requires => { 'Alien::Xrepo::Runtime' => 0 }, );
    $mm->Write;
    chdir $orig;
    ok -e $root->child('Makefile'),      'Makefile written';
    ok -e $root->child('xrepo-mm.json'), 'config written';
    my $cfg = JSON::PP::decode_json( $root->child('xrepo-mm.json')->slurp_utf8 );
    is $cfg->{module_name}, 'Exotic::Foo',                               'config module_name';
    is $cfg->{snapshot},    $mm->_dist->snapshot_path,                   'config snapshot is the derived path';
    is $cfg->{share_dir},   path( $cfg->{snapshot} )->parent->stringify, 'config share_dir defaults to the snapshot parent';
    is $cfg->{cache},       0,                                           'config cache';
};
subtest 'xrepo_update_repo folds into the write config' => sub {
    my $root = make_mini_dist();
    my $mm   = Alien::Xrepo::MM->new( module_name => 'Exotic::Foo', base_dir => $root->stringify, xrepo_update_repo => 1, );
    is $mm->xrepo_update_repo, 1, 'property read back';
    $mm->Write;
    my $cfg = JSON::PP::decode_json( $root->child('xrepo-mm.json')->slurp_utf8 );
    is $cfg->{update_repo}, 1, 'update_repo recorded in xrepo-mm.json';
};
subtest 'xrepo_verbose / xrepo_diagnosis fold into the write config' => sub {
    my $root = make_mini_dist();
    my $mm   = Alien::Xrepo::MM->new( module_name => 'Exotic::Foo', base_dir => $root->stringify, xrepo_verbose => 1, xrepo_diagnosis => 1, );
    is $mm->xrepo_verbose,   1, 'xrepo_verbose read back';
    is $mm->xrepo_diagnosis, 1, 'xrepo_diagnosis read back';
    $mm->Write;
    my $cfg = JSON::PP::decode_json( $root->child('xrepo-mm.json')->slurp_utf8 );
    is $cfg->{verbose},   1, 'verbose recorded in xrepo-mm.json';
    is $cfg->{diagnosis}, 1, 'diagnosis recorded in xrepo-mm.json';
    my $default = Alien::Xrepo::MM->new( module_name => 'Exotic::Foo', base_dir => $root->stringify );
    $default->Write;
    my $dcfg = JSON::PP::decode_json( $root->child('xrepo-mm.json')->slurp_utf8 );
    is $dcfg->{verbose},   0, 'verbose defaults to 0 in the config';
    is $dcfg->{diagnosis}, 0, 'diagnosis defaults to 0 in the config';
};
subtest 'snapshot_stale rejects a directory masquerading as the snapshot' => sub {
    my $root = make_mini_dist();
    my $mm   = Alien::Xrepo::MM->new( module_name => 'Exotic::Foo', base_dir => $root->stringify );
    my $snap = path( $mm->_dist->snapshot_path );
    $snap->mkpath;
    my $t = time;
    utime( $t + 100, $t + 100, $snap );

t/055_mm.t  view on Meta::CPAN

        is $@, '', 'no exception';
    }
    chdir $orig;
    like $out, qr[skipping xrepo build], 'prints the skip notice';
};
subtest 'run() short-circuits on a fresh snapshot' => sub {
    my $root = make_mini_dist();
    my $mm   = Alien::Xrepo::MM->new( module_name => 'Exotic::Foo', base_dir => $root->stringify );
    my $snap = path( $mm->_dist->snapshot_path );
    $snap->parent->mkpath;
    $snap->spew_utf8('{}');
    my $t = time;
    utime( $t + 100, $t + 100, $snap );
    $root->child('xrepo-mm.json')
        ->spew_utf8(
        JSON::PP::encode_json( { module_name => 'Exotic::Foo', snapshot => $snap->stringify, share_dir => $snap->parent->stringify, cache => 0, } ) );
    my $orig = Cwd::getcwd();
    chdir $root->stringify or die "chdir failed";
    my $out = '';
    {
        local *STDOUT;
        open STDOUT, '>', \$out or plan skip_all => "cannot capture STDOUT: $!";
        eval { Alien::Xrepo::MM::run('xrepo-mm.json') };
        is $@, '', 'no exception';
    }

t/056_process_info.t  view on Meta::CPAN

#
my $repo = Alien::Xrepo->new( verbose => 0, cache => 0 );

# The only library extension that is unambiguous on the platform we are running on: an import lib on Windows, a static
# archive everywhere else. Both are what a static-only port ships and neither has a shared object to dlopen.
my $static_name = $^O eq 'MSWin32' ? 'zlib.lib' : 'libz.a';
subtest 'an install tree holding libraries is not mistaken for a header-only package' => sub {
    my $dir = path( tempdir( CLEANUP => 1 ) )->child('zlib');
    $dir->child('lib')->mkpath;
    $dir->child('include')->mkpath;
    $dir->child( 'include', 'zlib.h' )->spew_utf8('');
    my $lib = $dir->child( 'lib', $static_name );
    $lib->spew_utf8('');
    my $info = $repo->_process_info(
        {   libfiles    => [],
            includedirs => [ $dir->child('include')->stringify ],
            linkdirs    => [],
            version     => '1.3.2',
            artifacts   => { installdir => $dir->stringify }
        }
    );
    is $info->libpath,           $lib->stringify,                   'libpath points at the library xrepo did not list';
    is [ @{ $info->libfiles } ], [ $lib->stringify ],               'libfiles recovered from the install tree';
    is $info->kind,              'library',                         'a package with libraries is not demoted to a binary tool';
    is [ @{ $info->linkdirs } ], [ $dir->child('lib')->stringify ], 'the directory that yielded files joins linkdirs';
    ok $info->find_header('zlib.h'), 'headers still resolve alongside the recovered library';
};
subtest 'a genuinely header-only package stays header-only' => sub {
    my $dir = path( tempdir( CLEANUP => 1 ) )->child('headers-only');
    $dir->child('lib')->mkpath;
    $dir->child('include')->mkpath;
    $dir->child( 'include', 'zlib.h' )->spew_utf8('');
    $dir->child( 'lib',     'zlib.pc' )->spew_utf8('');
    $dir->child( 'lib',     'notes.txt' )->spew_utf8('');
    my $info = $repo->_process_info(
        {   libfiles    => [],
            includedirs => [ $dir->child('include')->stringify ],
            linkdirs    => [],
            version     => '1.0.0',
            artifacts   => { installdir => $dir->stringify }
        }
    );
    is $info->libpath,           undef, 'libpath stays undef when the tree really has no library';
    is [ @{ $info->libfiles } ], [],    'no libfiles invented out of a lib dir of non-libraries';
    is [ @{ $info->linkdirs } ], [],    'a lib dir that yielded nothing does not join linkdirs';
};
subtest 'libfiles xrepo did report are left alone' => sub {
    my $dir  = path( tempdir( CLEANUP => 1 ) )->child('reported');
    my $real = $dir->child( 'lib', $static_name );
    $dir->child('lib')->mkpath;
    $real->spew_utf8('');
    my $other = "$dir/somewhere-else/$static_name";
    my $info  = $repo->_process_info(
        { libfiles => [$other], includedirs => [], linkdirs => [], version => '2.0.0', artifacts => { installdir => $dir->stringify } } );
    is $info->libpath,           $other,   'the reported libfile wins over anything found on disk';
    is [ @{ $info->libfiles } ], [$other], 'libfiles are not supplemented when xrepo already listed some';
};
subtest 'on Windows, the DLL the package links against wins the libpath' => sub {
    local $^O = 'MSWin32';    # exercise the Windows branch on any platform; tree is just files
    my $dir     = path( tempdir( CLEANUP => 1 ) )->child('sdl3_image');
    my $imp     = $dir->child( 'bin', 'SDL3_image.lib' );
    my $codec   = $dir->child( 'bin', 'libavif-16.dll' );
    my $runtime = $dir->child( 'bin', 'SDL3_image.dll' );
    $dir->child('bin')->mkpath;
    for ( $imp, $codec, $runtime ) { $_->spew_utf8(''); }
    my $info = $repo->_process_info(
        {   libfiles    => [ map { $_->stringify } $imp, $codec, $runtime ],
            includedirs => [],
            linkdirs    => [],
            version     => '3.4.0',
            links       => ['SDL3_image'],
            artifacts   => { installdir => $dir->stringify }
        }
    );
    is $info->libpath, $runtime->stringify, 'a DLL matching the package links wins over one that sorts first (libavif < SDL3_image)';

t/056_process_info.t  view on Meta::CPAN

# directly when a list has exactly one entry (core/base/table.lua:357). A package with a single link therefore arrives
# from `xrepo fetch --json` as the scalar "SDL3_image" rather than ["SDL3_image"]. The four sibling fields are already
# normalized above; this pins the same treatment for links, which used to die on the deref.
subtest 'a single scalar link is normalized to a list' => sub {
    local $^O = 'MSWin32';    # the crash was on the Windows DLL-selection path
    my $dir     = path( tempdir( CLEANUP => 1 ) )->child('scalar_links');
    my $imp     = $dir->child( 'bin', 'SDL3_image.lib' );
    my $codec   = $dir->child( 'bin', 'libavif-16.dll' );
    my $runtime = $dir->child( 'bin', 'SDL3_image.dll' );
    $dir->child('bin')->mkpath;
    for ( $imp, $codec, $runtime ) { $_->spew_utf8(''); }
    my $info = $repo->_process_info(
        {   libfiles    => [ map { $_->stringify } $imp, $codec, $runtime ],
            includedirs => [],
            linkdirs    => [],
            version     => '3.4.18',
            links       => 'SDL3_image',                                       # scalar, as vcpkg reports a one-element links list
            artifacts   => { installdir => $dir->stringify }
        }
    );
    is [ @{ $info->links } ], ['SDL3_image'],      'the scalar link is wrapped back into a list';
    is $info->libpath,        $runtime->stringify, 'the matching DLL still wins the libpath';
};
subtest 'on Windows, DLLs are preferred over import libs even when links match nothing' => sub {
    local $^O = 'MSWin32';
    my $dir   = path( tempdir( CLEANUP => 1 ) )->child('mismatched');
    my $imp   = $dir->child( 'bin', 'sdl3_image.lib' );
    my $codec = $dir->child( 'bin', 'libavif-16.dll' );
    $dir->child('bin')->mkpath;
    for ( $imp, $codec ) { $_->spew_utf8(''); }
    my $info = $repo->_process_info(
        {   libfiles    => [ map { $_->stringify } $imp, $codec ],
            includedirs => [],
            linkdirs    => [],
            version     => '3.4.0',
            links       => ['SDL2_unknown'],
            artifacts   => { installdir => $dir->stringify }
        }
    );
    is $info->libpath, $codec->stringify, 'falls back to the first DLL when no DLL matches the links';

t/057_runtime_deps.t  view on Meta::CPAN

    is $a->loader_env_var,                              'LD_LIBRARY_PATH', 'loader env var from the engine';
    like $a->runtime_dep_report,   qr/libdep\.so \[store\]/, 'report names the dep and its scope';
    unlike $a->runtime_dep_report, qr/KERNEL32/,             'report omits system libraries';
    my $pi = $a->package_info;
    is scalar( @{ $pi->runtime_deps } ), 2, 'package_info carries the runtime deps';
    ok $pi->with_runtime_deps( [] ) == $pi, 'already-attached info is returned unchanged';
};
subtest 'snapshot runtime_deps paths are rebased like other paths' => sub {
    my $share = path( $dir, 'share-snap' )->mkdir;
    my $snap  = $share->child('xrepo-snapshot.json');
    $snap->spew_utf8(
        encode_json(
            {   dist_name    => 'Exotic-Z',
                install_type => 'share',
                packages     => {
                    zstd => {
                        includedirs  => ['zstd/include'],
                        libfiles     => [],
                        license      => undef,
                        linkdirs     => ['zstd/lib'],
                        links        => ['zstd'],



( run in 1.906 second using v1.01-cache-2.11-cpan-234fa220139 )