Alien-Xrepo

 view release on metacpan or  search on metacpan

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

=pod

=encoding utf-8

=head1 NAME

Alien::Xrepo - Install libraries and third-party binaries for FFI, XS, and build systems

=head1 SYNOPSIS

    use v5.40;
    use Alien::Xrepo;
    use Path::Tiny;

    # Initialize
    my $repo = Alien::Xrepo->new();
    # my $repo = Alien::Xrepo->new( cache => 0 );   # live resolution, skip the warmed cache

    # Add a custom repository (optional)
    # $repo->add_repo( 'my-repo', 'https://github.com/my/repo.git' );

    # Install a shared lib with automatic configuration
    my $ogg = $repo->install('libvorbis');

    # Install a library with specific configuration
    # equivalent to: xrepo install -p windows -a x86_64 -m debug --configs='shared=true,vs_runtime=MD' libpng
    my $pkg = $repo->install(
        'libpng', '1.6.x',
        plat    => 'windows',
        arch    => 'x64',
        mode    => 'debug',
        configs => { vs_runtime => 'MD' }
    );
    die 'Install failed' unless $pkg;

    # Or install a binary tool and run it (ninja, cmake, python, node, ...)
    my $ninja = $repo->install('ninja');
    my ($ninja_exe) = map { path($_)->child($^O eq 'MSWin32' ? 'ninja.exe' : 'ninja') } $ninja->bin_dir;
    system $ninja_exe, '--version';

    # Wrap a single function from sqlite3 with Affix
    use Affix;
    my $sqlite3 = $repo->install('sqlite3');
    affix $sqlite3->libpath, 'sqlite3_libversion', [], String;
    say 'SQLite version: ' . sqlite3_libversion();

=head1 DESCRIPTION

This module acts as an intelligent bridge between Perl and a wide range of package systems:

=over

=item * L<xrepo|https://packages.xmake.io/>

=item * L<vcpkg|https://vcpkg.io/en/packages>

=item * L<conan|https://conan.io/center>

=item * L<brew|https://brew.sh/> (Homebrew/Linuxbrew)

=item * L<conda|https://anaconda.org/>

=item * L<dub|https://dub.pm/> (Dlang libs)

=item * L<apt|https://www.debian.org/distrib/packages> on Debian

=item * L<pacman|https://wiki.archlinux.org/title/Pacman#Installing_packages> (if you use Arch, btw)

=item * L<clib|https://github.com/clibs/clib/>

=item * L<Cargo|https://crates.io/> for Rust crates

=item * L<Portage|https://packages.gentoo.org/> on Gentoo

=item * L<Nimble|https://nimpackages.com/> for Nimlang

=item * L<NuGet|https://www.nuget.org/> for .NET

=item * L<Zypper|https://documentation.suse.com/smart/systems-management/html/concept-zypper/index.html> on openSUSE

=item * ...and even your own custom repositories as local files or a remote Git repo

=back

All with smart prerequisite management and dependency resolution.

With a single line, you can fetch or build static and shared libraries and install binary tools (interpreters, build
systems, etc.) without touching the system package manager. C<Alien::Xrepo> takes care of the most difficult parts of
C<Alien> management:

=over

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

=item B<kind>

Default package kind (C<shared> or C<static>) for every action this instance performs. A per-call C<kind =E<gt> ...>
wins. If left unset (the default), C<-k> is omitted entirely so installs behave exactly like a bare C<xrepo install>.
Useful when you know every package this repo builds should be a specific kind (e.g., C<shared> for FFI consumers).

=item B<cache>

Boolean, default on. C<install> memorizes each successful fetch result on disk (see L</"C<install( ... )>"> below) so a
repeated launch resolves the package with zero C<xrepo> spawns. Entries are LRU-bounded and validated against the
recorded install dir, so an uninstalled package is automatically forgotten and rebuilt. Pass C<cache =E<gt> 0> for pure
fetch-first behavior (one spawn per launch, none cached).

=back

=head2 C<install( ... )>

    my $pkg_info = $repo->install( $package_name, $version_constraint, %options );

Installs (if missing) and fetches the metadata for a package.

Resolution is staged so repeated calls avoid the C<xmake> process startup cost entirely:

=over

=item 1. A warm cache hit replays the memorized fetch result without invoking C<xrepo>. The entry is only trusted while its recorded install directory still exists on disk, and stale entries automatically prune themselves. (See the B<cache> construct...

=item 2. Otherwise, C<fetch --json> is tried first: an already-installed package answers with real paths immediately and the mutating C<xrepo install> is skipped. That single fetch is also memorized for next time.

=item 3. Only when a package truly is missing does C<xrepo install> run, followed by a mandatory fetch to learn where its output landed.

=back

=over

=item C<$package_name>

The name of the package (e.g., C<zlib>, C<opencv>).

=item B<$version_constraint>

Optional semantic version string (C<1.2.x>, C<latest>). Pass C<undef> or an empty string for the default.

=item C<%options>

Optional configuration options passed to C<xrepo> (shared by most other methods; missing options are filled in
automatically):

=over

=item C<plat>

Target platform (e.g., C<windows>, C<linux>, C<macosx>, C<android>, C<iphoneos>, C<wasm>).

=item C<arch>

Target architecture (e.g., C<x86_64>, C<arm64>, C<riscv64>).

=item C<mode>

Build mode: C<debug> or C<release>.

=item C<kind>

Library kind: C<shared> or C<static>. If omitted entirely, the package's own default applies, so a bare install behaves
exactly like C<xrepo install>.

I<Note: For FFI, you almost always want C<shared>, but C<static> is available if you are linking archives with, say, an
XS module.>

=item C<toolchain>

Specify a toolchain (e.g., C<llvm>, C<zig>, C<mingw>).

=item C<toolchain_host>

Specify the host toolchain for cross-compilation.

=item C<vs>, C<vs_toolset>, C<vs_sdkver>

Visual Studio toolset/SDK selection (e.g., C<--vs=2017>, C<--vs_toolset=14.0>).

=item C<ndk>

The Android NDK directory.

=item C<sdk>

The SDK directory of a cross-toolchain.

=item C<mingw>

The MinGW SDK directory.

=item C<jobs>, B<linkjobs>

Parallel compilation/link job counts.

=item C<force>

I<install/download>: force reinstall/redownload all packages. I<remove>: force removal even when still depended on.

=item C<shallow>

Do not install/download dependent packages.

=item C<build>

Always build and install from source.

=item C<debugdir>

Source directory used for debugging; enables C<force> and C<shallow> by default.

=item C<configs( ... )>

A hashref or string of package-specific configurations.

    configs => { openssl => 'true', shared => 'true' }
    # becomes --configs='openssl=true,shared=true'

Perl's built-in boolean scalars (C<use feature 'true'/'false'>, enabled by C<use v5.36+>) are normalized to the literal
strings C<'true'> / C<'false'>, so C<< configs => { shared => true } >> produces C<--configs='shared=true'>.

=item C<includes>

A list or string of extra C<rc> files to include in the environment.

Each include is forwarded to C<xmake> verbatim, so it must be a valid root-scope C<xmake> configuration (e.g.,
C<add_toolchains>); C<xmake> textually prepends C<rc> contents to the temporary project script. A vendored C<package()
{...}> recipe is NOT supported here: it is invalid in project scope and dies with e.g., C<unknown interface:
add_rules()>. The value is split/rejoined on the OS path separator (C<$Config{path_sep}>), and each path is normalized
to an absolute path before being passed on.

=item C<installdir>, B<cachedir>

Root directories for the installed packages and the download/build cache, applied per-call via the
C<XMAKE_PKG_INSTALLDIR> / C<XMAKE_PKG_CACHEDIR> environment variables. This lets each wrapper keep its libraries in a
project-local directory instead of the shared per-user store, which gives reproducible builds and protects against an
unrelated C<xrepo> run upgrading or removing the packages your wrapper depends on. Pass the same values to C<fetch>,
C<scan>, C<uninstall>, and friends so they operate on the same store.

=item C<theme>

Per-call C<xmake> output theme override. Defaults to the C<theme> constructor value (C<plain>). See L</"new( [...] )">.

=item C<yes>, C<confirm>

Per-call auto-confirmation overrides for the constructor C<yes =E<gt> ...> / C<confirm =E<gt> ...> options, applied as
C<-y> or C<--confirm=...> to the underlying C<xrepo> invocation. Defaults to the constructor values. See L</"new( [...]
)">.

=item C<cache>

Per-call override for the constructor C<cache> option (default on). Pass C<cache =E<gt> 0> to skip the on-disk replay
for this one resolution (still fetch-first). See L</"new( [...] )">.

=back

=back

Returns an L<Alien::Xrepo::PackageInfo> object.

=head2 C<fetch( ..., [ ... ] )>

    my $pkg_info = $repo->fetch( 'libpng' );
    my $cflags   = $repo->fetch( 'zlib', undef, cflags => 1 );

Fetches metadata for an already-installed package without installing it again. Returns an L<Alien::Xrepo::PackageInfo>
object, or a raw flag string when C<cflags> or C<ldflags> is requested.

=over

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

    }
    else {
        warn "zlib is unavailable in the configured repositories\n";
    }

C<search> returns whole tokens (C<zlib-v1.3.2>, C<zlib-ng-2.3.3>, ...), so C<grep> narrows the list to plain-name
matches even though C<xrepo search> also lists packages whose description matches the query.

=head3 Run a binary tool and check it worked

C<env> wraps the given program with the package's environment (PATH already adjusted) and returns its exit status, so
it doubles as a smoke test that the tool actually runs:

    use v5.40;
    use Alien::Xrepo;

    my $repo = Alien::Xrepo->new;
    my $cmake = $repo->install('cmake');            # kind: binary
    my $rc = $repo->env('cmake', '--version');      # runs cmake with its bin_dir on PATH
    die "cmake failed to run" unless $rc == 0;

=head3 Bundle a package for offline use

C<download> fetches the source archives without building, C<import_pkg> drops them into the local cache, and a
subsequent C<install> uses them even on a machine with no network. Handy for air-gapped CI or offline installs:

    use v5.40;
    use Alien::Xrepo;

    my $repo = Alien::Xrepo->new;

    $repo->download( 'zlib', undef, outputdir => './dl', shallow => 1 );   # fetch sources (no build)
    $repo->import_pkg( 'zlib', undef, packagedir => './dl' );              # load into the cache
    my $zlib = $repo->install('zlib');                                     # install offline
    say 'installed ' . $zlib->version;

=head3 Render the dependency graph

C<info( ... depgraph => 1, format => 'dot')> emits a Graphviz C<DOT> description of a package and everything it pulls
in. Pipe it to C<dot -Tpng dep.dot -o dep.png> to picture how a library's prerequisites resolve:

    use v5.40;
    use Alien::Xrepo;

    my $dot = Alien::Xrepo->new->info( 'libpng', depgraph => 1, format => 'dot' );
    say $dot;    # e.g.  dot -Tpng dep.dot -o dep.png

=head3 Cross-compile a library, then read its compiler/link flags

Install a library for another platform/architecture (the same switches C<xrepo> accepts become named options), then
C<fetch> the C<-I...> / C<-L.../-l...> flags you would pass to your own compiler:

    use v5.40;
    use Alien::Xrepo;

    my $repo = Alien::Xrepo->new;
    $repo->install(
        'libpng', '1.6.x',
        plat => 'windows',
        arch => 'x64',
        mode => 'debug',
        kind => 'shared'
    );

    my $cflags  = $repo->fetch( 'libpng', undef, cflags  => 1 );   # "-Ic:/.../include ..."
    my $ldflags = $repo->fetch( 'libpng', undef, ldflags => 1 );   # "-Lc:/.../lib -l... .."
    say "CFLAGS:  $cflags";
    say "LDFLAGS: $ldflags";

=head3 Remove a package from the cache

C<uninstall> removes a package from the local store (the same one C<install>/C<fetch>/C<scan> use, or an isolated
C<root> you installed into). It accepts the same options as C<install>; C<all> removes every stored variant, and
C<force> removes a package even when others still depend on it. It returns the underlying exit status, so check C<$?>:

    use v5.40;
    use Alien::Xrepo;

    my $repo = Alien::Xrepo->new;

    $repo->uninstall('freetype');               # remove one package
    $repo->uninstall('zl*', all => 1);          # every variant matching the pattern
    $repo->uninstall('fontconfig', force => 1); # remove even if still depended upon

Note that this edits the shared store. Unlike a builder's prune, which slims the C<share> directory a distribution
ships, C<uninstall> frees space in the store you manage yourself.

=head1 Third-party Package Managers

C<xrepo> can install from external package managers instead of (or alongside) the official C<xmake-repo>. You select
the manager with a package-spec namespace and every C<Alien::Xrepo> method takes it verbatim:

    # Vcpkg, Homebrew/Linuxbrew, Conan
    my $zlib = $repo->install( 'vcpkg::zlib' );
    my $zlib = $repo->install( 'brew::zlib'  );
    my $zlib = $repo->install( 'conan::zlib/1.2.11' );

    # Pacman (archlinux/msys2), Clib, Dub, Cargo, Conda, apt
    $repo->install( 'pacman::libcurl' );
    $repo->install( 'dub::log 0.4.3' );

Searching and flag fetching work against them too:

    $repo->search( 'vcpkg::pcre' );          # search the vcpkg namespace
    my $flags = $repo->fetch( 'conan::zlib/1.2.11', undef, cflags => 1, ldflags => 1 );

The installed results (C<libpath>, C<includedirs>, C<links>, ...) are decoded into an L<Alien::Xrepo::PackageInfo>
exactly like any C<xmake-repo> package, so your wrapper code does not care where the library came from.

See the C<xmake-repo> L<integration notes|https://github.com/xmake-io/xrepo-docs/blob/master/getting_started.md> for
the corresponding C<add_requires> syntax inside an C<xmake> project.

=head2 How third-party namespaces are installed

A package in a third-party namespace (C<vcpkg::zlib>) is installed by the I<external> manager, and C<xmake>'s
integration does not bootstrap that manager for you: e.g., the C<vcpkg> integration raises B<C<vcpkg not found!>> when
it cannot locate the tool (C<find_vcpkgdir> checks the C<xmake g --vcpkg> global config, C<$VCPKG_ROOT>,
C<$VCPKG_INSTALLATION_ROOT>, Homebrew, and the Windows C<vcpkg.path.txt> lookup in that order). A recipe that installs
from a third-party namespace therefore lists the B<bare tool package> that owns the namespace as well:

    packages => [ { name => 'vcpkg::zlib' }, { name => 'vcpkg' } ]



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