zoi-rs 1.25.3

Advanced Package Manager & Environment Orchestrator
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
//! # Zoi: The Advanced Package Manager & Environment Orchestrator
//!
//! This crate provides the core functionality of Zoi as a library, allowing
//! other Rust applications to leverage its package management and environment
//! setup capabilities.
//!
//! Architectural Design:
//! Zoi's library API is designed around "Pragmatic Transactionality". It allows
//! programmatic control over the two-phase installation process, SAT-based
//! dependency resolution, and cryptographically verified registry state.
//!
//! For user documentation please visit [Zoi's Docs](https://zillowe.qzz.io/docs/zds/zoi).
//!
//! ## Key Library Entry Points:
//! - `install_sources`: The high-level API used by the CLI for standard
//!   installations.
//! - `resolve_dependency_graph`: Calculate required packages without modifying
//!   disk.
//! - `build_with_options`: Create distributable `.zpa` archives.
//!
//! ## Getting Started
//!
//! To use Zoi as a library, add it using `cargo` or as a dependency in your
//! `Cargo.toml`:
//!
//! ```sh
//! cargo add zoi-rs
//! ```
//!
//! ```toml
//! [dependencies]
//! zoi-rs = "1"
//! ```
//!
//! ## Example: Install a package
//!
//! ```no_run
//! use std::path::Path;
//!
//! use anyhow::Result;
//! use zoi::{Scope, install_package_with_options};
//!
//! fn main() -> Result<()> {
//!     let archive_path =
//!         Path::new("path/to/your/package-1.0.0-linux-amd64.zpa");
//!     let options = zoi::PackageInstallOptions {
//!         scope_override: Some(Scope::User),
//!         registry_handle: "local".to_string(),
//!         yes: true,
//!         ..Default::default()
//!     };
//!
//!     let installed_files =
//!         install_package_with_options(archive_path, &options)?;
//!
//!     println!(
//!         "Package installed successfully. {} files were installed.",
//!         installed_files.len()
//!     );
//!
//!     Ok(())
//! }
//! ```

use std::path::{Path, PathBuf};

use anyhow::Result;
use colored::Colorize;
pub use zoi_cli::{cli, cmd, pkg, project};
pub use zoi_core::types::{self, Scope};
pub use zoi_core::utils;

/// Options for building a package from a `.pkg.lua` definition.
#[derive(Debug, Clone)]
pub struct BuildOptions<'a> {
    /// Build type to use, such as `source` or `pre-compiled`.
    pub build_type: Option<&'a str>,
    /// Target platforms to build for. Use platform strings such as
    /// `linux-amd64`.
    pub platforms: Vec<String>,
    /// Optional PGP key name or fingerprint used to sign the output archive.
    pub sign_key: Option<String>,
    /// Optional directory to output the built package to.
    pub output_dir: Option<PathBuf>,
    /// Optional sub-packages to build.
    pub sub_packages: Option<Vec<String>>,
    /// Whether to install build-time dependencies before building.
    pub install_deps: bool,
    /// Whether to run tests before building.
    pub test: bool,
    /// Build backend to use. Supported values are `native` and `docker`.
    pub method: &'a str,
    /// Docker image to use when `method` is `docker`.
    pub image: Option<&'a str>,
    /// Optional package version override.
    pub version_override: Option<&'a str>,
    /// Whether to force root ownership (UID/GID 0) in the built archive.
    pub fakeroot: bool
}

impl Default for BuildOptions<'_> {
    fn default() -> Self {
        Self {
            build_type: None,
            platforms: vec![
                zoi_core::utils::get_platform()
                    .unwrap_or_else(|_| "linux-amd64".to_string()),
            ],
            sign_key: None,
            output_dir: None,
            sub_packages: None,
            install_deps: true,
            test: false,
            method: "native",
            image: None,
            version_override: None,
            fakeroot: false
        }
    }
}

/// Options for installing a local `.zpa` archive.
#[derive(Debug, Clone)]
pub struct PackageInstallOptions {
    /// Optional installation scope override.
    pub scope_override: Option<Scope>,
    /// Registry handle to record for the installed package. Use `local` for
    /// local archives.
    pub registry_handle: String,
    /// Automatically answer yes to prompts.
    pub yes: bool,
    /// Optional split-package names to install from the archive.
    pub sub_packages: Option<Vec<String>>,
    /// Whether to create binary links for installed package binaries.
    pub link_bins: bool
}

impl Default for PackageInstallOptions {
    fn default() -> Self {
        Self {
            scope_override: Some(Scope::User),
            registry_handle: "local".to_string(),
            yes: true,
            sub_packages: None,
            link_bins: true
        }
    }
}

/// Options for installing one or more package source strings.
#[derive(Debug, Clone, Default)]
pub struct SourceInstallOptions {
    /// Optional git repository spec for `zoi install --repo`.
    pub repo: Option<String>,
    /// Force reinstalling packages that are already installed.
    pub force: bool,
    /// Accept all optional dependencies.
    pub all_optional: bool,
    /// Automatically answer yes to prompts.
    pub yes: bool,
    /// Optional installation scope override.
    pub scope_override: Option<Scope>,
    /// Save requested packages to the current project's `zoi.yaml`.
    pub save: bool,
    /// Build type to use when building from source.
    pub build_type: Option<String>,
    /// Print the install plan without performing the installation.
    pub dry_run: bool,
    /// Force building from source even when a prebuilt archive is available.
    pub build: bool,
    /// Enforce the current `zoi.lock` exactly for project installs.
    pub frozen: bool
}

/// Options for resolving a dependency graph without installing packages.
#[derive(Debug, Clone, Default)]
pub struct DependencyResolutionOptions {
    /// Optional scope to use when resolving dependencies.
    pub scope_override: Option<Scope>,
    /// Include packages even when they appear to be installed already.
    pub force: bool,
    /// Automatically answer yes to resolver prompts.
    pub yes: bool,
    /// Accept all optional dependencies.
    pub all_optional: bool,
    /// Build type used for selecting typed build dependencies.
    pub build_type: Option<String>,
    /// Suppress non-essential resolver output.
    pub quiet: bool
}

/// Result of resolving a single package source.
#[derive(Debug, Clone)]
pub struct ResolvedPackage {
    /// Parsed package metadata.
    pub package: types::Package,
    /// Resolved package version.
    pub version: String,
    /// Portable manifest information suitable for lockfiles.
    pub sharable_manifest: Option<types::SharableInstallManifest>,
    /// Local path to the resolved package definition.
    pub source_path: PathBuf,
    /// Registry handle, when the source came from a registry.
    pub registry_handle: Option<String>,
    /// Registry repository type (official, community, etc.).
    pub repo_type: Option<String>,
    /// Git commit SHA, when the source came from a git repository.
    pub git_sha: Option<String>
}

/// Dependency graph resolution result.
#[derive(Debug)]
pub struct DependencyResolution {
    /// Resolved Zoi package graph.
    pub graph: zoi_install::resolver::DependencyGraph,
    /// Dependencies handled by external package managers.
    pub non_zoi_dependencies: Vec<String>
}

/// Converts a generic Zoi scope to a CLI-specific install scope.
fn to_install_scope(scope: Scope) -> zoi_cli::cli::InstallScope {
    match scope {
        Scope::User => zoi_cli::cli::InstallScope::User,
        Scope::System => zoi_cli::cli::InstallScope::System,
        Scope::Project => zoi_cli::cli::InstallScope::Project
    }
}

/// Builds a Zoi package from a `.pkg.lua` definition using the provided
/// options.
///
/// # Errors
///
/// Returns an error if the build fails.
pub fn build_with_options(
    package_file: &Path,
    options: &BuildOptions<'_>
) -> Result<()> {
    if options.install_deps {
        for platform in &options.platforms {
            let current_platform = if platform == "current" {
                zoi_core::utils::get_platform()?
            } else {
                platform.clone()
            };

            if let Some(dep_strings) =
                zoi_package::build::get_build_dependencies(
                    package_file,
                    options.build_type,
                    &current_platform,
                    options.version_override,
                    false
                )?
                && !dep_strings.is_empty()
            {
                println!(
                    "{} Installing build dependencies...",
                    "::".bold().blue()
                );
                let processed =
                    std::sync::Mutex::new(std::collections::HashSet::new());
                let mut installed = Vec::new();
                for dep_str in dep_strings {
                    let dep = zoi_deps::parse_dependency_string(&dep_str)?;
                    zoi_install::dep_install::install_dependency(
                        &dep,
                        "build",
                        zoi_core::types::Scope::User,
                        true,
                        true,
                        &processed,
                        &mut installed,
                        None
                    )?;
                }
            }
        }
    }

    zoi_package::build::run(
        package_file,
        options.build_type,
        &options.platforms,
        options.sign_key.clone(),
        options.output_dir.as_deref(),
        options.version_override,
        options.sub_packages.clone(),
        false,
        options.method,
        options.image,
        options.fakeroot,
        options.install_deps,
        options.test
    )
}

/// Installs a local `.zpa` package archive using the provided options.
///
/// # Errors
///
/// Returns an error if the installation fails.
pub fn install_package_with_options(
    package_file: &Path,
    options: &PackageInstallOptions
) -> Result<Vec<String>> {
    zoi_install::pkg_install::run(
        package_file,
        options.scope_override,
        &options.registry_handle,
        None,
        options.yes,
        options.sub_packages.clone(),
        options.link_bins,
        None
    )
}

/// Installs one or more package sources using the provided options.
///
/// Sources can be registry package names, local `.pkg.lua` files, URLs, or
/// local manifests.
///
/// # Errors
///
/// Returns an error if the installation fails.
pub fn install_sources(
    sources: &[String],
    options: &SourceInstallOptions
) -> Result<()> {
    let plugin_manager = if zoi_core::utils::is_mini_mode() {
        None
    } else {
        let pm = zoi_plugins::PluginManager::new()?;
        let _ = pm.load_all(options.yes);
        Some(pm)
    };

    let pm_ptr = plugin_manager.as_ref();

    zoi_cli::cmd::install::run(
        sources,
        options.repo.clone(),
        options.force,
        options.all_optional,
        options.yes,
        options.scope_override.map(to_install_scope),
        false,
        false,
        options.save,
        options.build_type.as_deref(),
        options.dry_run,
        pm_ptr,
        options.build,
        options.frozen,
        false,
        false,
        3,
        false,
        false,
        None
    )
}

/// Updates one or more installed packages.
///
/// This function checks for updates in the configured registries and performs
/// a transactional upgrade if a newer version is available.
///
/// # Errors
///
/// Returns an error if the update fails.
pub fn update_packages(
    all: bool,
    package_names: &[String],
    yes: bool
) -> Result<()> {
    zoi_cli::cmd::update::run(
        all,
        package_names,
        yes,
        false,
        false,
        false,
        false
    )
}

/// Resolves a single source string into a package and its origin metadata.
///
/// # Errors
///
/// Returns an error if resolution fails.
pub fn resolve_package(source: &str, yes: bool) -> Result<ResolvedPackage> {
    let (
        package,
        version,
        sharable_manifest,
        source_path,
        registry_handle,
        repo_type,
        git_sha
    ) = zoi_resolver::resolve::resolve_package_and_version(
        source, None, true, yes
    )?;
    Ok(ResolvedPackage {
        package,
        version,
        sharable_manifest,
        source_path,
        registry_handle,
        repo_type,
        git_sha
    })
}

/// Resolves the dependency graph for one or more package sources.
///
/// # Errors
///
/// Returns an error if resolution fails.
pub fn resolve_dependency_graph(
    sources: &[String],
    options: &DependencyResolutionOptions
) -> Result<DependencyResolution> {
    let (graph, non_zoi_dependencies) =
        zoi_install::resolver::resolve_dependency_graph(
            sources,
            options.scope_override,
            options.force,
            options.yes,
            options.all_optional,
            options.build_type.as_deref(),
            options.quiet,
            None
        )?;
    Ok(DependencyResolution {
        graph,
        non_zoi_dependencies
    })
}

/// Bundles a Zoi package and its local assets into a `.zsa` archive.
///
/// This function intelligently parses the `.pkg.lua` file to identify and
/// include only the necessary local files.
///
/// # Errors
///
/// Returns an error if bundling fails.
pub fn bundle_package(
    package_file: &Path,
    output_dir: Option<&Path>,
    sign: Option<String>,
    version_override: Option<&str>,
    build_type: Option<&str>
) -> Result<()> {
    zoi_package::bundle::run(
        package_file,
        output_dir,
        sign,
        version_override,
        build_type
    )
}

/// Builds a Zoi package from a local `.pkg.lua` file.
///
/// This function reads a package definition, runs the build process, and
/// creates a distributable `.zpa` archive.
///
/// # Arguments
///
/// * `package_file`: Path to the `.pkg.lua` file.
/// * `build_type`: The type of package to build (e.g. "source",
///   "pre-compiled").
/// * `platforms`: A slice of platform strings to build for (e.g.
///   `["linux-amd64"]`).
/// * `sign_key`: An optional PGP key name or fingerprint to sign the package.
///
/// # Errors
///
/// Returns an error if the build process fails, if the package file cannot be
/// read, or if the specified build type is not supported by the package.
///
/// # Examples
///
/// ```no_run
/// use std::path::Path;
///
/// use anyhow::Result;
/// use zoi::build;
///
/// fn main() -> Result<()> {
///     let package_file = Path::new("my-package.pkg.lua");
///     let platforms = vec!["linux-amd64".to_string()];
///     build(
///         package_file,
///         Some("source"),
///         &platforms,
///         None,
///         true,
///         "native",
///         None,
///         None
///     )?;
///     println!("Package built successfully!");
///     Ok(())
/// }
/// ```
pub fn build(
    package_file: &Path,
    build_type: Option<&str>,
    platforms: &[String],
    sign_key: Option<String>,
    install_deps: bool,
    method: &str,
    image: Option<&str>,
    version_override: Option<&str>
) -> Result<()> {
    let options = BuildOptions {
        build_type,
        platforms: platforms.to_vec(),
        sign_key,
        output_dir: None,
        sub_packages: None,
        install_deps,
        test: false,
        method,
        image,
        version_override,
        fakeroot: false
    };
    build_with_options(package_file, &options)
}

/// Installs a Zoi package from a local package archive.
///
/// This function unpacks a `.zpa` archive and installs its contents
/// into the appropriate Zoi store, linking any binaries.
///
/// # Arguments
///
/// * `package_file`: Path to the local package archive.
/// * *`scope_override`*: Optionally override the installation scope (`User`,
///   `System`, `Project`).
/// * `registry_handle`: The handle of the registry this package belongs to
///   (e.g. "zoidberg", or "local").
/// * `yes`: Automatically answer "yes" to any confirmation prompts (e.g. file
///   conflicts).
/// * `sub_packages`: For split packages, optionally specify which sub-packages
///   to install.
///
/// # Returns
///
/// A `Result` containing a `Vec<String>` of all the file paths that were
/// installed.
///
/// # Errors
///
/// Returns an error if the installation fails, such as if the archive is
/// invalid or if there are file system permission issues.
///
/// # Examples
///
/// ```no_run
/// use std::path::Path;
///
/// use anyhow::Result;
/// use zoi::{Scope, install_package};
///
/// fn main() -> Result<()> {
///     let archive_path = Path::new("my-package-1.0.0-linux-amd64.zpa");
///     install_package(archive_path, Some(Scope::User), "local", true, None)?;
///     println!("Package installed!");
///     Ok(())
/// }
/// ```
pub fn install_package(
    package_file: &Path,
    scope_override: Option<Scope>,
    registry_handle: &str,
    yes: bool,
    sub_packages: Option<Vec<String>>
) -> Result<Vec<String>> {
    let options = PackageInstallOptions {
        scope_override,
        registry_handle: registry_handle.to_string(),
        yes,
        sub_packages,
        link_bins: true
    };
    install_package_with_options(package_file, &options)
}

/// Uninstalls a Zoi package.
///
/// This function removes a package's files from the Zoi store and unlinks its
/// binaries.
///
/// # Arguments
///
/// * `package_name`: The package identifier to uninstall. Use an explicit
///   source like `#handle@repo/name[:sub]@version` when multiple installed
///   packages share the same name.
/// * `scope_override`: Optionally specify the scope to uninstall from. If
///   `None`, Zoi will search for the package across all scopes.
///
/// # Errors
///
/// Returns an error if the package is not found or if the uninstallation
/// process fails.
///
/// # Examples
///
/// ```no_run
/// use anyhow::Result;
/// use zoi::{Scope, uninstall_package};
///
/// fn main() -> Result<()> {
///     uninstall_package("my-package", Some(Scope::User))?;
///     println!("Package uninstalled!");
///     Ok(())
/// }
/// ```
pub fn uninstall_package(
    package_name: &str,
    scope_override: Option<Scope>
) -> Result<()> {
    zoi_uninstall::run(package_name, scope_override, false, false, false)
        .map(|_| ())
}