Skip to main content

zoi_cli/cmd/
use_cmd.rs

1//! Command for adding and installing packages to a project or global
2//! configuration.
3
4use std::collections::HashMap;
5
6use anyhow::Result;
7use colored::Colorize;
8
9use crate::pkg::{config, types};
10
11/// Runs the 'use' command.
12///
13/// Adds the specified packages to either the global or project configuration
14/// and triggers an installation.
15///
16/// # Errors
17///
18/// Returns an error if:
19/// - A package name cannot be parsed.
20/// - Configuration update fails.
21/// - The installation process fails.
22/// - In project mode, 'zoi.lua' is missing.
23pub fn run(packages: &[String], global: bool) -> Result<()> {
24    if global {
25        run_global(packages)
26    } else {
27        run_project(packages)
28    }
29}
30
31/// Updates the global configuration with the specified packages and installs
32/// them.
33fn run_global(packages: &[String]) -> Result<()> {
34    println!(
35        "{} Adding packages to global configuration...",
36        "::".bold().blue()
37    );
38
39    let mut versions_to_add = HashMap::new();
40    for pkg_spec in packages {
41        let request = crate::pkg::resolve::parse_source_string(pkg_spec)?;
42        let version =
43            request.version_spec.unwrap_or_else(|| "latest".to_string());
44        versions_to_add.insert(request.name, version);
45    }
46
47    config::update_global_versions(versions_to_add)?;
48
49    println!("{} Installing global packages...", "::".bold().blue());
50    let options = crate::SourceInstallOptions {
51        scope_override: Some(types::Scope::User),
52        yes: true,
53        ..Default::default()
54    };
55
56    crate::install_sources(packages, &options)?;
57
58    println!("\n{}", "Global packages updated and installed.".green());
59    Ok(())
60}
61
62/// Installs project packages, persisting them to the `packages({...})`
63/// block of the project's `zoi.lua` file.
64fn run_project(packages: &[String]) -> Result<()> {
65    crate::project::config::add_packages_to_config(packages)?;
66
67    println!("{} Installing project packages...", "::".bold().blue());
68    let options = crate::SourceInstallOptions {
69        scope_override: Some(types::Scope::Project),
70        yes: true,
71        ..Default::default()
72    };
73
74    crate::install_sources(packages, &options)?;
75
76    println!("\n{}", "Project packages updated and installed.".green());
77    Ok(())
78}