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
//! Module for the lock file implementation.

use anyhow::Result;
use cargo_component_core::{
    lock::{FileLock, LockFile, LockedPackage, LockedPackageVersion},
    registry::{DependencyResolution, DependencyResolutionMap},
    terminal::{Colors, Terminal},
};
use semver::Version;
use std::{collections::HashMap, path::Path};
use warg_crypto::hash::AnyHash;
use warg_protocol::registry::PackageName;

/// The name of the lock file.
pub const LOCK_FILE_NAME: &str = "wit.lock";

pub(crate) fn acquire_lock_file_ro(
    terminal: &Terminal,
    config_path: &Path,
) -> Result<Option<FileLock>> {
    let path = config_path.with_file_name(LOCK_FILE_NAME);
    if !path.exists() {
        return Ok(None);
    }

    log::info!("opening lock file `{path}`", path = path.display());
    match FileLock::try_open_ro(&path)? {
        Some(lock) => Ok(Some(lock)),
        None => {
            terminal.status_with_color(
                "Blocking",
                format!("on access to lock file `{path}`", path = path.display()),
                Colors::Cyan,
            )?;

            FileLock::open_ro(&path).map(Some)
        }
    }
}

pub(crate) fn acquire_lock_file_rw(terminal: &Terminal, config_path: &Path) -> Result<FileLock> {
    let path = config_path.with_file_name(LOCK_FILE_NAME);
    log::info!("creating lock file `{path}`", path = path.display());
    match FileLock::try_open_rw(&path)? {
        Some(lock) => Ok(lock),
        None => {
            terminal.status_with_color(
                "Blocking",
                format!("on access to lock file `{path}`", path = path.display()),
                Colors::Cyan,
            )?;

            FileLock::open_rw(&path)
        }
    }
}

/// Constructs a `LockFile` from a `DependencyResolutionMap`.
pub fn to_lock_file(map: &DependencyResolutionMap) -> LockFile {
    type PackageKey = (PackageName, Option<String>);
    type VersionsMap = HashMap<String, (Version, AnyHash)>;
    let mut packages: HashMap<PackageKey, VersionsMap> = HashMap::new();

    for resolution in map.values() {
        match resolution.key() {
            Some((id, registry)) => {
                let pkg = match resolution {
                    DependencyResolution::Registry(pkg) => pkg,
                    DependencyResolution::Local(_) => unreachable!(),
                };

                let prev = packages
                    .entry((id.clone(), registry.map(str::to_string)))
                    .or_default()
                    .insert(
                        pkg.requirement.to_string(),
                        (pkg.version.clone(), pkg.digest.clone()),
                    );

                if let Some((prev, _)) = prev {
                    // The same requirements should resolve to the same version
                    assert!(prev == pkg.version)
                }
            }
            None => continue,
        }
    }

    let mut packages: Vec<_> = packages
        .into_iter()
        .map(|((name, registry), versions)| {
            let mut versions: Vec<LockedPackageVersion> = versions
                .into_iter()
                .map(|(requirement, (version, digest))| LockedPackageVersion {
                    requirement,
                    version,
                    digest,
                })
                .collect();

            versions.sort_by(|a, b| a.key().cmp(b.key()));

            LockedPackage {
                name,
                registry,
                versions,
            }
        })
        .collect();

    packages.sort_by(|a, b| a.key().cmp(&b.key()));

    LockFile::new(packages)
}