Skip to main content

vivacity_core/
layout.rs

1//! Where each package of the lock gets installed: `vendor/<name>[/<target-dir>]`
2//! by LibraryInstaller, or the path composer/installers gives it when that
3//! plugin is locked, allowed (`config.allow-plugins`) and ported
4//! (`installers::table_for`). A single pass, before touching the disk;
5//! anything not reproducible byte for byte becomes an `issue` (falls back to
6//! Composer).
7//!
8//! The path is relative to the project root and normalised (`normalizePath`,
9//! no trailing slash); that is the form Composer normalises before computing
10//! `install-path` (FilesystemRepository::write).
11
12use crate::installers::{self, Placement};
13use crate::lock::{Lock, LockPackage};
14use crate::pathutil::{find_shortest_path, normalize_path};
15use serde_json::Value;
16use std::collections::BTreeMap;
17use std::path::{Path, PathBuf};
18
19#[derive(Debug, Clone)]
20pub struct Layout {
21    /// Project root, absolute (as given, not canonicalised: the relative paths
22    /// derived from it do not depend on symlinks).
23    root: PathBuf,
24    /// name -> project-relative path (absent for a metapackage).
25    paths: BTreeMap<String, String>,
26    /// Emulated composer/installers tag, if the plugin is active.
27    pub installers_tag: Option<String>,
28    /// Installed packages (installed.json) to remove: name -> relative
29    /// directory to delete (`vendor/<name>` or the plugin's target), after
30    /// checking that Composer would recompute the same path today.
31    removals: BTreeMap<String, String>,
32}
33
34/// `allow-plugins` verdict for a package, like PluginManager in
35/// non-interactive mode.
36#[derive(Debug, PartialEq, Eq)]
37pub enum PluginVerdict {
38    Allowed,
39    /// Explicitly refused: Composer skips the plugin with a warning.
40    Blocked,
41    /// No rule covers it: Composer stops with an error.
42    Unlisted,
43}
44
45fn absolutize(dir: &Path) -> PathBuf {
46    if dir.is_absolute() {
47        dir.to_path_buf()
48    } else {
49        std::env::current_dir()
50            .map(|c| c.join(dir))
51            .unwrap_or_else(|_| dir.to_path_buf())
52    }
53}
54
55/// `BasePackage::packageNameToRegexp`: `{^<quote(pattern) with * -> .*>$}i`.
56fn pattern_matches(pattern: &str, name: &str) -> bool {
57    let p = pattern.to_ascii_lowercase();
58    let n = name.to_ascii_lowercase();
59    let parts: Vec<&str> = p.split('*').collect();
60    if parts.len() == 1 {
61        return p == n;
62    }
63    let mut rest = n.as_str();
64    for (i, part) in parts.iter().enumerate() {
65        if i == 0 {
66            let Some(r) = rest.strip_prefix(part) else {
67                return false;
68            };
69            rest = r;
70        } else if i == parts.len() - 1 {
71            return rest.ends_with(part);
72        } else {
73            let Some(pos) = rest.find(part) else {
74                return false;
75            };
76            rest = &rest[pos + part.len()..];
77        }
78    }
79    true
80}
81
82/// `Config::merge` for `allow-plugins`: the project value replaces the global
83/// one unless both are objects, in which case
84/// `array_merge($project, $global, $project)`: the project keys first, in
85/// their order, then those only the global config brings. Order matters: the
86/// first matching rule decides.
87pub fn merged_allow_plugins(project: Option<&Value>, global: Option<&Value>) -> Option<Value> {
88    match (project, global) {
89        (Some(Value::Object(p)), Some(Value::Object(g))) => {
90            let mut m = p.clone();
91            for (k, v) in g {
92                if !m.contains_key(k) {
93                    m.insert(k.clone(), v.clone());
94                }
95            }
96            Some(Value::Object(m))
97        }
98        (Some(p), _) => Some(p.clone()),
99        (None, Some(g)) => Some(g.clone()),
100        (None, None) => None,
101    }
102}
103
104/// `PluginManager::parseAllowedPlugins` + `isPluginAllowed` (non-interactive).
105fn plugin_verdict(allow: Option<&Value>, package: &str) -> PluginVerdict {
106    match allow {
107        Some(Value::Bool(true)) => PluginVerdict::Allowed,
108        Some(Value::Bool(false)) => PluginVerdict::Blocked,
109        Some(Value::Object(rules)) => {
110            for (pattern, v) in rules {
111                if pattern_matches(pattern, package) {
112                    return if v == &Value::Bool(true) {
113                        PluginVerdict::Allowed
114                    } else {
115                        PluginVerdict::Blocked
116                    };
117                }
118            }
119            PluginVerdict::Unlisted
120        }
121        _ => PluginVerdict::Unlisted,
122    }
123}
124
125/// Verdict for `package` under the project config merged with the global one.
126pub fn plugin_allowed(manifest: &Value, package: &str) -> PluginVerdict {
127    let allow = merged_allow_plugins(
128        manifest.get("config").and_then(|c| c.get("allow-plugins")),
129        global_allow_plugins().as_ref(),
130    );
131    plugin_verdict(allow.as_ref(), package)
132}
133
134/// `config.allow-plugins` from COMPOSER_HOME/config.json.
135pub fn global_allow_plugins() -> Option<Value> {
136    let path = crate::fetch::composer_home()?.join("config.json");
137    let text = std::fs::read_to_string(path).ok()?;
138    let v: Value = serde_json::from_str(&text).ok()?;
139    v.get("config")?.get("allow-plugins").cloned()
140}
141
142/// Project-relative path of a package handled by LibraryInstaller.
143fn vendor_rel(name: &str, target_dir: Option<&str>) -> String {
144    match target_dir {
145        Some(t) => format!("vendor/{name}/{t}"),
146        None => format!("vendor/{name}"),
147    }
148}
149
150/// Decision for a package (name, type, extra) under the current configuration.
151fn place(
152    table: Option<&installers::Table>,
153    root_extra: Option<&Value>,
154    name: &str,
155    package_type: &str,
156    package_extra: Option<&Value>,
157    target_dir: Option<&str>,
158) -> Result<String, String> {
159    let Some(table) = table else {
160        return Ok(vendor_rel(name, target_dir));
161    };
162    match installers::placement(table, root_extra, name, package_type, package_extra) {
163        Ok(Placement::Vendor) => Ok(vendor_rel(name, target_dir)),
164        Ok(Placement::Custom(p)) => {
165            if p.starts_with('/') || p.starts_with('\\') {
166                return Err(format!(
167                    "installers: {name} would install at an absolute path `{p}`"
168                ));
169            }
170            let rel = normalize_path(&p);
171            if rel.is_empty() || rel == "." {
172                return Err(format!(
173                    "installers: {name} would install at the project root"
174                ));
175            }
176            if rel.starts_with("../") || rel == ".." {
177                return Err(format!(
178                    "installers: {name} would install outside the project (`{p}`)"
179                ));
180            }
181            if rel == "vendor" || rel.starts_with("vendor/") {
182                return Err(format!(
183                    "installers: {name} targets `{p}` inside vendor/ (not emulated: use the default vendor layout)"
184                ));
185            }
186            Ok(rel)
187        }
188        Err(e) => Err(format!("installers: {name} ({package_type}): {e}")),
189    }
190}
191
192impl Layout {
193    /// Everything in vendor/ (no layout plugin), for tests and code paths
194    /// that have no plugin-aware lock.
195    pub fn vendor_only(project_dir: &Path, lock: &Lock, with_dev: bool) -> Layout {
196        let mut paths = BTreeMap::new();
197        for p in lock.wanted_packages(with_dev) {
198            if !p.is_metapackage() {
199                paths.insert(p.name().to_owned(), vendor_rel(p.name(), p.target_dir()));
200            }
201        }
202        Layout {
203            root: absolutize(project_dir),
204            paths,
205            installers_tag: None,
206            removals: BTreeMap::new(),
207        }
208    }
209
210    /// The full pass: plugin, allow-plugins, paths, refused targets, and the
211    /// removal plan for installed.json packages that went away.
212    pub fn resolve(
213        project_dir: &Path,
214        lock: &Lock,
215        manifest: &Value,
216        with_dev: bool,
217        plugins_enabled: bool,
218    ) -> Result<Layout, Vec<String>> {
219        let root = absolutize(project_dir);
220        let mut issues: Vec<String> = Vec::new();
221        let wanted: Vec<&LockPackage> = lock.wanted_packages(with_dev).collect();
222        let previous = installed_packages(&root);
223        let has_state = root.join("vendor/composer/installed.json").is_file();
224
225        // Is the plugin active? Composer loads it from installed.json
226        // (PluginManager::loadInstalledPlugins) and installs it first in the
227        // transaction; vivacity only emulates the states where both views
228        // agree. A plugin present on one side only (added, removed, or in
229        // require-dev with --no-dev) is a transition left to Composer.
230        let lock_plugin = wanted.iter().find(|p| p.name() == "composer/installers");
231        let prev_plugin = previous
232            .iter()
233            .find(|p| p["name"].as_str() == Some("composer/installers"));
234        let mut table: Option<&installers::Table> = None;
235        let mut installers_tag = None;
236        if plugins_enabled && (lock_plugin.is_some() || prev_plugin.is_some()) {
237            let allow = merged_allow_plugins(
238                manifest.get("config").and_then(|c| c.get("allow-plugins")),
239                global_allow_plugins().as_ref(),
240            );
241            match plugin_verdict(allow.as_ref(), "composer/installers") {
242                PluginVerdict::Allowed => {
243                    let version = lock_plugin
244                        .map(|p| p.version().to_owned())
245                        .or_else(|| {
246                            prev_plugin.and_then(|p| p["version"].as_str().map(str::to_owned))
247                        })
248                        .unwrap_or_default();
249                    let Some(t) = installers::table_for(&version) else {
250                        return Err(vec![format!(
251                            "composer/installers {version} is not a ported version (ported: {})",
252                            installers::ported_versions().collect::<Vec<_>>().join(", ")
253                        )]);
254                    };
255                    if has_state && lock_plugin.is_some() != prev_plugin.is_some() {
256                        let root_extra = manifest.get("extra");
257                        let taken = |name: &str, ty: &str, extra: Option<&Value>| {
258                            !matches!(
259                                installers::placement(t, root_extra, name, ty, extra),
260                                Ok(Placement::Vendor)
261                            )
262                        };
263                        let any_taken = wanted
264                            .iter()
265                            .any(|p| taken(p.name(), p.package_type(), p.raw.get("extra")))
266                            || previous.iter().any(|p| {
267                                taken(
268                                    p["name"].as_str().unwrap_or(""),
269                                    p["type"].as_str().unwrap_or("library"),
270                                    p.get("extra"),
271                                )
272                            });
273                        if any_taken {
274                            let how = if lock_plugin.is_some() {
275                                "added to"
276                            } else {
277                                "removed from"
278                            };
279                            return Err(vec![format!(
280                                "composer/installers is being {how} an existing install (installed.json and composer.lock disagree): let Composer handle this transition"
281                            )]);
282                        }
283                    }
284                    if lock_plugin.is_some() {
285                        installers_tag = Some(t.tag.clone());
286                        table = Some(t);
287                    }
288                }
289                PluginVerdict::Blocked => {} // Composer ignores it: everything in vendor/
290                PluginVerdict::Unlisted => {
291                    return Err(vec![
292                        "composer/installers is a plugin not covered by config.allow-plugins (Composer would refuse to run it)"
293                            .to_owned(),
294                    ]);
295                }
296            }
297        }
298
299        let root_extra = manifest.get("extra");
300        let mut paths: BTreeMap<String, String> = BTreeMap::new();
301        for p in &wanted {
302            if p.is_metapackage() {
303                continue;
304            }
305            match place(
306                table,
307                root_extra,
308                p.name(),
309                p.package_type(),
310                p.raw.get("extra"),
311                p.target_dir(),
312            ) {
313                Ok(rel) => {
314                    paths.insert(p.name().to_owned(), rel);
315                }
316                Err(e) => issues.push(e),
317            }
318        }
319
320        // Conflicting targets: two packages at the same place, or one under the other.
321        if table.is_some() {
322            let mut by_path: BTreeMap<&str, &str> = BTreeMap::new();
323            for (name, rel) in &paths {
324                if let Some(other) = by_path.insert(rel.as_str(), name.as_str()) {
325                    issues.push(format!(
326                        "installers: {name} and {other} would both install at `{rel}`"
327                    ));
328                }
329            }
330            let customs: Vec<(&str, &str)> = paths
331                .iter()
332                .filter(|(_, rel)| !rel.starts_with("vendor/"))
333                .map(|(n, r)| (n.as_str(), r.as_str()))
334                .collect();
335            for (name, rel) in &customs {
336                for (other, other_rel) in &paths {
337                    if other.as_str() != *name && other_rel.starts_with(&format!("{rel}/")) {
338                        issues.push(format!(
339                            "installers: {name} at `{rel}` would contain {other} at `{other_rel}`"
340                        ));
341                    }
342                }
343            }
344        }
345
346        // Removal plan: Composer recomputes the path of a removed package with
347        // the current configuration; we only delete if that path is the one
348        // where the package was laid out (installed.json), else fallback.
349        let mut removals = BTreeMap::new();
350        let wanted_names: std::collections::BTreeSet<&str> =
351            wanted.iter().map(|p| p.name()).collect();
352        let vendor_composer =
353            normalize_path(&format!("{}/vendor/composer", root.to_string_lossy()));
354        let root_norm = normalize_path(&root.to_string_lossy());
355        for prev in &previous {
356            let name = prev["name"].as_str().unwrap_or("");
357            if name.is_empty() || wanted_names.contains(name) {
358                continue;
359            }
360            let Some(old_ip) = prev.get("install-path").and_then(Value::as_str) else {
361                continue; // metapackage
362            };
363            let old_abs = if old_ip.starts_with('/') {
364                normalize_path(old_ip)
365            } else {
366                normalize_path(&format!("{vendor_composer}/{old_ip}"))
367            };
368            let Some(old_rel) = old_abs
369                .strip_prefix(&format!("{root_norm}/"))
370                .filter(|r| !r.is_empty())
371            else {
372                issues.push(format!(
373                    "installed package {name} lives outside the project (`{old_ip}`): not removing it"
374                ));
375                continue;
376            };
377            let expected = place(
378                table,
379                root_extra,
380                name,
381                prev.get("type")
382                    .and_then(Value::as_str)
383                    .unwrap_or("library"),
384                prev.get("extra"),
385                prev.get("target-dir")
386                    .and_then(Value::as_str)
387                    .map(|t| t.trim_matches('/'))
388                    .filter(|t| !t.is_empty()),
389            );
390            match expected {
391                Ok(rel) if rel == old_rel => {
392                    // LibraryInstaller::removeCode deletes getPackageBasePath:
393                    // vendor/<name> without the target-dir.
394                    let dir = if rel.starts_with("vendor/") {
395                        format!("vendor/{name}")
396                    } else {
397                        rel
398                    };
399                    removals.insert(name.to_owned(), dir);
400                }
401                Ok(rel) => issues.push(format!(
402                    "installed package {name} is at `{old_rel}` but the current layout puts it at `{rel}`: let Composer handle this removal"
403                )),
404                Err(e) => issues.push(format!("removal of {name}: {e}")),
405            }
406        }
407
408        if issues.is_empty() {
409            Ok(Layout {
410                root,
411                paths,
412                installers_tag,
413                removals,
414            })
415        } else {
416            Err(issues)
417        }
418    }
419
420    pub fn root(&self) -> &Path {
421        &self.root
422    }
423
424    /// Project-relative path (None: metapackage or unknown package).
425    pub fn rel(&self, name: &str) -> Option<&str> {
426        self.paths.get(name).map(String::as_str)
427    }
428
429    /// Absolute install path.
430    pub fn abs(&self, name: &str) -> Option<PathBuf> {
431        self.rel(name).map(|r| self.root.join(r))
432    }
433
434    /// Root to empty before laying out the package: `vendor/<name>`
435    /// (target-dir included) for LibraryInstaller, the target itself otherwise.
436    pub fn package_root(&self, name: &str) -> Option<PathBuf> {
437        let rel = self.rel(name)?;
438        Some(if rel.starts_with("vendor/") {
439            self.root.join("vendor").join(name)
440        } else {
441            self.root.join(rel)
442        })
443    }
444
445    /// `install-path` of installed.json / installed.php: relative to
446    /// vendor/composer (`findShortestPath($repoDir, $path, true)`).
447    pub fn install_path(&self, name: &str) -> Option<String> {
448        let rel = self.rel(name)?;
449        let root = self.root.to_string_lossy();
450        Some(find_shortest_path(
451            &format!("{root}/vendor/composer"),
452            &format!("{root}/{rel}"),
453            true,
454        ))
455    }
456
457    /// installed.json packages to remove, with their absolute path.
458    pub fn removals(&self) -> impl Iterator<Item = (&str, PathBuf)> {
459        self.removals
460            .iter()
461            .map(|(n, rel)| (n.as_str(), self.root.join(rel)))
462    }
463}
464
465fn installed_packages(root: &Path) -> Vec<Value> {
466    let path = root.join("vendor/composer/installed.json");
467    let Ok(text) = std::fs::read_to_string(&path) else {
468        return Vec::new();
469    };
470    let Ok(v) = serde_json::from_str::<Value>(&text) else {
471        return Vec::new();
472    };
473    v.get("packages")
474        .and_then(Value::as_array)
475        .cloned()
476        .unwrap_or_default()
477}
478
479#[cfg(test)]
480mod tests {
481    use super::*;
482    use serde_json::json;
483
484    fn lock_with(packages: Value) -> Lock {
485        Lock::parse(
486            &json!({"packages": packages, "packages-dev": [], "plugin-api-version": "2.6.0"})
487                .to_string(),
488        )
489        .expect("lock")
490    }
491
492    fn pkg(name: &str, ty: &str, version: &str) -> Value {
493        json!({"name": name, "version": version, "type": ty,
494               "dist": {"type": "zip", "url": "https://x/y.zip", "reference": "r"}})
495    }
496
497    fn root() -> PathBuf {
498        PathBuf::from("/proj")
499    }
500
501    #[test]
502    fn allow_plugins_patterns_and_merge() {
503        assert!(pattern_matches("composer/*", "composer/installers"));
504        assert!(pattern_matches(
505            "Composer/Installers",
506            "composer/installers"
507        ));
508        assert!(pattern_matches("*", "anything/here"));
509        assert!(!pattern_matches("composer/*", "other/installers"));
510        assert!(pattern_matches("*/installers", "composer/installers"));
511        let rules = json!({"composer/*": false, "composer/installers": true});
512        // First matching rule: `composer/*` -> refused.
513        assert_eq!(
514            plugin_verdict(Some(&rules), "composer/installers"),
515            PluginVerdict::Blocked
516        );
517        assert_eq!(
518            plugin_verdict(Some(&json!(true)), "x/y"),
519            PluginVerdict::Allowed
520        );
521        assert_eq!(
522            plugin_verdict(Some(&json!({})), "x/y"),
523            PluginVerdict::Unlisted
524        );
525        assert_eq!(plugin_verdict(None, "x/y"), PluginVerdict::Unlisted);
526        let merged = merged_allow_plugins(
527            Some(&json!({"a/b": false})),
528            Some(&json!({"a/b": true, "c/d": true})),
529        );
530        assert_eq!(merged, Some(json!({"a/b": false, "c/d": true})));
531    }
532
533    #[test]
534    fn without_plugin_everything_goes_to_vendor() {
535        let lock = lock_with(json!([
536            pkg("a/b", "wordpress-plugin", "1.0.0"),
537            pkg("a/meta", "metapackage", "1.0.0")
538        ]));
539        let manifest =
540            json!({"extra": {"installer-paths": {"web/{$name}": ["type:wordpress-plugin"]}}});
541        let l = Layout::resolve(&root(), &lock, &manifest, true, true).expect("layout");
542        assert_eq!(l.rel("a/b"), Some("vendor/a/b"));
543        assert_eq!(l.rel("a/meta"), None);
544        assert_eq!(l.install_path("a/b").as_deref(), Some("../a/b"));
545        assert!(l.installers_tag.is_none());
546    }
547
548    #[test]
549    fn plugin_allowed_places_packages_and_blocked_keeps_vendor() {
550        let lock = lock_with(json!([
551            pkg("composer/installers", "composer-plugin", "v2.3.0"),
552            pkg("wpackagist-plugin/akismet", "wordpress-plugin", "5.3"),
553            pkg(
554                "wpackagist-theme/twentytwentyfour",
555                "wordpress-theme",
556                "1.0"
557            ),
558            pkg("monolog/monolog", "library", "3.0.0"),
559            pkg("composer/pcre", "library", "3.0.0"),
560        ]));
561        let manifest = json!({
562            "config": {"allow-plugins": {"composer/installers": true}},
563            "extra": {"installer-paths": {"web/app/plugins/{$name}/": ["type:wordpress-plugin"]}}
564        });
565        let l = Layout::resolve(&root(), &lock, &manifest, true, true).expect("layout");
566        assert_eq!(l.installers_tag.as_deref(), Some("v2.3.0"));
567        assert_eq!(
568            l.rel("wpackagist-plugin/akismet"),
569            Some("web/app/plugins/akismet")
570        );
571        assert_eq!(
572            l.rel("wpackagist-theme/twentytwentyfour"),
573            Some("wp-content/themes/twentytwentyfour")
574        );
575        assert_eq!(l.rel("monolog/monolog"), Some("vendor/monolog/monolog"));
576        assert_eq!(
577            l.rel("composer/installers"),
578            Some("vendor/composer/installers")
579        );
580        assert_eq!(
581            l.install_path("wpackagist-plugin/akismet").as_deref(),
582            Some("../../web/app/plugins/akismet")
583        );
584        assert_eq!(l.install_path("composer/pcre").as_deref(), Some("./pcre"));
585        assert_eq!(
586            l.install_path("monolog/monolog").as_deref(),
587            Some("../monolog/monolog")
588        );
589        assert_eq!(
590            l.package_root("wpackagist-plugin/akismet"),
591            Some(PathBuf::from("/proj/web/app/plugins/akismet"))
592        );
593
594        let blocked = json!({"config": {"allow-plugins": {"composer/installers": false}}});
595        let l = Layout::resolve(&root(), &lock, &blocked, true, true).expect("layout");
596        assert_eq!(
597            l.rel("wpackagist-plugin/akismet"),
598            Some("vendor/wpackagist-plugin/akismet")
599        );
600
601        let unlisted = json!({"config": {"allow-plugins": {"other/x": true}}});
602        let err = Layout::resolve(&root(), &lock, &unlisted, true, true).expect_err("fallback");
603        assert!(err[0].contains("allow-plugins"), "{err:?}");
604
605        let missing = json!({});
606        assert!(Layout::resolve(&root(), &lock, &missing, true, true).is_err());
607    }
608
609    #[test]
610    fn unported_version_custom_framework_and_dangerous_targets_are_issues() {
611        let manifest = json!({"config": {"allow-plugins": true}});
612        let old = lock_with(json!([
613            pkg("composer/installers", "composer-plugin", "v1.12.0"),
614            pkg("a/b", "drupal-module", "1.0")
615        ]));
616        let err = Layout::resolve(&root(), &old, &manifest, true, true).expect_err("v1");
617        assert!(err[0].contains("not a ported version"), "{err:?}");
618
619        let cake = lock_with(json!([
620            pkg("composer/installers", "composer-plugin", "v2.2.0"),
621            pkg("a/b", "cakephp-plugin", "1.0")
622        ]));
623        let err = Layout::resolve(&root(), &cake, &manifest, true, true).expect_err("cake");
624        assert!(err[0].contains("custom path logic"), "{err:?}");
625
626        let lock = lock_with(json!([
627            pkg("composer/installers", "composer-plugin", "v2.3.0"),
628            pkg("a/b", "drupal-module", "1.0"),
629            pkg("a/c", "drupal-module", "1.0")
630        ]));
631        for (paths, needle) in [
632            (json!({"{$name}/../../x": ["a/b"]}), "outside the project"),
633            (json!({"vendor/{$name}": ["a/b"]}), "inside vendor/"),
634            (json!({"/abs/{$name}": ["a/b"]}), "absolute path"),
635            (json!({"same/": ["a/b", "a/c"]}), "would both install"),
636            (json!({"modules/": ["a/b"]}), "would contain"),
637        ] {
638            let m = json!({"config": {"allow-plugins": true}, "extra": {"installer-paths": paths}});
639            let err = Layout::resolve(&root(), &lock, &m, true, true).expect_err(needle);
640            assert!(err.iter().any(|e| e.contains(needle)), "{needle}: {err:?}");
641        }
642        // The root project: empty template.
643        let m =
644            json!({"config": {"allow-plugins": true}, "extra": {"installer-paths": {"": ["a/b"]}}});
645        let err = Layout::resolve(&root(), &lock, &m, true, true).expect_err("root");
646        assert!(err.iter().any(|e| e.contains("project root")), "{err:?}");
647    }
648
649    #[test]
650    fn removals_follow_installed_json_when_paths_agree() {
651        let dir = tempfile::tempdir().expect("tmp");
652        let vc = dir.path().join("vendor/composer");
653        std::fs::create_dir_all(&vc).expect("mkdir");
654        let plugin_entry = json!({"name": "composer/installers", "version": "v2.3.0", "type": "composer-plugin", "install-path": "./installers"});
655        std::fs::write(
656            vc.join("installed.json"),
657            json!({"packages": [
658                plugin_entry,
659                {"name": "gone/lib", "version": "1.0", "type": "library", "install-path": "../gone/lib"},
660                {"name": "gone/legacy", "version": "1.0", "type": "library", "target-dir": "Acme/Legacy", "install-path": "../gone/legacy/Acme/Legacy"},
661                {"name": "gone/plugin", "version": "1.0", "type": "wordpress-plugin", "install-path": "../../wp-content/plugins/plugin"},
662                {"name": "moved/plugin", "version": "1.0", "type": "wordpress-plugin", "install-path": "../../old/plugin"},
663                {"name": "gone/meta", "version": "1.0", "type": "metapackage", "install-path": null}
664            ], "dev": true, "dev-package-names": []})
665            .to_string(),
666        )
667        .expect("write");
668        let lock = lock_with(json!([pkg(
669            "composer/installers",
670            "composer-plugin",
671            "v2.3.0"
672        )]));
673        let manifest = json!({"config": {"allow-plugins": true}});
674        let err = Layout::resolve(dir.path(), &lock, &manifest, true, true).expect_err("moved");
675        assert!(
676            err.iter()
677                .any(|e| e.contains("moved/plugin") && e.contains("old/plugin")),
678            "{err:?}"
679        );
680
681        // Without the moved package, the plan is accepted; a target-dir package
682        // is deleted at vendor/<name> (getPackageBasePath), not at the sub-path.
683        std::fs::write(
684            vc.join("installed.json"),
685            json!({"packages": [
686                plugin_entry,
687                {"name": "gone/lib", "version": "1.0", "type": "library", "install-path": "../gone/lib"},
688                {"name": "gone/legacy", "version": "1.0", "type": "library", "target-dir": "Acme/Legacy", "install-path": "../gone/legacy/Acme/Legacy"},
689                {"name": "gone/plugin", "version": "1.0", "type": "wordpress-plugin", "install-path": "../../wp-content/plugins/plugin"}
690            ], "dev": true, "dev-package-names": []})
691            .to_string(),
692        )
693        .expect("write");
694        let l = Layout::resolve(dir.path(), &lock, &manifest, true, true).expect("layout");
695        let removals: Vec<(String, PathBuf)> =
696            l.removals().map(|(n, p)| (n.to_owned(), p)).collect();
697        assert_eq!(
698            removals,
699            vec![
700                (
701                    "gone/legacy".to_owned(),
702                    l.root().join("vendor/gone/legacy")
703                ),
704                ("gone/lib".to_owned(), l.root().join("vendor/gone/lib")),
705                (
706                    "gone/plugin".to_owned(),
707                    l.root().join("wp-content/plugins/plugin")
708                ),
709            ]
710        );
711    }
712
713    #[test]
714    fn plugin_present_on_one_side_only_is_a_transition_for_composer() {
715        let dir = tempfile::tempdir().expect("tmp");
716        let vc = dir.path().join("vendor/composer");
717        std::fs::create_dir_all(&vc).expect("mkdir");
718        let manifest = json!({"config": {"allow-plugins": true}});
719        let with_plugin = lock_with(json!([
720            pkg("composer/installers", "composer-plugin", "v2.3.0"),
721            pkg("a/wp", "wordpress-plugin", "1.0"),
722        ]));
723        let without_plugin = lock_with(json!([pkg("a/wp", "wordpress-plugin", "1.0")]));
724        let libs_only = lock_with(json!([
725            pkg("composer/installers", "composer-plugin", "v2.3.0"),
726            pkg("a/lib", "library", "1.0"),
727        ]));
728
729        // Addition: installed.json without the plugin, lock with it, and an affected package.
730        std::fs::write(
731            vc.join("installed.json"),
732            json!({"packages": [{"name": "a/wp", "version": "1.0", "type": "wordpress-plugin", "install-path": "../a/wp"}], "dev": true, "dev-package-names": []}).to_string(),
733        )
734        .expect("write");
735        let err =
736            Layout::resolve(dir.path(), &with_plugin, &manifest, true, true).expect_err("added");
737        assert!(err[0].contains("added to an existing install"), "{err:?}");
738        // Same addition without a package of a type taken by the plugin: nothing to transition.
739        std::fs::write(
740            vc.join("installed.json"),
741            json!({"packages": [{"name": "a/lib", "version": "1.0", "type": "library", "install-path": "../a/lib"}], "dev": true, "dev-package-names": []}).to_string(),
742        )
743        .expect("write");
744        assert!(Layout::resolve(dir.path(), &libs_only, &manifest, true, true).is_ok());
745
746        // Removal: installed.json with the plugin and a package outside vendor/, lock without.
747        std::fs::write(
748            vc.join("installed.json"),
749            json!({"packages": [
750                {"name": "composer/installers", "version": "v2.3.0", "type": "composer-plugin", "install-path": "./installers"},
751                {"name": "a/wp", "version": "1.0", "type": "wordpress-plugin", "install-path": "../../wp-content/plugins/wp"}
752            ], "dev": true, "dev-package-names": []}).to_string(),
753        )
754        .expect("write");
755        let err = Layout::resolve(dir.path(), &without_plugin, &manifest, true, true)
756            .expect_err("removed");
757        assert!(
758            err[0].contains("removed from an existing install"),
759            "{err:?}"
760        );
761
762        // --no-plugins: Composer ignores the plugin on both sides, everything in vendor/.
763        let l =
764            Layout::resolve(dir.path(), &with_plugin, &manifest, true, false).expect("no-plugins");
765        assert_eq!(l.rel("a/wp"), Some("vendor/a/wp"));
766        assert!(l.installers_tag.is_none());
767        // No on-disk state: the lock decides (fresh install).
768        std::fs::remove_file(vc.join("installed.json")).expect("rm");
769        let l = Layout::resolve(dir.path(), &with_plugin, &manifest, true, true).expect("fresh");
770        assert_eq!(l.rel("a/wp"), Some("wp-content/plugins/wp"));
771    }
772}