Skip to main content

vivacity_core/
scope.rs

1//! Out-of-scope detector: decides, BEFORE touching the disk, whether vivacity
2//! can install this lock natively or must delegate to `composer install`
3//! (default fallback) / fail explicitly (when Composer is not available).
4//!
5//! Principle (plan r1/F3-F5): never a silently divergent vendor/. An unknown
6//! plugin, or one that changes the layout, is out of scope. Plugins proven
7//! harmless at boot (fixture qualification) are installed like ordinary
8//! libraries, with a warning.
9
10use crate::layout::Layout;
11use crate::lock::{DistKind, Lock, LockPackage};
12use serde_json::Value;
13use std::path::Path;
14
15/// Plugins emulated natively by vivacity (identical output, drift test).
16/// composer/installers (see `layout`) is, under conditions checked before
17/// any write. drupal/core-composer-scaffold is deliberately absent: its
18/// source is GPL-2.0-or-later and cannot be ported here (NOTICE.md).
19pub const EMULATED_PLUGINS: &[&str] = &["symfony/runtime", "composer/installers"];
20
21/// Plugins whose inaction is proven to have no effect on the vendor/ content
22/// needed at boot (fixtures qualified with `--no-plugins`). Installed as
23/// libraries, reported with a warning.
24pub const BENIGN_PLUGINS: &[&str] = &[
25    "symfony/flex",
26    "composer/package-versions-deprecated",
27    "php-http/discovery",
28    "dealerdirect/phpcodesniffer-composer-installer",
29    "phpstan/extension-installer",
30    "rector/extension-installer",
31    "pestphp/pest-plugin",
32    // Only listens to POST_CREATE_PROJECT_CMD / POST_INSTALL_CMD to print a
33    // message (MessagePlugin::getSubscribedEvents): no disk effect.
34    "drupal/core-project-message",
35    // Only listens to POST_UPDATE_CMD / POST_CREATE_PROJECT_CMD, and only acts
36    // in a `require` context (Plugin::getSubscribedEvents): inert at install.
37    "drupal/core-recipe-unpack",
38];
39
40/// Plugins known to change the install layout or the package contents:
41/// always out of scope.
42pub const LAYOUT_PLUGINS: &[&str] = &[
43    "cweagans/composer-patches",
44    "oomphinc/composer-installers-extender",
45    "mnsami/composer-custom-directory-installer",
46];
47
48#[derive(Debug, PartialEq, Eq)]
49pub enum ScopeIssue {
50    /// Plugin absent from the known lists: unpredictable behaviour.
51    UnknownPlugin(String),
52    /// Plugin known to change the layout (patches, installers-extender...).
53    LayoutPlugin(String),
54    /// Non-reproducible layout (composer/installers: version not ported,
55    /// framework with custom logic, refused target...).
56    Layout(String),
57    /// Package without a usable zip dist (source-only, exotic dist).
58    NoUsableDist(String),
59}
60
61impl std::fmt::Display for ScopeIssue {
62    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63        match self {
64            ScopeIssue::UnknownPlugin(p) => {
65                write!(f, "plugin {p} is not on vivacity's known-plugin list")
66            }
67            ScopeIssue::LayoutPlugin(p) => {
68                write!(f, "plugin {p} changes the install layout (not emulated)")
69            }
70            ScopeIssue::Layout(why) => write!(f, "{why}"),
71            ScopeIssue::NoUsableDist(p) => write!(f, "package {p} has no zip dist (source-only)"),
72        }
73    }
74}
75
76#[derive(Debug, Default)]
77pub struct ScopeReport {
78    /// Blocking: at least one -> fallback (or error without Composer).
79    pub issues: Vec<ScopeIssue>,
80    /// Non-blocking: harmless plugins ignored, to report on stderr.
81    pub skipped_plugins: Vec<String>,
82    /// Resolved layout (None if a layout issue blocks).
83    pub layout: Option<Layout>,
84}
85
86impl ScopeReport {
87    pub fn is_native_ok(&self) -> bool {
88        self.issues.is_empty()
89    }
90}
91
92/// `plugins_enabled` = no `--no-plugins`: with the flag, Composer ignores
93/// every plugin, composer/installers included; everything goes into vendor/.
94pub fn analyze(
95    project_dir: &Path,
96    lock: &Lock,
97    root_manifest: &Value,
98    with_dev: bool,
99    plugins_enabled: bool,
100) -> ScopeReport {
101    let mut report = ScopeReport::default();
102
103    for p in lock.wanted_packages(with_dev) {
104        classify_package(p, &mut report);
105    }
106    match Layout::resolve(project_dir, lock, root_manifest, with_dev, plugins_enabled) {
107        Ok(layout) => report.layout = Some(layout),
108        Err(issues) => report
109            .issues
110            .extend(issues.into_iter().map(ScopeIssue::Layout)),
111    }
112    report
113}
114
115/// Blocking plugin issues alone (unknown or layout-changing plugins in the
116/// lock), for commands that do not install but would still let Composer run
117/// plugin listeners — `dump-autoload` and its PRE_AUTOLOAD_DUMP.
118pub fn plugin_issues(lock: &Lock, with_dev: bool) -> Vec<ScopeIssue> {
119    let mut report = ScopeReport::default();
120    for p in lock.wanted_packages(with_dev) {
121        classify_plugin(p, &mut report);
122    }
123    report.issues
124}
125
126fn classify_package(p: &LockPackage, report: &mut ScopeReport) {
127    classify_plugin(p, report);
128    if !p.is_metapackage() && p.dist_kind() != DistKind::Zip {
129        report
130            .issues
131            .push(ScopeIssue::NoUsableDist(p.name().to_owned()));
132    }
133}
134
135fn classify_plugin(p: &LockPackage, report: &mut ScopeReport) {
136    if p.package_type() != "composer-plugin" {
137        return;
138    }
139    let name = p.name().to_owned();
140    if EMULATED_PLUGINS.contains(&name.as_str()) {
141        // Emulated natively: nothing to report.
142    } else if BENIGN_PLUGINS.contains(&name.as_str()) {
143        report.skipped_plugins.push(name);
144    } else if LAYOUT_PLUGINS.contains(&name.as_str()) {
145        report.issues.push(ScopeIssue::LayoutPlugin(name));
146    } else {
147        report.issues.push(ScopeIssue::UnknownPlugin(name));
148    }
149}
150
151#[cfg(test)]
152mod tests {
153    use super::*;
154    use crate::lock::Lock;
155    use serde_json::json;
156
157    fn lock_with(packages: serde_json::Value) -> Lock {
158        Lock::parse(&json!({ "packages": packages, "packages-dev": [] }).to_string()).expect("lock")
159    }
160
161    fn zip_pkg(name: &str, r#type: &str) -> serde_json::Value {
162        json!({"name": name, "version": "1.0.0", "type": r#type,
163               "dist": {"type": "zip", "url": "https://x/y.zip", "reference": "r"}})
164    }
165
166    fn proj() -> std::path::PathBuf {
167        std::path::PathBuf::from("/nonexistent-vivacity-scope")
168    }
169
170    #[test]
171    fn plain_library_is_native() {
172        let lock = lock_with(json!([zip_pkg("a/b", "library")]));
173        let r = analyze(&proj(), &lock, &json!({}), true, true);
174        assert!(r.is_native_ok());
175        assert!(r.skipped_plugins.is_empty());
176        assert_eq!(r.layout.expect("layout").rel("a/b"), Some("vendor/a/b"));
177    }
178
179    #[test]
180    fn emulated_and_benign_plugins_stay_native() {
181        let lock = lock_with(json!([
182            zip_pkg("symfony/runtime", "composer-plugin"),
183            zip_pkg("symfony/flex", "composer-plugin"),
184        ]));
185        let r = analyze(&proj(), &lock, &json!({}), true, true);
186        assert!(r.is_native_ok());
187        assert_eq!(r.skipped_plugins, vec!["symfony/flex"]);
188    }
189
190    #[test]
191    fn unknown_or_layout_plugin_is_out_of_scope() {
192        let lock = lock_with(json!([
193            zip_pkg("acme/mystery-plugin", "composer-plugin"),
194            zip_pkg("cweagans/composer-patches", "composer-plugin"),
195        ]));
196        let r = analyze(&proj(), &lock, &json!({}), true, true);
197        assert_eq!(
198            r.issues,
199            vec![
200                ScopeIssue::UnknownPlugin("acme/mystery-plugin".into()),
201                ScopeIssue::LayoutPlugin("cweagans/composer-patches".into()),
202            ]
203        );
204    }
205
206    #[test]
207    fn installers_without_allow_plugins_and_sourceless_dist_are_out_of_scope() {
208        let lock = lock_with(json!([
209            {"name": "a/src-only", "version": "1.0.0", "type": "library",
210             "source": {"type": "git", "url": "https://g/x.git", "reference": "r"}},
211            {"name": "a/meta", "version": "1.0.0", "type": "metapackage"},
212            zip_pkg("composer/installers", "composer-plugin"),
213        ]));
214        // installer-paths alone is inert (as in Composer); the plugin without
215        // allow-plugins, however, blocks.
216        let manifest = json!({"extra": {"installer-paths": {"web/modules/{$name}": []}}});
217        let r = analyze(&proj(), &lock, &manifest, true, true);
218        assert_eq!(r.issues.len(), 2, "{:?}", r.issues);
219        assert_eq!(r.issues[0], ScopeIssue::NoUsableDist("a/src-only".into()));
220        assert!(matches!(&r.issues[1], ScopeIssue::Layout(m) if m.contains("allow-plugins")));
221    }
222
223    #[test]
224    fn no_dev_skips_dev_packages() {
225        let lock = Lock::parse(
226            &json!({
227                "packages": [zip_pkg("a/b", "library")],
228                "packages-dev": [zip_pkg("acme/mystery-plugin", "composer-plugin")]
229            })
230            .to_string(),
231        )
232        .expect("lock");
233        assert!(analyze(&proj(), &lock, &json!({}), false, true).is_native_ok());
234        assert!(!analyze(&proj(), &lock, &json!({}), true, true).is_native_ok());
235    }
236}