Alien-Xrepo

 view release on metacpan or  search on metacpan

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

use v5.40;
use feature 'class';
no warnings 'experimental::class';
#
class Alien::Xrepo v1.0.11 {
    use Alien::Xmake;
    use Alien::Xrepo::PackageInfo;
    use JSON::PP;
    use Digest::SHA qw[sha1_hex];
    use File::Copy  qw[move];
    use File::Temp  ();
    use Path::Tiny;
    use Config;
    use Capture::Tiny qw[capture capture_merged];
    use Cwd           ();
    #
    # Guards for the throwaway package files written for `system` installs; each File::Temp::Dir removes its
    # directory on DESTROY, so they are parked here for the life of the object.
    field $pkgfile_guards : param //= [];
    field $verbose        : param //= 0;
    field $diagnosis      : param //= 0;
    field $root           : param //= undef;
    field $theme          : param //= 'plain';

    # Auto-confirm interactive xrepo/xmake prompts (e.g. -y / --confirm=yes). Useful when output is captured so a
    # prompting install never hangs waiting on stdin.
    field $yes     : param //= 0;
    field $confirm : param //= ();
    field $xmake = Alien::Xmake->new;

    # Default package kind (-k) for every action; a per-call `kind` wins. undef omits -k so installs match a bare
    # `xrepo` command, matching cd52e9b behavior.
    field $kind : param //= ();

    # Warm-start resolution cache. install() memorizes a successful fetch result under this instance's store so a
    # repeat launch skips xrepo entirely. Entries are LRU-bounded and a hit is only trusted while its recorded install
    # dir still exists. Pass cache => 0 to disable (pure fetch-first behavior, one spawn per launch).
    field $cache : param //= 1;

    # Resolve which package store a call should operate on. A per-call `installdir` wins, then the `root` handed to the
    # constructor, then whatever xrepo/the environment chooses (global store).
    method _store_dir (%opts) { return $opts{installdir} // $root }
    method blah       ($msg)  { return unless $verbose; say $msg; }

    # Echo every command we are about to run
    method _debug_cmd (@cmd) {
        my $str = join( ' ', map { /\s/ ? qq{"$_"} : $_ } @cmd );
        my @env;
        push @env, "XMAKE_THEME=$ENV{XMAKE_THEME}"                   if defined $ENV{XMAKE_THEME};
        push @env, "XMAKE_PKG_INSTALLDIR=$ENV{XMAKE_PKG_INSTALLDIR}" if defined $ENV{XMAKE_PKG_INSTALLDIR};
        push @env, "XMAKE_PKG_CACHEDIR=$ENV{XMAKE_PKG_CACHEDIR}"     if defined $ENV{XMAKE_PKG_CACHEDIR};
        my $env = @env ? ' [ENV ' . join( ' ', @env ) . ']' : '';
        say "[XREPO] $str$env (cwd: @{[ Cwd::getcwd() ]})\n" if $verbose;
        return;
    }

    # Compose the full xrepo spec for a package: `<pkg> <version>` when pinned,
    # the bare name otherwise. One argv element either way, so a version never
    # splits on whitespace.
    method _full_spec ( $pkg_spec, $version ) {
        return defined $version && length $version ? "$pkg_spec $version" : $pkg_spec;
    }

    method install ( $pkg_spec, $version //= (), %opts ) {
        my $full_spec = $self->_full_spec( $pkg_spec, $version );
        local $ENV{XMAKE_THEME}          = $self->_theme(%opts);
        local $ENV{XMAKE_PKG_INSTALLDIR} = $self->_store_dir(%opts) if defined $self->_store_dir(%opts);
        local $ENV{XMAKE_PKG_CACHEDIR}   = $opts{cachedir}          if defined $opts{cachedir};

        # An install that wants system packages is driven through a generated package file instead of a bare spec,
        # because xrepo's shim decides `system` for us otherwise (see _package_file). The common arguments for
        # install and fetch: the mutating install gets an implicit -y unless the caller opted out; fetch is query-only,
        # so no confirm. configs ride along in the package file when there is one, since the shim drops --extra there.
        # The install also carries the optional -v/-D verbosity flags (see _verbosity_args); they are only added here
        # because install is the one action whose output is not captured and parsed.
        my $pkgfile = $self->_package_file( $full_spec, \%opts );
        my @args    = (
            $self->_confirm_args( \%opts ),
            $self->_build_args( defined $pkgfile ? { %opts, configs => undef } : \%opts ),
            $self->_verbosity_args( \%opts )
        );
        say "[*] xrepo: ensuring $full_spec is installed..." if $verbose;

        # Warm path: a prior successful install+fetch is replayed straight from disk, so a repeat launch (eg/webui.pl)
        # skips xrepo entirely. The LRU is validated against the recorded files (install dir and, when recorded, the
        # first lib) before an entry is trusted.
        my $use_cache = defined $opts{cache} ? $opts{cache}                                                    : $cache;
        my $key       = $use_cache           ? $self->_cache_key( $full_spec, \%opts )                         : undef;
        my $meta      = $use_cache           ? ( $self->_cache_load(%opts) || { order => [], entries => {} } ) : undef;
        if ( $meta && defined $key ) {
            if ( my $hit = $self->_cache_get( $key, $meta ) ) {
                my $info = eval { $self->_process_info( decode_json( $hit->{json} ) ) };
                if ( ref $info ) {
                    $self->_guard_store( $info, %opts );
                    $self->_cache_save( $meta, %opts );
                    return $info;
                }
            }
        }

        # Fetch-first: an already-installed package answers with real paths immediately, so the mutating install is
        # skipped (and the result is memorized for next launch).
        my ( $data, $err ) = $self->_try_fetch( $full_spec, \%opts );
        if ( defined $data && $self->_info_installed($data) ) {
            say "[*] xrepo: $full_spec already installed, reusing fetch result..." if $verbose;
            if ( $meta && defined $key ) {
                $self->_cache_put( $key, $meta, $self->_cache_entry($data) );
                $self->_cache_save( $meta, %opts );
            }
            return $self->_finalize( $data, %opts );
        }

        # Cold path: install, then fetch (which must succeed, since it tells us where things land).
        my @install_cmd = $self->_argv( 'install', \@args, defined $pkgfile ? $pkgfile : $full_spec );
        $self->_debug_cmd(@install_cmd);
        $self->blah("Running: @install_cmd");
        eval { system @install_cmd };
        if ( my $spawn_err = $@ ) {
            chomp $spawn_err;
            die "xrepo install failed for $full_spec\n" .
                "  command: @install_cmd\n" .
                ( $^O eq 'MSWin32' ? "  win32:   $^E\n" : () ) .
                "  error:   $spawn_err\n";
        }
        if ( $? != 0 ) {
            die "xrepo install failed for $full_spec\n" . "  command: @install_cmd\n" . "  exit:    " . ( $? >> 8 ) . "\n";
        }
        say "[*] xrepo: fetching paths..." if $verbose;
        my $fresh = $self->_require_fetch( $full_spec, \%opts, $err );
        if ( $meta && defined $key ) {
            $self->_cache_put( $key, $meta, $self->_cache_entry($fresh) );
            $self->_cache_save( $meta, %opts );
        }
        $self->_finalize( $fresh, %opts );
    }

    # LRU cap on cached resolutions. Entries are just the fetch JSON plus its install dir, so the bound keeps the file
    # a few hundred KB even after a long debugging session.
    sub _CACHE_MAX () {64}

    # Where the resolution cache lives: alongside the caller's/instance's store when one is set, else the xmake global
    # dir (~/.xmake) that xrepo itself uses for the default per-user store.
    method _cache_dir (%opts) {
        my $store = $self->_store_dir(%opts);
        return path($store)->child('.alien-xmake') if defined $store && length $store;
        my $home = $ENV{XMAKE_GLOBALDIR};
        $home //= $ENV{HOME};
        if ( !defined $home || !length $home ) {
            $home = $^O eq 'MSWin32' ? "$ENV{HOMEDRIVE}$ENV{HOMEPATH}" : ();
        }
        return () if !defined $home || !length $home;
        path($home)->child( '.xmake', '.alien-xmake' );
    }

    # Cache identity: everything that can move the installed layout. configs values run through the same boolean
    # stringifier as the CLI, so built-in true/false produce a stable key.
    method _cache_key ( $full_spec, $opts ) {
        my @parts = ( $full_spec, $opts->{kind} // '', $opts->{plat} // '', $opts->{arch} // '', $opts->{mode} // '' );

        # The private-build path and the system path can resolve a different package layout (one lands in this store,
        # the other may be satisfied from outside it), so they must not share a cache entry.
        push @parts, 'system' if $opts->{system};
        if ( my $c = $opts->{configs} ) {
            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};
    }

    method _cache_get ( $key, $meta ) {
        my $e = $meta->{entries}{$key} or return ();
        return () unless $self->_entry_alive($e);
        $e->{last_used} = time;
        $meta->{order}  = [ $key, grep { $_ ne $key } @{ $meta->{order} } ];
        $e;
    }

    method _cache_put ( $key, $meta, $entry, $max //= _CACHE_MAX() ) {
        $meta->{entries}{$key} = $entry;
        $meta->{order} = [ $key, grep { $_ ne $key } @{ $meta->{order} } ];
        while ( @{ $meta->{order} } > $max ) {
            delete $meta->{entries}{ pop @{ $meta->{order} } };
        }
        $meta;
    }

    method _cache_entry ($data) {
        my $info  = ref $data eq 'ARRAY' ? $data->[0] : $data;
        my %entry = ( json => encode_json($data), last_used => time );
        if ( ref $info eq 'HASH' ) {
            my $art = $info->{artifacts};
            if    ( ref $art eq 'HASH' && defined $art->{installdir} ) { $entry{installdir} = $art->{installdir}; }
            elsif ( defined $info->{installdir} )                      { $entry{installdir} = $info->{installdir}; }
            my $libs = $info->{libfiles} // [];
            $libs = [$libs] unless ref $libs eq 'ARRAY';
            if (@$libs) { $entry{libpath} = $libs->[0]; }
        }
        \%entry;
    }

    method _try_fetch ( $full_spec, $opts ) {
        my @fetch_args = $self->_build_args($opts);
        my @fetch_cmd  = $self->_argv( 'fetch', [ '--json', @fetch_args ], $full_spec );
        $self->_debug_cmd(@fetch_cmd);
        $self->blah("Running: @fetch_cmd");
        my ( $out, $err, $exit ) = capture { system @fetch_cmd };
        return ( undef, "Command: @fetch_cmd\nError:\n$err" ) if $exit != 0;
        return ( undef, "Command: @fetch_cmd\nNo JSON output" ) unless defined $out && length $out;
        my $data = eval { $self->_decode_json_output($out) };
        return ( undef, "Command: @fetch_cmd\n$@" ) if !defined $data;
        ( $data, undef );
    }

    # Mandatory fetch: after an install we have to know where the output landed, so a failure here is fatal. $why
    # carries the earlier probe error so the die explains which attempt failed.
    method _require_fetch ( $full_spec, $opts, $why //= () ) {
        my ( $data, $err ) = $self->_try_fetch( $full_spec, $opts );
        unless ( defined $data ) {
            die "xrepo fetch failed:\n$err\n" . ( defined $why && length $why ? "\n(an earlier fetch probe also failed:\n$why)" : () );
        }
        $data;
    }

    # Verify a fetched record corresponds to files that actually exist on disk; xrepo fetch of a not-yet-installed
    # package can still exit 0 with an empty/speculative record.
    method _info_installed ($data) {
        my $info = ref $data eq 'ARRAY' ? $data->[0] : $data;
        return () unless ref $info eq 'HASH';
        my $art        = $info->{artifacts};
        my $installdir = ref $art eq 'HASH' && defined $art->{installdir} ? $art->{installdir} : $info->{installdir};
        return 1 if defined $installdir && -d $installdir;
        my $libs = $info->{libfiles} // [];
        $libs = [$libs] unless ref $libs eq 'ARRAY';
        for my $f (@$libs) { return 1 if -f $f; }
        my $bins = $info->{bindirs} // [];
        $bins = [$bins] unless ref $bins eq 'ARRAY';
        for my $d (@$bins) { return 1 if -d $d; }
        ();
    }

    # A pinned store (constructor `root` or per-call `installdir`) promises a self-contained layout but xmake can
    # satisfy a requirement from the system (Homebrew, apt, ...) instead of building into the store. Such a resolution
    # lives OUTSIDE the pinned store, so it would silently break the promise; it is rejected here rather than returned.
    # A caller that explicitly asked for system packages (see _package_file) has traded that promise away on purpose,
    # so for those the guard stands down.
    method _finalize ( $data, %opts ) {
        return () unless defined $data;
        $data = $data->[0] if ref $data eq 'ARRAY';
        $self->_guard_store( $data, %opts );
        return $self->_process_info($data);
    }

    method _guard_store ( $info, %opts ) {
        my $store = $self->_store_dir(%opts);
        return $info unless defined $store && length $store;

        # `system` asks xmake to prefer the machine's own packages (Homebrew, apt, vcpkg, ...); resolving outside the
        # store is the point of the request, not a violation of it, so the pinned-store promise does not apply.
        return $info if $opts{system};
        return $info if $self->_in_store( $info, $store );
        my $found = $self->_anchor_of($info) // 'an unknown location';
        die "xrepo resolved a package outside the requested store (wanted '$store', found '$found'). " .
            'xmake prefers system packages (e.g. Homebrew, apt) over building, so an isolated ' .
            'install is impossible for this package. Drop the root/installdir requirement or use ' .

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

        my $ref = ref $info;
        return $info->installdir if $ref eq 'Alien::Xrepo::PackageInfo' && defined $info->installdir;
        return $info->libpath    if $ref eq 'Alien::Xrepo::PackageInfo' && defined $info->libpath;
        return () unless $ref eq 'HASH';
        my $art = $info->{artifacts};
        return $art->{installdir}  if ref $art eq 'HASH' && defined $art->{installdir};
        return $info->{installdir} if defined $info->{installdir};
        my $libs = $info->{libfiles} // [];
        $libs = [$libs] unless ref $libs eq 'ARRAY';
        my $incs = $info->{includedirs} // [];
        $incs = [$incs] unless ref $incs eq 'ARRAY';
        return path( $libs->[0] )->parent->parent->stringify if @$libs;
        return path( $incs->[0] )->parent->stringify         if @$incs;
        ();
    }

    method uninstall ( $pkg_spec, %opts ) {
        local $ENV{XMAKE_THEME}          = $self->_theme(%opts);
        local $ENV{XMAKE_PKG_INSTALLDIR} = $self->_store_dir(%opts) if defined $self->_store_dir(%opts);
        local $ENV{XMAKE_PKG_CACHEDIR}   = $opts{cachedir}          if defined $opts{cachedir};
        my @args = ( $self->_confirm_args( \%opts ), $self->_build_args( \%opts ) );
        push @args, '--all'   if $opts{all};
        push @args, '--force' if $opts{force};
        say "[*] xrepo: uninstalling $pkg_spec..." if $verbose;
        my @cmd = $self->_argv( 'remove', \@args, $pkg_spec );
        system @cmd;
    }

    # Parse C<xrepo search> (a.k.a. C<xmake require --search>) output. The layout per matched query term:
    #
    #     The package names:                    (or "The addon names:" with --addon)
    #         <query>:
    #           -> <name>[-<version>]: <description> (in <repo>)
    #
    # The token before the first ": " is the package identity exactly as xrepo prints it. Names can contain '-', e.g.
    # serial-tools-v1.0.4 is the package serial-tools at version 1.0.4, but zlib-ng-2.3.3 could read as name 'zlib-ng'
    # OR name 'zlib-ng-2.3.3' with no version - the name/version boundary is not derivable from output alone, so
    # callers receive the whole token (install() accepts it as a versioned spec). '::' namespaces (vcpkg::pcre) contain
    # ':' but never ': '.
    #
    # xrepo iterates the per-query blocks in Lua hash order (unordered), but each call runs one query, so there is
    # exactly one block and the within-block order is deterministic (Levenshtein-sorted by the matched name).
    #
    # xrepo will accept patches to export this to json but I'm lazy
    method _parse_search ($out) {
        my %seen;
        my @hits;
        for my $line ( split /\r?\n/, $out // '' ) {
            next unless $line =~ /^\s{6}->\s+(.+?): (.*)$/;
            my $token = $1;
            push @hits, $token unless $seen{$token}++;
        }
        return @hits;
    }

    method search ( $query, %opts ) {
        local $ENV{XMAKE_THEME} = $self->_theme(%opts);
        say "[*] xrepo: searching for $query..." if $verbose;
        my @flags = $opts{addon} ? ('--addon') : ();
        my @cmd   = $self->_argv( 'search', \@flags, $query );
        $self->_debug_cmd(@cmd);
        my ( $out, $err, $exit ) = capture { system @cmd };
        if ( $exit != 0 ) {
            warn "Alien::Xrepo: search for '$query' failed (exit $exit): $err\n";
            return;
        }
        return $self->_parse_search($out);
    }

    method clean (%opts) {
        local $ENV{XMAKE_THEME}          = $self->_theme(%opts);
        local $ENV{XMAKE_PKG_INSTALLDIR} = $self->_store_dir(%opts) if defined $self->_store_dir(%opts);
        local $ENV{XMAKE_PKG_CACHEDIR}   = $opts{cachedir}          if defined $opts{cachedir};
        say '[*] xrepo: cleaning cache...' if $verbose;
        my @cmd = $self->_argv( 'clean', ['-y'] );
        system @cmd;
    }

    method add_repo ( $name, $url, $branch //= () ) {
        local $ENV{XMAKE_THEME} = $self->_theme;
        say "[*] xrepo: adding repo $name..." if $verbose;
        my @cmd = $self->_argv( 'add-repo', ['-y'], $name, $url, $branch );
        my ( $out, $err, $exit ) = capture { system @cmd };
        die "xrepo add-repo failed:\n$err" if $exit != 0;
        1;
    }

    method rm_repo ($name) {
        local $ENV{XMAKE_THEME} = $self->_theme;
        say "[*] xrepo: removing repo $name..." if $verbose;
        my @cmd = $self->_argv( 'rm-repo', ['-y'], $name );
        system @cmd;
    }

    method update_repo ( $name //= () ) {
        local $ENV{XMAKE_THEME} = $self->_theme;
        say '[*] xrepo: updating repositories...' if $verbose;
        my @cmd = $self->_argv( 'update-repo', ['-y'], $name );
        system @cmd;
    }

    # xrepo's install shim (xmake/modules/private/xrepo/action/install.lua) always re-execs
    method _package_file ( $full_spec, $opts ) {
        return () unless $opts->{system};
        my ($name) = split( /\s+/, $full_spec );
        my $dir = File::Temp->newdir( 'alien-xrepo-XXXXXXXX', TMPDIR => 1 );
        push @$pkgfile_guards, $dir;    # File::Temp::Dir deletes itself on DESTROY, so hold it for the object's life
        my $file = path("$dir")->child('xrepo.lua');

        # configs move out of the command line and into add_requireconfs, since with a package file the shim
        # ignores --configs anyway. `kind` is not a config on the shim's path (it only feeds the dropped --extra),
        # so fold the shared/static choice in explicitly.
        my %configs = ref $opts->{configs} eq 'HASH' ? %{ $opts->{configs} } : ();
        my $kind    = defined $opts->{kind} && length $opts->{kind} ? $opts->{kind} : $kind;
        $configs{shared} = $kind eq 'static' ? false : true if !exists $opts->{no_kind} && defined $kind && length $kind;

        # NOTE: no `system` option at all. In xmake, `system = true` means system packages ONLY (it errors out
        # 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"};
    }

    # Render a configs value as Lua. Perl's v5.40 built-in true/false are refs, so compare against the same
    # _bool_str the command line uses and never emit 1 / "".
    method _lua_value ($v) {

        # A JSON::PP::Boolean (including false, which is falsey but a ref) renders through the same
        # _bool_str the command line uses, so built-in true/false never leak out as 1 / "".
        return Alien::Xmake::_bool_str($v) if ref $v;
        my $b = Alien::Xmake::_bool_str($v);
        return 'false' if $b eq '' || $b eq 'false';
        return 'true'  if $b eq 'true';
        return $b      if $b =~ /\A-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?\z/;    # 0/1 stay numbers, as --configs renders them
        return $self->_lua_str($b);
    }
    method _lua_key ($k) { $k =~ /\A[A-Za-z_][A-Za-z0-9_]*\z/ ? $k : $self->_lua_str($k) }
    #
    method _build_args ( $opts, $extra //= [] ) {
        my @args;

        # Auto-confirm interactive xrepo/xmake prompts so captured installs never hang.
        my $yes_c     = $opts->{yes}     // $yes;
        my $confirm_c = $opts->{confirm} // $confirm;
        push @args, '--confirm=' . $confirm_c if defined $confirm_c && length $confirm_c;
        push @args, '-y'                      if $yes_c             && !( defined $confirm_c && length $confirm_c );

        # Standard xmake/xrepo flags
        push @args, '-p', $opts->{plat} if $opts->{plat};                    # platform (iphoneos, android, etc)
        push @args, '-a', $opts->{arch} if $opts->{arch};                    # architecture (arm64, x86_64)
        push @args, '-m', $opts->{mode} if $opts->{mode};                    # debug/release
        my $kind = defined $opts->{kind} && length $opts->{kind} ? $opts->{kind} : $kind;
        push @args, '-k', $kind
            if !exists $opts->{no_kind} && defined $kind && length $kind;    # emit `-k` only when a consumer asks for a specific kind
        push @args, '--toolchain=' . $opts->{toolchain}           if $opts->{toolchain};
        push @args, '--toolchain_host=' . $opts->{toolchain_host} if $opts->{toolchain_host};

        # Visual Studio
        push @args, '--vs=' . $opts->{vs}                 if $opts->{vs};
        push @args, '--vs_toolset=' . $opts->{vs_toolset} if $opts->{vs_toolset};
        push @args, '--vs_sdkver=' . $opts->{vs_sdkver}   if $opts->{vs_sdkver};

        # Android NDK
        push @args, '--ndk=' . $opts->{ndk} if $opts->{ndk};

        # Cross compilation
        push @args, '--sdk=' . $opts->{sdk}     if $opts->{sdk};
        push @args, '--mingw=' . $opts->{mingw} if $opts->{mingw};

        # Parallel builds / linking
        push @args, '-j', $opts->{jobs} if $opts->{jobs};
        push @args, '--linkjobs=' . $opts->{linkjobs} if $opts->{linkjobs};

        # Other configuration
        push @args, '--force'                         if $opts->{force};
        push @args, '--shallow'                       if $opts->{shallow};
        push @args, '--build'                         if $opts->{build};
        push @args, '--debugdir=' . $opts->{debugdir} if $opts->{debugdir};

        # Complex configs (passed as --configs='key=val,key2=val2')
        if ( my $c = $opts->{configs} ) {
            if ( ref $c eq 'HASH' ) {
                my $str = join( ',', map { "$_=" . Alien::Xmake::_bool_str( $c->{$_} ) } sort keys %$c );
                push @args, "--configs=$str";
            }
            else {
                push @args, "--configs=$c";
            }
        }

        # Build Includes. xrepo splits the `--includes` value on the OS path separator and rejoins with path.joinenv
        # into XMAKE_RCFILES, the contents of which are textually PREPENDED to the temp project xmake.lua. Only genuine
        # root-scope rc content (add_toolchains, etc.) belongs here: a vendored *package recipe* (package() {...}) is
        # invalid in that scope and dies with e.g. "unknown interface: add_rules()", so recipe overrides are not supported.
        my @rc;
        if ( my $i = $opts->{includes} ) {
            my @incs = ref $i eq 'ARRAY' ? @$i : split( /\Q$Config{path_sep}\E/, $i );
            push @rc,   map { path($_)->absolute->stringify } @incs;
            push @args, '--includes=' . join( $Config{path_sep}, @rc ) if @rc;
        }

        # Extra per-action flags (e.g. --json, --cflags, --ldflags)
        push @args, @$extra;
        return @args;
    }

    # Theme used for xmake/xrepo output. Defaults to 'plain' (no ANSI); callers may pass `theme =>` per-call, or
    # `theme =>` to the constructor. xmake reads $ENV{XMAKE_THEME}.
    method _theme (%opts) { $opts{theme} // $theme }

    # Assemble a full xrepo CLI argv
    method _ensure_working_project () {
        return unless $^O eq 'MSWin32';
        my $tmp = $ENV{TEMP};
        return unless defined $tmp && length $tmp && -d $tmp;
        my ( undef, undef, undef, $mday, $mon, $year ) = localtime;
        my $work = path($tmp)->child( '.xmake', sprintf( '%02d%02d%02d', $year % 100, $mon + 1, $mday ), 'xrepo', 'working' );
        $work->mkpath;
        my $xmake_lua = $work->child('xmake.lua');
        if ( !$xmake_lua->exists || $xmake_lua->slurp =~ /\$\{/ ) {

            # A failed create leaves a read-only raw template here; Path::Tiny's spew renames over it and dies
            # Permission denied, so unlink first.
            $xmake_lua->remove if $xmake_lua->exists;
            $xmake_lua->spew(<<~'add_rules');
                add_rules("mode.debug", "mode.release")
                    target("working")
                        set_kind("binary")
                        add_files("src/*.cpp")
                add_rules
            my $main = $work->child( 'src', 'main.cpp' );
            $work->child('src')->mkpath               unless $main->parent->is_dir;
            $main->spew("int main() { return 0; }\n") unless $main->exists;
            return;
        }
    }

    method _ensure_templates_available() {
        return unless $^O eq 'MSWin32';
        my $exe = eval { $xmake->exe };
        return unless defined $exe && length $exe && -e $exe;
        my $src = path($exe)->parent->child('templates');
        return unless $src->is_dir;

        # ExtUtils::Install ships these as 0444, and on Windows that attribute survives xmake's
        # {writeable=true} copy, so `xmake create` dies "cannot open file ... Permission denied" while
        # rewriting the copied xmake.lua. The installed tree under perl/lib should stay read-only, so mirror
        # the built-in templates into the user's writable xmake global dir instead -- <globaldir>/templates,
        # xmake's own per-user override, which it resolves before <programdir>/templates. Seeded once per
        # installed xmake version; an upgrade recopies the mirror wholesale.
        #
        # The global dir comes from xmake itself: its `~` mapping (LOCALAPPDATA on Windows) and the
        # %APPDATA% legacy fallback are not portable to replicate in Perl, but `lua -c` prints the very
        # directory create will consult. Single-quoted Lua strings only: win32's naive argv quoting mangles
        # embedded double quotes (which surfaces as a bogus "Can't spawn" warning and exit 255).
        my $script  = q{import('core.base.global'); print('XREPO_GLOBALDIR=' .. global.directory())};
        my $lines   = capture { system $exe, 'lua', '-c', $script };
        my ($gldir) = $lines =~ /^XREPO_GLOBALDIR=(.+)$/m;
        return unless defined $gldir;
        $gldir =~ s/\s+$//;
        my $dst = path($gldir)->child('templates');
        $dst->mkpath;
        my $marker = $dst->child('.alien-xrepo-synced');
        my $ver    = eval { $xmake->_getver } // '';
        my $synced = $marker->exists ? $marker->slurp : '';
        return if length $synced && ( !length $ver || $synced eq "$ver\n" );
        $src->visit(
            sub {
                my $file = shift;
                return if $file->is_dir;
                my $to = $dst->child( $file->relative($src) );
                $to->parent->mkpath;

                # Windows copies carry the source's read-only attribute with them, so force the per-user mirror
                # writable (it lives in <globaldir>/templates, xmake's own mutable per-user template override).
                $file->copy($to);
                $to->chmod( $to->stat->mode | 0200 );
            },
            { recurse => 1 }
        );
        $marker->spew("$ver\n");
    }

    method _argv ( $action, $flags, @spec ) {
        $self->_ensure_working_project;
        $self->_ensure_templates_available;

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

    }

    method env ( $program //= (), %opts ) {
        local $ENV{XMAKE_THEME}          = $self->_theme(%opts);
        local $ENV{XMAKE_PKG_INSTALLDIR} = $self->_store_dir(%opts) if defined $self->_store_dir(%opts);
        local $ENV{XMAKE_PKG_CACHEDIR}   = $opts{cachedir}          if defined $opts{cachedir};
        my @extra;
        push @extra, '--show' if $opts{show};
        push @extra, '--add',    $opts{add}    if $opts{add};
        push @extra, '--remove', $opts{remove} if $opts{remove};
        push @extra, '-l' if $opts{list};
        push @extra, '-b', $opts{bind} if $opts{bind};
        my @args = $self->_build_args( { %opts, no_kind => 1 }, \@extra );
        my @cmd  = $self->_argv( 'env', \@args, ( defined $program && length $program ) ? $program : (), @{ $opts{arguments} // [] } );
        say "[*] xrepo: running in package environment..." if $verbose;
        system @cmd;
    }

    # Decode xrepo `--json` output. xrepo can prefix the JSON with non-JSON "checking for X" chatter (e.g. the
    # MSVC/compiler check on first install on Windows), so we skip leading prose lines and decode starting at the first
    # JSON value line instead of demanding the whole capture be pure JSON.
    method _decode_json_output ($raw) {
        die "xrepo produced no JSON: got empty output" unless defined $raw && length $raw;
        my ( $rest, $found );
        for my $line ( split /\r?\n/, $raw ) {
            if ( $line =~ /^\s*[\[{"]/ ) { $found = 1; }
            next unless $found;
            $rest .= $line . "\n";
        }
        die "xrepo produced no JSON; the probe/check chatter did not yield any JSON value.\nOutput was:\n$raw" unless $found;
        my $decoded = eval { decode_json($rest) };
        die "Failed to decode xrepo JSON output: $@\nOutput was:\n$raw" if !defined $decoded;
        return $decoded;
    }

    # A shared library's own `libpath` is only half the story for an FFI consumer: the dynamic linker resolves
    # its DT_NEEDED/import-table/LC_LOAD_DYLIB entries *before* dlopen returns, so any transitive library that
    # is not on the loader's default search path (a vendored freetype behind libsdl3_ttf, say) has to be made
    # findable first. xmake already knows how to read those tables (a native C reader in core.base.binutils,
    # with dumpbin/ldd/otool fallbacks) and how to resolve @rpath/@loader_path/$ORIGIN/absolute names against a
    # set of search paths. These methods expose that as a post-install diagnostic.
    #
    # The environment variable this platform's loader consults last (Windows) or at all (ELF/Mach-O).
    method loader_env_var () {
        return 'PATH'              if $^O eq 'MSWin32';
        return 'DYLD_LIBRARY_PATH' if $^O eq 'darwin';
        return 'LD_LIBRARY_PATH';
    }

    # `xrepo fetch --json --deps` emits one entry per package in the dependency closure (the package plus
    # everything it transitively needs), each with its own libfiles/linkdirs/bindirs/installdir. The plain
    # fetch collapses to the primary package, so this is what lets a caller find where a transitive provider
    # (freetype behind libsdl3_ttf) lives.
    method fetch_closure ( $pkg_spec, $version //= (), %opts ) {
        my $full_spec = $self->_full_spec( $pkg_spec, $version );
        local $ENV{XMAKE_THEME}          = $self->_theme(%opts);
        local $ENV{XMAKE_PKG_INSTALLDIR} = $self->_store_dir(%opts) if defined $self->_store_dir(%opts);
        local $ENV{XMAKE_PKG_CACHEDIR}   = $opts{cachedir}          if defined $opts{cachedir};
        my @args = ( '--json', $self->_build_args( \%opts, ['--deps'] ) );
        my @cmd  = $self->_argv( 'fetch', \@args, $full_spec );
        $self->_debug_cmd(@cmd);
        $self->blah("Running: @cmd");
        my ( $out, $err, $exit ) = capture { system @cmd };
        return () if $exit != 0;
        my $data = eval { $self->_decode_json_output($out) };
        return () unless ref $data eq 'ARRAY';
        return grep { ref $_ eq 'HASH' } @$data;
    }

    # Ask xmake to list the direct runtime dependencies of $libpath, resolving each to an absolute path where
    # possible using the supplied search directories. Returns the raw entries: an absolute path when resolved,
    # otherwise the bare loader name (e.g. `KERNEL32.dll`).
    method scan_runtime_deps ( $libpath, @search_dirs ) {
        return () unless defined $libpath && length $libpath && -f $libpath;
        my $script = File::Temp->new( SUFFIX => '.lua' );
        print {$script} <<~'LUA';
            import("core.base.json")
            import("utils.binary.deplibs")
            function main(lib, ...)
                local dirs = {...}
                local deps = deplibs(lib, {resolve_path = true, resolve_search_paths = dirs}) or {}
                io.write(json.encode(deps or {}), "\n")
            end
            LUA
        close $script;
        local $ENV{XMAKE_THEME} = $theme;
        my @cmd = ( $xmake->exe, 'l', '-q', $script->filename, $libpath, grep {defined} @search_dirs );
        $self->_debug_cmd(@cmd);
        my ( $out, $err, $exit ) = capture { system @cmd };
        return () if $exit != 0;
        my $deps = eval { $self->_decode_json_output($out) };
        return () unless ref $deps eq 'ARRAY';
        return @$deps;
    }

    # Scan $libpath and classify every direct dependency by where it lives:
    #   store      - resolved into one of the provided store/closure directories (the consumer must make it findable)
    #   host       - resolved somewhere else on the machine that is not a default system dir (Homebrew, /usr/local)
    #   system     - a default OS library directory, or a loader-name that is plainly part of the C runtime
    #   unresolved - a bare name that matched no search dir and no system pattern (the genuinely missing case)
    # Options: search_dirs => [...], store_dirs => [...], system_dirs => [...] (defaults to this OS's dirs).
    method runtime_deps ( $libpath, %opts ) {
        my @raw = $self->scan_runtime_deps( $libpath, @{ $opts{search_dirs} // [] } );
        return [] unless @raw;
        my @store  = @{ $opts{store_dirs}  // [] };
        my @system = @{ $opts{system_dirs} // [ $self->_system_lib_dirs ] };
        my @out;
        for my $dep (@raw) {
            next unless defined $dep && length $dep;
            my %r = ( raw => $dep );
            if ( path($dep)->is_absolute ) {
                my $p = path($dep);
                $r{path}  = $p->stringify;
                $r{name}  = $p->basename;
                $r{dir}   = $p->parent->stringify;
                $r{scope} = $self->_path_under( $r{path}, @store ) ? 'store' : $self->_path_under( $r{path}, @system ) ? 'system' : 'host';
            }
            else {
                $r{name}  = $dep;
                $r{scope} = $self->_looks_system_lib($dep) ? 'system' : 'unresolved';
            }
            push @out, \%r;
        }
        return \@out;
    }

    # Directories to offer the loader when resolving a library's dependency table, plus the install roots used to
    # recognise a resolved path as "ours". Input is a list of fetch/closure entries (each with an optional
    # artifacts.installdir and libfiles / linkdirs / bindirs). Returns (\@search_dirs, \@store_dirs).
    method dep_search_dirs ($entries) {
        my ( @search, @store, %seen );
        my $add = sub { my $d = shift; return unless defined $d && length $d; push @search, $d unless $seen{$d}++ };
        for my $e ( grep { ref $_ eq 'HASH' } @{ $entries // [] } ) {
            my $id = $e->{artifacts}{installdir};
            if ( defined $id && length $id ) {
                push @store, $id;
                $add->( path($id)->child($_)->stringify ) for qw[bin lib];
            }
            for my $key (qw[libfiles linkdirs bindirs]) {
                my $v = $e->{$key} // [];
                $v = [$v] unless ref $v eq 'ARRAY';
                for my $p (@$v) {
                    next unless defined $p && length $p;
                    $add->( $key eq 'libfiles' ? path($p)->parent->stringify : $p );
                }
            }
        }
        return ( \@search, \@store );



( run in 0.829 second using v1.01-cache-2.11-cpan-c32d3c3b8f1 )