Alien-Xrepo

 view release on metacpan or  search on metacpan

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

        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)" : () );

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

    }

    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};



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