Skip to main content

composer_autoload/
autoloader.rs

1//! Live, in-memory autoloader model.
2//!
3//! `dump_autoload` is now a thin wrapper around `Autoloader::bootstrap`
4//! followed by `Autoloader::emit`. The split lets a long-running
5//! process (e.g. a long-lived host) hold an `Autoloader` between
6//! requests and apply single-file edits via `apply_changed_path` /
7//! `apply_deleted_path` without re-walking the whole project. See
8//! `INCREMENTAL_AUTOLOADER_PLAN.md`.
9//!
10//! What this module owns:
11//!
12//! - The fully-resolved classmap task list (same shape Composer's
13//!   `AutoloadGenerator::dump` walks; see [`collect::build_classmap_tasks`]).
14//! - Per-task per-file class lists (`BTreeMap<rel_path, Vec<class>>`):
15//!   the patch flow needs each file individually addressable so an
16//!   edit replaces just that file's contribution.
17//! - The merged `class → path_expr` map used by both
18//!   `vendor/composer/autoload_classmap.php` and the static-loader's
19//!   `$classMap` array.
20//! - The PSR-4 / PSR-0 / files entry lists and the prolog/header bits
21//!   (`suffix`, `apcu_prefix`) — these are pure functions of
22//!   `composer.lock` + `composer.json`, computed once at bootstrap.
23//!   A patch only mutates `tasks[*].per_file` and `merged`.
24//! - An [`AutoloadHeader`] capturing the inputs the bootstrap reduced
25//!   to its current state. The server compares against a fresh
26//!   request via [`Autoloader::header_matches`] to decide whether a
27//!   live patch is enough or a full re-bootstrap is required.
28
29use std::collections::{BTreeMap, BTreeSet};
30use std::path::{Path, PathBuf};
31
32use rayon::prelude::*;
33
34use crate::collect::{
35    ClassmapEntry, Entry, FileEntry, Task, build_classmap_tasks, canonical, installed_versions_row,
36    strip_leading_slash, task_path_expr,
37};
38use crate::emit;
39use crate::installed;
40use crate::lock::{self, RootManifest};
41use crate::scan::{self, ExcludePatterns, NamespaceFilter, ScanWarning};
42use crate::vendored;
43use crate::{
44    DumpError, DumpRequest, PsrWarning, format_relative_path, random_hex_chars, write_atomic,
45};
46
47/// Per-task live state. `task` is the immutable scan descriptor.
48/// `per_file` maps a file's path (relative to `task.install_abs`) to
49/// the ordered list of classes that file contributes to the classmap.
50/// Files with zero classes after filtering are absent.
51#[derive(Debug)]
52struct TaskState {
53    task: Task,
54    per_file: BTreeMap<PathBuf, Vec<String>>,
55}
56
57/// Snapshot of the inputs that produced this autoloader's state.
58/// Compared against a fresh [`DumpRequest`] to detect drift: a header
59/// match means a live patch is sufficient; a mismatch means the
60/// project needs a full re-bootstrap.
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub struct AutoloadHeader {
63    /// `composer.lock`'s `content-hash` at bootstrap time.
64    pub lock_content_hash: String,
65    /// Hash of the root manifest's autoload block (psr-4 / psr-0 /
66    /// classmap / files / exclude-from-classmap). A user editing
67    /// `composer.json` to add a new PSR-4 root invalidates this.
68    pub autoload_config_hash: String,
69    /// Flag bits that affect what gets emitted. `optimize` and
70    /// `classmap_authoritative` change which tasks the build
71    /// constructs; `no_dev` filters which packages contribute.
72    pub flags: HeaderFlags,
73}
74
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub struct HeaderFlags {
77    pub optimize: bool,
78    pub classmap_authoritative: bool,
79    pub no_dev: bool,
80    pub apcu_autoloader: bool,
81}
82
83/// One project's classmap model.
84///
85/// Construct via [`Autoloader::bootstrap`]; emit to disk via
86/// [`Autoloader::emit`]. Between the two, the server can call
87/// [`Autoloader::apply_changed_path`] / [`Autoloader::apply_deleted_path`]
88/// to fold filesystem events into the merged classmap.
89#[derive(Debug)]
90pub struct Autoloader {
91    project_root: PathBuf,
92    tasks: Vec<TaskState>,
93    exclude_default: ExcludePatterns,
94    exclude_with_vendor: ExcludePatterns,
95    /// Sorted by class name (`BTreeMap` iteration order) → ready for
96    /// `emit::classmap` after a `.into_iter()` map.
97    merged: BTreeMap<String, String>,
98    psr4: Vec<Entry>,
99    psr0: Vec<Entry>,
100    files: Vec<FileEntry>,
101    suffix: String,
102    apcu_prefix: Option<String>,
103    classmap_authoritative: bool,
104    no_dev: bool,
105    /// Rendered `platform_check.php` body, or `None` when
106    /// `config.platform-check` is off or there's nothing to check. When
107    /// `Some`, `emit` writes the file and `autoload_real.php` gets the
108    /// matching `require` line. Computed once at bootstrap — it's a pure
109    /// function of `composer.{json,lock}` requirements + config, which
110    /// don't change under live code edits.
111    platform_check: Option<String>,
112    header: AutoloadHeader,
113    /// PSR-noncompliance warnings collected during the bootstrap scan.
114    /// `Autoloader::warnings()` exposes them in the `relative_path`
115    /// shape Composer renders (project-root-relative, leading `./`).
116    /// Incremental `apply_*` calls don't update this list — the CLI's
117    /// `Generated …` footer is only emitted by `dump_autoload`, so
118    /// live-patch callers don't surface warnings.
119    psr_warnings: Vec<PsrWarning>,
120}
121
122impl Autoloader {
123    /// Read `composer.lock` + `composer.json`, build the classmap
124    /// scan task list, drive the parallel scan, and produce a ready-
125    /// to-emit `Autoloader`. Performs no I/O beyond reading source
126    /// files; emit is a separate step.
127    #[tracing::instrument(skip_all)]
128    pub fn bootstrap(req: &DumpRequest<'_>) -> Result<Self, DumpError> {
129        let lock = lock::read_lock(req.project_root)?;
130        let manifest = lock::read_root_manifest(req.project_root)?;
131
132        let suffix: String = req
133            .autoloader_suffix
134            .clone()
135            .or_else(|| manifest.config.autoloader_suffix.clone())
136            .unwrap_or_else(|| lock.content_hash.clone());
137
138        let apcu_prefix: Option<String> = if req.apcu_autoloader {
139            Some(
140                req.apcu_prefix
141                    .clone()
142                    .unwrap_or_else(|| random_hex_chars(20)),
143            )
144        } else {
145            None
146        };
147
148        // `composer/installers` install-path overrides from the root
149        // `extra.installer-paths`. Empty (the common case) → every
150        // package resolves to `vendor/<name>` and output is unchanged.
151        let installer_paths = composer_installers::InstallerPaths::from_extra(&manifest.extra);
152
153        let psr4 = crate::collect::psr4(&manifest, &lock, req.no_dev, &installer_paths);
154        let psr0 = crate::collect::psr0(&manifest, &lock, req.no_dev, &installer_paths);
155        let files = crate::collect::files(&manifest, &lock, req.no_dev, &installer_paths);
156
157        // `--classmap-authoritative` implies `--optimize` (Composer's
158        // dump() does `if (classmapAuthoritative) $scanPsrPackages =
159        // true`).
160        let optimize = req.optimize || req.classmap_authoritative;
161
162        let set = build_classmap_tasks(
163            &manifest,
164            &lock,
165            req.no_dev,
166            optimize,
167            req.project_root,
168            &installer_paths,
169        );
170        let exclude_default = set.exclude_default;
171        let exclude_with_vendor = set.exclude_with_vendor;
172
173        // Parallel per-task scan capturing per-file class lists +
174        // PSR-noncompliance warnings (the filter emits one per
175        // rejected class when *no* class in a file passed; classmap-
176        // style scans never produce warnings).
177        let per_task_scans: Vec<scan::PerFileScan> = set
178            .tasks
179            .par_iter()
180            .map(|task| {
181                let exclude = if task.needs_vendor_exclude {
182                    &exclude_with_vendor
183                } else {
184                    &exclude_default
185                };
186                scan::scan_per_file(&task.scan_root, &task.install_abs, &task.filter, exclude)
187            })
188            .collect();
189
190        let mut raw_warnings: Vec<ScanWarning> = Vec::new();
191        let tasks: Vec<TaskState> = set
192            .tasks
193            .into_iter()
194            .zip(per_task_scans)
195            .map(|(task, scan_out)| {
196                raw_warnings.extend(scan_out.warnings);
197                TaskState {
198                    task,
199                    per_file: scan_out.per_file,
200                }
201            })
202            .collect();
203
204        let psr_warnings: Vec<PsrWarning> = raw_warnings
205            .into_iter()
206            .map(|w| PsrWarning {
207                class: w.class,
208                relative_path: format_relative_path(&w.file, req.project_root),
209                psr_version: if w.psr0 { 0 } else { 4 },
210            })
211            .collect();
212
213        let merged = merge_classmap(&tasks);
214
215        // `platform_check.php`: aggregate the root + prod-package
216        // `php`/`ext-*` requirements. Dev packages are excluded
217        // (Composer skips `$devPackageNames`), so this is independent of
218        // `--no-dev`.
219        let platform_check = {
220            let mut pkgs = vec![emit::platform_check::PkgLinks {
221                require: &manifest.require,
222                replace: &manifest.replace,
223                provide: &manifest.provide,
224            }];
225            for pkg in &lock.packages {
226                pkgs.push(emit::platform_check::PkgLinks {
227                    require: &pkg.require,
228                    replace: &pkg.replace,
229                    provide: &pkg.provide,
230                });
231            }
232            emit::platform_check::generate(&pkgs, manifest.config.platform_check)
233        };
234
235        let header = AutoloadHeader {
236            lock_content_hash: lock.content_hash.clone(),
237            autoload_config_hash: autoload_config_hash(&manifest),
238            flags: HeaderFlags {
239                optimize,
240                classmap_authoritative: req.classmap_authoritative,
241                no_dev: req.no_dev,
242                apcu_autoloader: req.apcu_autoloader,
243            },
244        };
245
246        Ok(Self {
247            project_root: req.project_root.to_path_buf(),
248            tasks,
249            exclude_default,
250            exclude_with_vendor,
251            merged,
252            psr4,
253            psr0,
254            files,
255            suffix,
256            apcu_prefix,
257            classmap_authoritative: req.classmap_authoritative,
258            no_dev: req.no_dev,
259            platform_check,
260            header,
261            psr_warnings,
262        })
263    }
264
265    /// Number of entries actually written to `autoload_classmap.php`
266    /// (the `Generated … containing N classes` figure — always includes
267    /// the synthetic `Composer\InstalledVersions` row). This is the
268    /// merged classmap minus the volatile-root classes held back by
269    /// [`Autoloader::excluded_volatile_classes`], so the count never
270    /// over-reports relative to the emitted file.
271    pub fn class_count(&self) -> usize {
272        self.merged.len() - self.excluded_volatile_classes().len()
273    }
274
275    /// PSR-noncompliance warnings collected during bootstrap.
276    pub fn warnings(&self) -> &[PsrWarning] {
277        &self.psr_warnings
278    }
279
280    /// Write every `vendor/composer/autoload_*.php` file plus the
281    /// runtime `ClassLoader`, `InstalledVersions`, LICENSE, and
282    /// `installed.{json,php}`. Atomic per file (rename-based).
283    #[tracing::instrument(skip_all)]
284    pub fn emit(&self) -> Result<(), DumpError> {
285        let composer_dir = self.project_root.join("vendor").join("composer");
286        std::fs::create_dir_all(&composer_dir)?;
287
288        let classmap = self.classmap_entries();
289
290        write_atomic(
291            &composer_dir.join("autoload_psr4.php"),
292            emit::psr4(&self.psr4).as_bytes(),
293        )?;
294        write_atomic(
295            &composer_dir.join("autoload_namespaces.php"),
296            emit::psr0(&self.psr0).as_bytes(),
297        )?;
298        write_atomic(
299            &composer_dir.join("autoload_classmap.php"),
300            emit::classmap(&classmap).as_bytes(),
301        )?;
302        if !self.files.is_empty() {
303            write_atomic(
304                &composer_dir.join("autoload_files.php"),
305                emit::files(&self.files).as_bytes(),
306            )?;
307        }
308
309        write_atomic(
310            &self.project_root.join("vendor").join("autoload.php"),
311            emit::entry(&self.suffix).as_bytes(),
312        )?;
313
314        write_atomic(
315            &composer_dir.join("autoload_real.php"),
316            emit::real::emit(
317                &self.suffix,
318                !self.files.is_empty(),
319                self.classmap_authoritative,
320                self.apcu_prefix.as_deref(),
321                self.platform_check.is_some(),
322            )
323            .as_bytes(),
324        )?;
325
326        // `platform_check.php` accompanies the `require` line emitted
327        // into `autoload_real.php` above. Composer deletes a stale copy
328        // when the check is off; we only ever write atomically here, so
329        // a project that turns the check off leaves no dangling require
330        // (the require line is gated on the same `Option`).
331        if let Some(body) = &self.platform_check {
332            write_atomic(&composer_dir.join("platform_check.php"), body.as_bytes())?;
333        }
334
335        write_atomic(
336            &composer_dir.join("autoload_static.php"),
337            emit::static_loader::emit(&self.suffix, &self.psr4, &self.psr0, &classmap, &self.files)
338                .as_bytes(),
339        )?;
340
341        vendored::write_runtime_files(&composer_dir, write_atomic)?;
342
343        write_atomic(
344            &composer_dir.join("installed.json"),
345            installed::emit_installed_json(&self.project_root, self.no_dev)?.as_bytes(),
346        )?;
347        write_atomic(
348            &composer_dir.join("installed.php"),
349            installed::emit_installed_php(&self.project_root, self.no_dev)?.as_bytes(),
350        )?;
351
352        Ok(())
353    }
354
355    /// Re-scan one file and fold the result into the merged classmap.
356    ///
357    /// Returns `Ok(true)` iff `self.merged` actually changed (so the
358    /// caller can skip emitting when an edit didn't move the
359    /// classmap, e.g. a comment-only change). Returns `Ok(false)`
360    /// when `abs_path` falls outside every task's `scan_root`, when
361    /// it's excluded by `exclude-from-classmap`, when its extension
362    /// isn't `.php` / `.inc`, or when the post-edit content
363    /// produces the same class list as before.
364    pub fn apply_changed_path(&mut self, abs_path: &Path) -> Result<bool, DumpError> {
365        if !has_php_ext(abs_path) {
366            return Ok(false);
367        }
368        let canon = canonical(abs_path.to_path_buf());
369        let matching: Vec<usize> = self
370            .tasks
371            .iter()
372            .enumerate()
373            .filter_map(|(i, s)| canon.starts_with(&s.task.scan_root).then_some(i))
374            .collect();
375        if matching.is_empty() {
376            return Ok(false);
377        }
378
379        let mut any_state_change = false;
380        for i in matching {
381            let exclude = if self.tasks[i].task.needs_vendor_exclude {
382                &self.exclude_with_vendor
383            } else {
384                &self.exclude_default
385            };
386            let rel = canon
387                .strip_prefix(&self.tasks[i].task.install_abs)
388                .map_or_else(|_| canon.clone(), Path::to_path_buf);
389
390            let new_classes = scan::scan_one(&canon, &self.tasks[i].task.filter, exclude);
391            let state = &mut self.tasks[i];
392            match new_classes {
393                Some(classes) => {
394                    let prev = state.per_file.get(&rel);
395                    if prev != Some(&classes) {
396                        state.per_file.insert(rel, classes);
397                        any_state_change = true;
398                    }
399                }
400                None => {
401                    if state.per_file.remove(&rel).is_some() {
402                        any_state_change = true;
403                    }
404                }
405            }
406        }
407
408        if !any_state_change {
409            return Ok(false);
410        }
411
412        let new_merged = merge_classmap(&self.tasks);
413        if new_merged == self.merged {
414            return Ok(false);
415        }
416        self.merged = new_merged;
417        Ok(true)
418    }
419
420    /// Drop a deleted path from every task's `per_file` map and
421    /// re-merge. Returns `Ok(true)` iff `self.merged` changed.
422    /// Idempotent: a delete for a file the autoloader never saw is
423    /// a no-op.
424    ///
425    /// `abs_path` may be either a file or a directory — recursive
426    /// directory deletes on macOS often arrive as a single Remove
427    /// event for the directory with no per-file follow-ups, so we
428    /// drop every `per_file` entry whose absolute path is at or
429    /// under `abs_path`.
430    pub fn apply_deleted_path(&mut self, abs_path: &Path) -> Result<bool, DumpError> {
431        // A deleted path can't be canonicalized directly (the target is
432        // gone). Walk up to the nearest existing ancestor, canonicalize
433        // that, then re-attach the trailing components so the result
434        // matches the canonicalized scan_roots / install_abs.
435        let canon = canonicalize_deleted(abs_path);
436        let mut any_state_change = false;
437        for state in &mut self.tasks {
438            // Process this task if `canon` is inside the scan root
439            // (file or sub-dir delete) OR if `canon` is an ancestor of
440            // the scan root (a delete higher up that wipes the whole
441            // task's tree).
442            if !canon.starts_with(&state.task.scan_root)
443                && !state.task.scan_root.starts_with(&canon)
444            {
445                continue;
446            }
447            let before = state.per_file.len();
448            state.per_file.retain(|rel, _| {
449                let full = state.task.install_abs.join(rel);
450                !full.starts_with(&canon)
451            });
452            if state.per_file.len() != before {
453                any_state_change = true;
454            }
455        }
456        if !any_state_change {
457            return Ok(false);
458        }
459        let new_merged = merge_classmap(&self.tasks);
460        if new_merged == self.merged {
461            return Ok(false);
462        }
463        self.merged = new_merged;
464        Ok(true)
465    }
466
467    /// Reconcile every scan task intersecting `path` against the
468    /// current on-disk tree: re-walk the task's `scan_root`, replace its
469    /// `per_file` wholesale, and re-merge. Picks up newly-created files
470    /// and drops deleted ones in a single pass.
471    ///
472    /// This is the recovery primitive for *volatile* directories a
473    /// framework mutates out-of-band — Magento wipes and regenerates
474    /// `generated/` (and `generated/code`) on every `cache:clean` /
475    /// `setup:di:compile`, often as a bulk `rm -rf` + `mkdir -p` whose
476    /// individual file events the watcher can miss or coalesce. A
477    /// directory-level event (the parent created or removed) routes here
478    /// so the subtree is brought back into sync regardless of which leaf
479    /// events were delivered. `path` may be the scan root, a sub-dir, or
480    /// an ancestor (e.g. `generated/` for the `generated/code` root); any
481    /// task whose `scan_root` overlaps `path` is reconciled. Returns
482    /// `Ok(true)` iff `merged` changed.
483    pub fn rescan_root(&mut self, path: &Path) -> Result<bool, DumpError> {
484        let canon = canonicalize_deleted(path);
485        let mut any_state_change = false;
486        for state in &mut self.tasks {
487            let sr = &state.task.scan_root;
488            if !canon.starts_with(sr) && !sr.starts_with(&canon) {
489                continue;
490            }
491            let exclude = if state.task.needs_vendor_exclude {
492                &self.exclude_with_vendor
493            } else {
494                &self.exclude_default
495            };
496            let fresh =
497                scan::scan_per_file(sr, &state.task.install_abs, &state.task.filter, exclude);
498            if fresh.per_file != state.per_file {
499                state.per_file = fresh.per_file;
500                any_state_change = true;
501            }
502        }
503        if !any_state_change {
504            return Ok(false);
505        }
506        let new_merged = merge_classmap(&self.tasks);
507        if new_merged == self.merged {
508            return Ok(false);
509        }
510        self.merged = new_merged;
511        Ok(true)
512    }
513
514    /// Inputs match the request that produced this autoloader.
515    /// `false` means the manager should re-bootstrap.
516    pub fn header_matches(&self, req: &DumpRequest<'_>) -> bool {
517        let Ok(lock) = lock::read_lock(req.project_root) else {
518            return false;
519        };
520        let Ok(manifest) = lock::read_root_manifest(req.project_root) else {
521            return false;
522        };
523        let optimize = req.optimize || req.classmap_authoritative;
524        let candidate = AutoloadHeader {
525            lock_content_hash: lock.content_hash,
526            autoload_config_hash: autoload_config_hash(&manifest),
527            flags: HeaderFlags {
528                optimize,
529                classmap_authoritative: req.classmap_authoritative,
530                no_dev: req.no_dev,
531                apcu_autoloader: req.apcu_autoloader,
532            },
533        };
534        candidate == self.header
535    }
536
537    /// Read-only access to the change-detection header. Exposed for
538    /// tests and the manager's bookkeeping; the manager doesn't
539    /// mutate it directly — re-bootstrap produces a new `Autoloader`.
540    pub fn header(&self) -> &AutoloadHeader {
541        &self.header
542    }
543
544    fn classmap_entries(&self) -> Vec<ClassmapEntry> {
545        let excluded = self.excluded_volatile_classes();
546        self.merged
547            .iter()
548            .filter(|(class, _)| !excluded.contains(class.as_str()))
549            .map(|(class, path_expr)| ClassmapEntry {
550                class: class.clone(),
551                path_expr: path_expr.clone(),
552            })
553            .collect()
554    }
555
556    /// Classes contributed by a *volatile* scan root (see
557    /// [`is_volatile_scan_root`]) that must be kept out of the emitted
558    /// classmap. Frameworks like Magento clear and regenerate
559    /// `generated/code` out-of-band (every `cache:clean` /
560    /// `setup:di:compile`), so any classmap entry pointing into such a
561    /// root can become a dangling `include` target the moment the
562    /// framework wipes the directory. Composer's `ClassLoader` has no
563    /// `file_exists` guard on a classmap hit, so a dangling entry both
564    /// emits a fatal-looking warning *and* claims the class — shadowing
565    /// the framework's own generator autoloader so it never regenerates.
566    /// A re-dump can't save an already-running process (e.g. the very
567    /// `setup:di:compile` doing the wipe) whose classmap is already in
568    /// memory.
569    ///
570    /// The safe-to-drop condition depends on how the root was scanned:
571    ///
572    /// - **PSR-\* task** (`psr-0` / `psr-4`): the same paths are also
573    ///   emitted as a runtime PSR fallback (`autoload_namespaces.php` /
574    ///   `autoload_psr4.php`), so a class absent from the classmap still
575    ///   resolves via the fallback — and a *missing* file there returns
576    ///   `false`, letting the framework's generator fire. So we drop
577    ///   **all** of the root's classes from the classmap, present or not.
578    ///   Magento's `generated/code` (a `psr-0` `""` root) is the case.
579    /// - **`autoload.classmap` directive** (`NamespaceFilter::None`):
580    ///   there is *no* PSR fallback — the classmap is the only way to
581    ///   load the class — so dropping a present entry would make it
582    ///   unloadable. Here we keep present entries and drop only the
583    ///   *dangling* (deleted-file) ones, the original emit-time backstop.
584    fn excluded_volatile_classes(&self) -> BTreeSet<&str> {
585        let mut excluded: BTreeSet<&str> = BTreeSet::new();
586        for state in &self.tasks {
587            if !is_volatile_scan_root(&state.task.scan_root) {
588                continue;
589            }
590            // A PSR-* scan has a runtime fallback; a plain classmap dir
591            // does not (see doc comment).
592            let has_psr_fallback = !matches!(state.task.filter, NamespaceFilter::None);
593            for (rel, classes) in &state.per_file {
594                // Without a fallback, only drop entries whose file is gone.
595                if !has_psr_fallback && state.task.install_abs.join(rel).exists() {
596                    continue;
597                }
598                let path_expr = task_path_expr(&state.task, rel);
599                for class in classes {
600                    // First-seen-wins: only exclude if `merged` still
601                    // resolves this class to the volatile file (a
602                    // non-volatile task may legitimately provide it).
603                    if self.merged.get(class) == Some(&path_expr) {
604                        excluded.insert(class.as_str());
605                    }
606                }
607            }
608        }
609        excluded
610    }
611}
612
613/// Re-merge the per-task per-file class lists into one
614/// `class → path_expr` map. First-seen wins across tasks (and across
615/// files within a task; `BTreeMap` iteration is path-sorted, which
616/// matches the walker's sort).
617fn merge_classmap(tasks: &[TaskState]) -> BTreeMap<String, String> {
618    let mut merged: BTreeMap<String, String> = BTreeMap::new();
619    for state in tasks {
620        for (rel, classes) in &state.per_file {
621            let path_expr = task_path_expr(&state.task, rel);
622            for class in classes {
623                merged
624                    .entry(class.clone())
625                    .or_insert_with(|| path_expr.clone());
626            }
627        }
628    }
629    let (iv_class, iv_path) = installed_versions_row();
630    merged.entry(iv_class).or_insert(iv_path);
631    merged
632}
633
634fn has_php_ext(p: &Path) -> bool {
635    p.extension()
636        .and_then(|e| e.to_str())
637        .is_some_and(|e| e.eq_ignore_ascii_case("php") || e.eq_ignore_ascii_case("inc"))
638}
639
640/// A scan root is *volatile* when it lives under a framework build-output
641/// directory cleared and regenerated out-of-band. Magento's
642/// `generated/code` (registered via the root `psr-0` `""` prefix, so it
643/// lands in the optimized classmap) is the motivating case: it's wiped on
644/// every `cache:clean` / `setup:di:compile`. Classes from such roots are
645/// held back from the emitted classmap by
646/// [`Autoloader::excluded_volatile_classes`] — fully when a PSR-\* fallback
647/// can resolve them, dangling-only otherwise — so a class the framework
648/// wipes is never left as a dangling `include` target. The check is a
649/// path-component scan for `generated`, matching `generated/` and
650/// `generated/code/...`.
651fn is_volatile_scan_root(scan_root: &Path) -> bool {
652    scan_root.components().any(
653        |c| matches!(c, std::path::Component::Normal(n) if n.eq_ignore_ascii_case("generated")),
654    )
655}
656
657/// Hash of the root manifest's autoload block — covers psr-4, psr-0,
658/// classmap, files, and exclude-from-classmap. A user editing
659/// `composer.json` to add or remove an autoload directive flips this
660/// hash, so [`Autoloader::header_matches`] reports drift and the
661/// manager re-bootstraps. The lockfile-side autoload metadata is
662/// already covered by `composer.lock`'s content-hash.
663fn autoload_config_hash(manifest: &RootManifest) -> String {
664    use md5::{Digest, Md5};
665    use std::fmt::Write as _;
666
667    let mut hasher = Md5::new();
668    let push_pairs = |h: &mut Md5, label: &str, pairs: &[(String, Vec<String>)]| {
669        h.update(label.as_bytes());
670        h.update([0]);
671        for (k, vs) in pairs {
672            h.update(k.as_bytes());
673            h.update([1]);
674            for v in vs {
675                h.update(v.as_bytes());
676                h.update([2]);
677            }
678            h.update([3]);
679        }
680    };
681    let push_list = |h: &mut Md5, label: &str, vs: &[String]| {
682        h.update(label.as_bytes());
683        h.update([0]);
684        for v in vs {
685            h.update(v.as_bytes());
686            h.update([1]);
687        }
688    };
689    push_pairs(&mut hasher, "psr4", &manifest.autoload.psr4);
690    push_pairs(&mut hasher, "psr0", &manifest.autoload.psr0);
691    push_list(&mut hasher, "classmap", &manifest.autoload.classmap);
692    push_list(&mut hasher, "files", &manifest.autoload.files);
693    push_list(
694        &mut hasher,
695        "exclude",
696        &manifest.autoload.exclude_from_classmap,
697    );
698
699    let digest = hasher.finalize();
700    let mut out = String::with_capacity(32);
701    for b in digest {
702        let _ = write!(out, "{b:02x}");
703    }
704    out
705}
706
707/// Directories the server's filesystem watcher needs to arm for live
708/// patches: every root autoload `scan_root` plus the `scan_roots` of
709/// any `dist.type: "path"` package in `composer.lock`. Vendor proper
710/// (`zip` / `tar` dists) is intentionally excluded — those only
711/// change via `composer install`, which rewrites `composer.lock` and
712/// triggers a full re-bootstrap.
713///
714/// Reads only `composer.lock` + `composer.json` — sub-ms, so the
715/// manager can call this before spawning the heavy bootstrap scan
716/// and arm the watcher first (the ordering invariant in the plan's
717/// "Save during Warming" test).
718pub fn user_code_roots(req: &DumpRequest<'_>) -> Result<Vec<PathBuf>, DumpError> {
719    let lock = lock::read_lock(req.project_root)?;
720    let manifest = lock::read_root_manifest(req.project_root)?;
721
722    let mut roots: Vec<PathBuf> = Vec::new();
723    let mut push = |p: PathBuf| {
724        let c = canonical(p);
725        if !roots.iter().any(|r| r == &c) {
726            roots.push(c);
727        }
728    };
729
730    let project_root = req.project_root;
731    for (_, dirs) in &manifest.autoload.psr4 {
732        for d in dirs {
733            push(project_root.join(strip_leading_slash(d)));
734        }
735    }
736    for (_, dirs) in &manifest.autoload.psr0 {
737        for d in dirs {
738            push(project_root.join(strip_leading_slash(d)));
739        }
740    }
741    for d in &manifest.autoload.classmap {
742        push(project_root.join(strip_leading_slash(d)));
743    }
744
745    // Path-repo packages — Composer's `path` repository installs
746    // typically symlink `vendor/<name>` to the source directory.
747    // We canonicalize so the watcher arms the real source, not the
748    // symlink (notify doesn't follow symlinks on read events).
749    let installer_paths = composer_installers::InstallerPaths::from_extra(&manifest.extra);
750    for pkg in lock.iter_packages(req.no_dev) {
751        let is_path = pkg.dist.as_ref().is_some_and(|d| d.kind == "path");
752        if !is_path {
753            continue;
754        }
755        let rel = composer_installers::install_path(
756            &pkg.name,
757            pkg.package_type.as_deref(),
758            &installer_paths,
759        );
760        let install_abs = canonical(project_root.join(rel));
761        let mut pushed = false;
762        for (_, dirs) in &pkg.autoload.psr4 {
763            for d in dirs {
764                push(install_abs.join(strip_leading_slash(d)));
765                pushed = true;
766            }
767        }
768        for (_, dirs) in &pkg.autoload.psr0 {
769            for d in dirs {
770                push(install_abs.join(strip_leading_slash(d)));
771                pushed = true;
772            }
773        }
774        for d in &pkg.autoload.classmap {
775            push(install_abs.join(strip_leading_slash(d)));
776            pushed = true;
777        }
778        // Some path-repo packages declare no autoload at all (e.g.
779        // a binary-only package). Watching `install_abs` lets a
780        // subsequent autoload-config edit in that package's
781        // composer.json be picked up by the lockfile watcher rather
782        // than missed.
783        if !pushed {
784            push(install_abs);
785        }
786    }
787
788    Ok(roots)
789}
790
791/// Resolve a path that may not exist on disk anymore (the typical case
792/// inside [`Autoloader::apply_deleted_path`]). `std::fs::canonicalize`
793/// fails outright for missing targets; we walk up to the nearest
794/// existing ancestor, canonicalize that, then re-attach the trailing
795/// components. The result matches a path that `canonical` would have
796/// produced *before* the delete, so it lines up with the canonicalized
797/// `scan_root` / `install_abs` stored at bootstrap time.
798fn canonicalize_deleted(p: &Path) -> PathBuf {
799    if let Ok(c) = std::fs::canonicalize(p) {
800        return c;
801    }
802    let mut trailing: Vec<&std::ffi::OsStr> = Vec::new();
803    let mut cursor = p;
804    while let Some(parent) = cursor.parent() {
805        if let Some(name) = cursor.file_name() {
806            trailing.push(name);
807        }
808        if let Ok(c) = std::fs::canonicalize(parent) {
809            let mut out = c;
810            for name in trailing.iter().rev() {
811                out.push(name);
812            }
813            return out;
814        }
815        cursor = parent;
816    }
817    p.to_path_buf()
818}