vivacity-core 0.19.0

Manifests, content hash, platform checks, dist fetching, content-addressed store and installation for vivacity
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
//! Out-of-scope detector: decides, BEFORE touching the disk, whether vivacity
//! can install this lock natively or must delegate to `composer install`
//! (default fallback) / fail explicitly (when Composer is not available).
//!
//! Principle (plan r1/F3-F5): never a silently divergent vendor/. An unknown
//! plugin, or one that changes the layout, is out of scope. Plugins proven
//! harmless at boot (fixture qualification) are installed like ordinary
//! libraries, with a warning.

use crate::layout::Layout;
use crate::lock::{DistKind, Lock, LockPackage};
use serde_json::Value;
use std::path::Path;

/// Plugins emulated natively by vivacity (identical output, drift test).
/// composer/installers (see `layout`) is, under conditions checked before
/// any write. drupal/core-composer-scaffold is deliberately absent: its
/// source is GPL-2.0-or-later and cannot be ported here (NOTICE.md).
pub const EMULATED_PLUGINS: &[&str] = &[
    "symfony/runtime",
    "composer/installers",
    "pestphp/pest-plugin",
    "dealerdirect/phpcodesniffer-composer-installer",
    "phpstan/extension-installer",
    "rector/extension-installer",
    "wikimedia/composer-merge-plugin",
    "composer/package-versions-deprecated",
    // At install: `POST_INSTALL_CMD` copies `.env` from its `.dist` and
    // prints, `symfony-pack` packages are laid out as metapackages, and
    // nothing else fires (`fetchRecipes` is POST_UPDATE_CMD only). The
    // resolution commands have their own rules (`resolution_effect`).
    "symfony/flex",
    "yiisoft/yii2-composer",
    "codeception/c3",
    "bamarni/composer-bin-plugin",
    "roots/wordpress-core-installer",
    "mnsami/composer-custom-directory-installer",
];

/// Plugins proven to write nothing at install time under a Composer whose
/// plugins are active (the corpus baseline, docs/corpus/): installed as
/// libraries, reported with a note. A plugin that writes a file is either
/// emulated (EMULATED_PLUGINS) or unknown — never listed here. Removed on
/// the corpus's evidence (2026-09-16): pestphp/pest-plugin
/// (vendor/pest-plugins.json), phpstan/extension-installer and
/// rector/extension-installer (GeneratedConfig.php),
/// dealerdirect/phpcodesniffer-composer-installer (CodeSniffer.conf).
/// `metasyntactical/composer-plugin-license-check` checks each installed
/// package's licence against the root's `extra` lists and throws when one
/// is denied — Composer stops, vendor/ half written. With no list
/// configured every package passes and the plugin writes nothing: benign
/// then, handed over when it is configured.
pub const LICENSE_CHECK_PLUGIN: &str = "metasyntactical/composer-plugin-license-check";

/// Its configuration, as `ComposerConfig` reads it: `array_filter` over
/// `allow-list`, `deny-list` and `allowed-packages`, so empty (or absent)
/// lists mean no check at all.
pub fn license_check_configured(root_manifest: &Value) -> bool {
    let Some(cfg) = root_manifest
        .get("extra")
        .and_then(|e| e.get(LICENSE_CHECK_PLUGIN))
    else {
        return false;
    };
    ["allow-list", "deny-list"].iter().any(|k| {
        cfg.get(*k).and_then(Value::as_array).is_some_and(|l| {
            l.iter()
                .any(|v| !matches!(v, Value::Null | Value::Bool(false)))
        })
    })
}

pub const BENIGN_PLUGINS: &[&str] = &[
    "php-http/discovery",
    // Only listens to POST_CREATE_PROJECT_CMD / POST_INSTALL_CMD to print a
    // message (MessagePlugin::getSubscribedEvents): no disk effect.
    "drupal/core-project-message",
    // Only listens to POST_UPDATE_CMD / POST_CREATE_PROJECT_CMD, and only acts
    // in a `require` context (Plugin::getSubscribedEvents): inert at install.
    "drupal/core-recipe-unpack",
    LICENSE_CHECK_PLUGIN,
    // A `CommandProvider` (`ibexa setup`) whose activate/deactivate only
    // write at DEBUG verbosity; no listener (read at v5.0.10).
    "ibexa/post-install",
    // `Thanks::activate` arms its reminder only when the command is
    // `update`; `POST_PACKAGE_UPDATE` then `POST_UPDATE_CMD` print it after
    // a GitHub GraphQL call. On `install`: two commands added, nothing
    // else (read at v1.4.1).
    "symfony/thanks",
    // A `CommandProvider` (`composer normalize`) with an empty `activate`
    // and no listener (NormalizePlugin, read at 2.45.0).
    "ergebnis/composer-normalize",
];

/// Plugins known to change the install layout or the package contents:
/// always out of scope.
pub const LAYOUT_PLUGINS: &[&str] = &[
    "cweagans/composer-patches",
    "oomphinc/composer-installers-extender",
];

/// The resolution commands (`update`, `require`, `remove`): Composer loads
/// the installed plugins before resolving (`PluginManager::loadInstalledPlugins`
/// from installed.json, global ones included), and some of them change what
/// gets resolved or written. Read in the plugins' sources (plan v0.16):
/// these have no listener that touches the resolution or the lock —
/// `POST_INSTALL/UPDATE_CMD` writers of files under vendor/ (handled at
/// install), install-path mappers, message printers.
pub const RESOLUTION_INERT: &[&str] = &[
    "composer/installers",
    "symfony/runtime",
    "pestphp/pest-plugin",
    "dealerdirect/phpcodesniffer-composer-installer",
    "phpstan/extension-installer",
    "rector/extension-installer",
    "composer/package-versions-deprecated",
    "ergebnis/composer-normalize",
    // `POST_INSTALL_CMD` / `POST_UPDATE_CMD` copy `c3.php` to the root:
    // the install side's business, emulated there.
    "codeception/c3",
    // `COMMAND` forwards `install` / `update` to vendor-bin/* when
    // `forward-command` is true — nested installs, the root lock untouched;
    // the install side refuses that configuration.
    "bamarni/composer-bin-plugin",
    // An installer for the `wordpress-core` type: install paths only.
    "roots/wordpress-core-installer",
    // `COMMAND` (a verbose-only line) and `POST_PACKAGE_INSTALL/UPDATE`,
    // where it only ever throws: the lock is untouched either way.
    "metasyntactical/composer-plugin-license-check",
    "ibexa/post-install",
    // `POST_INSTALL/UPDATE_CMD`: an in-process `require` of a PSR
    // implementation only when one is missing — with a complete lock, a
    // no-op (verified on install with the corpus).
    "php-http/discovery",
    "drupal/core-project-message",
    // `PRE_UPDATE_CMD` gathers patches, `POST_PACKAGE_*` applies them: the
    // lock is untouched; the install side already hands these to Composer.
    "cweagans/composer-patches",
    "mlocati/composer-patcher",
    "oomphinc/composer-installers-extender",
    "mnsami/composer-custom-directory-installer",
];

/// A resolution command, for the per-plugin rules below.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResolutionCommand {
    Update,
    Require,
    Remove,
}

impl ResolutionCommand {
    pub fn name(self) -> &'static str {
        match self {
            ResolutionCommand::Update => "update",
            ResolutionCommand::Require => "require",
            ResolutionCommand::Remove => "remove",
        }
    }
}

/// What an active plugin does to `command`, as far as the lock is
/// concerned: nothing (inert, or emulated for this command), or something
/// vivacity does not emulate (the reason, for the fallback line).
/// `with_install`: the command installs after resolving (no `--no-install`).
pub fn resolution_effect(
    plugin: &str,
    command: ResolutionCommand,
    with_install: bool,
) -> Option<String> {
    if RESOLUTION_INERT.contains(&plugin) {
        return None;
    }
    Some(match plugin {
        // `PRE_POOL_CREATE` filters the pool against `extra.symfony.require`
        // (`Restricting packages listed in "symfony/symfony" to …`) —
        // emulated (`vivacity_resolver::flex_filter`) for `update` and
        // `remove` without install. `require` resolves Flex aliases and
        // `POST_UPDATE_CMD` applies recipes to the installed packages
        // (files, symfony.lock): with install, or on `require`, Composer.
        "symfony/flex" => {
            if command == ResolutionCommand::Require {
                "resolves Flex aliases and applies recipes on require (not emulated)".to_owned()
            } else if with_install && command == ResolutionCommand::Remove {
                "applies recipes to the packages it installs (not emulated; --no-install resolves natively)".to_owned()
            } else {
                // `update` with install is decided once the lock is solved
                // (`flex_install_reason`): what Flex would do depends on the
                // packages the install lays out.
                return None;
            }
        }
        // `POST_PACKAGE_UPDATE` arms the reminder, `POST_UPDATE_CMD` prints
        // it after a GitHub GraphQL query (`GitHubClient`): without a token
        // that is Composer's GitHub auth prompt (an exception under
        // `--no-interaction`) — stderr and exit code differ. Only once a
        // package was actually updated, which is not known before
        // resolving: `update` with install, Composer (`activate` arms it
        // for the `update` command only: `require` / `remove` stay inert).
        "symfony/thanks" => {
            if command == ResolutionCommand::Update && with_install {
                "prints a reminder after a package update, after querying GitHub (not emulated; --no-install resolves natively)".to_owned()
            } else {
                return None;
            }
        }
        // `POST_PACKAGE_UPDATE` records updates, `POST_UPDATE_CMD` prints
        // yiisoft/yii2's UPGRADE.md notes when it was updated — only with
        // install, and only known after resolving: with install, Composer.
        "yiisoft/yii2-composer" => {
            if with_install {
                "prints yiisoft/yii2's upgrade notes after an update with install (not emulated; --no-install resolves natively)".to_owned()
            } else {
                return None;
            }
        }
        // INIT / `PRE_UPDATE_CMD` merge other manifests into the root
        // before resolving: emulated (`vivacity_resolver::merge_plugin`),
        // the merged links, stability flags, aliases and references in
        // the pool. A merged `repositories` section is the exception,
        // checked by the caller on the merge itself.
        "wikimedia/composer-merge-plugin" => return None,
        // `POST_UPDATE_CMD`, acting only in a `require` context: unpacks
        // recipes into composer.json.
        "drupal/core-recipe-unpack" => {
            if command == ResolutionCommand::Require {
                "unpacks recipes into composer.json on require (not emulated)".to_owned()
            } else {
                return None;
            }
        }
        _ => "is not on vivacity's known-plugin list".to_owned(),
    })
}

/// The plugins Composer would load for a resolution command, and what
/// each does to it: those installed (installed.json of the project and
/// of `COMPOSER_HOME`) that `allow-plugins` allows. Empty under
/// `--no-plugins`. One issue per plugin that is not inert for `command`.
pub fn resolution_issues(
    project_dir: &Path,
    root_manifest: &Value,
    command: ResolutionCommand,
    plugins_enabled: bool,
    with_install: bool,
) -> Vec<ScopeIssue> {
    let mut issues = Vec::new();
    for name in active_plugins(project_dir, root_manifest, plugins_enabled) {
        if let Some(effect) = resolution_effect(&name, command, with_install) {
            issues.push(ScopeIssue::ResolutionPlugin(name, effect));
        }
    }
    issues
}

/// The plugins Composer loads for a command: `composer-plugin` packages of
/// installed.json (project and `COMPOSER_HOME`) that `allow-plugins`
/// allows. Empty under `--no-plugins`.
pub fn active_plugins(
    project_dir: &Path,
    root_manifest: &Value,
    plugins_enabled: bool,
) -> Vec<String> {
    if !plugins_enabled {
        return Vec::new();
    }
    let mut names: Vec<String> = Vec::new();
    let mut collect = |packages: Vec<Value>| {
        for p in packages {
            if p.get("type").and_then(Value::as_str) == Some("composer-plugin") {
                if let Some(n) = p.get("name").and_then(Value::as_str) {
                    if !names.iter().any(|x| x == n) {
                        names.push(n.to_owned());
                    }
                }
            }
        }
    };
    collect(crate::layout::installed_packages_of(
        project_dir,
        root_manifest,
    ));
    if let Some(home) = crate::fetch::composer_home() {
        collect(crate::layout::installed_packages_at(
            &home.join("vendor").join("composer"),
        ));
    }
    names.retain(|name| {
        matches!(
            crate::layout::plugin_allowed(root_manifest, name),
            crate::layout::PluginVerdict::Allowed
        )
    });
    names
}

#[derive(Debug, PartialEq, Eq)]
pub enum ScopeIssue {
    /// Plugin absent from the known lists: unpredictable behaviour.
    UnknownPlugin(String),
    /// An installed, allowed plugin that changes what `update`/`require`/
    /// `remove` resolve or write (name, what it does).
    ResolutionPlugin(String, String),
    /// Plugin known to change the layout (patches, installers-extender...).
    LayoutPlugin(String),
    /// Non-reproducible layout (composer/installers: version not ported,
    /// framework with custom logic, refused target...).
    Layout(String),
    /// Package without a usable zip dist (source-only, exotic dist).
    NoUsableDist(String),
    /// A `config` key vivacity does not read and that changes the layout
    /// (`vendor-dir`, `bin-dir`, `preferred-install: source`): Composer's
    /// output would differ, so the lock is handed over.
    Config(String),
    /// `wikimedia/composer-merge-plugin` could not be emulated for this
    /// run (a `require` pattern without match, an invalid included file,
    /// or a bare vendor whose lock misses a merged requirement — where
    /// Composer would run the plugin's implicit update).
    MergePlugin(String),
}

impl std::fmt::Display for ScopeIssue {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ScopeIssue::UnknownPlugin(p) => {
                write!(f, "plugin {p} is not on vivacity's known-plugin list")
            }
            ScopeIssue::LayoutPlugin(p) => {
                write!(f, "plugin {p} changes the install layout (not emulated)")
            }
            ScopeIssue::ResolutionPlugin(p, what) => write!(f, "plugin {p} {what}"),
            ScopeIssue::Layout(why) => write!(f, "{why}"),
            ScopeIssue::NoUsableDist(p) => {
                write!(
                    f,
                    "package {p} has no usable dist (no zip or tar dist, no path source)"
                )
            }
            ScopeIssue::Config(why) => write!(f, "config {why} is not supported natively"),
            ScopeIssue::MergePlugin(why) => write!(f, "wikimedia/composer-merge-plugin: {why}"),
        }
    }
}

#[derive(Debug, Default)]
pub struct ScopeReport {
    /// Blocking: at least one -> fallback (or error without Composer).
    pub issues: Vec<ScopeIssue>,
    /// Non-blocking: harmless plugins ignored, to report on stderr.
    pub skipped_plugins: Vec<String>,
    /// Resolved layout (None if a layout issue blocks).
    pub layout: Option<Layout>,
}

impl ScopeReport {
    pub fn is_native_ok(&self) -> bool {
        self.issues.is_empty()
    }
}

/// `plugins_enabled` = no `--no-plugins`: with the flag, Composer ignores
/// every plugin, composer/installers included; everything goes into vendor/.
pub fn analyze(
    project_dir: &Path,
    lock: &Lock,
    root_manifest: &Value,
    with_dev: bool,
    plugins_enabled: bool,
) -> ScopeReport {
    let mut report = ScopeReport::default();

    for p in lock.wanted_packages(with_dev) {
        classify_package(project_dir, p, plugins_enabled, &mut report);
    }
    // yii2-composer's installer writes three `Yii.php` shims for
    // `yiisoft/yii2-dev` (`linkBaseYiiFiles`): not emulated.
    if plugins_enabled
        && matches!(
            crate::layout::plugin_allowed(root_manifest, crate::yii2_composer::PLUGIN_NAME),
            crate::layout::PluginVerdict::Allowed
        )
        && lock
            .wanted_packages(with_dev)
            .any(|p| p.name() == crate::yii2_composer::PLUGIN_NAME)
        && lock
            .wanted_packages(with_dev)
            .any(|p| p.name() == crate::yii2_composer::YII2_DEV)
    {
        report.issues.push(ScopeIssue::UnknownPlugin(format!(
            "{} with {} (the Yii.php shims are not emulated); it",
            crate::yii2_composer::PLUGIN_NAME,
            crate::yii2_composer::YII2_DEV
        )));
    }
    // The licence check, configured: a denied licence stops Composer
    // mid-install, which vivacity does not reproduce.
    if plugins_enabled
        && license_check_configured(root_manifest)
        && matches!(
            crate::layout::plugin_allowed(root_manifest, LICENSE_CHECK_PLUGIN),
            crate::layout::PluginVerdict::Allowed
        )
        && lock
            .wanted_packages(with_dev)
            .any(|p| p.name() == LICENSE_CHECK_PLUGIN)
    {
        report.issues.push(ScopeIssue::UnknownPlugin(format!(
            "{LICENSE_CHECK_PLUGIN} with an allow-list or deny-list in `extra` (it stops the install on a denied licence); it"
        )));
    }
    // bamarni/composer-bin-plugin: `forward-command: true` runs nested
    // installs under vendor-bin/ (not emulated); a wrong setting type is
    // Composer's abort.
    if plugins_enabled
        && matches!(
            crate::layout::plugin_allowed(root_manifest, crate::bamarni_bin::PLUGIN_NAME),
            crate::layout::PluginVerdict::Allowed
        )
        && lock
            .wanted_packages(with_dev)
            .any(|p| p.name() == crate::bamarni_bin::PLUGIN_NAME)
    {
        match crate::bamarni_bin::config(root_manifest.get("extra")) {
            Ok(cfg) if cfg.forward_command => report.issues.push(ScopeIssue::UnknownPlugin(
                format!(
                    "{} with extra.bamarni-bin.forward-command true (forwards the command to vendor-bin/*, not emulated); it",
                    crate::bamarni_bin::PLUGIN_NAME
                ),
            )),
            Ok(_) => {}
            Err(msg) => report.issues.push(ScopeIssue::Config(format!(
                "extra.bamarni-bin ({msg})"
            ))),
        }
    }
    report.issues.extend(
        config_issues(root_manifest, lock, with_dev)
            .into_iter()
            .map(ScopeIssue::Config),
    );
    match Layout::resolve(project_dir, lock, root_manifest, with_dev, plugins_enabled) {
        Ok(layout) => report.layout = Some(layout),
        Err(issues) => report
            .issues
            .extend(issues.into_iter().map(ScopeIssue::Layout)),
    }
    report
}

/// Blocking plugin issues alone (unknown or layout-changing plugins in the
/// lock), for commands that do not install but would still let Composer run
/// plugin listeners — `dump-autoload` and its PRE_AUTOLOAD_DUMP.
pub fn plugin_issues(lock: &Lock, with_dev: bool) -> Vec<ScopeIssue> {
    let mut report = ScopeReport::default();
    for p in lock.wanted_packages(with_dev) {
        classify_plugin(p, &mut report);
    }
    report.issues
}

/// The `config` keys of the manifest (or the global config) that vivacity
/// does not honour: a `preferred-install` that is not exactly `dist`.
///
/// `DownloadManager::resolvePackageInstallPreference` takes the FIRST pattern
/// that matches, and with no match at all it answers
/// `$package->isDev() ? 'source' : 'dist'`. So `auto` and any partial pattern
/// map install a dev-version package from **source** — a git clone where
/// vivacity extracts a dist, i.e. a different vendor/ and not a missing line.
/// Composer's own default is the string `dist` (`Config`), which is why the
/// common case needs no refusal. A map is accepted only when every value is
/// `dist` AND a `*` pattern makes it total; anything else hands over.
/// (`vendor-dir` / `bin-dir` are resolved by `dirs::Dirs`; the forms it
/// refuses come back as layout issues.)
/// `BaseCommand::getPreferredInstallOptions`: the `preferred-install` this
/// command really runs with, once `--prefer-source`, `--prefer-dist` and
/// `--prefer-install` have had their say — `None` when they say nothing and the
/// config stands.
///
/// The cascade, ported: the config's string sets one of the two flags (`auto`, a
/// map, or anything else sets neither); `--prefer-install` may not be combined
/// with either flag (`InvalidArgumentException`) and its value stands in for the
/// matching flag, `auto` clearing both; finally, if either flag is set, the two
/// flags replace whatever the config said.
///
/// Reported as the effective `preferred-install`, which is what the refusal is
/// about: `config_issues` then judges it per package, exactly as
/// `resolvePackageInstallPreference` does. `Err` is Composer's own usage
/// message, printed as text with exit 1.
pub fn effective_preferred_install(
    root_manifest: &Value,
    prefer_source: bool,
    prefer_dist: bool,
    prefer_install: Option<&str>,
) -> Result<Option<Value>, String> {
    if prefer_install.is_none() && !prefer_source && !prefer_dist {
        return Ok(None);
    }
    let config = root_manifest
        .get("config")
        .and_then(|c| c.get("preferred-install"))
        .cloned()
        .or_else(|| crate::layout::global_config_value("preferred-install"));
    let mut flag_source = prefer_source;
    let mut flag_dist = prefer_dist;
    let mut cleared = false;
    if let Some(value) = prefer_install {
        if prefer_source {
            return Err(
                "--prefer-source can not be used together with --prefer-install".to_owned(),
            );
        }
        if prefer_dist {
            return Err("--prefer-dist can not be used together with --prefer-install".to_owned());
        }
        match value {
            "dist" => flag_dist = true,
            "source" => flag_source = true,
            "auto" => cleared = true,
            other => {
                return Err(format!(
                    "--prefer-install accepts one of \"dist\", \"source\" or \"auto\", got {other}"
                ))
            }
        }
    }
    if flag_source {
        return Ok(Some(Value::String("source".to_owned())));
    }
    if flag_dist {
        return Ok(Some(Value::String("dist".to_owned())));
    }
    if cleared {
        // Both flags off: the config's string no longer applies, but its map
        // still reaches `setPreferences`, so only a string is replaced.
        return Ok(Some(match config {
            Some(Value::Object(m)) => Value::Object(m),
            _ => Value::String("auto".to_owned()),
        }));
    }
    Ok(None)
}

/// `DownloadManager::resolvePackageInstallPreference` plus `Factory`'s switch,/// `DownloadManager::resolvePackageInstallPreference` plus `Factory`'s switch,
/// for one package: would Composer install it from source?
///
/// A string is handled by the switch — `dist` forces dist, `source` forces
/// source, anything else (including `auto`) leaves both flags off and falls
/// through to the per-package rule with no patterns. A map goes to
/// `setPreferences`, where the FIRST matching pattern decides: `dist` is dist,
/// `auto` is dist only for a non-dev package, and anything else is source.
/// With no pattern matching at all: `$package->isDev() ? 'source' : 'dist'`.
fn prefers_source(preference: &Value, name: &str, is_dev: bool) -> bool {
    match preference {
        Value::String(s) => match s.as_str() {
            "dist" => false,
            "source" => true,
            _ => is_dev,
        },
        Value::Object(map) => {
            for (pattern, pref) in map {
                if pattern_matches(pattern, name) {
                    return match pref.as_str() {
                        Some("dist") => false,
                        Some("auto") => is_dev,
                        _ => true,
                    };
                }
            }
            is_dev
        }
        _ => is_dev,
    }
}

/// `'{^'.str_replace('\*', '.*', preg_quote($pattern)).'$}i'`: a whole-name
/// The pattern of `resolvePackageInstallPreference`, built as
/// `preg_quote($pattern)` with `\*` turned into `.*`, anchored, `i`: the whole
/// name, case-insensitive, `*` the only metacharacter and everything else
/// literal. Greedy left to right, as `.*` is.
fn pattern_matches(pattern: &str, name: &str) -> bool {
    let name = name.to_ascii_lowercase();
    let pieces: Vec<String> = pattern
        .to_ascii_lowercase()
        .split('*')
        .map(str::to_owned)
        .collect();
    if pieces.len() == 1 {
        return name == pieces[0];
    }
    let first = &pieces[0];
    let last = &pieces[pieces.len() - 1];
    if !name.starts_with(first.as_str()) || !name.ends_with(last.as_str()) {
        return false;
    }
    // The first and last pieces may not overlap in the name.
    if name.len() < first.len() + last.len() {
        return false;
    }
    let mut rest = &name[first.len()..name.len() - last.len()];
    for piece in &pieces[1..pieces.len() - 1] {
        match rest.find(piece.as_str()) {
            Some(pos) => rest = &rest[pos + piece.len()..],
            None => return false,
        }
    }
    true
}

/// `Package::isDev()`: the version's stability is `dev`.
fn is_dev_version(version: &str) -> bool {
    version.starts_with("dev-") || version.ends_with("-dev")
}

pub fn config_issues(root_manifest: &Value, lock: &Lock, with_dev: bool) -> Vec<String> {
    let value = |key: &str| -> Option<Value> {
        root_manifest
            .get("config")
            .and_then(|c| c.get(key))
            .cloned()
            .or_else(|| crate::layout::global_config_value(key))
    };
    let mut out = Vec::new();
    if let Some(v) = value("preferred-install") {
        if lock
            .wanted_packages(with_dev)
            .any(|p| prefers_source(&v, p.name(), is_dev_version(p.version())))
        {
            out.push(format!("preferred-install {v}"));
        }
    }
    out
}

fn classify_package(
    project_dir: &Path,
    p: &LockPackage,
    plugins_enabled: bool,
    report: &mut ScopeReport,
) {
    // Under --no-plugins Composer never loads a plugin (PluginManager::
    // registerPackage returns at once): the package is a plain library in
    // vendor/, whatever it would do when active, and nothing is printed.
    if plugins_enabled {
        classify_plugin(p, report);
    }
    if p.is_metapackage() {
        return;
    }
    let usable = match p.dist_kind() {
        DistKind::Zip | DistKind::Tar => true,
        // A `path` package is laid out natively (symlink or mirror) on
        // Linux/macOS when its source directory is there; Windows
        // (junctions) is left to Composer.
        DistKind::Path => cfg!(unix) && p.dist_url().is_some_and(|u| project_dir.join(u).is_dir()),
        DistKind::Other | DistKind::Missing => false,
    };
    if !usable {
        report
            .issues
            .push(ScopeIssue::NoUsableDist(p.name().to_owned()));
    }
}

fn classify_plugin(p: &LockPackage, report: &mut ScopeReport) {
    if p.package_type() != "composer-plugin" {
        return;
    }
    let name = p.name().to_owned();
    if EMULATED_PLUGINS.contains(&name.as_str()) {
        // Emulated natively: nothing to report.
    } else if BENIGN_PLUGINS.contains(&name.as_str()) {
        report.skipped_plugins.push(name);
    } else if LAYOUT_PLUGINS.contains(&name.as_str()) {
        report.issues.push(ScopeIssue::LayoutPlugin(name));
    } else {
        report.issues.push(ScopeIssue::UnknownPlugin(name));
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::lock::Lock;
    use serde_json::json;

    fn lock_with(packages: serde_json::Value) -> Lock {
        Lock::parse(&json!({ "packages": packages, "packages-dev": [] }).to_string()).expect("lock")
    }

    fn zip_pkg(name: &str, r#type: &str) -> serde_json::Value {
        json!({"name": name, "version": "1.0.0", "type": r#type,
               "dist": {"type": "zip", "url": "https://x/y.zip", "reference": "r"}})
    }

    fn proj() -> std::path::PathBuf {
        std::path::PathBuf::from("/nonexistent-vivacity-scope")
    }

    #[test]
    fn preferred_install_auto_hands_over_for_a_dev_package() {
        // `resolvePackageInstallPreference` with no pattern answers
        // `$package->isDev() ? 'source' : 'dist'`, so `auto` clones a dev
        // version from source — a git checkout where vivacity extracts a dist.
        // Measured against Composer 2.10.3: `  - Syncing … into cache` for the
        // dev packages, `  - Downloading …` for the stable ones.
        let dev = json!({"name": "a/b", "version": "dev-main", "type": "library",
                         "dist": {"type": "zip", "url": "https://x/y.zip", "reference": "r"}});
        for preference in [
            json!("auto"),
            json!("source"),
            json!({"*": "auto"}),
            json!({"a/*": "auto"}),
            // No pattern matches, so the default rule applies to a dev package.
            json!({"other/*": "dist"}),
        ] {
            let lock = lock_with(json!([dev.clone()]));
            let manifest = json!({"config": {"preferred-install": preference}});
            assert!(
                !analyze(&proj(), &lock, &manifest, true, true).is_native_ok(),
                "{preference} with a dev package must hand over"
            );
            // The same preference with a stable package is dist throughout.
            let stable = lock_with(json!([zip_pkg("a/b", "library")]));
            let native = analyze(&proj(), &stable, &manifest, true, true).is_native_ok();
            assert_eq!(
                native,
                preference != json!("source"),
                "{preference} with a stable package"
            );
        }
    }

    #[test]
    fn install_preference_patterns_match_like_pcre() {
        // `preg_quote` then `\*` -> `.*`, anchored, case-insensitive.
        for (pattern, name, want) in [
            ("a/b", "a/b", true),
            ("a/b", "a/bc", false),
            ("A/B", "a/b", true),
            ("*", "anything/at-all", true),
            ("acme/*", "acme/thing", true),
            ("acme/*", "acmex/thing", false),
            ("*/thing", "acme/thing", true),
            ("a*b", "a/xb", true),
            // `.*` matches the empty string.
            ("a*b", "ab", true),
            ("a**b", "a/b", true),
            // A dot is literal, not "any character".
            ("a.b/c", "axb/c", false),
            ("a.b/c", "a.b/c", true),
            ("acme/*-bundle", "acme/my-bundle", true),
            ("acme/*-bundle", "acme/bundle", false),
        ] {
            assert_eq!(
                pattern_matches(pattern, name),
                want,
                "pattern {pattern:?} against {name:?}"
            );
        }
    }

    #[test]
    fn plain_library_is_native() {
        let lock = lock_with(json!([zip_pkg("a/b", "library")]));
        let r = analyze(&proj(), &lock, &json!({}), true, true);
        assert!(r.is_native_ok());
        assert!(r.skipped_plugins.is_empty());
        assert_eq!(r.layout.expect("layout").rel("a/b"), Some("vendor/a/b"));
    }

    #[test]
    fn emulated_and_benign_plugins_stay_native() {
        let lock = lock_with(json!([
            zip_pkg("symfony/runtime", "composer-plugin"),
            zip_pkg("symfony/flex", "composer-plugin"),
        ]));
        let r = analyze(&proj(), &lock, &json!({}), true, true);
        assert!(r.is_native_ok());
        // Both are emulated now (symfony/flex since its POST_INSTALL_CMD
        // listener is): nothing to report as merely skipped.
        assert!(r.skipped_plugins.is_empty(), "{:?}", r.skipped_plugins);
    }

    #[test]
    fn thanks_and_normalize_are_benign_at_install() {
        let lock = lock_with(json!([
            zip_pkg("symfony/thanks", "composer-plugin"),
            zip_pkg("ergebnis/composer-normalize", "composer-plugin"),
        ]));
        let r = analyze(&proj(), &lock, &json!({}), true, true);
        assert!(r.is_native_ok(), "{:?}", r.issues);
        assert_eq!(
            r.skipped_plugins,
            vec!["symfony/thanks", "ergebnis/composer-normalize"]
        );
    }

    #[test]
    fn thanks_reminder_only_on_update_with_install() {
        use ResolutionCommand::*;
        let effect = |c, i| resolution_effect("symfony/thanks", c, i);
        assert!(effect(Update, true).is_some());
        assert!(effect(Update, false).is_none());
        assert!(effect(Require, true).is_none());
        assert!(effect(Remove, true).is_none());
        assert!(resolution_effect("ergebnis/composer-normalize", Update, true).is_none());
    }

    #[test]
    fn yii2_composer_is_emulated_except_with_yii2_dev() {
        let allow = json!({"config": {"allow-plugins": {"yiisoft/yii2-composer": true}}});
        let lock = lock_with(json!([
            zip_pkg("yiisoft/yii2-composer", "composer-plugin"),
            zip_pkg("yiisoft/yii2-gii", "yii2-extension"),
        ]));
        assert!(analyze(&proj(), &lock, &allow, true, true).is_native_ok());
        let lock = lock_with(json!([
            zip_pkg("yiisoft/yii2-composer", "composer-plugin"),
            zip_pkg("yiisoft/yii2-dev", "yii2-extension"),
        ]));
        let r = analyze(&proj(), &lock, &allow, true, true);
        assert!(!r.is_native_ok());
        assert!(
            r.issues[0].to_string().contains("yiisoft/yii2-dev"),
            "{}",
            r.issues[0]
        );
        // Under --no-plugins the shims are not written by Composer either.
        assert!(analyze(&proj(), &lock, &allow, true, false).is_native_ok());
    }

    #[test]
    fn license_check_native_unless_configured() {
        let lock = lock_with(json!([zip_pkg(
            "metasyntactical/composer-plugin-license-check",
            "composer-plugin"
        )]));
        let manifest = |extra: serde_json::Value| json!({"config": {"allow-plugins": {"metasyntactical/composer-plugin-license-check": true}}, "extra": extra});
        // No list: `ComposerConfig` filters everything away, nothing checked.
        for extra in [
            json!({}),
            json!({"metasyntactical/composer-plugin-license-check": {}}),
            json!({"metasyntactical/composer-plugin-license-check": {"allow-list": []}}),
            json!({"metasyntactical/composer-plugin-license-check": {"allowed-packages": {"a/b": "why"}}}),
        ] {
            let r = analyze(&proj(), &lock, &manifest(extra.clone()), true, true);
            assert!(
                r.is_native_ok(),
                "{extra} should stay native: {:?}",
                r.issues
            );
        }
        for key in ["allow-list", "deny-list"] {
            let extra = json!({"metasyntactical/composer-plugin-license-check": {key: ["MIT"]}});
            let r = analyze(&proj(), &lock, &manifest(extra), true, true);
            assert!(
                r.issues[0].to_string().contains("allow-list or deny-list"),
                "{key}: {:?}",
                r.issues
            );
        }
    }

    #[test]
    fn bamarni_bin_native_unless_it_forwards() {
        let lock = lock_with(json!([zip_pkg(
            "bamarni/composer-bin-plugin",
            "composer-plugin"
        )]));
        let allow = |extra: serde_json::Value| json!({"config": {"allow-plugins": {"bamarni/composer-bin-plugin": true}}, "extra": extra});
        assert!(analyze(&proj(), &lock, &allow(json!({})), true, true).is_native_ok());
        let r = analyze(
            &proj(),
            &lock,
            &allow(json!({"bamarni-bin": {"forward-command": true}})),
            true,
            true,
        );
        assert!(
            r.issues[0].to_string().contains("forward-command true"),
            "{}",
            r.issues[0]
        );
        let r = analyze(
            &proj(),
            &lock,
            &allow(json!({"bamarni-bin": {"bin-links": "no"}})),
            true,
            true,
        );
        assert!(
            r.issues[0].to_string().contains("boolean value"),
            "{}",
            r.issues[0]
        );
    }

    #[test]
    fn no_plugins_makes_every_plugin_a_plain_library() {
        let lock = lock_with(json!([
            zip_pkg("acme/mystery-plugin", "composer-plugin"),
            zip_pkg("cweagans/composer-patches", "composer-plugin"),
            zip_pkg("symfony/flex", "composer-plugin"),
        ]));
        let r = analyze(&proj(), &lock, &json!({}), true, false);
        assert!(r.is_native_ok(), "{:?}", r.issues);
        assert!(r.skipped_plugins.is_empty());
        assert_eq!(
            r.layout.expect("layout").rel("acme/mystery-plugin"),
            Some("vendor/acme/mystery-plugin")
        );
    }

    #[test]
    fn unknown_or_layout_plugin_is_out_of_scope() {
        let lock = lock_with(json!([
            zip_pkg("acme/mystery-plugin", "composer-plugin"),
            zip_pkg("cweagans/composer-patches", "composer-plugin"),
        ]));
        let r = analyze(&proj(), &lock, &json!({}), true, true);
        assert_eq!(
            r.issues,
            vec![
                ScopeIssue::UnknownPlugin("acme/mystery-plugin".into()),
                ScopeIssue::LayoutPlugin("cweagans/composer-patches".into()),
            ]
        );
    }

    #[test]
    fn installers_without_allow_plugins_and_sourceless_dist_are_out_of_scope() {
        let lock = lock_with(json!([
            {"name": "a/src-only", "version": "1.0.0", "type": "library",
             "source": {"type": "git", "url": "https://g/x.git", "reference": "r"}},
            {"name": "a/meta", "version": "1.0.0", "type": "metapackage"},
            zip_pkg("composer/installers", "composer-plugin"),
        ]));
        // installer-paths alone is inert (as in Composer); the plugin without
        // allow-plugins, however, blocks.
        let manifest = json!({"extra": {"installer-paths": {"web/modules/{$name}": []}}});
        let r = analyze(&proj(), &lock, &manifest, true, true);
        assert_eq!(r.issues.len(), 2, "{:?}", r.issues);
        assert_eq!(r.issues[0], ScopeIssue::NoUsableDist("a/src-only".into()));
        assert!(matches!(&r.issues[1], ScopeIssue::Layout(m) if m.contains("allow-plugins")));
    }

    #[test]
    fn path_package_is_native_when_its_source_exists() {
        let tmp = tempfile::tempdir().expect("tmp");
        std::fs::create_dir_all(tmp.path().join("packages/here")).expect("mkdir");
        let lock = lock_with(json!([
            {"name": "a/here", "version": "dev-main", "type": "library",
             "dist": {"type": "path", "url": "packages/here", "reference": "r"}},
            {"name": "a/gone", "version": "dev-main", "type": "library",
             "dist": {"type": "path", "url": "packages/gone", "reference": "r"}},
        ]));
        let r = analyze(tmp.path(), &lock, &json!({}), true, true);
        let expected = if cfg!(unix) {
            vec![ScopeIssue::NoUsableDist("a/gone".into())]
        } else {
            vec![
                ScopeIssue::NoUsableDist("a/here".into()),
                ScopeIssue::NoUsableDist("a/gone".into()),
            ]
        };
        assert_eq!(r.issues, expected);
    }

    #[test]
    fn unread_config_keys_are_scope_issues() {
        // `preferred-install` is judged per package, as
        // `resolvePackageInstallPreference` judges it: only a package that
        // would come from source is a reason to hand over.
        let lock = lock_with(json!([zip_pkg("acme/thing", "library")]));
        let manifest = json!({"config": {"vendor-dir": "lib/", "bin-dir": "vendor/bin",
            "preferred-install": {"acme/*": "source", "*": "dist"}}});
        let r = analyze(&proj(), &lock, &manifest, true, true);
        assert_eq!(
            r.issues,
            vec![ScopeIssue::Config(
                "preferred-install {\"acme/*\":\"source\",\"*\":\"dist\"}".into()
            ),]
        );
        // The same map with a package no source pattern matches: Composer
        // installs it from dist, so there is nothing to hand over.
        let lock = lock_with(json!([zip_pkg("a/b", "library")]));
        let manifest = json!({"config": {"vendor-dir": "vendor",
            "preferred-install": {"acme/*": "source", "*": "dist"}}});
        assert!(analyze(&proj(), &lock, &manifest, true, true).is_native_ok());
        // `auto` with a stable package is dist.
        let manifest = json!({"config": {"vendor-dir": "vendor", "preferred-install": "auto"}});
        assert!(analyze(&proj(), &lock, &manifest, true, true).is_native_ok());
    }

    #[test]
    fn no_dev_skips_dev_packages() {
        let lock = Lock::parse(
            &json!({
                "packages": [zip_pkg("a/b", "library")],
                "packages-dev": [zip_pkg("acme/mystery-plugin", "composer-plugin")]
            })
            .to_string(),
        )
        .expect("lock");
        assert!(analyze(&proj(), &lock, &json!({}), false, true).is_native_ok());
        assert!(!analyze(&proj(), &lock, &json!({}), true, true).is_native_ok());
    }
}