Skip to main content

vivacity_core/
installer.rs

1//! The install transaction: diff (lock vs installed state), parallel fetch
2//! into the store, store-to-vendor clone, bin proxies, state files, runtime
3//! stub. Idempotent (rerun after an interruption, it converges): the reference
4//! state is `installed.json` + the presence of the directories, and each
5//! package is laid out by cloning into a previously removed vendor/<name>.
6
7use crate::error::{Error, Result};
8use crate::fetch::{Fetcher, Provenance};
9use crate::layout::Layout;
10use crate::lock::{DistKind, Lock, LockPackage};
11use crate::state::RootPackage;
12use crate::store::Store;
13use serde_json::Value;
14use std::collections::BTreeMap;
15use std::path::Path;
16use std::sync::Arc;
17
18pub struct InstallOptions {
19    pub with_dev: bool,
20    pub offline: bool,
21    /// Download/extraction parallelism.
22    pub jobs: usize,
23}
24
25impl Default for InstallOptions {
26    fn default() -> Self {
27        InstallOptions {
28            with_dev: true,
29            offline: false,
30            jobs: 16,
31        }
32    }
33}
34
35#[derive(Debug, Default)]
36pub struct InstallReport {
37    pub installed: usize,
38    pub removed: usize,
39    pub unchanged: usize,
40    pub from_cache: usize,
41    pub from_network: usize,
42    pub store_hits: usize,
43    /// Unchanged packages extracted into the store (pre-existing vendor).
44    pub store_warmed: usize,
45    /// The local repository after the transaction: the lock's entries for
46    /// the packages installed or updated, the previous installed.json
47    /// entries for the unchanged ones (Composer keeps the loaded objects and
48    /// dumps them back; the autoloader is generated from them too).
49    pub local_repository: Option<Lock>,
50    /// Lines Composer prints on stderr during the operations and vivacity
51    /// reproduces (`Skipped installation of bin …`).
52    pub messages: Vec<String>,
53}
54
55/// Installed identity of a package: version + dist reference.
56fn identity(p: &LockPackage) -> (String, String) {
57    (
58        p.version().to_owned(),
59        p.dist_reference().unwrap_or("").to_owned(),
60    )
61}
62
63/// What installed.json says of a package: its identity and, for a `path`
64/// package, the source it was laid out from.
65struct Installed {
66    identity: (String, String),
67    path_source: Option<String>,
68    /// The entry as written, for a package that stays.
69    raw: serde_json::Map<String, Value>,
70}
71
72fn installed_packages(composer_dir: &Path) -> BTreeMap<String, Installed> {
73    let mut out = BTreeMap::new();
74    let path = composer_dir.join("installed.json");
75    let Some(v) = crate::jsonfile::read(&path) else {
76        return out;
77    };
78    for p in v["packages"].as_array().into_iter().flatten() {
79        let name = p["name"].as_str().unwrap_or_default();
80        let version = p["version"].as_str().unwrap_or_default();
81        let reference = p["dist"]["reference"].as_str().unwrap_or_default();
82        let path_source = (p["dist"]["type"].as_str() == Some("path"))
83            .then(|| p["dist"]["url"].as_str().map(str::to_owned))
84            .flatten();
85        out.insert(
86            name.to_owned(),
87            Installed {
88                identity: (version.to_owned(), reference.to_owned()),
89                path_source,
90                raw: p.as_object().cloned().unwrap_or_default(),
91            },
92        );
93    }
94    out
95}
96
97/// The local repository the state files and the autoloader are produced
98/// from: the lock, where an unchanged package keeps the entry installed.json
99/// already had (minus what is recomputed).
100fn local_repository(
101    lock: &Lock,
102    previous: &BTreeMap<String, Installed>,
103    unchanged_names: &std::collections::BTreeSet<&str>,
104) -> Lock {
105    let mut local = lock.clone();
106    for p in local
107        .packages
108        .iter_mut()
109        .chain(local.packages_dev.iter_mut())
110    {
111        if !unchanged_names.contains(p.name()) {
112            continue;
113        }
114        if let Some(prev) = previous.get(p.name()) {
115            let mut raw = prev.raw.clone();
116            for key in ["version_normalized", "installation-source", "install-path"] {
117                raw.remove(key);
118            }
119            p.raw = raw;
120        }
121    }
122    local
123}
124
125/// The local repository `install` will produce when its transaction is
126/// empty (every wanted package present in installed.json with the same
127/// identity, its directory in place): computable before the install runs,
128/// so the autoloader can be planned while the install waits on the
129/// network. `None` when a wanted package is not that — the caller then
130/// plans after the install, as before.
131pub fn local_repository_if_unchanged(lock: &Lock, layout: &Layout, with_dev: bool) -> Option<Lock> {
132    let previous = installed_packages(&layout.composer_dir());
133    let mut unchanged: std::collections::BTreeSet<&str> = std::collections::BTreeSet::new();
134    for p in lock.wanted_packages(with_dev) {
135        if previous.get(p.name()).map(|i| &i.identity) != Some(&identity(p)) {
136            return None;
137        }
138        if layout.install_path(p.name()).is_some()
139            && !layout.abs(p.name()).is_some_and(|d| d.is_dir())
140        {
141            return None;
142        }
143        unchanged.insert(p.name());
144    }
145    Some(local_repository(lock, &previous, &unchanged))
146}
147
148pub async fn install(
149    _project_dir: &Path,
150    lock: &Lock,
151    root_manifest: &Value,
152    layout: &Layout,
153    store: Arc<Store>,
154    fetcher: Arc<Fetcher>,
155    opts: &InstallOptions,
156) -> Result<InstallReport> {
157    // Absolute root (the layout's): the relative paths of the proxies and of
158    // the state files must not depend on a relative --working-dir.
159    let project_dir = layout.root();
160    let vendor = layout.vendor_dir();
161    let bin_dir = layout.bin_dir();
162    std::fs::create_dir_all(&vendor).map_err(Error::io(&vendor))?;
163
164    let mut report = InstallReport::default();
165    let wanted: Vec<&LockPackage> = lock.wanted_packages(opts.with_dev).collect();
166    let wanted_names: std::collections::BTreeSet<&str> = wanted.iter().map(|p| p.name()).collect();
167    // `Factory::purgePackages`: a package of installed.json whose install
168    // path is gone is not installed at all (a fresh install, not an
169    // update — no `removeBinaries`, no removal of the old path).
170    let mut previous = installed_packages(&layout.composer_dir());
171    previous.retain(|name, _| {
172        layout
173            .abs(name)
174            .or_else(|| layout.removals().find(|(n, _)| n == name).map(|(_, d)| d))
175            .is_some_and(|d| d.exists())
176    });
177
178    // To lay out: changed identity, or missing directory. Unchanged packages
179    // whose store entry is missing (vendor/ laid out by Composer before vivacity)
180    // are extracted into the store without being re-cloned: the classmap
181    // cache applies from the next run on.
182    let mut to_install: Vec<&LockPackage> = Vec::new();
183    let mut to_warm: Vec<&LockPackage> = Vec::new();
184    let mut unchanged_names: std::collections::BTreeSet<&str> = std::collections::BTreeSet::new();
185    for p in &wanted {
186        // Installed nowhere (a metapackage, a Flex pack): the layout has no
187        // path for it.
188        if layout.install_path(p.name()).is_none() {
189            if previous.get(p.name()).map(|i| &i.identity) == Some(&identity(p)) {
190                unchanged_names.insert(p.name());
191            }
192            continue;
193        }
194        // `LibraryInstaller::isInstalled`: a dangling link is not installed
195        // (`is_dir` follows links).
196        let unchanged = previous.get(p.name()).map(|i| &i.identity) == Some(&identity(p))
197            && layout.abs(p.name()).is_some_and(|d| d.is_dir());
198        if unchanged {
199            unchanged_names.insert(p.name());
200            report.unchanged += 1;
201            if p.dist_kind() == DistKind::Zip
202                && !store.contains(p.name(), p.version(), p.dist_reference())
203            {
204                to_warm.push(p);
205            }
206        } else {
207            to_install.push(p);
208        }
209    }
210    // `PathDownloader::download`: a package cannot be laid out inside its
211    // own source; checked before anything is written.
212    for p in &to_install {
213        if p.dist_kind() == DistKind::Path {
214            if let (Some(dest), Some(url)) = (layout.abs(p.name()), p.dist_url()) {
215                crate::path_install::check_not_inside_source(project_dir, &dest, url, p.name())?;
216            }
217        }
218    }
219
220    // Fetch + extraction into the store, with bounded parallelism. Packages to
221    // "warm" only use the local cache (never the network) and their failure
222    // is silent: it is an optimisation, not an obligation.
223    let sem = Arc::new(tokio::sync::Semaphore::new(opts.jobs.max(1)));
224    let mut tasks = tokio::task::JoinSet::new();
225    let warm_names: std::collections::BTreeSet<&str> = to_warm.iter().map(|p| p.name()).collect();
226    for p in to_install.iter().chain(to_warm.iter()) {
227        if p.dist_kind() == DistKind::Path {
228            continue;
229        }
230        if store.contains(p.name(), p.version(), p.dist_reference()) {
231            report.store_hits += 1;
232            continue;
233        }
234        let warm_only =
235            warm_names.contains(p.name()) && !to_install.iter().any(|q| q.name() == p.name());
236        let (name, version) = (p.name().to_owned(), p.version().to_owned());
237        let dist_ref = p.dist_reference().map(str::to_owned);
238        let url = p.dist_url_expanded().ok_or_else(|| Error::Http {
239            url: name.clone(),
240            message:
241                "package without a dist url (the scope detector should have routed to the fallback)"
242                    .to_owned(),
243        })?;
244        let shasum = p.dist_shasum().map(str::to_owned);
245        let (store, fetcher, sem) = (store.clone(), fetcher.clone(), sem.clone());
246        let offline = opts.offline || warm_only;
247        tasks.spawn(async move {
248            let _permit = sem.acquire().await.map_err(|_| Error::Http {
249                url: url.clone(),
250                message: "semaphore closed".to_owned(),
251            })?;
252            let fetched = fetcher
253                .dist_bytes(&name, &url, shasum.as_deref(), offline)
254                .await;
255            let (bytes, provenance) = match fetched {
256                Ok(v) => v,
257                // Warming: zip missing from the cache, do not insist.
258                Err(_) if warm_only => return Ok::<Option<Provenance>, Error>(None),
259                Err(e) => return Err(e),
260            };
261            let store_name = name.clone();
262            let version2 = version.clone();
263            let dist_ref2 = dist_ref.clone();
264            tokio::task::spawn_blocking(move || {
265                store.ensure(&store_name, &version2, dist_ref2.as_deref(), &bytes)
266            })
267            .await
268            .map_err(|e| Error::Http {
269                url: name.clone(),
270                message: format!("extraction task interrupted: {e}"),
271            })??;
272            Ok::<Option<Provenance>, Error>(Some(provenance))
273        });
274    }
275    while let Some(joined) = tasks.join_next().await {
276        let provenance = joined.map_err(|e| Error::Http {
277            url: "join".to_owned(),
278            message: e.to_string(),
279        })??;
280        match provenance {
281            Some(Provenance::Cache) => report.from_cache += 1,
282            Some(Provenance::Network) => report.from_network += 1,
283            None => {}
284        }
285    }
286    report.store_warmed = to_warm.len();
287
288    // Removals: present before, no longer wanted, at the path validated by the
289    // layout (old install-path = recomputed path, like LibraryInstaller).
290    for name in previous.keys() {
291        if !wanted_names.contains(name.as_str()) {
292            report.removed += 1;
293        }
294    }
295    for (name, dir) in layout.removals() {
296        // `PathDownloader::remove`: the install path that *is* the source
297        // stays (", source is still present").
298        let own_source = previous
299            .get(name)
300            .and_then(|i| i.path_source.as_deref())
301            .is_some_and(|url| {
302                crate::path_install::is_own_source(project_dir, &dir.to_string_lossy(), url)
303            });
304        if own_source {
305            continue;
306        }
307        if std::fs::symlink_metadata(&dir).is_ok() {
308            crate::path_install::remove_path(&dir)?;
309            prune_empty_parent(project_dir, &dir);
310        }
311    }
312
313    // Layout: remove the old version, then clone from the store.
314    // Packages land in disjoint directories → fan-out where parallel I/O
315    // pays (Linux: sylius vendor/ wiped 3.75 s -> 1.68 s on ext4/WSL2);
316    // sequential where it does not (APFS clonefile is metadata-bound and
317    // contends: 607 ms -> 635 ms on an M4 Max). Each package stays atomic
318    // (remove-before-clone); only the inter-package order changes, which
319    // affects nothing but mtimes. `VIVACITY_PARALLEL_IO=0|1` overrides.
320    let place = |p: &&LockPackage| -> Result<bool> {
321        let (Some(pkg_root), Some(dest)) = (layout.package_root(p.name()), layout.abs(p.name()))
322        else {
323            return Ok(false);
324        };
325        if p.dist_kind() == DistKind::Path {
326            let url = p.dist_url().unwrap_or_default();
327            // `FileDownloader::update` removes the previous layout before
328            // `install` (a link becomes a mirror when the options changed);
329            // a fresh install keeps a path that already resolves to the
330            // source.
331            if previous.contains_key(p.name()) {
332                crate::path_install::remove_path(&pkg_root)?;
333            }
334            crate::path_install::install(project_dir, &dest, url, p.raw.get("transport-options"))?;
335            return Ok(true);
336        }
337        // Always start again from an empty package root (target-dir included).
338        if std::fs::symlink_metadata(&pkg_root).is_ok() {
339            crate::path_install::remove_path(&pkg_root)?;
340        }
341        let src = store.entry_path(p.name(), p.version(), p.dist_reference());
342        crate::clone::clone_tree(&src, &dest)?;
343        Ok(true)
344    };
345    let placed: Vec<bool> = if crate::platform::parallel_io() {
346        use rayon::prelude::*;
347        to_install.par_iter().map(place).collect::<Result<_>>()?
348    } else {
349        to_install.iter().map(place).collect::<Result<_>>()?
350    };
351    let installed: usize = placed.into_iter().filter(|placed| *placed).count();
352    report.installed += installed;
353
354    // `BinaryInstaller::removeBinaries` runs `initializeBinDir` before
355    // looking at the package's binaries: an update, a removal, or the
356    // reinstall of a package still listed in installed.json creates
357    // vendor/bin even when nothing has a `bin`.
358    let touches_installed = to_install.iter().any(|p| previous.contains_key(p.name()))
359        || previous.keys().any(|n| !wanted_names.contains(n.as_str()));
360    if touches_installed {
361        std::fs::create_dir_all(&bin_dir).map_err(Error::io(&bin_dir))?;
362    }
363
364    // Bin proxies: rebuilt for the packages actually (re)placed
365    // (`BinaryInstaller::installBinaries` on install/update), and — like
366    // `Installer::run`'s `ensureBinariesPresence` over every installed
367    // package — written for an unchanged package only where the proxy is
368    // MISSING (`installBinaries(..., warnOnOverwrite: false)` skips an
369    // existing one): a wiped `vendor/bin` comes back on a no-op install,
370    // and a no-op install otherwise touches nothing. The purge of orphaned
371    // proxies (removed packages) runs on `wanted`. The `.bat` follows the
372    // resolved bin-compat (`full`, or `auto` on Windows/WSL), like
373    // Composer's BinaryInstaller — a plain Linux/macOS install writes no
374    // `.bat`.
375    let bin_compat = crate::binproxy::resolve_bin_compat(root_manifest)?;
376    let placed: std::collections::HashSet<&str> = to_install.iter().map(|p| p.name()).collect();
377    // `LibraryInstaller::update` removes the old version's binaries before
378    // installing the new ones (`removeBinaries` then `installBinaries`); a
379    // fresh install only adds. The bin directory is removed when a removal
380    // leaves it empty — and recreated by the next `initializeBinDir`.
381    let previous_bins = |name: &str| -> Vec<String> {
382        previous
383            .get(name)
384            .and_then(|i| i.raw.get("bin"))
385            .and_then(Value::as_array)
386            .map(|a| {
387                a.iter()
388                    .filter_map(Value::as_str)
389                    .map(str::to_owned)
390                    .collect()
391            })
392            .unwrap_or_default()
393    };
394    for p in &wanted {
395        let bins = p.bins();
396        let Some(dir) = layout.abs(p.name()) else {
397            continue;
398        };
399        if placed.contains(p.name()) && previous.contains_key(p.name()) {
400            let old = previous_bins(p.name());
401            let old: Vec<&str> = old.iter().map(String::as_str).collect();
402            crate::binproxy::remove_binaries(&bin_dir, &old)?;
403        }
404        if bins.is_empty() {
405            continue;
406        }
407        let missing = || {
408            bins.iter().any(|b| {
409                let b = b.trim_start_matches("./");
410                let link_name = b.rsplit_once('/').map(|(_, f)| f).unwrap_or(b);
411                dir.join(b).exists() && !bin_dir.join(link_name).exists()
412            })
413        };
414        if placed.contains(p.name()) {
415            report.messages.extend(crate::binproxy::install_binaries(
416                &vendor,
417                &bin_dir,
418                p.name(),
419                &dir,
420                &bins,
421                bin_compat,
422                true,
423            )?);
424        } else if missing() {
425            crate::binproxy::install_binaries(
426                &vendor,
427                &bin_dir,
428                p.name(),
429                &dir,
430                &bins,
431                bin_compat,
432                false,
433            )?;
434        }
435    }
436    // Removed packages: `removeBinaries` on each (their proxies and `.bat`).
437    for name in previous.keys() {
438        if !wanted_names.contains(name.as_str()) {
439            let old = previous_bins(name);
440            let old: Vec<&str> = old.iter().map(String::as_str).collect();
441            crate::binproxy::remove_binaries(&bin_dir, &old)?;
442        }
443    }
444    prune_stale_bat_proxies(&bin_dir, &wanted, bin_compat)?;
445
446    // State files + runtime stub, from the local repository: an unchanged
447    // package keeps the entry installed.json already had (its own
448    // `version_normalized`/`installation-source`/`install-path` are
449    // recomputed), so a lock that changed a package's metadata without
450    // changing its identity — routine with `path` packages whose reference
451    // is a git HEAD or none — leaves installed.json and the autoloader as
452    // Composer leaves them.
453    let local = local_repository(lock, &previous, &unchanged_names);
454    let root = RootPackage::detect(root_manifest, project_dir, opts.with_dev);
455    crate::state::write_state_files(
456        &layout.composer_dir(),
457        &local,
458        &root,
459        root_manifest,
460        opts.with_dev,
461        layout,
462    )?;
463    report.local_repository = Some(local);
464
465    Ok(report)
466}
467
468/// `LibraryInstaller::uninstall`: the parent directory of the removed package
469/// (vendor/<ns>, web/app/plugins...) is removed if empty, never the project
470/// root.
471fn prune_empty_parent(project_dir: &Path, removed: &Path) {
472    let Some(parent) = removed.parent() else {
473        return;
474    };
475    if parent == project_dir {
476        return;
477    }
478    if std::fs::read_dir(parent)
479        .map(|mut d| d.next().is_none())
480        .unwrap_or(false)
481    {
482        let _ = std::fs::remove_dir(parent);
483    }
484}
485
486/// A `<bin>.bat` next to an expected proxy is the Windows proxy of that
487/// bin — kept only when the resolved bin-compat writes `.bat` proxies at
488/// all; otherwise a leftover from a previous full-mode install, purged so
489/// the tree converges on what Composer produces on a bare checkout.
490/// Nothing else is touched: the bin directory may be the project's own.
491fn prune_stale_bat_proxies(
492    bin_dir: &Path,
493    wanted: &[&LockPackage],
494    bin_compat: crate::binproxy::BinCompat,
495) -> Result<()> {
496    if bin_compat == crate::binproxy::BinCompat::Full {
497        return Ok(());
498    }
499    let Ok(entries) = std::fs::read_dir(bin_dir) else {
500        return Ok(());
501    };
502    let mut expected: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
503    for p in wanted {
504        for bin in p.bins() {
505            let bin = bin.trim_start_matches("./");
506            let link = bin.rsplit_once('/').map(|(_, f)| f).unwrap_or(bin);
507            expected.insert(link.to_owned());
508        }
509    }
510    for entry in entries.flatten() {
511        let file_name = entry.file_name().to_string_lossy().into_owned();
512        if file_name
513            .strip_suffix(".bat")
514            .is_some_and(|stem| expected.contains(stem))
515        {
516            let p = entry.path();
517            std::fs::remove_file(&p).map_err(Error::io(&p))?;
518        }
519    }
520    Ok(())
521}