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