zoi-install 1.29.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
use std::path::PathBuf;
use std::{env, fs};

use anyhow::{Result, anyhow};
use walkdir::WalkDir;
use zoi_core::config;
use zoi_core::types::Scope;
use zoi_core::utils::{ask_for_confirmation, symlink_file};
use zoi_db as db;
use zoi_plugins::PluginManager;
use zoi_project as project;
use zoi_resolver::{local, resolve};
#[cfg(target_os = "linux")]
use zoi_sandbox as sandbox;

/// Runs a binary through the Zoi shim mechanism.
///
/// # Errors
///
/// Returns an error if the binary cannot be resolved, if sandboxing fails,
/// or if execution of the binary fails.
pub fn run_shim(
    bin_name: &str,
    args: Vec<String>,
    plugin_manager: Option<&PluginManager>,
    auto_install: Option<&dyn Fn(&str, &str) -> Result<()>>
) -> Result<()> {
    let bin_path =
        resolve_to_installed_bin(bin_name, plugin_manager, auto_install)?;

    #[cfg(target_os = "linux")]
    {
        let mut current = bin_path.parent();
        let mut manifest: Option<zoi_core::types::InstallManifest> = None;
        let mut pkg_version_dir = None;

        while let Some(path) = current {
            let mut manifest_path = None;
            if let Ok(entries) = fs::read_dir(path) {
                for entry in entries.flatten() {
                    let name = entry.file_name().to_string_lossy().to_string();
                    if name.starts_with("manifest")
                        && std::path::Path::new(&name)
                            .extension()
                            .is_some_and(|ext| ext.eq_ignore_ascii_case("yaml"))
                    {
                        manifest_path = Some(entry.path());
                        break;
                    }
                }
            }

            if let Some(mp) = manifest_path
                && let Ok(content) = fs::read_to_string(mp)
                && let Ok(m) = serde_yaml::from_str::<
                    zoi_core::types::InstallManifest
                >(&content)
            {
                manifest = Some(m);
                pkg_version_dir = Some(path.to_path_buf());
                break;
            }
            current = path.parent();
        }

        if let Some(m) = manifest
            && let Some(sandbox) = m.sandbox
            && sandbox.enabled
            && let Some(version_dir) = pkg_version_dir
        {
            use std::os::unix::process::CommandExt;
            let mut cmd = sandbox::wrap_command(
                &bin_path,
                &args,
                &sandbox,
                &version_dir
            )?;
            let err = cmd.exec();
            return Err(anyhow!(
                "Failed to execute sandboxed binary '{bin_name}': {err}"
            ));
        }
    }

    let mut cmd = std::process::Command::new(bin_path);
    cmd.args(args);

    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt;
        let err = cmd.exec();
        Err(anyhow!("Failed to execute binary '{bin_name}': {err}"))
    }

    #[cfg(windows)]
    {
        let mut child = cmd.spawn()?;
        let status = child.wait()?;
        std::process::exit(status.code().unwrap_or(0));
    }
}

/// Resolves a binary name to its installed path in the Zoi store.
///
/// # Errors
///
/// Returns an error if the binary cannot be found in the store, if the
/// desired version cannot be determined, or if automatic installation fails.
pub fn resolve_to_installed_bin(
    bin_name: &str,
    plugin_manager: Option<&PluginManager>,
    auto_install: Option<&dyn Fn(&str, &str) -> Result<()>>
) -> Result<PathBuf> {
    let desired_version = get_desired_version(bin_name, plugin_manager)?;

    let providers = db::find_provides("local", bin_name)?;

    if let Some(version) = &desired_version {
        for (pkg, _) in &providers {
            if let Some(path) =
                search_store_for_version(&pkg.name, version, bin_name)?
            {
                return Ok(path);
            }
        }

        if let Some(install) = auto_install
            && ask_for_confirmation(
                &format!(
                    "Binary '{bin_name}' v{version} is required but not \
                     installed. Install it now?"
                ),
                false
            )
        {
            install(bin_name, version)?;
            let providers = db::find_provides("local", bin_name)?;
            for (pkg, _) in &providers {
                if let Some(path) =
                    search_store_for_version(&pkg.name, version, bin_name)?
                {
                    return Ok(path);
                }
            }
        }
    }

    if providers.is_empty() {
        return Err(anyhow!(
            "No installed package provides binary '{bin_name}'. Run 'zoi \
             provides {bin_name}' to find providers."
        ));
    }

    if let Some(version) = &desired_version {
        for (pkg, _) in &providers {
            if let Some(path) =
                search_store_for_version(&pkg.name, version, bin_name)?
            {
                return Ok(path);
            }
        }
    }

    let Some((pkg, _)) = providers.first() else {
        return Err(anyhow!(
            "No installed package provides binary '{bin_name}'."
        ));
    };

    if let Some(path) = search_store_for_version(&pkg.name, "latest", bin_name)?
    {
        return Ok(path);
    }

    let version = pkg.version.as_deref().ok_or_else(|| {
        anyhow!("Package '{}' has no version info in DB", pkg.name)
    })?;

    if let Some(path) = search_store_for_version(&pkg.name, version, bin_name)?
    {
        return Ok(path);
    }

    for scope in [Scope::Project, Scope::User, Scope::System] {
        let store_root = local::get_store_base_dir(scope)?;
        if !store_root.exists() {
            continue;
        }

        for entry in fs::read_dir(store_root)? {
            let entry = entry?;
            let path = entry.path();
            if !path.is_dir() {
                continue;
            }

            if let Some(dir_name) = path.file_name().and_then(|s| s.to_str())
                && dir_name.ends_with(&format!("-{}", pkg.name))
            {
                let latest_dir = path.join("latest");
                if latest_dir.exists()
                    && let Some(p) = find_bin_in_dir(&latest_dir, bin_name)
                {
                    return Ok(p);
                }
            }
        }
    }

    Err(anyhow!(
        "Could not locate binary '{bin_name}' in the Zoi store. Try \
         reinstalling the provider package."
    ))
}

/// Finds the version for a binary in a `.tool-versions` file.
///
/// asdf allows several tool/version pairs on one line
/// (`node 20.1.0 ruby 3.2.1`), so the pairs are walked rather than only the
/// first two tokens. Reading just the first pair silently ignored every tool
/// after the first on a line, so those binaries fell through to `latest`
/// instead of the pinned version.
fn find_tool_versions_version(bin_name: &str) -> Result<Option<String>> {
    find_tool_versions_version_from(bin_name, &env::current_dir()?)
}

/// Searches `start` and its parent directories for a `.tool-versions` entry for
/// `bin_name`.
///
/// Taking the starting directory as an argument keeps this free of the
/// process-wide working directory, so it can be tested without mutating global
/// state.
fn find_tool_versions_version_from(
    bin_name: &str,
    start: &std::path::Path
) -> Result<Option<String>> {
    let mut current_dir = start.to_path_buf();
    loop {
        let tool_versions_path = current_dir.join(".tool-versions");
        if tool_versions_path.exists() {
            let content = fs::read_to_string(&tool_versions_path)?;
            for line in content.lines() {
                let line = line.trim();
                if line.is_empty() || line.starts_with('#') {
                    continue;
                }
                let parts: Vec<&str> = line.split_whitespace().collect();
                for pair in parts.chunks(2) {
                    if let (Some(tool), Some(version)) =
                        (pair.first(), pair.get(1))
                        && *tool == bin_name
                    {
                        return Ok(Some((*version).to_string()));
                    }
                }
            }
        }
        if !current_dir.pop() {
            break;
        }
    }
    Ok(None)
}

/// Gets the desired version for a binary from various sources.
fn get_desired_version(
    bin_name: &str,
    plugin_manager: Option<&PluginManager>
) -> Result<Option<String>> {
    let env_var_name =
        format!("ZOI_{}_VERSION", bin_name.to_uppercase().replace('-', "_"));
    if let Ok(v) = env::var(&env_var_name) {
        return Ok(Some(v));
    }

    if let Some(pm) = plugin_manager
        && let Ok(Some(v)) = pm.trigger_resolve_shim_version(bin_name)
    {
        return Ok(Some(v));
    }

    if let Ok(project_cfg) = project::config::load() {
        for pkg_spec in project_cfg.pkgs {
            if let Ok(req) = resolve::parse_source_string(&pkg_spec) {
                let is_match = req.name == bin_name || {
                    if let Ok(providers) = db::find_provides("local", bin_name)
                    {
                        providers.iter().any(|(p, _)| p.name == req.name)
                    } else {
                        false
                    }
                };

                if is_match && let Some(v) = req.version_spec {
                    return Ok(Some(v));
                }
            }
        }
    }

    if let Ok(Some(v)) = find_tool_versions_version(bin_name) {
        return Ok(Some(v));
    }

    let cfg = config::read_config()?;
    if let Some(v) = cfg.versions.get(bin_name) {
        return Ok(Some(v.clone()));
    }

    Ok(None)
}

/// Searches the Zoi store for a specific version of a package that provides a
/// binary.
fn search_store_for_version(
    pkg_name: &str,
    version: &str,
    bin_name: &str
) -> Result<Option<PathBuf>> {
    for scope in [Scope::Project, Scope::User, Scope::System] {
        let store_root = local::get_store_base_dir(scope)?;
        if !store_root.exists() {
            continue;
        }

        for entry in fs::read_dir(store_root)? {
            let entry = entry?;
            let path = entry.path();
            if !path.is_dir() {
                continue;
            }

            if let Some(dir_name) = path.file_name().and_then(|s| s.to_str())
                && dir_name.ends_with(&format!("-{pkg_name}"))
            {
                let latest_dir = path.join("latest");
                if latest_dir.exists()
                    && (version == "latest" || version.is_empty())
                    && let Some(p) = find_bin_in_dir(&latest_dir, bin_name)
                {
                    return Ok(Some(p));
                }

                if version != "latest" && !version.is_empty() {
                    let version_dir = path.join(version);
                    if version_dir.exists()
                        && let Some(p) = find_bin_in_dir(&version_dir, bin_name)
                    {
                        return Ok(Some(p));
                    }

                    for v_entry in fs::read_dir(&path)? {
                        let v_entry = v_entry?;
                        let v_name =
                            v_entry.file_name().to_string_lossy().to_string();
                        if v_name.starts_with(version)
                            && v_name != "latest"
                            && v_name != "dependents"
                        {
                            let v_dir = path.join(v_name);
                            if let Some(p) = find_bin_in_dir(&v_dir, bin_name) {
                                return Ok(Some(p));
                            }
                        }
                    }
                }
            }
        }
    }
    Ok(None)
}

/// Finds a binary in a directory, checking `bin/` first and then walking the
/// directory.
fn find_bin_in_dir(dir: &std::path::Path, bin_name: &str) -> Option<PathBuf> {
    let bin_path = dir.join("bin").join(bin_name);
    if bin_path.exists() {
        return Some(bin_path);
    }

    for entry in WalkDir::new(dir)
        .into_iter()
        .filter_map(std::result::Result::ok)
    {
        if entry.file_type().is_file()
            && entry.file_name().to_string_lossy() == bin_name
        {
            return Some(entry.path().to_path_buf());
        }
    }
    None
}

/// Creates a shim for the current Zoi executable at the specified path.
///
/// # Errors
///
/// Returns an error if the current executable path cannot be determined
/// or if creating the symbolic link fails.
pub fn create_shim(link_path: &std::path::Path) -> Result<()> {
    let zoi_exe = env::current_exe()?;
    symlink_file(&zoi_exe, link_path)
        .map_err(|e| anyhow!("Failed to create shim: {e}"))
}

#[cfg(test)]
mod tests {
    use super::find_tool_versions_version_from;

    /// Looks up `bin` in a scratch directory holding the given
    /// `.tool-versions` contents.
    fn lookup(contents: &str, bin: &str) -> Option<String> {
        let dir = tempfile::tempdir().expect("temp dir should be created");
        std::fs::write(dir.path().join(".tool-versions"), contents)
            .expect("write should succeed");
        find_tool_versions_version_from(bin, dir.path())
            .expect("lookup should not fail")
    }

    /// asdf allows several tool/version pairs on one line. Every one of them
    /// has to be findable, not just the first.
    #[test]
    fn tool_versions_reads_every_pair_on_a_line() {
        let line = "node 20.1.0 ruby 3.2.1 python 3.12.0";
        assert_eq!(lookup(line, "node").as_deref(), Some("20.1.0"));
        assert_eq!(lookup(line, "ruby").as_deref(), Some("3.2.1"));
        assert_eq!(lookup(line, "python").as_deref(), Some("3.12.0"));
    }

    /// One tool per line must keep working, and an absent tool must stay absent
    /// rather than picking up a neighbour's version.
    #[test]
    fn tool_versions_handles_single_pairs_and_missing_tools() {
        let multi = "node 18.0.0\npython 3.11.0\n";
        assert_eq!(lookup(multi, "node").as_deref(), Some("18.0.0"));
        assert_eq!(lookup(multi, "ruby"), None);
    }
}