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, PathBuf};
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}
51
52/// Installed identity of a package: version + dist reference.
53fn identity(p: &LockPackage) -> (String, String) {
54    (
55        p.version().to_owned(),
56        p.dist_reference().unwrap_or("").to_owned(),
57    )
58}
59
60/// What installed.json says of a package: its identity and, for a `path`
61/// package, the source it was laid out from.
62struct Installed {
63    identity: (String, String),
64    path_source: Option<String>,
65    /// The entry as written, for a package that stays.
66    raw: serde_json::Map<String, Value>,
67}
68
69fn installed_packages(vendor: &Path) -> BTreeMap<String, Installed> {
70    let mut out = BTreeMap::new();
71    let path = vendor.join("composer/installed.json");
72    let Ok(text) = std::fs::read_to_string(&path) else {
73        return out;
74    };
75    let Ok(v) = serde_json::from_str::<Value>(&text) 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
97pub async fn install(
98    _project_dir: &Path,
99    lock: &Lock,
100    root_manifest: &Value,
101    layout: &Layout,
102    store: Arc<Store>,
103    fetcher: Arc<Fetcher>,
104    opts: &InstallOptions,
105) -> Result<InstallReport> {
106    // Absolute root (the layout's): the relative paths of the proxies and of
107    // the state files must not depend on a relative --working-dir.
108    let project_dir = layout.root();
109    let vendor = project_dir.join("vendor");
110    std::fs::create_dir_all(&vendor).map_err(Error::io(&vendor))?;
111
112    let mut report = InstallReport::default();
113    let wanted: Vec<&LockPackage> = lock.wanted_packages(opts.with_dev).collect();
114    let wanted_names: std::collections::BTreeSet<&str> = wanted.iter().map(|p| p.name()).collect();
115    // `Factory::purgePackages`: a package of installed.json whose install
116    // path is gone is not installed at all (a fresh install, not an
117    // update — no `removeBinaries`, no removal of the old path).
118    let mut previous = installed_packages(&vendor);
119    previous.retain(|name, _| {
120        layout
121            .abs(name)
122            .or_else(|| layout.removals().find(|(n, _)| n == name).map(|(_, d)| d))
123            .is_some_and(|d| d.exists())
124    });
125
126    // To lay out: changed identity, or missing directory. Unchanged packages
127    // whose store entry is missing (vendor/ laid out by Composer before vivacity)
128    // are extracted into the store without being re-cloned: the classmap
129    // cache applies from the next run on.
130    let mut to_install: Vec<&LockPackage> = Vec::new();
131    let mut to_warm: Vec<&LockPackage> = Vec::new();
132    let mut unchanged_names: std::collections::BTreeSet<&str> = std::collections::BTreeSet::new();
133    for p in &wanted {
134        // Installed nowhere (a metapackage, a Flex pack): the layout has no
135        // path for it.
136        if layout.install_path(p.name()).is_none() {
137            if previous.get(p.name()).map(|i| &i.identity) == Some(&identity(p)) {
138                unchanged_names.insert(p.name());
139            }
140            continue;
141        }
142        // `LibraryInstaller::isInstalled`: a dangling link is not installed
143        // (`is_dir` follows links).
144        let unchanged = previous.get(p.name()).map(|i| &i.identity) == Some(&identity(p))
145            && layout.abs(p.name()).is_some_and(|d| d.is_dir());
146        if unchanged {
147            unchanged_names.insert(p.name());
148            report.unchanged += 1;
149            if p.dist_kind() == DistKind::Zip
150                && !store.contains(p.name(), p.version(), p.dist_reference())
151            {
152                to_warm.push(p);
153            }
154        } else {
155            to_install.push(p);
156        }
157    }
158    // `PathDownloader::download`: a package cannot be laid out inside its
159    // own source; checked before anything is written.
160    for p in &to_install {
161        if p.dist_kind() == DistKind::Path {
162            if let (Some(dest), Some(url)) = (layout.abs(p.name()), p.dist_url()) {
163                crate::path_install::check_not_inside_source(project_dir, &dest, url, p.name())?;
164            }
165        }
166    }
167
168    // Fetch + extraction into the store, with bounded parallelism. Packages to
169    // "warm" only use the local cache (never the network) and their failure
170    // is silent: it is an optimisation, not an obligation.
171    let sem = Arc::new(tokio::sync::Semaphore::new(opts.jobs.max(1)));
172    let mut tasks = tokio::task::JoinSet::new();
173    let warm_names: std::collections::BTreeSet<&str> = to_warm.iter().map(|p| p.name()).collect();
174    for p in to_install.iter().chain(to_warm.iter()) {
175        if p.dist_kind() == DistKind::Path {
176            continue;
177        }
178        if store.contains(p.name(), p.version(), p.dist_reference()) {
179            report.store_hits += 1;
180            continue;
181        }
182        let warm_only =
183            warm_names.contains(p.name()) && !to_install.iter().any(|q| q.name() == p.name());
184        let (name, version) = (p.name().to_owned(), p.version().to_owned());
185        let dist_ref = p.dist_reference().map(str::to_owned);
186        let url = p.dist_url_expanded().ok_or_else(|| Error::Http {
187            url: name.clone(),
188            message:
189                "package without a dist url (the scope detector should have routed to the fallback)"
190                    .to_owned(),
191        })?;
192        let shasum = p.dist_shasum().map(str::to_owned);
193        let (store, fetcher, sem) = (store.clone(), fetcher.clone(), sem.clone());
194        let offline = opts.offline || warm_only;
195        tasks.spawn(async move {
196            let _permit = sem.acquire().await.map_err(|_| Error::Http {
197                url: url.clone(),
198                message: "semaphore closed".to_owned(),
199            })?;
200            let fetched = fetcher
201                .dist_bytes(&name, &url, shasum.as_deref(), offline)
202                .await;
203            let (bytes, provenance) = match fetched {
204                Ok(v) => v,
205                // Warming: zip missing from the cache, do not insist.
206                Err(_) if warm_only => return Ok::<Option<Provenance>, Error>(None),
207                Err(e) => return Err(e),
208            };
209            let store_name = name.clone();
210            let version2 = version.clone();
211            let dist_ref2 = dist_ref.clone();
212            tokio::task::spawn_blocking(move || {
213                store.ensure(&store_name, &version2, dist_ref2.as_deref(), &bytes)
214            })
215            .await
216            .map_err(|e| Error::Http {
217                url: name.clone(),
218                message: format!("extraction task interrupted: {e}"),
219            })??;
220            Ok::<Option<Provenance>, Error>(Some(provenance))
221        });
222    }
223    while let Some(joined) = tasks.join_next().await {
224        let provenance = joined.map_err(|e| Error::Http {
225            url: "join".to_owned(),
226            message: e.to_string(),
227        })??;
228        match provenance {
229            Some(Provenance::Cache) => report.from_cache += 1,
230            Some(Provenance::Network) => report.from_network += 1,
231            None => {}
232        }
233    }
234    report.store_warmed = to_warm.len();
235
236    // Removals: present before, no longer wanted, at the path validated by the
237    // layout (old install-path = recomputed path, like LibraryInstaller).
238    for name in previous.keys() {
239        if !wanted_names.contains(name.as_str()) {
240            report.removed += 1;
241        }
242    }
243    for (name, dir) in layout.removals() {
244        // `PathDownloader::remove`: the install path that *is* the source
245        // stays (", source is still present").
246        let own_source = previous
247            .get(name)
248            .and_then(|i| i.path_source.as_deref())
249            .is_some_and(|url| {
250                crate::path_install::is_own_source(project_dir, &dir.to_string_lossy(), url)
251            });
252        if own_source {
253            continue;
254        }
255        if std::fs::symlink_metadata(&dir).is_ok() {
256            crate::path_install::remove_path(&dir)?;
257            prune_empty_parent(project_dir, &dir);
258        }
259    }
260
261    // Layout: remove the old version, then clone from the store.
262    // Packages land in disjoint directories → fan-out where parallel I/O
263    // pays (Linux: sylius vendor/ wiped 3.75 s -> 1.68 s on ext4/WSL2);
264    // sequential where it does not (APFS clonefile is metadata-bound and
265    // contends: 607 ms -> 635 ms on an M4 Max). Each package stays atomic
266    // (remove-before-clone); only the inter-package order changes, which
267    // affects nothing but mtimes. `VIVACITY_PARALLEL_IO=0|1` overrides.
268    let place = |p: &&LockPackage| -> Result<bool> {
269        let (Some(pkg_root), Some(dest)) = (layout.package_root(p.name()), layout.abs(p.name()))
270        else {
271            return Ok(false);
272        };
273        if p.dist_kind() == DistKind::Path {
274            let url = p.dist_url().unwrap_or_default();
275            // `FileDownloader::update` removes the previous layout before
276            // `install` (a link becomes a mirror when the options changed);
277            // a fresh install keeps a path that already resolves to the
278            // source.
279            if previous.contains_key(p.name()) {
280                crate::path_install::remove_path(&pkg_root)?;
281            }
282            crate::path_install::install(project_dir, &dest, url, p.raw.get("transport-options"))?;
283            return Ok(true);
284        }
285        // Always start again from an empty package root (target-dir included).
286        if std::fs::symlink_metadata(&pkg_root).is_ok() {
287            crate::path_install::remove_path(&pkg_root)?;
288        }
289        let src = store.entry_path(p.name(), p.version(), p.dist_reference());
290        crate::clone::clone_tree(&src, &dest)?;
291        Ok(true)
292    };
293    let placed: Vec<bool> = if crate::platform::parallel_io() {
294        use rayon::prelude::*;
295        to_install.par_iter().map(place).collect::<Result<_>>()?
296    } else {
297        to_install.iter().map(place).collect::<Result<_>>()?
298    };
299    let installed: usize = placed.into_iter().filter(|placed| *placed).count();
300    report.installed += installed;
301
302    // `BinaryInstaller::removeBinaries` runs `initializeBinDir` before
303    // looking at the package's binaries: an update, a removal, or the
304    // reinstall of a package still listed in installed.json creates
305    // vendor/bin even when nothing has a `bin`.
306    let touches_installed = to_install.iter().any(|p| previous.contains_key(p.name()))
307        || previous.keys().any(|n| !wanted_names.contains(n.as_str()));
308    if touches_installed {
309        let bin_dir = vendor.join("bin");
310        std::fs::create_dir_all(&bin_dir).map_err(Error::io(&bin_dir))?;
311    }
312
313    // Bin proxies: rebuilt for the packages actually (re)placed
314    // (`BinaryInstaller::installBinaries` on install/update), and — like
315    // `Installer::run`'s `ensureBinariesPresence` over every installed
316    // package — written for an unchanged package only where the proxy is
317    // MISSING (`installBinaries(..., warnOnOverwrite: false)` skips an
318    // existing one): a wiped `vendor/bin` comes back on a no-op install,
319    // and a no-op install otherwise touches nothing. The purge of orphaned
320    // proxies (removed packages) runs on `wanted`. The `.bat` follows the
321    // resolved bin-compat (`full`, or `auto` on Windows/WSL), like
322    // Composer's BinaryInstaller — a plain Linux/macOS install writes no
323    // `.bat`.
324    let bin_compat = crate::binproxy::resolve_bin_compat(root_manifest)?;
325    let placed: std::collections::HashSet<&str> = to_install.iter().map(|p| p.name()).collect();
326    for p in &wanted {
327        let bins = p.bins();
328        if bins.is_empty() {
329            continue;
330        }
331        let Some(dir) = layout.abs(p.name()) else {
332            continue;
333        };
334        let missing = || {
335            bins.iter().any(|b| {
336                let b = b.trim_start_matches("./");
337                let link_name = b.rsplit_once('/').map(|(_, f)| f).unwrap_or(b);
338                dir.join(b).exists() && !vendor.join("bin").join(link_name).exists()
339            })
340        };
341        if placed.contains(p.name()) || missing() {
342            crate::binproxy::install_binaries(&vendor, &dir, &bins, bin_compat)?;
343        }
344    }
345    prune_orphan_bin_proxies(&vendor, &wanted, bin_compat)?;
346
347    // State files + runtime stub, from the local repository: an unchanged
348    // package keeps the entry installed.json already had (its own
349    // `version_normalized`/`installation-source`/`install-path` are
350    // recomputed), so a lock that changed a package's metadata without
351    // changing its identity — routine with `path` packages whose reference
352    // is a git HEAD or none — leaves installed.json and the autoloader as
353    // Composer leaves them.
354    let mut local = lock.clone();
355    for p in local
356        .packages
357        .iter_mut()
358        .chain(local.packages_dev.iter_mut())
359    {
360        if !unchanged_names.contains(p.name()) {
361            continue;
362        }
363        if let Some(prev) = previous.get(p.name()) {
364            let mut raw = prev.raw.clone();
365            for key in ["version_normalized", "installation-source", "install-path"] {
366                raw.remove(key);
367            }
368            p.raw = raw;
369        }
370    }
371    let root = RootPackage::detect(root_manifest, project_dir, opts.with_dev);
372    crate::state::write_state_files(
373        &vendor.join("composer"),
374        &local,
375        &root,
376        root_manifest,
377        opts.with_dev,
378        layout,
379    )?;
380    report.local_repository = Some(local);
381
382    Ok(report)
383}
384
385/// `LibraryInstaller::uninstall`: the parent directory of the removed package
386/// (vendor/<ns>, web/app/plugins...) is removed if empty, never the project
387/// root.
388fn prune_empty_parent(project_dir: &Path, removed: &Path) {
389    let Some(parent) = removed.parent() else {
390        return;
391    };
392    if parent == project_dir {
393        return;
394    }
395    if std::fs::read_dir(parent)
396        .map(|mut d| d.next().is_none())
397        .unwrap_or(false)
398    {
399        let _ = std::fs::remove_dir(parent);
400    }
401}
402
403fn prune_orphan_bin_proxies(
404    vendor: &Path,
405    wanted: &[&LockPackage],
406    bin_compat: crate::binproxy::BinCompat,
407) -> Result<()> {
408    let bin_dir = vendor.join("bin");
409    let Ok(entries) = std::fs::read_dir(&bin_dir) else {
410        return Ok(());
411    };
412    let mut expected: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
413    for p in wanted {
414        for bin in p.bins() {
415            let bin = bin.trim_start_matches("./");
416            let link = bin.rsplit_once('/').map(|(_, f)| f).unwrap_or(bin);
417            expected.insert(link.to_owned());
418        }
419    }
420    for entry in entries.flatten() {
421        let file_name = entry.file_name().to_string_lossy().into_owned();
422        // A `.bat` is the Windows proxy of an expected bin — kept only when
423        // the resolved bin-compat writes `.bat` proxies at all (otherwise a
424        // leftover from a previous full-mode install, purged, converging on
425        // what Composer produces on a bare checkout) — or the proxy of a
426        // removed package (purged), or a user-placed file.
427        let keep = expected.contains(&file_name)
428            || (bin_compat == crate::binproxy::BinCompat::Full
429                && file_name
430                    .strip_suffix(".bat")
431                    .is_some_and(|stem| expected.contains(stem)));
432        if !keep {
433            let p = entry.path();
434            std::fs::remove_file(&p).map_err(Error::io(&p))?;
435        }
436    }
437    Ok(())
438}
439
440/// Utility path: the project's vendor/composer.
441pub fn vendor_composer_dir(project_dir: &Path) -> PathBuf {
442    project_dir.join("vendor/composer")
443}