zoi-cli 1.25.4

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
//! Helper functions for package installation and uninstallation,
//! including elevated operations and validation.

use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf};

use anyhow::{Result, anyhow};
use mlua::{Function, Lua, Table};
use sha2::{Digest, Sha256, Sha512};

use crate::pkg::install::manifest;
use crate::pkg::install::resolver::InstallNode;
use crate::pkg::{local, types};

/// Installs a package with elevated privileges.
///
/// # Errors
///
/// Returns an error if the node JSON file cannot be read, if the node JSON is
/// invalid, or if the installation process fails.
pub fn elevate_install_node(
    cmd: &crate::cmd::helper::ElevateInstallNodeCommand
) -> Result<()> {
    let content = std::fs::read_to_string(&cmd.node_json)?;
    let node: InstallNode = serde_json::from_str(&content)?;

    let pkg = &node.pkg;
    let handle = &node.registry_handle;
    let sub_packages_vec = node.sub_package.clone().map(|s| vec![s]);

    let installed_files = crate::pkg::install::pkg_install::run(
        &cmd.archive,
        Some(pkg.scope),
        handle,
        Some(&node.version),
        cmd.yes,
        sub_packages_vec,
        cmd.link_bins,
        None
    )?;

    if let types::InstallReason::Dependency { ref parent } = node.reason {
        let package_dir =
            local::get_package_dir(pkg.scope, handle, &pkg.repo, &pkg.name)?;
        local::add_dependent(&package_dir, parent)?;
    }

    let manifest = manifest::create_manifest(
        pkg,
        node.reason.clone(),
        node.dependencies.clone(),
        Some(cmd.install_method.clone()),
        installed_files,
        handle,
        node.repo_type.clone(),
        &node.chosen_options,
        &node.chosen_optionals,
        node.sub_package.clone()
    )?;

    local::write_manifest(&manifest)?;
    local::persist_package_source(&manifest, Path::new(&node.source))?;

    Ok(())
}

/// Uninstalls a package with elevated privileges.
///
/// # Errors
///
/// Returns an error if the manifest JSON file cannot be read, if the manifest
/// JSON is invalid, or if the uninstallation process fails.
pub fn elevate_uninstall(
    cmd: &crate::cmd::helper::ElevateUninstallCommand
) -> Result<()> {
    let content = std::fs::read_to_string(&cmd.manifest_json)?;
    let manifest: types::InstallManifest = serde_json::from_str(&content)?;

    let handle = &manifest.registry_handle;
    let scope = manifest.scope;
    let package_dir =
        local::get_package_dir(scope, handle, &manifest.repo, &manifest.name)?;
    let version_dir = package_dir.join(&manifest.version);

    let pkg_lua_path = local::get_package_source_path(&manifest)?;
    let mut pkg_opt = None;
    if pkg_lua_path.exists() {
        let path_str = pkg_lua_path
            .to_str()
            .ok_or_else(|| anyhow!("Package path contains invalid UTF-8"))?;
        if let Ok(p) = crate::pkg::lua::parser::parse_lua_package(
            path_str,
            Some(&manifest.version),
            Some(manifest.scope),
            true
        ) {
            pkg_opt = Some(p);
        }
    }

    if let Some(pkg) = &pkg_opt
        && let Some(hooks) = &pkg.hooks
    {
        let _ = crate::pkg::hooks::run_hooks(
            hooks,
            crate::pkg::hooks::HookType::PreRemove,
            manifest.scope
        );
    }

    if pkg_lua_path.exists() {
        let lua = Lua::new();
        if crate::pkg::lua::functions::setup_lua_environment(
            &lua,
            &crate::pkg::utils::get_platform()?,
            Some(&manifest.version),
            pkg_lua_path.to_str(),
            None,
            None,
            None,
            manifest.sub_package.as_deref(),
            Some(manifest.scope),
            None,
            true
        )
        .is_ok()
        {
            let lua_code = std::fs::read_to_string(&pkg_lua_path)?;
            if lua.load(&lua_code).exec().is_ok() {
                if let Ok(uninstall_fn) =
                    lua.globals().get::<Function>("uninstall")
                {
                    let _ = uninstall_fn.call::<()>(());
                }

                if let Ok(uninstall_ops) =
                    lua.globals().get::<Table>("__ZoiUninstallOperations")
                {
                    for op in uninstall_ops.sequence_values::<Table>() {
                        if let Ok(op) = op
                            && let Ok(op_type) = op.get::<String>("op")
                            && op_type == "zrm"
                        {
                            let mut path_to_remove: String =
                                op.get("path").unwrap_or_default();
                            path_to_remove = path_to_remove.replace(
                                "${pkgstore}",
                                &version_dir.to_string_lossy()
                            );
                            if let Some(home_dir) =
                                crate::pkg::utils::get_user_home()
                            {
                                path_to_remove = path_to_remove.replace(
                                    "${usrhome}",
                                    &home_dir.to_string_lossy()
                                );
                            }
                            path_to_remove = path_to_remove.replace(
                                "${usrroot}",
                                &crate::pkg::sysroot::apply_sysroot(
                                    PathBuf::from("/")
                                )
                                .to_string_lossy()
                            );

                            let path = std::path::PathBuf::from(path_to_remove);
                            if path.exists() {
                                if path.is_dir() {
                                    let _ = std::fs::remove_dir_all(path);
                                } else {
                                    let _ = std::fs::remove_file(path);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    if let Some(bins) = &manifest.bins {
        let bin_root = if cfg!(target_os = "windows") {
            Path::new("C:\\ProgramData\\zoi\\pkgs\\bin").to_path_buf()
        } else {
            Path::new("/usr/local/bin").to_path_buf()
        };

        for bin in bins {
            let symlink_path = bin_root.join(bin);
            if symlink_path.is_symlink() || symlink_path.exists() {
                let _ = std::fs::remove_file(&symlink_path);
            }
        }
    }

    for file_path_str in &manifest.installed_files {
        let file_path = Path::new(file_path_str);
        if file_path.exists() {
            if file_path.is_dir() {
                let _ = std::fs::remove_dir_all(file_path);
            } else {
                let _ = std::fs::remove_file(file_path);
            }
        }
    }

    let manifest_filename = if let Some(sub) = &manifest.sub_package {
        format!("manifest-{sub}.yaml")
    } else {
        "manifest.yaml".to_string()
    };
    let manifest_path = version_dir.join(manifest_filename);
    if manifest_path.exists() {
        std::fs::remove_file(manifest_path)?;
    }

    if version_dir.exists() && std::fs::read_dir(&version_dir)?.next().is_none()
    {
        std::fs::remove_dir_all(version_dir)?;
    }

    if package_dir.exists() {
        let _ = crate::pkg::service::cleanup_service(&manifest.name, scope);
        if let Ok(mut entries) = std::fs::read_dir(&package_dir)
            && entries.next().is_none()
        {
            std::fs::remove_dir_all(package_dir)?;
        }
    }

    let parent_id = format!(
        "#{}@{}/{}@{}",
        manifest.registry_handle,
        manifest.repo,
        manifest.name,
        manifest.version
    );
    for dep_str in &manifest.installed_dependencies {
        if let Ok(dep) =
            crate::pkg::dependencies::parse_dependency_string(dep_str)
            && dep.manager == "zoi"
        {
            let dep_req =
                crate::pkg::resolve::parse_source_string(dep.package)?;
            let dep_matches =
                crate::pkg::local::find_installed_manifests_matching(
                    &dep_req, scope
                )?;
            if dep_matches.len() == 1
                && let Some(dep_manifest) = dep_matches.first()
                && let Ok(dep_pkg_dir) = crate::pkg::local::get_package_dir(
                    dep_manifest.scope,
                    &dep_manifest.registry_handle,
                    &dep_manifest.repo,
                    &dep_manifest.name
                )
            {
                let _ = crate::pkg::local::remove_dependent(
                    &dep_pkg_dir,
                    &parent_id
                );
            }
        }
    }

    if let Some(pkg) = &pkg_opt
        && let Some(hooks) = &pkg.hooks
    {
        let _ = crate::pkg::hooks::run_hooks(
            hooks,
            crate::pkg::hooks::HookType::PostRemove,
            manifest.scope
        );
    }

    Ok(())
}

/// Supported hash types for file verification.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HashType {
    /// SHA-512 hash.
    Sha512,
    /// SHA-256 hash.
    Sha256
}

/// Updates a digest from a reader.
fn update_digest_from_reader<R: Read, D: Digest>(
    reader: &mut R,
    hasher: &mut D
) -> Result<()> {
    let mut buffer = [0; 8192];
    loop {
        let bytes_read = reader.read(&mut buffer)?;
        if bytes_read == 0 {
            break;
        }
        if let Some(chunk) = buffer.get(..bytes_read) {
            hasher.update(chunk);
        }
    }
    Ok(())
}

/// Calculates the hash of a file or remote URL.
///
/// # Errors
///
/// Returns an error if the file cannot be opened or read, or if the remote URL
/// cannot be downloaded.
pub fn get_hash(source: &str, hash_type: HashType) -> Result<String> {
    let mut hasher_sha512 = Sha512::new();
    let mut hasher_sha256 = Sha256::new();

    if source.starts_with("http://") || source.starts_with("https://") {
        let client = crate::pkg::utils::get_http_client()?;
        let mut response = client.get(source).send()?;
        if !response.status().is_success() {
            let status = response.status();
            return Err(anyhow!("Failed to download file from URL: {status}"));
        }
        match hash_type {
            HashType::Sha512 => {
                update_digest_from_reader(&mut response, &mut hasher_sha512)?;
            }
            HashType::Sha256 => {
                update_digest_from_reader(&mut response, &mut hasher_sha256)?;
            }
        }
    } else {
        let mut file = File::open(source)?;
        match hash_type {
            HashType::Sha512 => {
                update_digest_from_reader(&mut file, &mut hasher_sha512)?;
            }
            HashType::Sha256 => {
                update_digest_from_reader(&mut file, &mut hasher_sha256)?;
            }
        }
    }

    let hash = match hash_type {
        HashType::Sha512 => hex::encode(hasher_sha512.finalize()),
        HashType::Sha256 => hex::encode(hasher_sha256.finalize())
    };

    Ok(hash)
}

/// Validation utilities for Zoi specification files.
pub mod validate {
    use std::path::Path;

    use anyhow::{Result, anyhow};
    use colored::Colorize;

    /// Validates a Zoi specification file (e.g. registries.json, repo.yaml).
    ///
    /// # Errors
    ///
    /// Returns an error if the file does not exist, cannot be read, or if the
    /// file content does not match any known Zoi specification.
    pub fn run(file: &Path) -> Result<()> {
        if !file.exists() {
            let path = file.display();
            return Err(anyhow!("File does not exist: {path}"));
        }

        let content = std::fs::read_to_string(file)?;
        let file_name = file
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or_default();

        let path = file.display();
        println!("{} Validating {path}...", "::".bold().blue());

        if file_name == "registries.json" {
            let _: crate::pkg::purl::CentralDbSpec =
                serde_json::from_str(&content).map_err(|e| {
                    anyhow!("Invalid registries.json spec: {e}")
                })?;
            println!(
                "{} file is a valid registries.json spec.",
                "OK".bold().green()
            );
        } else if file_name == "repo.yaml" || file_name == "repo.yml" {
            let _: crate::pkg::types::RepoConfig =
                serde_yaml::from_str(&content)
                    .map_err(|e| anyhow!("Invalid repo.yaml spec: {e}"))?;
            println!("{} file is a valid repo.yaml spec.", "OK".bold().green());
        } else if file_name == "advisories.json" {
            let _: crate::pkg::types::AdvisoryRegistry =
                serde_json::from_str(&content).map_err(|e| {
                    anyhow!("Invalid advisories.json spec: {e}")
                })?;
            println!(
                "{} file is a valid advisories.json spec.",
                "OK".bold().green()
            );
        } else if file_name == "packages.json" {
            let _: crate::pkg::purl::RegistryIndex =
                serde_json::from_str(&content)
                    .map_err(|e| anyhow!("Invalid packages.json spec: {e}"))?;
            println!(
                "{} file is a valid packages.json spec.",
                "OK".bold().green()
            );
        } else if file_name.ends_with(".sec.yaml")
            || file_name.ends_with(".sec.yml")
        {
            let _: crate::pkg::types::Advisory = serde_yaml::from_str(&content)
                .map_err(|e| {
                    anyhow!("Invalid security advisory (.sec.yaml) spec: {e}")
                })?;
            println!("{} file is a valid .sec.yaml spec.", "OK".bold().green());
        } else if file.extension().and_then(|e| e.to_str()) == Some("json") {
            if serde_json::from_str::<crate::pkg::purl::CentralDbSpec>(&content).is_ok() {
                println!("{} file matches registries.json spec.", "OK".bold().green());
            } else if serde_json::from_str::<crate::pkg::types::AdvisoryRegistry>(&content)
                .is_ok()
            {
                println!("{} file matches advisories.json spec.", "OK".bold().green());
            } else if serde_json::from_str::<crate::pkg::purl::RegistryIndex>(&content).is_ok()
            {
                println!("{} file matches packages.json spec.", "OK".bold().green());
            } else {
                return Err(anyhow!(
                    "File does not match any known Zoi JSON spec (registries.json, advisories.json, or packages.json)"
                ));
            }
        } else if file.extension().and_then(|e| e.to_str()) == Some("yaml")
            || file.extension().and_then(|e| e.to_str()) == Some("yml")
        {
            if serde_yaml::from_str::<crate::pkg::types::RepoConfig>(&content)
                .is_ok()
            {
                println!(
                    "{} file matches repo.yaml spec.",
                    "OK".bold().green()
                );
            } else if serde_yaml::from_str::<crate::pkg::types::Advisory>(
                &content
            )
            .is_ok()
            {
                println!(
                    "{} file matches .sec.yaml spec.",
                    "OK".bold().green()
                );
            } else {
                return Err(anyhow!(
                    "File does not match any known Zoi YAML spec (repo.yaml \
                     or .sec.yaml)"
                ));
            }
        } else {
            return Err(anyhow!(
                "Unsupported file extension. Please provide a .json or .yaml \
                 file"
            ));
        }

        Ok(())
    }
}