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