Skip to main content

zoi_resolver/
local.rs

1//! Local package management and store interaction.
2//!
3//! This module provides functions for interacting with the local package store,
4//! listing installed packages, and managing package manifests and dependencies.
5
6use std::fs;
7use std::path::{Path, PathBuf};
8
9use anyhow::Result;
10use walkdir::WalkDir;
11use zoi_core::types::{self, InstallManifest, Scope};
12use zoi_core::{config, utils};
13
14use crate::resolve::{PackageRequest, get_db_root};
15
16/// Returns the base directory of the package store for a given scope.
17///
18/// # Errors
19///
20/// Returns an error if the store base directory cannot be determined.
21pub fn get_store_base_dir(scope: Scope) -> Result<PathBuf> {
22    utils::get_store_base_dir(scope)
23}
24
25/// Returns the directory for a specific package in the store.
26///
27/// # Errors
28///
29/// Returns an error if the package directory path cannot be constructed.
30pub fn get_package_dir(
31    scope: Scope,
32    registry_handle: &str,
33    repo_path: &str,
34    package_name: &str
35) -> Result<PathBuf> {
36    let base_dir = get_store_base_dir(scope)?;
37    let package_id =
38        utils::generate_package_id(registry_handle, repo_path, package_name);
39    let package_dir_name =
40        utils::get_package_dir_name(&package_id, package_name);
41    Ok(base_dir.join(package_dir_name))
42}
43
44/// Returns the directory for a specific version of a package in the store.
45///
46/// # Errors
47///
48/// Returns an error if the package version directory path cannot be
49/// constructed.
50pub fn get_package_version_dir(
51    scope: Scope,
52    registry_handle: &str,
53    repo_path: &str,
54    package_name: &str,
55    version: &str
56) -> Result<PathBuf> {
57    let package_dir =
58        get_package_dir(scope, registry_handle, repo_path, package_name)?;
59    Ok(package_dir.join(version))
60}
61
62use rayon::prelude::*;
63
64/// Returns a list of all installed packages across all scopes.
65///
66/// # Errors
67///
68/// Returns an error if the store cannot be accessed or manifests cannot be
69/// read.
70pub fn get_installed_packages() -> Result<Vec<InstallManifest>> {
71    let scopes = [Scope::User, Scope::System, Scope::Project];
72
73    let installed: Vec<InstallManifest> = scopes
74        .into_par_iter()
75        .map(|scope| {
76            let mut manifests = Vec::new();
77            if let Ok(store_root) = get_store_base_dir(scope)
78                && store_root.exists()
79                && let Ok(entries) = fs::read_dir(store_root)
80            {
81                for entry in entries.flatten() {
82                    let path = entry.path();
83                    if !path.is_dir() {
84                        continue;
85                    }
86                    let latest_path = path.join("latest");
87                    if (latest_path.is_symlink() || latest_path.is_dir())
88                        && let Ok(sub_entries) = fs::read_dir(&latest_path)
89                    {
90                        for sub_entry in sub_entries.flatten() {
91                            let file_name = sub_entry
92                                .file_name()
93                                .to_string_lossy()
94                                .to_string();
95                            if file_name.starts_with("manifest")
96                                && std::path::Path::new(&file_name)
97                                    .extension()
98                                    .is_some_and(|ext| {
99                                        ext.eq_ignore_ascii_case("yaml")
100                                    })
101                            {
102                                let manifest_path = sub_entry.path();
103                                if manifest_path.exists()
104                                    && let Ok(content) =
105                                        fs::read_to_string(manifest_path)
106                                    && let Ok(manifest) =
107                                        serde_yaml::from_str::<InstallManifest>(
108                                            &content
109                                        )
110                                {
111                                    manifests.push(manifest);
112                                }
113                            }
114                        }
115                    }
116                }
117            }
118            manifests
119        })
120        .flatten()
121        .collect();
122
123    let mut sorted_installed = installed;
124    sorted_installed.sort_by(|a, b| a.name.cmp(&b.name));
125    Ok(sorted_installed)
126}
127
128/// Represents an installed package with basic metadata.
129#[derive(Debug)]
130pub struct InstalledPackage {
131    /// The name of the package.
132    pub name: String,
133    /// The sub-package name, if any.
134    pub sub_package: Option<String>,
135    /// The installed version.
136    pub version: String,
137    /// The repository the package was installed from.
138    pub repo: String,
139    /// The type of package.
140    pub package_type: zoi_core::types::PackageType
141}
142
143/// Returns a list of all installed packages with their basic metadata.
144///
145/// # Errors
146///
147/// Returns an error if installed packages cannot be retrieved.
148pub fn get_installed_packages_with_type() -> Result<Vec<InstalledPackage>> {
149    let manifests = get_installed_packages()?;
150    Ok(manifests
151        .into_iter()
152        .map(|m| InstalledPackage {
153            name: m.name,
154            sub_package: m.sub_package,
155            version: m.version,
156            repo: m.repo,
157            package_type: m.package_type
158        })
159        .collect())
160}
161
162/// Checks if a package is installed in a given scope and returns its manifest
163/// if found.
164///
165/// # Errors
166///
167/// Returns an error if the store cannot be accessed or manifests cannot be
168/// read.
169pub fn is_package_installed(
170    package_name: &str,
171    sub_package_name: Option<&str>,
172    scope: Scope
173) -> Result<Option<InstallManifest>> {
174    let store_root = get_store_base_dir(scope)?;
175    if !store_root.exists() {
176        return Ok(None);
177    }
178
179    for entry in fs::read_dir(store_root)? {
180        let entry = entry?;
181        let path = entry.path();
182        if !path.is_dir() {
183            continue;
184        }
185
186        if let Some(file_name) = path.file_name().and_then(|n| n.to_str()) {
187            let parts: Vec<&str> = file_name.splitn(2, '-').collect();
188            if parts.len() == 2
189                && parts.get(1) == Some(&package_name)
190                && parts.first().is_some_and(|p| p.len() == 32)
191            {
192                let latest_path = path.join("latest");
193                if (latest_path.is_symlink() || latest_path.is_dir())
194                    && let Ok(entries) = fs::read_dir(&latest_path)
195                {
196                    for entry in entries.filter_map(Result::ok) {
197                        let file_name =
198                            entry.file_name().to_string_lossy().to_string();
199                        if file_name.starts_with("manifest")
200                            && std::path::Path::new(&file_name)
201                                .extension()
202                                .is_some_and(|ext| {
203                                    ext.eq_ignore_ascii_case("yaml")
204                                })
205                        {
206                            let manifest_path = entry.path();
207                            if manifest_path.exists() {
208                                let content =
209                                    fs::read_to_string(manifest_path)?;
210                                let manifest: InstallManifest =
211                                    serde_yaml::from_str(&content)?;
212                                if manifest.name == package_name
213                                    && manifest.sub_package.as_deref()
214                                        == sub_package_name
215                                {
216                                    return Ok(Some(manifest));
217                                }
218                            }
219                        }
220                    }
221                }
222            }
223        }
224    }
225
226    Ok(None)
227}
228
229/// Returns all installed manifests in a specific scope.
230///
231/// # Errors
232///
233/// Returns an error if the store cannot be accessed or manifests cannot be
234/// read.
235pub fn get_installed_manifests_in_scope(
236    scope: Scope
237) -> Result<Vec<InstallManifest>> {
238    let store_root = get_store_base_dir(scope)?;
239    if !store_root.exists() {
240        return Ok(Vec::new());
241    }
242
243    let mut manifests = Vec::new();
244    for entry in fs::read_dir(store_root)? {
245        let entry = entry?;
246        let path = entry.path();
247        if !path.is_dir() {
248            continue;
249        }
250
251        let latest_path = path.join("latest");
252        if !(latest_path.is_symlink() || latest_path.is_dir()) {
253            continue;
254        }
255
256        let Ok(entries) = fs::read_dir(&latest_path) else {
257            continue;
258        };
259
260        for entry in entries.filter_map(Result::ok) {
261            let file_name = entry.file_name().to_string_lossy().to_string();
262            if !file_name.starts_with("manifest")
263                || !std::path::Path::new(&file_name)
264                    .extension()
265                    .is_some_and(|ext| ext.eq_ignore_ascii_case("yaml"))
266            {
267                continue;
268            }
269
270            let manifest_path = entry.path();
271            if !manifest_path.exists() {
272                continue;
273            }
274
275            let content = fs::read_to_string(manifest_path)?;
276            let manifest: InstallManifest = serde_yaml::from_str(&content)?;
277            manifests.push(manifest);
278        }
279    }
280
281    Ok(manifests)
282}
283
284/// Finds installed manifests matching a package request in a specific scope.
285///
286/// # Errors
287///
288/// Returns an error if installed manifests cannot be retrieved.
289pub fn find_installed_manifests_matching(
290    request: &PackageRequest,
291    scope: Scope
292) -> Result<Vec<InstallManifest>> {
293    let manifests = get_installed_manifests_in_scope(scope)?;
294    Ok(manifests
295        .into_iter()
296        .filter(|manifest| {
297            manifest.name == request.name
298                && manifest.sub_package == request.sub_package
299                && request
300                    .handle
301                    .as_ref()
302                    .is_none_or(|handle| manifest.registry_handle == *handle)
303                && request
304                    .repo
305                    .as_ref()
306                    .is_none_or(|repo| manifest.repo == *repo)
307                && request
308                    .version_spec
309                    .as_ref()
310                    .is_none_or(|version| manifest.version == *version)
311        })
312        .collect())
313}
314
315/// Formats a package source string from its components.
316pub fn package_source_string(
317    registry_handle: &str,
318    repo: &str,
319    name: &str,
320    sub_package: Option<&str>,
321    version: &str
322) -> String {
323    let registry_handle = registry_handle.trim();
324    let repo = repo.trim();
325    let name = name.trim();
326    let version = version.trim();
327
328    if let Some(sub_package) = sub_package {
329        format!(
330            "#{}@{}/{}:{}@{}",
331            registry_handle,
332            repo,
333            name,
334            sub_package.trim(),
335            version
336        )
337    } else {
338        format!("#{registry_handle}@{repo}/{name}@{version}")
339    }
340}
341
342/// Returns the source string for an installed manifest.
343pub fn installed_manifest_source(manifest: &InstallManifest) -> String {
344    package_source_string(
345        &manifest.registry_handle,
346        &manifest.repo,
347        &manifest.name,
348        manifest.sub_package.as_deref(),
349        &manifest.version
350    )
351}
352
353/// Returns all available packages from a list of repositories.
354///
355/// # Errors
356///
357/// Returns an error if the database root cannot be determined or if package
358/// files cannot be parsed.
359pub fn get_packages_from_repos(
360    repos: &[String]
361) -> Result<Vec<zoi_core::types::Package>> {
362    let db_root = get_db_root()?;
363    if !db_root.exists() {
364        return Err(anyhow::anyhow!(
365            "Package database not found. Please run 'zoi sync' first."
366        ));
367    }
368
369    let mut available = Vec::new();
370
371    for repo_name in repos {
372        let repo_path = db_root.join(repo_name);
373        if !repo_path.exists() {
374            continue;
375        }
376        for entry in WalkDir::new(repo_path).into_iter().filter_map(Result::ok)
377        {
378            if !entry.file_type().is_dir() {
379                continue;
380            }
381
382            let pkg_name = entry.file_name().to_string_lossy();
383            let pkg_file_path =
384                entry.path().join(format!("{pkg_name}.pkg.lua"));
385
386            if pkg_file_path.is_file() {
387                let pkg_file_path_str =
388                    pkg_file_path.to_str().ok_or_else(|| {
389                        anyhow::anyhow!(
390                            "Package path contains invalid UTF-8: {}",
391                            pkg_file_path.display()
392                        )
393                    })?;
394                let mut pkg: zoi_core::types::Package =
395                    zoi_lua::parser::parse_lua_package(
396                        pkg_file_path_str,
397                        None,
398                        None,
399                        true
400                    )?;
401
402                if let Ok(repo_subpath) = entry.path().strip_prefix(&db_root) {
403                    let mut repo_path = repo_subpath
404                        .to_string_lossy()
405                        .to_string()
406                        .replace('\\', "/");
407                    let pkg_name_suffix = format!("/{}", pkg.name);
408                    if repo_path.ends_with(&pkg_name_suffix) {
409                        repo_path = repo_path
410                            [..repo_path.len() - pkg_name_suffix.len()]
411                            .to_string();
412                    } else if repo_path == pkg.name {
413                        repo_path = String::new();
414                    }
415                    pkg.repo = repo_path;
416                }
417
418                available.push(pkg);
419            }
420        }
421    }
422
423    available.sort_by(|a, b| a.name.cmp(&b.name));
424    Ok(available)
425}
426
427/// Returns all available packages in the default registry.
428///
429/// # Errors
430///
431/// Returns an error if the configuration cannot be read or available packages
432/// cannot be retrieved.
433pub fn get_all_available_packages() -> Result<Vec<zoi_core::types::Package>> {
434    let config = config::read_config()?;
435    if let Some(handle) = config
436        .default_registry
437        .as_ref()
438        .map(|r| &r.handle)
439        .filter(|h| !h.is_empty())
440    {
441        let repos_with_handle: Vec<String> = config
442            .repos
443            .iter()
444            .map(|repo| format!("{handle}/{repo}"))
445            .collect();
446        get_packages_from_repos(&repos_with_handle)
447    } else {
448        Ok(Vec::new())
449    }
450}
451
452/// Adds a dependent ID to a package's dependents list.
453///
454/// # Errors
455///
456/// Returns an error if the dependent file cannot be written.
457pub fn add_dependent(package_dir: &Path, dependent_id: &str) -> Result<()> {
458    let dependents_dir = package_dir.join("dependents");
459    fs::create_dir_all(&dependents_dir)?;
460    let dependent_file = dependents_dir.join(hex::encode(dependent_id));
461    fs::write(dependent_file, "")?;
462    Ok(())
463}
464
465/// Removes a dependent ID from a package's dependents list.
466///
467/// # Errors
468///
469/// Returns an error if the dependent file cannot be removed.
470pub fn remove_dependent(package_dir: &Path, dependent_id: &str) -> Result<()> {
471    let dependents_dir = package_dir.join("dependents");
472    if dependents_dir.exists() {
473        let dependent_file = dependents_dir.join(hex::encode(dependent_id));
474        if dependent_file.exists() {
475            fs::remove_file(dependent_file)?;
476        } else if let Some(pos) = dependent_id.rfind('@') {
477            let legacy_id = &dependent_id[..pos];
478            let legacy_file = dependents_dir.join(hex::encode(legacy_id));
479            if legacy_file.exists() {
480                fs::remove_file(legacy_file)?;
481            }
482        }
483    }
484    Ok(())
485}
486
487/// Returns a list of all dependent IDs for a package.
488///
489/// # Errors
490///
491/// Returns an error if the dependents directory cannot be read.
492pub fn get_dependents(package_dir: &Path) -> Result<Vec<String>> {
493    let dependents_dir = package_dir.join("dependents");
494    let mut dependents = Vec::new();
495    if dependents_dir.exists() {
496        for entry in fs::read_dir(dependents_dir)? {
497            let entry = entry?;
498            let path = entry.path();
499            if path.is_file()
500                && let Some(file_name) =
501                    path.file_name().and_then(|s| s.to_str())
502                && let Ok(decoded) = hex::decode(file_name)
503                && let Ok(dependent_id) = String::from_utf8(decoded)
504            {
505                dependents.push(dependent_id);
506            }
507        }
508    }
509    Ok(dependents)
510}
511
512/// Writes an installation manifest to the store and updates the 'latest'
513/// symlink.
514///
515/// # Errors
516///
517/// Returns an error if the manifest cannot be serialized or written.
518pub fn write_manifest(manifest: &InstallManifest) -> Result<()> {
519    let version_dir = get_package_version_dir(
520        manifest.scope,
521        &manifest.registry_handle,
522        &manifest.repo,
523        &manifest.name,
524        &manifest.version
525    )?;
526    fs::create_dir_all(&version_dir)?;
527
528    let manifest_filename = if let Some(sub) = &manifest.sub_package {
529        format!("manifest-{sub}.yaml")
530    } else {
531        "manifest.yaml".to_string()
532    };
533    let manifest_path = version_dir.join(manifest_filename);
534
535    let content = serde_yaml::to_string(&manifest)?;
536    fs::write(manifest_path, content)?;
537
538    let package_dir = get_package_dir(
539        manifest.scope,
540        &manifest.registry_handle,
541        &manifest.repo,
542        &manifest.name
543    )?;
544    let latest_symlink_path = package_dir.join("latest");
545    zoi_core::utils::symlink_dir(&version_dir, &latest_symlink_path)?;
546
547    Ok(())
548}
549
550/// Returns the path where the package source file should be stored.
551///
552/// # Errors
553///
554/// Returns an error if the source path cannot be constructed.
555pub fn get_package_source_path(manifest: &InstallManifest) -> Result<PathBuf> {
556    let version_dir = get_package_version_dir(
557        manifest.scope,
558        &manifest.registry_handle,
559        &manifest.repo,
560        &manifest.name,
561        &manifest.version
562    )?;
563    Ok(version_dir.join("package.pkg.lua"))
564}
565
566/// Persists the package source file to the store.
567///
568/// # Errors
569///
570/// Returns an error if the source file cannot be copied.
571pub fn persist_package_source(
572    manifest: &InstallManifest,
573    source_path: &Path
574) -> Result<()> {
575    let stored_source_path = get_package_source_path(manifest)?;
576    if let Some(parent) = stored_source_path.parent() {
577        fs::create_dir_all(parent)?;
578    }
579    fs::copy(source_path, stored_source_path)?;
580    Ok(())
581}
582
583/// Updates the installation reason in a package's manifest.
584///
585/// # Errors
586///
587/// Returns an error if the manifest cannot be updated.
588pub fn update_manifest_reason(
589    manifest: &InstallManifest,
590    new_reason: types::InstallReason
591) -> Result<()> {
592    let mut updated_manifest = manifest.clone();
593    updated_manifest.reason = new_reason;
594    write_manifest(&updated_manifest)?;
595    Ok(())
596}