Skip to main content

composer_install/
orchestrate.rs

1//! `install_from_lock` — apply a resolved `composer.lock` to a project.
2//!
3//! Reads `composer.json` + `composer.lock`, verifies the content-hash, diffs
4//! against the existing `vendor/composer/installed.json` to skip packages that
5//! are already up-to-date, runs preflight (rejecting source-only and non-zip
6//! dists which can't be installed at all; surfacing plugins / post-install
7//! scripts as warnings since the package zips are installed but their PHP is
8//! never run), builds [`DistRequest`]s only for changed/new packages, removes
9//! stale packages, downloads + extracts into `vendor/` via a [`Fetcher`],
10//! materializes `type: path` packages, applies patches, runs the declarative
11//! install plugins (Magento deploy, Laravel discovery), hands off to
12//! [`composer_autoload::dump_autoload`] for `vendor/autoload.php` +
13//! `installed.{json,php}`, and links `vendor/bin` proxies.
14//!
15//! Preflight failures are aggregated into a single error so the caller sees
16//! every blocker in one pass rather than fix-one-hit-next. Preflight warnings
17//! are returned alongside on success via [`InstallSummary::warnings`].
18//!
19//! The three app-specific seams are injected via [`InstallEnv`]: the network
20//! ([`Fetcher`]), the dist cache location (`cache_root`), and progress
21//! reporting ([`Progress`]). Root-script execution is opted in with
22//! [`ScriptHooks`]; pass `None` for the deterministic scripts-off behavior.
23
24use std::collections::{HashMap, HashSet};
25use std::hash::{Hash, Hasher};
26use std::path::{Path, PathBuf};
27
28use composer_autoload::{DumpRequest, dump_autoload};
29use composer_manifest::lockfile::{self, Lock, LockPackage};
30use composer_patches::{ApplyOptions, FailureMode, MaterializedPatch, PatchPlan, apply_patch_text};
31use eyre::{Context, Result, eyre};
32use serde_json::Value;
33
34use crate::archive::ArchiveKind;
35use crate::auth::{AuthCredentials, read_all_auth_with};
36use crate::downloader::{DistCandidate, DistOutcome, DistRequest, fetch_and_extract_dists};
37use crate::error::InstallError;
38use crate::fetch::Fetcher;
39use crate::progress::Progress;
40use crate::source::{SourceFetcher, SourceSpec, materialize_sources};
41use crate::stale::{InstallRecord, remove_stale_packages};
42
43/// The runtime seams an install needs, injected so the crate stays free of any
44/// HTTP-client / progress-bar / paths policy. Build it with
45/// [`InstallEnv::new`] plus the `with_*` methods, and pass it by reference to
46/// [`install_from_lock`].
47#[derive(Clone, Copy)]
48#[non_exhaustive]
49pub struct InstallEnv<'a> {
50    /// Downloads each dist URL to a verified cache file. Use
51    /// [`crate::ReqwestFetcher`] for the batteries-included default.
52    pub fetcher: &'a dyn Fetcher,
53    /// Per-package progress callbacks. Use [`crate::NoProgress`] for silence.
54    pub progress: &'a dyn Progress,
55    /// Directory the dist archives are cached under (persistent across runs;
56    /// created if absent). Composer keeps the equivalent in
57    /// `~/.composer/cache/files/`.
58    pub cache_root: &'a Path,
59    /// Installs packages the lock pins to a git `source` with no dist. `None`
60    /// (the default) makes such packages a preflight error.
61    pub source_fetcher: Option<&'a dyn SourceFetcher>,
62    /// Machine-wide credentials from the caller's own store (a CLI's login
63    /// command, say), merged above the global `auth.json` and below the
64    /// project's sources: composer.json `config`, project `auth.json` and
65    /// `COMPOSER_AUTH` still win.
66    pub machine_auth: Option<&'a HashMap<String, AuthCredentials>>,
67    /// File name, under `vendor/composer/`, of the autoloader freshness
68    /// marker. Defaults to `.composer-install-autoload-fresh`.
69    pub autoload_marker: &'a str,
70    /// How warnings and preflight blockers name the calling tool and its
71    /// commands. Defaults to tool-neutral text; see [`Wording`].
72    pub wording: Wording<'a>,
73}
74
75/// The words messages use for the calling tool, so a CLI built on this crate
76/// can point its users at its own commands. Start from
77/// [`Wording::default`] and set the fields that differ.
78#[derive(Debug, Clone, Copy, PartialEq, Eq)]
79#[non_exhaustive]
80pub struct Wording<'a> {
81    /// The tool, as the subject of a sentence: "… that `tool` does not
82    /// relocate". Defaults to `this installer`.
83    pub tool: &'a str,
84    /// The command that regenerates `composer.lock`. Defaults to
85    /// `composer update`.
86    pub update_command: &'a str,
87    /// The command that installs what this crate cannot (plugin hooks,
88    /// non-git sources, other dist types). Defaults to `composer install`.
89    pub install_command: &'a str,
90    /// A sentence telling the user how to have root scripts run. Defaults to
91    /// naming [`ScriptHooks`], the library seam.
92    pub scripts_hint: &'a str,
93}
94
95impl Default for Wording<'_> {
96    fn default() -> Self {
97        Self {
98            tool: "this installer",
99            update_command: "composer update",
100            install_command: "composer install",
101            scripts_hint: "Supply a `ScriptHooks` implementation to run them.",
102        }
103    }
104}
105
106impl<'a> InstallEnv<'a> {
107    /// The required seams: a dist fetcher, a progress sink, and the dist cache
108    /// directory. Source installs are off until
109    /// [`with_source_fetcher`](Self::with_source_fetcher).
110    pub fn new(fetcher: &'a dyn Fetcher, progress: &'a dyn Progress, cache_root: &'a Path) -> Self {
111        Self {
112            fetcher,
113            progress,
114            cache_root,
115            source_fetcher: None,
116            machine_auth: None,
117            autoload_marker: AUTOLOAD_FRESH_MARKER,
118            wording: Wording::default(),
119        }
120    }
121
122    /// Name the calling tool and its commands in warnings and preflight
123    /// blockers; see [`Wording`].
124    #[must_use]
125    pub fn with_wording(mut self, wording: Wording<'a>) -> Self {
126        self.wording = wording;
127        self
128    }
129
130    /// Add machine-wide credentials from the caller's own store; see
131    /// [`machine_auth`](Self::machine_auth) for the precedence.
132    #[must_use]
133    pub fn with_machine_auth(mut self, auth: &'a HashMap<String, AuthCredentials>) -> Self {
134        self.machine_auth = Some(auth);
135        self
136    }
137
138    /// Use another file name for the autoloader freshness marker, so a tool
139    /// that already writes its own keeps its warm state.
140    #[must_use]
141    pub fn with_autoload_marker(mut self, name: &'a str) -> Self {
142        self.autoload_marker = name;
143        self
144    }
145
146    /// Install git-source packages with `source_fetcher` — typically a
147    /// [`crate::GitSourceFetcher`].
148    #[must_use]
149    pub fn with_source_fetcher(mut self, source_fetcher: &'a dyn SourceFetcher) -> Self {
150        self.source_fetcher = Some(source_fetcher);
151        self
152    }
153}
154
155impl std::fmt::Debug for InstallEnv<'_> {
156    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
157        f.debug_struct("InstallEnv")
158            .field("cache_root", &self.cache_root)
159            .field("source_fetcher", &self.source_fetcher.is_some())
160            .field("machine_auth", &self.machine_auth.map(HashMap::len))
161            .field("autoload_marker", &self.autoload_marker)
162            .field("wording", &self.wording)
163            .finish_non_exhaustive()
164    }
165}
166
167/// How a dist's files are materialized into `vendor/`.
168#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
169pub enum LinkMode {
170    /// Decompress each cached `<key>.zip` straight into `vendor/` on every
171    /// install (the portable default; independent trees, safe to mutate).
172    #[default]
173    Extract,
174    /// Decompress each dist ONCE into a persistent extracted store next to the
175    /// zip cache, then **hard-link** the store tree into `vendor/`. Skips the
176    /// per-install decompression and file writes when the store is warm.
177    ///
178    /// Safe to mutate `vendor/` afterwards **only** because every writer in this
179    /// installer (and `composer-patches`) replaces a file atomically — a temp
180    /// file in the same dir plus a rename — which drops the hard link and gives
181    /// the touched file a fresh inode, leaving the shared store intact. An
182    /// in-place-truncating writer would corrupt the store for the next install.
183    Hardlink,
184}
185
186/// Caller-supplied install options. Mirrors the subset of Composer's `install`
187/// flags this installer honors.
188#[derive(Debug, Clone, Copy, Default)]
189pub struct InstallOptions {
190    /// Skip packages in `composer.lock`'s `packages-dev` AND pass
191    /// `no_dev=true` to the autoloader so dev autoload entries don't reach
192    /// `vendor/autoload.php`.
193    pub no_dev: bool,
194    /// How dist files land in `vendor/` (see [`LinkMode`]). Defaults to
195    /// [`LinkMode::Extract`].
196    pub link_mode: LinkMode,
197}
198
199/// Lifecycle hooks fired during an install when root-script execution is opted
200/// in. The installer stays command- and PHP-agnostic: the caller supplies an
201/// implementation that maps each hook to the right Composer event
202/// (`pre-install-cmd` vs `pre-update-cmd`, …) and runs it.
203///
204/// `Some(hooks)` is the scripts-ON gate: when present, the native Laravel
205/// discovery + its drift guard are skipped (the real `post-autoload-dump`
206/// entries run instead), and the "scripts not run" warning is suppressed.
207/// `None` keeps the deterministic scripts-OFF behavior.
208pub trait ScriptHooks {
209    /// `pre-install-cmd` / `pre-update-cmd` — before package operations.
210    fn pre_cmd(&self) -> Result<()>;
211    /// `pre-autoload-dump` — before the autoloader is regenerated.
212    fn pre_autoload_dump(&self) -> Result<()>;
213    /// `post-autoload-dump` — after the autoloader is regenerated. Runs the
214    /// project's real entries (e.g. Laravel's `package:discover`).
215    fn post_autoload_dump(&self) -> Result<()>;
216    /// `post-install-cmd` / `post-update-cmd` — at the very end.
217    fn post_cmd(&self) -> Result<()>;
218}
219
220/// What happened. Returned to the caller for machine emission and a one-line
221/// text summary.
222#[derive(Debug, Clone)]
223pub struct InstallSummary {
224    pub project_root: PathBuf,
225    pub packages_installed: u32,
226    pub packages_already_present: u32,
227    /// Packages whose dist reference matched `installed.json` and whose vendor
228    /// directory already existed — skipped entirely (no download, no
229    /// extraction).
230    pub packages_up_to_date: u32,
231    /// Composer-plugin packages installed like any other package (Composer
232    /// installs them too), but whose install-time hooks are NOT run — this
233    /// installer never executes plugin PHP. Their files ARE extracted, so
234    /// packages that happen to be `type: composer-plugin` yet provide
235    /// runtime code (e.g. `php-http/discovery`) are not left missing.
236    pub plugin_hooks_skipped: u32,
237    /// Packages that were in the previous `installed.json` but are no longer in
238    /// the lock file (or excluded by `--no-dev`) and had their vendor directory
239    /// removed.
240    pub packages_removed: u32,
241    pub bins_installed: u32,
242    /// Files copied into the project root by the native
243    /// `magento/magento-composer-installer` deploy (`extra.map`). Zero for
244    /// non-Magento projects.
245    pub files_deployed: u64,
246    pub no_dev: bool,
247    /// On-disk bytes of the dist archives fetched this run (cache hits
248    /// contribute nothing).
249    pub download_bytes: u64,
250    /// Wall-clock of the autoload dump, in milliseconds. `0` when the freshness
251    /// marker let the dump be skipped entirely.
252    pub autoload_ms: u64,
253    /// Soft preflight findings — one per Composer plugin, one for a non-empty
254    /// `scripts` section, plus any Magento deploy warnings. Callers typically
255    /// print these as `warning: …` lines.
256    pub warnings: Vec<String>,
257}
258
259/// Apply `composer.lock` to `project_root`. See module docs for the flow.
260///
261/// # Errors
262///
263/// Returns `Err` when the project is not a Composer project (missing
264/// `composer.json`/`composer.lock`), preflight finds a hard blocker, a download
265/// or extraction fails, or the autoloader dump fails.
266pub fn install_from_lock(
267    env: &InstallEnv<'_>,
268    project_root: &Path,
269    opts: InstallOptions,
270    hooks: Option<&dyn ScriptHooks>,
271) -> Result<InstallSummary> {
272    install_from_lock_with_patches(env, project_root, opts, hooks, None)
273}
274
275/// Like [`install_from_lock`], but also applies a resolved [`PatchPlan`]
276/// (cweagans-style patches, applied natively). `patches` is `None` for the
277/// patches-disabled path, which keeps install-set diffing dist-ref-only.
278///
279/// The plan drives **two** touch points required for re-application
280/// correctness: pre-extraction it forces every package whose patch fingerprint
281/// changed into the install set (so a changed patch set re-extracts pristine),
282/// and post-extraction it applies the patches and rewrites `patches.lock.json`.
283///
284/// # Errors
285///
286/// As [`install_from_lock`], plus a patch that fails to apply under
287/// [`FailureMode::Abort`].
288///
289/// # Panics
290///
291/// Only on an internal invariant violation: every package with a dist yields
292/// at least its own dist URL.
293///
294#[tracing::instrument(skip_all, fields(project_root = %project_root.display()))]
295pub fn install_from_lock_with_patches(
296    env: &InstallEnv<'_>,
297    project_root: &Path,
298    opts: InstallOptions,
299    hooks: Option<&dyn ScriptHooks>,
300    patches: Option<&PatchPlan>,
301) -> Result<InstallSummary> {
302    let composer_json_path = project_root.join("composer.json");
303    let composer_lock_path = project_root.join("composer.lock");
304    let composer_json_bytes = match std::fs::read(&composer_json_path) {
305        Ok(bytes) => bytes,
306        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
307            return Err(InstallError::MissingManifest {
308                path: composer_json_path,
309            }
310            .into());
311        }
312        Err(e) => {
313            return Err(
314                eyre::Report::new(e).wrap_err(format!("reading {}", composer_json_path.display()))
315            );
316        }
317    };
318    let lock = if composer_lock_path.exists() {
319        Lock::read(&composer_lock_path)?
320    } else {
321        return Err(InstallError::MissingLock {
322            path: composer_lock_path,
323        }
324        .into());
325    };
326
327    // A stale lock (content-hash mismatch) warns rather than blocks — same as
328    // Composer. Surface it first so it leads the warning list.
329    let mut warnings = Vec::new();
330    let wording = &env.wording;
331    warnings.extend(content_hash_warning(&composer_json_bytes, &lock, wording)?);
332    warnings.extend(preflight(
333        &composer_json_bytes,
334        &lock,
335        opts.no_dev,
336        hooks.is_some(),
337        env.source_fetcher.is_some(),
338        wording,
339    )?);
340
341    // Assemble per-host auth from every source Composer understands —
342    // composer.json `config`, global `auth.json`, project-level `auth.json`,
343    // and the `COMPOSER_AUTH` env var. Dist URLs sitting behind the same auth
344    // as the metadata (Magento's `/archives/…`, private satis, GitLab CI
345    // Composer ZIPs) need the header; public-CDN dists from Packagist do not.
346    let composer_json_value: Value = serde_json::from_slice(&composer_json_bytes).map_err(|e| {
347        InstallError::InvalidManifest {
348            path: composer_json_path.clone(),
349            detail: e.to_string(),
350        }
351    })?;
352    let auth: HashMap<String, AuthCredentials> =
353        read_all_auth_with(&composer_json_value, project_root, env.machine_auth)?;
354
355    // `pre-install-cmd` / `pre-update-cmd` — before any package operation
356    // (download/extract). Only when the user opted into root scripts.
357    if let Some(hooks) = hooks {
358        hooks.pre_cmd()?;
359    }
360
361    // Gather the packages actually installed. Filters:
362    //   - `path` dists: materialized separately (symlink-or-copy).
363    //   - metapackages: no `dist` and no code — pure require-graph nodes.
364    // Composer-plugin packages install like any other package (Composer does
365    // too — their files may provide runtime code); only their install-time
366    // hooks are skipped, since this installer never runs plugin PHP. Preflight
367    // warns about them.
368    let candidates: Vec<&LockPackage> = if opts.no_dev {
369        lock.packages.iter().collect()
370    } else {
371        lock.all_packages().collect()
372    };
373    let plugin_hooks_skipped =
374        u32::try_from(candidates.iter().filter(|p| p.is_composer_plugin()).count())
375            .unwrap_or(u32::MAX);
376
377    // Drift guard for native Laravel discovery. This installer substitutes its
378    // own package:discover + clearCompiled for Laravel's `post-autoload-dump`
379    // script instead of running it. A custom step *after* the defaults is fine
380    // (the defaults still run first). But a step *before* or *between* them — or
381    // a renamed/removed discovery command — could change what the defaults see,
382    // so it can't be safely reproduced: fail fast rather than leave the app
383    // half-configured. Only applies when laravel/framework is installed.
384    //
385    // Skipped entirely when root scripts are opted in (`hooks.is_some()`): the
386    // real `post-autoload-dump` entries run via the hook.
387    if hooks.is_none() && candidates.iter().any(|p| p.name == "laravel/framework") {
388        let scripts = composer_json_value
389            .get("scripts")
390            .cloned()
391            .unwrap_or(Value::Null);
392        let blocking = composer_installers::blocking_post_autoload_dump(&scripts);
393        if !blocking.is_empty() {
394            return Err(eyre!(
395                "Laravel post-autoload-dump runs steps before/among the default Laravel steps \
396                 that {tool} does not reproduce:\n  {}\n\n\
397                 `artisan package:discover` and `ComposerScripts::postAutoloadDump` are reproduced natively, \
398                 but only when they run first — a step ahead of or between them may change what \
399                 they see. Steps appended *after* the defaults are fine. Reorder so custom steps \
400                 come last, or run the script yourself (`composer run-script post-autoload-dump`). \
401                 If Laravel changed its default post-autoload-dump, the native discovery is out of \
402                 date — please report it.",
403                blocking.join("\n  "),
404                tool = wording.tool,
405            ));
406        }
407    }
408    let installable: Vec<&LockPackage> = candidates
409        .iter()
410        .copied()
411        .filter(|p| !p.is_path_dist() && !p.is_metapackage())
412        .collect();
413
414    // Path packages are materialized separately (symlink-or-copy), not
415    // downloaded.
416    let installer_paths = composer_installers::InstallerPaths::parse(&composer_json_value);
417    let path_packages: Vec<&LockPackage> = candidates
418        .iter()
419        .copied()
420        .filter(|p| p.is_path_dist())
421        .collect();
422    let path_dests: Vec<PathBuf> = path_packages
423        .iter()
424        .map(|p| {
425            let rel = composer_installers::install_path(
426                &p.name,
427                p.package_type.as_deref(),
428                &installer_paths,
429            );
430            project_root.join(rel)
431        })
432        .collect();
433
434    // Diff against the existing installed state to skip packages whose dist
435    // reference hasn't changed and whose vendor dir is still present.
436    //
437    // Patch-aware step: any package whose desired patch fingerprint differs
438    // from the applied one (`patches.lock.json`) is forced back into the
439    // install set even when its dist reference is unchanged — a patch is only
440    // ever applied to a pristine tree.
441    let installed_state = read_installed_state(project_root);
442    let force_patch: HashSet<&str> = patches
443        .map(|plan| compute_force_set(plan, &installable, installed_state.as_ref(), project_root))
444        .unwrap_or_default();
445    let (install_set, packages_up_to_date) = diff_install_set_with_force(
446        &installable,
447        installed_state.as_ref(),
448        project_root,
449        &force_patch,
450    );
451
452    // Remove packages that left the lock. `new_record` is every package this
453    // install puts on disk (path and dist alike), at its installer path; it is
454    // written once the install succeeds so the next one knows what to remove
455    // even if an autoloader dump rewrote `installed.json` in between. See
456    // `crate::stale`.
457    let new_record = InstallRecord::for_packages(&candidates, &installer_paths);
458    let packages_removed = remove_stale_packages(project_root, &new_record);
459
460    // Native `composer/installers`: a package's on-disk location can be
461    // remapped by its `type` and the root `extra.installer-paths`. For the
462    // common case (every Magento 2 module) this resolves to `vendor/<name>`.
463    // The same computation runs in the autoloader so the generated autoload +
464    // `installed.json` install-path point at the relocated tree.
465    let vendor_dirs: Vec<PathBuf> = install_set
466        .iter()
467        .map(|p| {
468            let rel = composer_installers::install_path(
469                &p.name,
470                p.package_type.as_deref(),
471                &installer_paths,
472            );
473            // Surface composer/installers types this installer doesn't
474            // relocate: the package lands in vendor/ and a framework expecting
475            // it elsewhere won't find it. Only warn when it actually fell back
476            // to vendor/<name>.
477            if rel == format!("vendor/{}", p.name)
478                && let Some(framework) =
479                    composer_installers::unsupported_framework(p.package_type.as_deref())
480            {
481                warnings.push(format!(
482                    "{}: package type '{}' is a composer/installers '{}' type that {tool} \
483                     does not relocate — installing to vendor/{} (the framework may expect it \
484                     elsewhere; add an extra.installer-paths entry to override)",
485                    p.name,
486                    p.package_type.as_deref().unwrap_or(""),
487                    framework,
488                    p.name,
489                    tool = wording.tool,
490                ));
491            }
492            project_root.join(rel)
493        })
494        .collect();
495    // Expand each dist into its ordered candidate URL list —
496    // `LockPackage::dist_urls()` puts a `preferred` mirror ahead of the dist's
497    // own URL — and pre-render each candidate's `Authorization` header when its
498    // host matches the auth map. Mirrors can sit on a different host than the
499    // dist URL, so auth is resolved per candidate. String storage lives in a
500    // sibling vec so `DistRequest` can carry borrowed data.
501    //
502    // The changed set splits into dist installs and git-source installs.
503    // `vendor_dirs` is index-aligned to `install_set`; both channels fill the
504    // same destinations, and everything after (patches, deploy, autoload,
505    // bins) treats a source checkout exactly like an extracted dist.
506    let dist_indices: Vec<usize> = (0..install_set.len())
507        .filter(|&i| install_set[i].dist.is_some())
508        .collect();
509    let source_indices: Vec<usize> = (0..install_set.len())
510        .filter(|&i| install_set[i].is_source_install())
511        .collect();
512    let candidate_sets: Vec<Vec<DistCandidate>> = dist_indices
513        .iter()
514        .map(|&i| {
515            install_set[i]
516                .dist_urls()
517                .into_iter()
518                .map(|url| {
519                    let auth_entry = composer_auth::auth_key(&url)
520                        .and_then(|origin| auth.get(origin))
521                        .map(|creds| (creds.header_value(), creds.header_name()));
522                    DistCandidate {
523                        url,
524                        auth_header: auth_entry.as_ref().map(|(v, _)| v.clone()),
525                        auth_header_name: auth_entry.as_ref().map(|(_, n)| *n),
526                    }
527                })
528                .collect()
529        })
530        .collect();
531    let dists: Vec<DistRequest<'_>> = dist_indices
532        .iter()
533        .zip(candidate_sets.iter())
534        .filter_map(|(&i, candidates)| {
535            let p = install_set[i];
536            let dist = p.dist.as_ref()?;
537            // `dist_urls()` yields at least the dist's own URL for every package
538            // with a dist.
539            let (primary, fallbacks) = candidates
540                .split_first()
541                .expect("non-empty dist_urls for a dist package");
542            Some(DistRequest {
543                package_name: &p.name,
544                url: &primary.url,
545                sha1: dist.shasum.as_deref().unwrap_or(""),
546                reference: dist.reference.as_deref().unwrap_or(""),
547                strip_prefix: None,
548                // Preflight rejected every other dist type.
549                archive: ArchiveKind::from_dist_type(&dist.kind).unwrap_or(ArchiveKind::Zip),
550                vendor_dest: &vendor_dirs[i],
551                auth_header: primary.auth_header.as_deref(),
552                auth_header_name: primary.auth_header_name,
553                project_root,
554                fallbacks,
555            })
556        })
557        .collect();
558    let source_url_sets: Vec<Vec<String>> = source_indices
559        .iter()
560        .map(|&i| install_set[i].source_urls())
561        .collect();
562    let source_specs: Vec<SourceSpec<'_>> = source_indices
563        .iter()
564        .zip(source_url_sets.iter())
565        .map(|(&i, urls)| {
566            let p = install_set[i];
567            SourceSpec {
568                package_name: &p.name,
569                urls,
570                reference: p.source.as_ref().map_or("", |s| s.reference.as_str()),
571                dest: &vendor_dirs[i],
572            }
573        })
574        .collect();
575
576    let outcomes = fetch_and_extract_dists(
577        env.fetcher,
578        env.cache_root,
579        &dists,
580        env.progress,
581        opts.link_mode,
582    )?;
583
584    // Clone + check out git-source packages. Preflight rejected them unless a
585    // source fetcher is configured.
586    let sources_installed = match env.source_fetcher {
587        Some(fetcher) if !source_specs.is_empty() => materialize_sources(fetcher, &source_specs)?,
588        _ => 0,
589    };
590
591    // Materialize `type: path` packages (symlink-or-copy) into their vendor
592    // destinations. Done before the autoload dump so the generated autoloader
593    // sees the linked trees.
594    let path_summary = crate::path_link::materialize_path_packages(
595        project_root,
596        &path_packages,
597        &path_dests,
598        installed_state.as_ref(),
599    );
600    warnings.extend(path_summary.warnings);
601
602    // Native patch application. Every `install_set` member is pristine here
603    // (freshly extracted), so this is the only safe place to patch. Must run
604    // *before* the Magento deploy so `extra.map`-copied files carry the patched
605    // content — Composer's ordering.
606    if let Some(plan) = patches {
607        // Deferred (vendor-shipped) patches can be read now that their owning
608        // packages are extracted: materialize and fold them into the plan
609        // before applying, so they patch and earn a `patches.lock.json`
610        // fingerprint like any other. The clone keeps the caller's plan intact.
611        let resolved;
612        let plan = if plan.deferred.is_empty() {
613            plan
614        } else {
615            let mut p = plan.clone();
616            p.resolve_deferred()
617                .wrap_err("materializing vendor-shipped patches after install")?;
618            resolved = p;
619            &resolved
620        };
621        apply_patch_plan(
622            plan,
623            &install_set,
624            &vendor_dirs,
625            project_root,
626            &mut warnings,
627        )?;
628    }
629
630    // Native `magento/magento-composer-installer`: for every freshly-extracted
631    // Magento 2 component, copy its `extra.map` files into the project root and
632    // apply `extra.chmod`. Driving this off `install_set` (only changed/new
633    // packages) matches Composer. A deploy failure is a warning, not an abort.
634    let deploy_summary = deploy_components(&install_set, &vendor_dirs, project_root);
635    warnings.extend(deploy_summary.warnings);
636
637    // `pre-autoload-dump` — before the autoloader is regenerated.
638    if let Some(hooks) = hooks {
639        hooks.pre_autoload_dump()?;
640    }
641
642    // Autoloader freshness fast-path. The non-optimized autoloader is a pure
643    // function of the root manifest and the lock. When nothing was installed or
644    // removed this run, that fingerprint is unchanged, and the output is still
645    // on disk, a regenerated tree would be byte-identical — so the dump is pure
646    // waste and is skipped. Restricted to scripts-off: with root scripts on the
647    // unconditional dump is kept so the pre/post-autoload-dump lifecycle is
648    // observable exactly as before.
649    let autoload_marker = project_root
650        .join("vendor/composer")
651        .join(env.autoload_marker);
652    let lock_bytes = std::fs::read(&composer_lock_path).unwrap_or_default();
653    let fingerprint =
654        autoload_fingerprint(&composer_json_bytes, &lock_bytes, opts.no_dev).to_string();
655    let autoload_fresh = hooks.is_none()
656        && install_set.is_empty()
657        && packages_removed == 0
658        && path_summary.linked == 0
659        && project_root.join("vendor/autoload.php").is_file()
660        && std::fs::read_to_string(&autoload_marker)
661            .ok()
662            .as_deref()
663            .map(str::trim)
664            == Some(fingerprint.as_str());
665
666    let autoload_started = std::time::Instant::now();
667    if !autoload_fresh {
668        dump_autoload(&DumpRequest {
669            project_root,
670            optimize: false,
671            classmap_authoritative: false,
672            no_dev: opts.no_dev,
673            apcu_autoloader: false,
674            apcu_prefix: None,
675            autoloader_suffix: None,
676        })
677        .map_err(|e| eyre!("autoload dump failed: {e}"))?;
678        // Record the fingerprint so the next unchanged sync can skip the dump.
679        // Best-effort: a write failure just means we regenerate next time.
680        if let Err(e) = std::fs::write(&autoload_marker, &fingerprint) {
681            warnings.push(format!(
682                "could not write autoload freshness marker {}: {e}",
683                autoload_marker.display()
684            ));
685        }
686    }
687    let autoload_ms = u64::try_from(autoload_started.elapsed().as_millis()).unwrap_or(u64::MAX);
688
689    match hooks {
690        // Scripts ON: run the project's real `post-autoload-dump` entries.
691        Some(hooks) => hooks.post_autoload_dump()?,
692        // Scripts OFF: native Laravel package discovery — the effect of
693        // Laravel's `post-autoload-dump` script, which this installer won't
694        // run. Gated on `laravel/framework` being installed. Runs after the
695        // autoload dump because it reads the freshly-written `installed.json`.
696        None => {
697            if candidates.iter().any(|p| p.name == "laravel/framework")
698                && let Err(e) = run_laravel_discovery(project_root, &composer_json_value)
699            {
700                warnings.push(format!("laravel package discovery failed: {e}"));
701            }
702        }
703    }
704
705    let bin_summary = crate::bin_proxy::install_bin_proxies(project_root, &candidates);
706    warnings.extend(bin_summary.warnings);
707
708    // `post-install-cmd` / `post-update-cmd` — at the very end, after bins.
709    if let Some(hooks) = hooks {
710        hooks.post_cmd()?;
711    }
712
713    let packages_installed = u32::try_from(
714        outcomes
715            .iter()
716            .filter(|o| matches!(o, DistOutcome::Downloaded { .. }))
717            .count(),
718    )
719    .unwrap_or(u32::MAX);
720    let download_bytes: u64 = outcomes
721        .iter()
722        .map(|o| match o {
723            DistOutcome::Downloaded { bytes } => *bytes,
724            DistOutcome::CacheHit => 0,
725        })
726        .sum();
727    let packages_already_present = u32::try_from(
728        outcomes
729            .iter()
730            .filter(|o| **o == DistOutcome::CacheHit)
731            .count(),
732    )
733    .unwrap_or(u32::MAX);
734    // Fold path-package materialization into the totals: a freshly linked/copied
735    // path package counts as installed; an unchanged one counts as up-to-date.
736    // Git-source installs (always freshly checked out when in the install
737    // set) count as installed too.
738    let packages_installed = packages_installed
739        .saturating_add(path_summary.linked)
740        .saturating_add(u32::try_from(sources_installed).unwrap_or(u32::MAX));
741    let packages_up_to_date = packages_up_to_date.saturating_add(path_summary.up_to_date);
742    if let Err(e) = new_record.write(project_root) {
743        warnings.push(format!(
744            "could not record the installed packages ({e}); the next install may not \
745             remove packages that leave the lock"
746        ));
747    }
748    Ok(InstallSummary {
749        project_root: project_root.to_path_buf(),
750        packages_installed,
751        packages_already_present,
752        packages_up_to_date,
753        plugin_hooks_skipped,
754        packages_removed,
755        bins_installed: bin_summary.bins_installed,
756        files_deployed: deploy_summary.files_deployed,
757        no_dev: opts.no_dev,
758        download_bytes,
759        autoload_ms,
760        warnings,
761    })
762}
763
764/// The set of packages to force back into the install set for patching: those
765/// whose patch fingerprint changed, plus — for project-root patches — every
766/// package coupled to one already being re-extracted.
767///
768/// A root ("top-level") patch is applied atomically at the project root, so its
769/// packages must stay in lockstep: if any one is re-extracted this run, all of
770/// them must be re-extracted together and the patch re-applied. The coupling is
771/// expanded to a fixpoint because root patches can chain through a shared
772/// package.
773fn compute_force_set<'a>(
774    plan: &'a PatchPlan,
775    installable: &[&'a LockPackage],
776    installed_state: Option<&InstalledState>,
777    project_root: &Path,
778) -> HashSet<&'a str> {
779    // Seed: packages whose patch fingerprint changed since the applied state.
780    let mut force: HashSet<&str> = plan
781        .tracked_packages()
782        .filter(|name| plan.fingerprint_changed(name))
783        .collect();
784
785    // Deferred (vendor-shipped) patches have no fingerprint yet: their source
786    // isn't readable until the owning package is on disk. Force their targets
787    // so they're re-extracted pristine before the patch is applied after the
788    // install. On a clean vendor/ the target is extracted anyway; this also
789    // covers a present target whose patch-owning package alone was missing.
790    for target in plan.deferred_targets() {
791        if let Some(p) = installable.iter().find(|p| p.name == target) {
792            force.insert(p.name.as_str());
793        }
794    }
795
796    if plan.root_patches.is_empty() {
797        return force;
798    }
799
800    let by_name: HashMap<&str, &LockPackage> =
801        installable.iter().map(|p| (p.name.as_str(), *p)).collect();
802    // Whether a package needs a fresh extract for a non-patch reason (its dist
803    // reference changed, its vendor dir is gone, or there is no prior state).
804    let needs_reextract = |name: &str| -> bool {
805        by_name.get(name).is_some_and(|p| {
806            installed_state.is_none_or(|state| !dist_up_to_date(p, state, project_root))
807        })
808    };
809
810    loop {
811        let mut added = false;
812        for rp in &plan.root_patches {
813            let any_reextract = rp
814                .packages
815                .iter()
816                .any(|pkg| force.contains(pkg.as_str()) || needs_reextract(pkg));
817            if any_reextract {
818                for pkg in &rp.packages {
819                    // Only force packages actually installable this run.
820                    if let Some(p) = by_name.get(pkg.as_str())
821                        && force.insert(p.name.as_str())
822                    {
823                        added = true;
824                    }
825                }
826            }
827        }
828        if !added {
829            break;
830        }
831    }
832    force
833}
834
835/// Apply a resolved [`PatchPlan`] to the freshly-extracted `install_set`, then
836/// rewrite `patches.lock.json` (always — it is load-bearing for the next run's
837/// diff). Package-scoped patches apply into each target's install dir;
838/// project-root patches apply once at the project root. Every re-extracted
839/// tracked package then earns the desired fingerprint (fully applied) or loses
840/// it (partial apply, or no longer patched). Returns `Err` only in `Abort`
841/// failure mode; otherwise apply failures surface as `warnings`.
842fn apply_patch_plan(
843    plan: &PatchPlan,
844    install_set: &[&LockPackage],
845    vendor_dirs: &[PathBuf],
846    project_root: &Path,
847    warnings: &mut Vec<String>,
848) -> Result<()> {
849    let mut new_fingerprints = plan.applied.clone();
850    let install_names: HashSet<&str> = install_set.iter().map(|p| p.name.as_str()).collect();
851
852    // Packages whose patch set did not fully apply this run. They must not earn
853    // a fingerprint, so the next run re-extracts pristine and retries.
854    let mut failed: HashSet<String> = HashSet::new();
855
856    // 1. Package-scoped patches: apply into each package's install dir.
857    for (pkg, vendor_dir) in install_set.iter().zip(vendor_dirs.iter()) {
858        let Some(pkg_patches) = plan.patches.get(&pkg.name) else {
859            continue;
860        };
861        let res = composer_patches::apply_package_patches(
862            vendor_dir,
863            &pkg.name,
864            pkg_patches,
865            plan.failure_mode,
866            plan.skip_report,
867        )?;
868        warnings.extend(res.warnings);
869        if res.fingerprint.is_none() {
870            failed.insert(pkg.name.clone());
871        }
872    }
873
874    // 2. Project-root patches: apply once each, at the project root. Coupling
875    // guarantees a root patch's packages are all-in or all-out of the install
876    // set, so `all_pristine` distinguishes "re-extracted this run, (re)apply
877    // now" from "untouched, already applied before".
878    let vendor_by_name: HashMap<&str, &PathBuf> = install_set
879        .iter()
880        .zip(vendor_dirs.iter())
881        .map(|(p, dir)| (p.name.as_str(), dir))
882        .collect();
883    for rp in &plan.root_patches {
884        let all_pristine = rp
885            .packages
886            .iter()
887            .all(|p| install_names.contains(p.as_str()));
888        if !all_pristine {
889            continue;
890        }
891        if apply_root_patch(project_root, &rp.patch, plan.failure_mode, warnings)? {
892            // Record the patch in each touched package's `PATCHES.txt`.
893            if !plan.skip_report {
894                for pkg in &rp.packages {
895                    if let Some(dir) = vendor_by_name.get(pkg.as_str())
896                        && let Err(e) = composer_patches::append_patches_txt(dir, &[&rp.patch])
897                    {
898                        warnings.push(format!(
899                            "could not update PATCHES.txt in `{}`: {e}",
900                            dir.display()
901                        ));
902                    }
903                }
904            }
905        } else {
906            failed.extend(rp.packages.iter().cloned());
907        }
908    }
909
910    // 3. Recompute fingerprints for every tracked package re-extracted this run.
911    // Untouched packages keep their prior fingerprint.
912    for name in plan.tracked_packages() {
913        if !install_names.contains(name) {
914            continue;
915        }
916        match (failed.contains(name), plan.desired_fingerprint(name)) {
917            // Fully applied → record the combined (package + root) fingerprint.
918            (false, Some(fp)) => {
919                new_fingerprints.insert(name.to_string(), fp);
920            }
921            // Partial apply, or no longer patched → drop, so the next run
922            // re-extracts pristine (and retries any failed patch).
923            _ => {
924                new_fingerprints.remove(name);
925            }
926        }
927    }
928
929    let human = plan.write_lock.then(|| plan.human_view());
930    if let Err(e) = composer_patches::lock::write_with_human(project_root, &new_fingerprints, human)
931    {
932        warnings.push(format!("could not write patches.lock.json: {e}"));
933    }
934    Ok(())
935}
936
937/// Apply a single project-root ("top-level") patch at the project root (the
938/// caller records it in each touched package's `PATCHES.txt`). Returns whether
939/// it applied cleanly: in `Abort` mode a failure is an `Err`; in `SkipAndWarn`
940/// it pushes a warning and returns `Ok(false)`.
941fn apply_root_patch(
942    project_root: &Path,
943    patch: &MaterializedPatch,
944    failure_mode: FailureMode,
945    warnings: &mut Vec<String>,
946) -> Result<bool> {
947    let text = std::fs::read_to_string(&patch.local_path)
948        .with_context(|| format!("reading patch `{}`", patch.local_path.display()))?;
949    let opts = ApplyOptions {
950        depth: patch.depth,
951        ..ApplyOptions::default()
952    };
953    match apply_patch_text(project_root, &text, &opts) {
954        Ok(_) => Ok(true),
955        Err(e) => match failure_mode {
956            FailureMode::Abort => Err(eyre!(
957                "patch `{}` failed to apply at the project root: {e:#}",
958                patch.description
959            )),
960            FailureMode::SkipAndWarn => {
961                warnings.push(format!(
962                    "patch `{}` failed to apply at the project root: {e:#}",
963                    patch.description
964                ));
965                Ok(false)
966            }
967        },
968    }
969}
970
971/// Outcome of the native Magento deploy pass.
972struct DeploySummary {
973    files_deployed: u64,
974    warnings: Vec<String>,
975}
976
977/// Run the native `magento/magento-composer-installer` deploy over the
978/// freshly-extracted packages. `install_set[i]` was extracted to
979/// `vendor_dirs[i]`, so the two slices are zipped. For each Magento 2 component
980/// we copy its `extra.map` into `project_root` and apply `extra.chmod`; if any
981/// `magento2-component` was deployed we emit `app/etc/vendor_path.php`. Deploy
982/// failures become warnings.
983fn deploy_components(
984    install_set: &[&LockPackage],
985    vendor_dirs: &[PathBuf],
986    project_root: &Path,
987) -> DeploySummary {
988    let mut files_deployed = 0u64;
989    let mut warnings = Vec::new();
990    let mut deployed_component = false;
991
992    for (pkg, vendor_dir) in install_set.iter().zip(vendor_dirs.iter()) {
993        let Some(plan) = composer_installers::plan_deploy(pkg.package_type.as_deref(), &pkg.extra)
994        else {
995            continue;
996        };
997        if plan.map.is_empty() && plan.chmod.is_empty() {
998            continue;
999        }
1000        match composer_installers::apply_deploy(&plan, vendor_dir, project_root) {
1001            Ok(stats) => {
1002                files_deployed += stats.files_copied;
1003                deployed_component |= plan.is_component;
1004                warnings.extend(
1005                    stats
1006                        .warnings
1007                        .into_iter()
1008                        .map(|w| format!("deploy of {}: {w}", pkg.name)),
1009                );
1010            }
1011            Err(e) => {
1012                warnings.push(format!("deploy of {} failed: {e}", pkg.name));
1013            }
1014        }
1015    }
1016
1017    // `app/etc/vendor_path.php` is generated by the installer (it is not one of
1018    // magento2-base's mapped files); Magento's bootstrap reads it to locate
1019    // `vendor/`. Emit it once whenever a component laid down the root skeleton.
1020    if deployed_component && let Err(e) = write_vendor_path_php(project_root) {
1021        warnings.push(format!("writing app/etc/vendor_path.php failed: {e}"));
1022    }
1023
1024    DeploySummary {
1025        files_deployed,
1026        warnings,
1027    }
1028}
1029
1030/// Reproduce Laravel's package discovery: rebuild `bootstrap/cache/packages.php`
1031/// from `installed.json` + the root `extra.laravel`, then clear the stale
1032/// compiled caches Laravel's `clearCompiled()` removes. Mirrors what
1033/// `artisan package:discover` (run via `post-autoload-dump`) would do.
1034fn run_laravel_discovery(project_root: &Path, composer_json_value: &Value) -> Result<()> {
1035    let installed_path = project_root.join("vendor/composer/installed.json");
1036    let bytes = std::fs::read(&installed_path)
1037        .wrap_err_with(|| format!("reading {}", installed_path.display()))?;
1038    let installed: Value = serde_json::from_slice(&bytes).wrap_err("parsing installed.json")?;
1039    let root_extra = composer_json_value
1040        .get("extra")
1041        .cloned()
1042        .unwrap_or(Value::Null);
1043
1044    let manifest = composer_installers::build_package_manifest(&installed, &root_extra);
1045    let php = composer_installers::render_packages_php(&manifest);
1046
1047    let cache_path = project_root.join(composer_installers::PACKAGES_CACHE);
1048    if let Some(parent) = cache_path.parent() {
1049        std::fs::create_dir_all(parent)
1050            .wrap_err_with(|| format!("creating {}", parent.display()))?;
1051    }
1052    std::fs::write(&cache_path, php)
1053        .wrap_err_with(|| format!("writing {}", cache_path.display()))?;
1054
1055    // clearCompiled(): drop the config/services caches so they can't reference
1056    // a package set that just changed.
1057    for rel in composer_installers::STALE_CACHES {
1058        let path = project_root.join(rel);
1059        if path.exists() {
1060            let _ = std::fs::remove_file(path);
1061        }
1062    }
1063    Ok(())
1064}
1065
1066/// Write `app/etc/vendor_path.php` (creating `app/etc/` if needed).
1067fn write_vendor_path_php(project_root: &Path) -> Result<()> {
1068    let dir = project_root.join("app/etc");
1069    std::fs::create_dir_all(&dir).wrap_err_with(|| format!("creating {}", dir.display()))?;
1070    std::fs::write(
1071        dir.join("vendor_path.php"),
1072        composer_installers::VENDOR_PATH_PHP,
1073    )
1074    .wrap_err("writing vendor_path.php")?;
1075    Ok(())
1076}
1077
1078/// Snapshot of `vendor/composer/installed.json` — the packages and dist
1079/// references that were installed on the previous run.
1080pub(crate) struct InstalledState {
1081    /// Package name → dist reference from the previous install.
1082    pub(crate) packages: HashMap<String, String>,
1083}
1084
1085/// Read `vendor/composer/installed.json` and extract the package name → dist
1086/// reference mapping. Returns `None` if the file doesn't exist or can't be
1087/// parsed (first install, corrupted state, etc.).
1088fn read_installed_state(project_root: &Path) -> Option<InstalledState> {
1089    let path = project_root.join("vendor/composer/installed.json");
1090    let bytes = std::fs::read(&path).ok()?;
1091    let value: Value = serde_json::from_slice(&bytes).ok()?;
1092    let obj = value.as_object()?;
1093
1094    let packages_arr = obj.get("packages")?.as_array()?;
1095    let mut packages = HashMap::with_capacity(packages_arr.len());
1096    for pkg in packages_arr {
1097        let name = pkg.get("name").and_then(|v| v.as_str()).unwrap_or("");
1098        if name.is_empty() {
1099            continue;
1100        }
1101        // The dist reference, or the source reference for a git-source
1102        // install, so source packages diff on their checked-out commit.
1103        let reference = pkg
1104            .get("dist")
1105            .and_then(|d| d.get("reference"))
1106            .and_then(|r| r.as_str())
1107            .or_else(|| {
1108                pkg.get("source")
1109                    .and_then(|s| s.get("reference"))
1110                    .and_then(|r| r.as_str())
1111            })
1112            .unwrap_or("");
1113        packages.insert(name.to_string(), reference.to_string());
1114    }
1115
1116    Some(InstalledState { packages })
1117}
1118
1119/// Diff the lock file's installable set against the existing `installed.json`
1120/// state. Returns the subset of packages that need downloading/extracting and
1121/// the count already up-to-date. Removing packages that left the lock is
1122/// separate; see [`crate::stale::remove_stale_packages`].
1123#[cfg(test)]
1124pub(crate) fn diff_install_set<'a>(
1125    installable: &[&'a LockPackage],
1126    installed_state: Option<&InstalledState>,
1127    project_root: &Path,
1128) -> (Vec<&'a LockPackage>, u32) {
1129    diff_install_set_with_force(installable, installed_state, project_root, &HashSet::new())
1130}
1131
1132/// Like [`diff_install_set`], but `force` names packages that must be
1133/// (re-)installed even when their dist reference matches and the vendor dir is
1134/// present — the patch-aware path.
1135pub(crate) fn diff_install_set_with_force<'a>(
1136    installable: &[&'a LockPackage],
1137    installed_state: Option<&InstalledState>,
1138    project_root: &Path,
1139    force: &HashSet<&str>,
1140) -> (Vec<&'a LockPackage>, u32) {
1141    let Some(state) = installed_state else {
1142        return (installable.to_vec(), 0);
1143    };
1144
1145    let mut need_install: Vec<&'a LockPackage> = Vec::new();
1146    let mut up_to_date: u32 = 0;
1147    for p in installable {
1148        if !force.contains(p.name.as_str()) && dist_up_to_date(p, state, project_root) {
1149            up_to_date = up_to_date.saturating_add(1);
1150            continue;
1151        }
1152        need_install.push(p);
1153    }
1154    (need_install, up_to_date)
1155}
1156
1157/// Whether `p` is already installed at the locked revision: its recorded dist
1158/// reference matches the lock and its `vendor/<name>` directory is present. The
1159/// single source of truth for "no fresh extract needed", shared by the
1160/// install-set diff and the patch-coupling force computation.
1161fn dist_up_to_date(p: &LockPackage, state: &InstalledState, project_root: &Path) -> bool {
1162    // The dist reference, or the source reference for a git-source install:
1163    // a source package re-clones only when its locked commit changes.
1164    let lock_ref = p.install_reference();
1165    state.packages.get(&p.name).is_some_and(|installed_ref| {
1166        installed_ref == lock_ref && project_root.join("vendor").join(&p.name).is_dir()
1167    })
1168}
1169
1170/// Marker file (under `vendor/composer/`) holding the autoloader freshness
1171/// fingerprint from the last dump. Its presence + match lets a subsequent
1172/// unchanged sync skip the autoloader regeneration.
1173pub(crate) const AUTOLOAD_FRESH_MARKER: &str = ".composer-install-autoload-fresh";
1174
1175/// Fingerprint of everything the non-optimized autoloader output depends on:
1176/// the root manifest bytes (autoload / config / installer-paths in `extra`) and
1177/// the lock bytes (the full package set and each package's own `autoload`
1178/// block), plus the dev flag.
1179///
1180/// Non-cryptographic on purpose — this is a local freshness cache, not a trust
1181/// boundary. A hash collision would only cost a skipped regeneration,
1182/// recoverable with an explicit re-dump.
1183fn autoload_fingerprint(composer_json_bytes: &[u8], lock_bytes: &[u8], no_dev: bool) -> u64 {
1184    let mut h = std::hash::DefaultHasher::new();
1185    composer_json_bytes.hash(&mut h);
1186    lock_bytes.hash(&mut h);
1187    no_dev.hash(&mut h);
1188    h.finish()
1189}
1190
1191/// Check the lock's `content-hash` field against the current `composer.json`
1192/// bytes, using the same algorithm Composer runs (delegated to
1193/// [`composer_manifest::lockfile::content_hash`]).
1194///
1195/// A mismatch is *not* a hard failure: Composer only warns and installs the
1196/// lock's package set anyway, so the user gets a reproducible (if slightly
1197/// stale) environment rather than a refusal. We mirror that — return the
1198/// warning string on mismatch, `None` otherwise.
1199fn content_hash_warning(
1200    composer_json_bytes: &[u8],
1201    lock: &Lock,
1202    wording: &Wording<'_>,
1203) -> Result<Option<String>> {
1204    let Some(expected) = &lock.content_hash else {
1205        // Pre-1.10 lockfiles don't carry a content-hash. Composer tolerates
1206        // them; we do too rather than refuse to install a working historical
1207        // project.
1208        return Ok(None);
1209    };
1210    let actual = lockfile::content_hash(composer_json_bytes)?;
1211    if actual.eq_ignore_ascii_case(expected) {
1212        return Ok(None);
1213    }
1214    Ok(Some(format!(
1215        "composer.lock is out of sync with composer.json (content-hash {expected} → {actual}); \
1216         installing the locked package set anyway — you may be getting outdated dependencies. \
1217         Run `{}` to regenerate the lock.",
1218        wording.update_command,
1219    )))
1220}
1221
1222/// Split lockfile contents into hard blockers (returned as `Err`) and soft
1223/// warnings (returned as `Ok`).
1224///
1225/// Hard blockers are things this installer genuinely cannot install:
1226/// source-only packages (no `dist`) and non-zip dists. The downstream loop
1227/// relies on preflight having rejected these and unwraps accordingly.
1228///
1229/// Warnings are things deliberately not executed but installed around: Composer
1230/// plugins (the package zip is skipped) and a non-empty `scripts` section when
1231/// script execution isn't opted in.
1232///
1233/// Every hard reason is aggregated into a single error.
1234fn preflight(
1235    composer_json_bytes: &[u8],
1236    lock: &Lock,
1237    no_dev: bool,
1238    scripts_on: bool,
1239    sources_on: bool,
1240    wording: &Wording<'_>,
1241) -> Result<Vec<String>> {
1242    let Wording {
1243        tool,
1244        install_command,
1245        scripts_hint,
1246        ..
1247    } = *wording;
1248    let mut reasons: Vec<String> = Vec::new();
1249    let mut warnings: Vec<String> = Vec::new();
1250    let mut plugin_packages: Vec<String> = Vec::new();
1251
1252    // composer.json scripts → not run unless opted in. When scripts are off,
1253    // warn — but only about scripts not already reproduced natively (Laravel's
1254    // discovery `post-autoload-dump` runs either way). When scripts are on, the
1255    // hooks run them: no warning.
1256    if !scripts_on
1257        && let Ok(value) = serde_json::from_slice::<Value>(composer_json_bytes)
1258        && value
1259            .get("scripts")
1260            .and_then(Value::as_object)
1261            .is_some_and(|s| !s.is_empty())
1262        && !composer_installers::only_reproduced_scripts(
1263            value.get("scripts").unwrap_or(&Value::Null),
1264        )
1265    {
1266        warnings.push(format!(
1267            "composer.json declares `scripts`; they are not run by default. {scripts_hint}"
1268        ));
1269    }
1270
1271    let packages: Vec<&LockPackage> = if no_dev {
1272        lock.packages.iter().collect()
1273    } else {
1274        lock.all_packages().collect()
1275    };
1276
1277    for p in packages {
1278        // path dists materialize via symlink-or-copy — outside the dist-archive
1279        // flow. A project that has *only* path dists works fine; no rejection.
1280        if p.is_path_dist() {
1281            continue;
1282        }
1283        if p.is_metapackage() {
1284            // Metapackages legitimately have no `dist` — pure require-graph
1285            // aggregators. Nothing to install.
1286            continue;
1287        }
1288        if p.is_composer_plugin() {
1289            // Plugin install-time hooks are arbitrary PHP we won't run, but the
1290            // package's FILES install like any other (plugins can double as
1291            // runtime libraries: php-http/discovery's classes are called by
1292            // opensearch-php at runtime). Collect the name for one aggregated
1293            // hooks-not-run warning after the loop, then fall through to the
1294            // dist checks below: since we extract it, its dist must be
1295            // installable.
1296            plugin_packages.push(p.name.clone());
1297        }
1298        let Some(dist) = &p.dist else {
1299            // No dist: install from a git `source` when a source fetcher is
1300            // configured. Composer normalizes github/gitlab/bitbucket sources
1301            // to `git` in the lock; hg/svn sources are not supported.
1302            match &p.source {
1303                Some(src) if src.kind == "git" && sources_on => {}
1304                Some(src) if src.kind == "git" => reasons.push(format!(
1305                    "package `{}` has no `dist` block, only a git source, and git source \
1306                     installs are not enabled — configure a source fetcher, or install it \
1307                     with `{install_command}`.",
1308                    p.name,
1309                )),
1310                Some(src) => reasons.push(format!(
1311                    "package `{}` has a `{}` source; {tool} can only install git \
1312                     sources — install it with `{install_command}`.",
1313                    p.name, src.kind,
1314                )),
1315                None => reasons.push(format!(
1316                    "package `{}` has no `dist` block and no git `source` to clone — install \
1317                     it with `{install_command}`.",
1318                    p.name,
1319                )),
1320            }
1321            continue;
1322        };
1323        if ArchiveKind::from_dist_type(&dist.kind).is_none() {
1324            reasons.push(format!(
1325                "package `{}` uses dist type `{}`; {tool} handles only `zip` and \
1326                 `tar` dists — install it with `{install_command}`.",
1327                p.name, dist.kind,
1328            ));
1329        }
1330        // Missing/empty `dist.shasum` is normal: every VCS-driver dist
1331        // (GitHub/GitLab/Bitbucket zipballs) emits an empty shasum. Composer
1332        // treats empty/null as skip-verify; the downloader does the same and
1333        // keys the cache off `dist.reference`.
1334    }
1335
1336    if !plugin_packages.is_empty() {
1337        let names = plugin_packages.join(", ");
1338        let noun = if plugin_packages.len() == 1 {
1339            "package"
1340        } else {
1341            "packages"
1342        };
1343        warnings.push(format!(
1344            "{noun} {names} {verb} Composer plugins (type `composer-plugin`); \
1345             {pronoun} files install like any other package's, but {tool} \
1346             does not run plugin install-time hooks. Run `{install_command}` \
1347             if the hook behavior is required.",
1348            verb = if plugin_packages.len() == 1 {
1349                "is a"
1350            } else {
1351                "are"
1352            },
1353            pronoun = if plugin_packages.len() == 1 {
1354                "its"
1355            } else {
1356                "their"
1357            },
1358        ));
1359    }
1360
1361    if reasons.is_empty() {
1362        Ok(warnings)
1363    } else {
1364        Err(InstallError::Unsupported { reasons }.into())
1365    }
1366}
1367
1368#[cfg(test)]
1369mod tests;