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, anyhow};
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 and prompts to update 'zoi.lua'.
63fn run_project(packages: &[String]) -> Result<()> {
64    if !std::path::Path::new("zoi.lua").exists() {
65        return Err(anyhow!(
66            "No 'zoi.lua' found in the current directory. Run 'zoi use \
67             --global' or initialize a project first."
68        ));
69    }
70
71    println!(
72        "{} Project uses zoi.lua. Automatic saving is not supported for Lua \
73         configurations.",
74        "Note:".yellow().bold()
75    );
76    println!(
77        "   Please add the following to your packages() block in zoi.lua:"
78    );
79    for pkg in packages {
80        println!("   - \"{pkg}\"");
81    }
82
83    println!("{} Installing project packages...", "::".bold().blue());
84    let options = crate::SourceInstallOptions {
85        scope_override: Some(types::Scope::Project),
86        yes: true,
87        ..Default::default()
88    };
89
90    crate::install_sources(packages, &options)?;
91
92    println!("\n{}", "Project packages updated and installed.".green());
93    Ok(())
94}