aboutsummaryrefslogtreecommitdiffhomepage
path: root/crates/mozart-registry/src/installer_executor/transaction.rs
blob: 95f9718392ac6258a4b598bb0064390285f61d3e (plain)
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
//! Transaction computation — lock-vs-installed diff and alias reconciliation.
//!
//! Mirrors `Composer\DependencyResolver\Transaction::calculateOperations` and
//! `Composer\Installer\InstalledFilesystemRepository` (the `ArrayDumper`
//! path). Kept separate so both `install` and `update` commands can share the
//! same operation-computation machinery without going through the `install`
//! command module.

use crate::installed::{InstalledPackageEntry, InstalledPackages};
use crate::lockfile::{LockFile, LockedPackage};
use indexmap::IndexSet;
use std::path::Path;

/// The action to take for a package during install.
#[derive(Debug, PartialEq, Eq)]
pub enum Action {
    Install,
    Update,
    Skip,
}

/// Compute install operations by comparing locked packages against installed packages.
///
/// Returns `(ops, removals)` where:
/// - `ops`: list of `(package, action)` ordered topologically — every package's
///   lock-internal `require` deps appear before it, matching Composer's
///   `Transaction::calculateOperations`.
/// - `removals`: list of package names that are installed but not locked.
pub fn compute_operations<'a>(
    locked: &[&'a LockedPackage],
    installed: &InstalledPackages,
) -> (Vec<(&'a LockedPackage, Action)>, Vec<String>) {
    let ordered = topological_sort(locked);

    let mut ops: Vec<(&'a LockedPackage, Action)> = Vec::new();
    for pkg in ordered {
        let installed_entry = installed
            .packages
            .iter()
            .find(|p| p.name.eq_ignore_ascii_case(&pkg.name));
        let action = match installed_entry {
            None => Action::Install,
            Some(entry) if entry.version != pkg.version => Action::Update,
            Some(entry) if !installed_refs_match_locked(entry, pkg) => Action::Update,
            Some(entry) if !installed_abandoned_matches_locked(entry, pkg) => Action::Update,
            Some(_) => Action::Skip,
        };
        ops.push((pkg, action));
    }

    // Compute removals: packages in installed but not in locked. Iterate
    // installed.json in reverse, mirroring Composer's
    // `Transaction::calculateOperations`, which seeds `removeMap` from
    // `presentPackages` in order and then `array_unshift`s each entry onto
    // `operations` — flipping the iteration order.
    let locked_names: IndexSet<String> = locked.iter().map(|p| p.name.to_lowercase()).collect();
    let removals: Vec<String> = installed
        .packages
        .iter()
        .rev()
        .filter(|p| !locked_names.contains(&p.name.to_lowercase()))
        .map(|p| p.name.clone())
        .collect();

    (ops, removals)
}

/// Order a slice of locked packages so every package's `require` deps that
/// are present in the same slice come before it. Mirrors
/// `Composer\DependencyResolver\Transaction::calculateOperations` — the
/// stack-based DFS over the result map.
fn topological_sort<'a>(packages: &[&'a LockedPackage]) -> Vec<&'a LockedPackage> {
    use std::collections::BTreeMap;

    // Reverse-alphabetical sort, mirroring `setResultPackageMaps`.
    let mut sorted: Vec<&'a LockedPackage> = packages.to_vec();
    sorted.sort_by_key(|p| std::cmp::Reverse(p.name.to_lowercase()));

    // Multimap: name → [packages]. A package contributes itself under its
    // own name *and* under every `provide`/`replace` entry.
    let mut resolves: BTreeMap<String, Vec<&'a LockedPackage>> = BTreeMap::new();
    for pkg in &sorted {
        let names = std::iter::once(pkg.name.to_lowercase())
            .chain(pkg.provide.keys().map(|s| s.to_lowercase()))
            .chain(pkg.replace.keys().map(|s| s.to_lowercase()));
        for n in names {
            resolves.entry(n).or_default().push(*pkg);
        }
    }

    // Mirror Composer's `getRootPackages`: walk in sorted order, removing
    // each package's required providers from the candidate-roots set.
    let mut roots_set: IndexSet<String> = sorted.iter().map(|p| p.name.to_lowercase()).collect();
    for pkg in &sorted {
        let pkg_lower = pkg.name.to_lowercase();
        if !roots_set.contains(&pkg_lower) {
            continue;
        }
        for dep in pkg.require.keys() {
            let dep_lower = dep.to_lowercase();
            if let Some(matches) = resolves.get(&dep_lower) {
                for &m in matches {
                    let m_lower = m.name.to_lowercase();
                    if m_lower != pkg_lower {
                        roots_set.shift_remove(&m_lower);
                    }
                }
            }
        }
    }

    let mut stack: Vec<&'a LockedPackage> = sorted
        .iter()
        .filter(|p| roots_set.contains(&p.name.to_lowercase()))
        .copied()
        .collect();

    let mut visited: IndexSet<String> = IndexSet::new();
    let mut processed: IndexSet<String> = IndexSet::new();
    let mut ordered: Vec<&'a LockedPackage> = Vec::with_capacity(packages.len());

    while let Some(pkg) = stack.pop() {
        let lower = pkg.name.to_lowercase();
        if processed.contains(&lower) {
            continue;
        }
        if !visited.contains(&lower) {
            visited.insert(lower);
            stack.push(pkg);
            for dep in pkg.require.keys() {
                let dep_lower = dep.to_lowercase();
                if let Some(matches) = resolves.get(&dep_lower) {
                    for &m in matches {
                        stack.push(m);
                    }
                }
            }
        } else {
            processed.insert(lower);
            ordered.push(pkg);
        }
    }

    // Cycle / disconnected fallback: append any leftover packages.
    for pkg in packages {
        let lower = pkg.name.to_lowercase();
        if !processed.contains(&lower) {
            processed.insert(lower);
            ordered.push(*pkg);
        }
    }

    ordered
}

/// Pre-rendered MarkAliasUninstalled operation. Caller pre-computes the
/// display strings so the executor call site stays simple.
pub struct StaleInstalledAlias {
    pub name: String,
    pub alias_full: String,
    pub target_full: String,
}

/// `(package_name_lowercase, alias_pretty)` pairs the *new* lock's packages
/// will surface — used by `compute_stale_installed_aliases` to determine which
/// currently-installed alias packages no longer have a counterpart in the new
/// lock. Mirrors `Locker::getLockedRepository` running every locked package
/// through `ArrayLoader`.
fn lock_alias_pretty_pairs(lock: &LockFile) -> std::collections::HashSet<(String, String)> {
    use std::collections::HashSet;
    let mut set: HashSet<(String, String)> = HashSet::new();
    for a in &lock.aliases {
        set.insert((a.package.to_lowercase(), a.alias.clone()));
    }
    for pkg in lock
        .packages
        .iter()
        .chain(lock.packages_dev.iter().flatten())
    {
        let mut emitted_explicit = false;
        if let Some(map) = pkg
            .extra_fields
            .get("extra")
            .and_then(|e| e.get("branch-alias"))
            .and_then(|b| b.as_object())
        {
            for (source, target) in map {
                if !source.eq_ignore_ascii_case(&pkg.version) {
                    continue;
                }
                let Some(target_str) = target.as_str() else {
                    continue;
                };
                if !target_str.to_lowercase().ends_with("-dev") {
                    continue;
                }
                set.insert((pkg.name.to_lowercase(), target_str.to_string()));
                emitted_explicit = true;
            }
        }
        if emitted_explicit {
            continue;
        }
        let is_default_branch = pkg
            .extra_fields
            .get("default-branch")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);
        if !is_default_branch {
            continue;
        }
        let version_lower = pkg.version.to_lowercase();
        let is_dev_branch = version_lower.starts_with("dev-") || version_lower.ends_with("-dev");
        if !is_dev_branch {
            continue;
        }
        set.insert((pkg.name.to_lowercase(), "9999999-dev".to_string()));
    }
    set
}

/// Walk every `installed.json` entry, expand its `extra.branch-alias` map, and
/// emit a [`StaleInstalledAlias`] for each whose alias version doesn't appear
/// in the new lock. Mirrors `Transaction::calculateOperations`
/// `MarkAliasUninstalledOperation` logic.
pub fn compute_stale_installed_aliases(
    installed: &InstalledPackages,
    lock: &LockFile,
) -> Vec<StaleInstalledAlias> {
    use super::{
        format_full_pretty_version_for_installed, format_full_pretty_with_pretty_for_installed,
    };

    let preserved = lock_alias_pretty_pairs(lock);
    let still_present = |name: &str, alias_pretty: &str| -> bool {
        preserved.contains(&(name.to_lowercase(), alias_pretty.to_string()))
    };
    let mut stale = Vec::new();
    for entry in &installed.packages {
        let mut emitted_explicit = false;
        if let Some(branch_alias) = entry
            .extra_fields
            .get("extra")
            .and_then(|e| e.get("branch-alias"))
            .and_then(|b| b.as_object())
        {
            for (target_branch, alias_value) in branch_alias {
                if entry.version != *target_branch {
                    continue;
                }
                let Some(alias_pretty) = alias_value.as_str() else {
                    continue;
                };
                emitted_explicit = true;
                if still_present(&entry.name, alias_pretty) {
                    continue;
                }
                stale.push(StaleInstalledAlias {
                    name: entry.name.clone(),
                    alias_full: format_full_pretty_with_pretty_for_installed(alias_pretty, entry),
                    target_full: format_full_pretty_version_for_installed(entry),
                });
            }
        }

        // Synthetic `9999999-dev` default-branch alias.
        if emitted_explicit {
            continue;
        }
        let is_default_branch = entry
            .extra_fields
            .get("default-branch")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);
        if !is_default_branch {
            continue;
        }
        let version_lower = entry.version.to_lowercase();
        let is_dev_branch = version_lower.starts_with("dev-") || version_lower.ends_with("-dev");
        if !is_dev_branch {
            continue;
        }
        const DEFAULT_BRANCH_ALIAS: &str = "9999999-dev";
        if still_present(&entry.name, DEFAULT_BRANCH_ALIAS) {
            continue;
        }
        stale.push(StaleInstalledAlias {
            name: entry.name.clone(),
            alias_full: format_full_pretty_with_pretty_for_installed(DEFAULT_BRANCH_ALIAS, entry),
            target_full: format_full_pretty_version_for_installed(entry),
        });
    }
    stale
}

/// Collect the alias normalized-versions a previous install recorded for
/// `pkg_name`. Mirrors Composer's `presentAliasMap` seeding.
pub fn previously_installed_alias_versions(
    installed: &InstalledPackages,
    pkg_name: &str,
) -> Vec<String> {
    let mut out = Vec::new();
    for entry in &installed.packages {
        if !entry.name.eq_ignore_ascii_case(pkg_name) {
            continue;
        }
        let version_lower = entry.version.to_lowercase();
        let is_dev_branch = version_lower.starts_with("dev-") || version_lower.ends_with("-dev");
        if !is_dev_branch {
            continue;
        }

        let mut emitted_explicit_alias = false;
        if let Some(branch_alias_map) = entry
            .extra_fields
            .get("extra")
            .and_then(|e| e.get("branch-alias"))
            .and_then(|b| b.as_object())
        {
            for (source, target) in branch_alias_map {
                if !source.eq_ignore_ascii_case(&entry.version) {
                    continue;
                }
                let Some(target_str) = target.as_str() else {
                    continue;
                };
                if !target_str.to_lowercase().ends_with("-dev") {
                    continue;
                }
                if let Some(normalized) = crate::resolver::normalize_branch_alias_target(target_str)
                {
                    out.push(normalized);
                    emitted_explicit_alias = true;
                }
            }
        }

        if !emitted_explicit_alias
            && entry
                .extra_fields
                .get("default-branch")
                .and_then(|v| v.as_bool())
                .unwrap_or(false)
        {
            out.push("9999999.9999999.9999999.9999999-dev".to_string());
        }
    }
    out
}

/// Convert a `LockedPackage` to an `InstalledPackageEntry`.
///
/// Mirrors Composer's `InstalledFilesystemRepository::write()` via
/// `ArrayDumper` — `extra_fields` is forwarded verbatim so flags like
/// `abandoned` and `default-branch` survive the lock → installed.json round
/// trip.
pub fn locked_to_installed_entry(pkg: &LockedPackage, _vendor_dir: &Path) -> InstalledPackageEntry {
    let install_path = format!("../{}", pkg.name);
    InstalledPackageEntry {
        name: pkg.name.clone(),
        version: pkg.version.clone(),
        version_normalized: pkg.version_normalized.clone(),
        source: pkg
            .source
            .as_ref()
            .map(|s| serde_json::to_value(s).unwrap_or_default()),
        dist: pkg
            .dist
            .as_ref()
            .map(|d| serde_json::to_value(d).unwrap_or_default()),
        package_type: pkg.package_type.clone(),
        install_path: Some(install_path),
        autoload: pkg.autoload.clone(),
        aliases: vec![],
        homepage: pkg.homepage.clone(),
        support: pkg.support.clone(),
        extra_fields: pkg.extra_fields.clone(),
    }
}

fn installed_refs_match_locked(entry: &InstalledPackageEntry, locked: &LockedPackage) -> bool {
    let installed_source_ref = entry
        .source
        .as_ref()
        .and_then(|v| v.get("reference"))
        .and_then(|v| v.as_str());
    let installed_dist_ref = entry
        .dist
        .as_ref()
        .and_then(|v| v.get("reference"))
        .and_then(|v| v.as_str());
    let locked_source_ref = locked.source.as_ref().and_then(|s| s.reference.as_deref());
    let locked_dist_ref = locked.dist.as_ref().and_then(|d| d.reference.as_deref());
    installed_source_ref == locked_source_ref && installed_dist_ref == locked_dist_ref
}

fn abandoned_state(v: Option<&serde_json::Value>) -> (bool, Option<&str>) {
    match v {
        Some(serde_json::Value::Bool(b)) => (*b, None),
        Some(serde_json::Value::String(s)) => (true, Some(s.as_str())),
        _ => (false, None),
    }
}

fn installed_abandoned_matches_locked(
    entry: &InstalledPackageEntry,
    locked: &LockedPackage,
) -> bool {
    abandoned_state(entry.extra_fields.get("abandoned"))
        == abandoned_state(locked.extra_fields.get("abandoned"))
}