changepacks-core 0.3.3

Core types and traits for changepacks workspace and package management
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
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
use std::path::{Path, PathBuf};

use crate::project::Project;
use anyhow::{Context, Result};
use async_trait::async_trait;

/// Generates `projects()`, `projects_mut()`, `project_count()`,
/// `extend_projects()`, `extend_projects_mut()`, and `contains_project()` for
/// finders backed by a `projects: HashMap<PathBuf, Project>` field.
///
/// The `extend_projects` / `extend_projects_mut` bodies drain
/// `self.projects.values()` / `self.projects.values_mut()` straight into the
/// caller's buffer, so the intermediate `Vec` that `projects()` /
/// `projects_mut()` has to materialize is never built. Yield order is
/// `HashMap::values()` / `HashMap::values_mut()` in both bodies, so overriding
/// is order-preserving with respect to the defaulted
/// [`ProjectFinder::extend_projects`] and
/// [`ProjectFinder::extend_projects_mut`].
///
/// The `contains_project` body is the O(1) hashed probe the map already
/// offers, replacing the defaulted linear scan over `projects()` — see
/// [`ProjectFinder::contains_project`]. `HashMap<PathBuf, Project>` borrows
/// its keys as `Path`, so the probe neither allocates nor clones.
#[macro_export]
macro_rules! impl_projects_hashmap_accessors {
    () => {
        fn projects(&self) -> ::std::vec::Vec<&$crate::Project> {
            self.projects.values().collect::<::std::vec::Vec<_>>()
        }
        fn projects_mut(&mut self) -> ::std::vec::Vec<&mut $crate::Project> {
            self.projects.values_mut().collect::<::std::vec::Vec<_>>()
        }
        fn project_count(&self) -> ::std::primitive::usize {
            self.projects.len()
        }
        fn extend_projects<'a>(&'a self, out: &mut ::std::vec::Vec<&'a $crate::Project>) {
            out.extend(self.projects.values());
        }
        fn extend_projects_mut<'a>(
            &'a mut self,
            out: &mut ::std::vec::Vec<&'a mut $crate::Project>,
        ) {
            out.extend(self.projects.values_mut());
        }
        fn contains_project(&self, path: &::std::path::Path) -> ::std::primitive::bool {
            self.projects.contains_key(path)
        }
    };
}

/// Generates `dependencies()` and `add_dependency()` for types with a
/// `dependencies: HashSet<String>` field.
///
/// `add_dependency` probes membership with `contains` before allocating.
/// `HashSet<String>` borrows its keys as `str`, so the probe is
/// allocation-free, while the previous unconditional
/// `insert(dependency.to_string())` heap-allocated a fresh `String` that
/// `insert` immediately dropped whenever the name was already present.
/// Callers hit that duplicate path routinely: a manifest that lists the same
/// package in more than one dependency section (e.g. `dependencies` and
/// `peerDependencies` in `package.json`) is walked section by section, and
/// every section after the first re-adds a name already in the set. The set
/// contents are unchanged either way — a `HashSet` keeps its existing key on
/// a duplicate insert — so this is purely allocation elision.
#[macro_export]
macro_rules! impl_dependencies_accessors {
    () => {
        fn dependencies(&self) -> &::std::collections::HashSet<::std::string::String> {
            &self.dependencies
        }
        fn add_dependency(&mut self, dependency: &str) {
            if !self.dependencies.contains(dependency) {
                self.dependencies
                    .insert(::std::string::ToString::to_string(dependency));
            }
        }
    };
}

/// Generates `is_publishable_by_default()` for package/workspace structs with a
/// `publishable_by_default: bool` field.
///
/// Contract: the implementing struct MUST own a field named exactly
/// `publishable_by_default` of type `bool` — the same field
/// [`impl_discovered_new!`] initializes. Language crates whose publishability
/// is derived from a differently named field (e.g. Java's `has_publish_task`)
/// must keep their hand-rolled body instead.
#[macro_export]
macro_rules! impl_publishable_by_default {
    () => {
        fn is_publishable_by_default(&self) -> ::std::primitive::bool {
            self.publishable_by_default
        }
    };
}

/// Generates const-backed publish command defaults.
///
/// Two arguments return `Some($dry_run.to_string())`; one argument returns
/// `None` for ecosystems without a built-in dry-run command.
#[macro_export]
macro_rules! impl_const_publish_commands {
    ($publish:path, $dry_run:path) => {
        fn default_publish_command(&self) -> ::std::string::String {
            $publish.to_string()
        }
        fn default_dry_run_publish_command(&self) -> ::std::option::Option<::std::string::String> {
            ::std::option::Option::Some($dry_run.to_string())
        }
    };
    // CSharp variant: `dotnet nuget push` has no built-in `--dry-run`
    // mode, so the default returns `None`. The actual dry-run flow
    // lives in `CSharpPackage::dry_run_publish` (see
    // `crates/csharp/src/dry_run.rs::resolve_and_run_dry_run`), which
    // honors `config.publishDryRun` overrides first and falls back to a
    // managed `dotnet pack` + `dotnet nuget push` against ephemeral
    // `tempfile::TempDir` directories when no override is set.
    ($publish:path) => {
        fn default_publish_command(&self) -> ::std::string::String {
            $publish.to_string()
        }
        fn default_dry_run_publish_command(&self) -> ::std::option::Option<::std::string::String> {
            ::std::option::Option::None
        }
    };
}

/// Generates the `get_publish_command` / `get_dry_run_publish_command`
/// trait defaults shared by [`Package`](crate::Package) and
/// [`Workspace`](crate::Workspace).
///
/// Both traits resolve their publish commands through the exact same
/// [`crate::publish`] ladder — only the surrounding doc prose used to
/// differ — so the bodies live here once instead of being kept
/// byte-identical by hand in two files.
///
/// Contract: the invoking trait MUST already declare `relative_path()`,
/// `language()`, `default_publish_command()`, and
/// `default_dry_run_publish_command()`.
///
/// The sibling `publish` / `dry_run_publish` defaults live in
/// [`impl_publish_flows!`], which takes the differing missing-directory
/// message constant as an argument.
#[macro_export]
macro_rules! impl_publish_command_resolvers {
    () => {
        /// Get the publish command for this project, checking config first.
        ///
        /// The `default_publish_command()` closure is `FnOnce`, so the
        /// project's language-specific default (e.g. Node's
        /// `detect_package_manager_recursive`, which walks the ancestor chain
        /// with sync filesystem stats) is only invoked when config supplies
        /// neither a per-path nor a per-language override — the common case
        /// where the user configures a custom publish command in
        /// `.changepacks/config.json` now avoids one `String` allocation and,
        /// for Node, the ancestor-walking probe.
        fn get_publish_command(&self, config: &$crate::Config) -> ::std::string::String {
            $crate::publish::resolve_publish_command(
                self.relative_path(),
                self.language(),
                || self.default_publish_command(),
                config,
            )
        }

        /// Get the dry-run publish command for this project, checking config
        /// first, then falling back to the project's
        /// `default_dry_run_publish_command`.
        ///
        /// Mirrors `get_publish_command` — the default closure is `FnOnce` so
        /// it is only invoked on the cache-miss path.
        fn get_dry_run_publish_command(
            &self,
            config: &$crate::Config,
        ) -> ::std::option::Option<::std::string::String> {
            $crate::publish::resolve_dry_run_publish_command(
                self.relative_path(),
                self.language(),
                || self.default_dry_run_publish_command(),
                config,
            )
        }
    };
}

/// Generates the `publish` / `dry_run_publish` trait defaults shared by
/// [`Package`](crate::Package) and [`Workspace`](crate::Workspace).
///
/// `$dir_not_found` is the only thing that differed between the two hand-kept
/// copies: [`crate::publish::PACKAGE_DIR_NOT_FOUND`] for `Package`,
/// [`crate::publish::WORKSPACE_DIR_NOT_FOUND`] for `Workspace`.
///
/// Contract: the invoking trait MUST already declare `path()`,
/// `get_publish_command()`, and `get_dry_run_publish_command()` — the latter
/// two come from [`impl_publish_command_resolvers!`].
///
/// The two methods are emitted in the shape `#[async_trait]` would produce
/// rather than as `async fn`, because an attribute macro cannot see through a
/// `macro_rules!` invocation in a trait body: `#[async_trait]` runs BEFORE
/// this macro expands, so an `async fn` emitted here would survive as a
/// native RPITIT method and make `Package` / `Workspace` dyn-incompatible,
/// breaking `Box<dyn Package>` in `crate::Project`. Emitting the boxed-future
/// signature keeps the defaults object safe and keeps them overridable by
/// `#[async_trait]` impls in the language crates (Node, Java, C#), whose
/// generated signatures this shape matches.
#[macro_export]
macro_rules! impl_publish_flows {
    ($dir_not_found:path) => {
        /// Publish this project using the configured command or default.
        ///
        /// # Errors
        /// Returns error if the publish command fails to spawn or the project
        /// directory is missing. A non-zero exit code is reported via
        /// `PublishOutput::success = false`.
        fn publish<'life0, 'life1, 'async_trait>(
            &'life0 self,
            config: &'life1 $crate::Config,
        ) -> ::core::pin::Pin<
            ::std::boxed::Box<
                dyn ::core::future::Future<
                        Output = ::anyhow::Result<$crate::publish::PublishOutput>,
                    > + ::core::marker::Send
                    + 'async_trait,
            >,
        >
        where
            'life0: 'async_trait,
            'life1: 'async_trait,
            Self: 'async_trait,
        {
            ::std::boxed::Box::pin(async move {
                let command = self.get_publish_command(config);
                $crate::publish::run_publish_flow(&command, self.path(), &[], $dir_not_found).await
            })
        }

        /// Run the publish command in dry-run mode to verify the pre-release
        /// flow works without actually publishing.
        ///
        /// Returns `Ok(Some(output))` with the captured command output, or
        /// `Ok(None)` when the language does not support a dry-run mode and
        /// the user has not provided an override in `config.publish_dry_run`.
        ///
        /// # Errors
        /// Returns error if the dry-run command fails to spawn or the project
        /// directory is missing. A non-zero exit code is reported via
        /// `PublishOutput::success = false`.
        fn dry_run_publish<'life0, 'life1, 'async_trait>(
            &'life0 self,
            config: &'life1 $crate::Config,
        ) -> ::core::pin::Pin<
            ::std::boxed::Box<
                dyn ::core::future::Future<
                        Output = ::anyhow::Result<
                            ::std::option::Option<$crate::publish::PublishOutput>,
                        >,
                    > + ::core::marker::Send
                    + 'async_trait,
            >,
        >
        where
            'life0: 'async_trait,
            'life1: 'async_trait,
            Self: 'async_trait,
        {
            ::std::boxed::Box::pin(async move {
                let command = self.get_dry_run_publish_command(config);
                $crate::publish::run_dry_run_publish_flow(
                    command.as_deref(),
                    self.path(),
                    &[],
                    $dir_not_found,
                )
                .await
            })
        }
    };
}

/// Generates the `check_changed`, `is_publishable_by_default`, and
/// `is_dry_run_publishable_by_default` trait defaults shared by
/// [`Package`](crate::Package) and [`Workspace`](crate::Workspace).
///
/// These three bodies were byte-identical hand-kept copies in `package.rs`
/// and `workspace.rs`; they live here once for the same reason
/// [`impl_publish_flows!`] and [`impl_publish_command_resolvers!`] do.
///
/// Contract: the invoking trait MUST already declare `is_changed()`,
/// `set_changed()`, and `path()` (the manifest path — its parent is the
/// project directory). Like its two publish siblings, this macro emits trait
/// *default methods*, so it is only meaningful inside the `Package` /
/// `Workspace` trait definitions in this crate.
///
/// `check_changed` is a sync default, so unlike [`impl_publish_flows!`] it
/// needs no `Pin<Box<dyn Future>>` desugaring and does not interact with
/// `#[async_trait]`.
///
/// The emitted `check_changed` is monotonic: it early-returns once the
/// project is already changed and only ever flips `changed` to `true` via the
/// pure, stateless `should_mark_changed`. That is the invariant
/// [`ProjectFinder::check_changed_many`] relies on for its project-major loop
/// order and early `break`.
#[macro_export]
macro_rules! impl_shared_project_defaults {
    () => {
        /// # Errors
        /// Returns error if the parent path cannot be determined.
        fn check_changed(&mut self, path: &::std::path::Path) -> ::anyhow::Result<()> {
            if self.is_changed() {
                return ::core::result::Result::Ok(());
            }
            if $crate::change_detection::should_mark_changed(path, self.path())? {
                self.set_changed(true);
            }
            ::core::result::Result::Ok(())
        }

        /// Whether this project should be included in publish runs when no
        /// project-path or language command override is configured.
        fn is_publishable_by_default(&self) -> ::std::primitive::bool {
            true
        }

        /// Whether this project should be included in dry-run publish runs when no
        /// project-path or language command override is configured.
        fn is_dry_run_publishable_by_default(&self) -> ::std::primitive::bool {
            self.is_publishable_by_default()
        }
    };
}

/// Generates the shared basic accessors for package/workspace structs with
/// `name`, `version`, `path`, `relative_path`, and `is_changed` fields.
#[macro_export]
macro_rules! impl_basic_accessors {
    () => {
        fn name(&self) -> ::std::option::Option<&::std::primitive::str> {
            self.name.as_deref()
        }
        fn version(&self) -> ::std::option::Option<&::std::primitive::str> {
            self.version.as_deref()
        }
        fn path(&self) -> &::std::path::Path {
            &self.path
        }
        fn relative_path(&self) -> &::std::path::Path {
            &self.relative_path
        }
        fn is_changed(&self) -> ::std::primitive::bool {
            self.is_changed
        }
        fn set_changed(&mut self, changed: ::std::primitive::bool) {
            self.is_changed = changed;
        }
        fn set_name(&mut self, name: ::std::string::String) {
            self.name = ::std::option::Option::Some(name);
        }
    };
}

/// Asserts the `name()` / `set_name()` round trip generated by
/// [`impl_basic_accessors!`] for the project value produced by `$project`.
///
/// Every language crate had a byte-identical `test_set_name` body — build a
/// name-less package/workspace, assert `name()` is `None`, `set_name` it, then
/// assert `name()` observes the new value — differing only in the concrete type
/// and its manifest path. All eleven exercise the exact same
/// [`impl_basic_accessors!`] expansion, so the assertions live here once and
/// each site supplies only its own constructor.
///
/// Contract: `$project` must evaluate to a value whose `name` starts as `None`,
/// and the `Package` or `Workspace` trait supplying `name()` / `set_name()`
/// must be in scope at the call site.
#[macro_export]
macro_rules! assert_set_name_roundtrip {
    ($project:expr) => {{
        let mut project = $project;
        ::std::assert_eq!(
            project.name(),
            ::std::option::Option::None,
            "a project constructed with no name must report None"
        );
        project.set_name(::std::string::ToString::to_string("my-project"));
        ::std::assert_eq!(
            project.name(),
            ::std::option::Option::Some("my-project"),
            "set_name must be observable through name()"
        );
    }};
}

/// Asserts the `is_changed()` / `set_changed()` round trip generated by
/// [`impl_basic_accessors!`] for the project value produced by `$project`.
///
/// Every language crate had a byte-identical `set_changed` body — build a
/// project, assert it starts unchanged, flip it to `true`, assert, flip it back
/// to `false`, assert — differing only in the concrete type and its manifest
/// path. All eleven exercise the exact same [`impl_basic_accessors!`]
/// expansion, so the assertions live here once and each site supplies only its
/// own constructor.
///
/// Contract: `$project` must evaluate to a freshly constructed value whose
/// `is_changed` starts as `false`, and the `Package` or `Workspace` trait
/// supplying `is_changed()` / `set_changed()` must be in scope at the call site.
#[macro_export]
macro_rules! assert_set_changed_roundtrip {
    ($project:expr) => {{
        let mut project = $project;
        ::std::assert!(
            !project.is_changed(),
            "a freshly constructed project must start unchanged"
        );
        project.set_changed(true);
        ::std::assert!(
            project.is_changed(),
            "set_changed(true) must be observable through is_changed()"
        );
        project.set_changed(false);
        ::std::assert!(
            !project.is_changed(),
            "set_changed(false) must clear is_changed() again"
        );
    }};
}

/// Asserts the `dependencies()` / `add_dependency()` round trip generated by
/// [`impl_dependencies_accessors!`] for the project value produced by
/// `$project`.
///
/// Every language crate had a byte-identical dependencies body — build a
/// project, assert `dependencies()` starts empty, add two names, assert the set
/// has both and a length of two, re-add the first, assert the length is still
/// two — differing only in the concrete type and the two dependency-name
/// literals. All ten exercise the exact same [`impl_dependencies_accessors!`]
/// expansion, including its `contains`-before-`insert` duplicate path, so the
/// assertions live here once and each site supplies only its own constructor
/// and names.
///
/// Contract: `$project` must evaluate to a freshly constructed value whose
/// `dependencies` set starts empty, `$first` and `$second` must be distinct
/// `&str` names, and the `Package` or `Workspace` trait supplying
/// `dependencies()` / `add_dependency()` must be in scope at the call site.
#[macro_export]
macro_rules! assert_dependencies_roundtrip {
    ($project:expr, $first:expr, $second:expr) => {{
        let mut project = $project;
        ::std::assert!(
            project.dependencies().is_empty(),
            "a freshly constructed project must start with no dependencies"
        );
        project.add_dependency($first);
        project.add_dependency($second);
        let deps = project.dependencies();
        ::std::assert_eq!(deps.len(), 2, "both added dependencies must be recorded");
        ::std::assert!(
            deps.contains($first),
            "add_dependency must be observable through dependencies()"
        );
        ::std::assert!(
            deps.contains($second),
            "add_dependency must be observable through dependencies()"
        );
        project.add_dependency($first);
        ::std::assert_eq!(
            project.dependencies().len(),
            2,
            "re-adding an existing dependency must not grow the set"
        );
    }};
}

/// Generates constructors for discovered package/workspace structs with a
/// `publishable_by_default` field.
#[macro_export]
macro_rules! impl_discovered_new {
    () => {
        #[must_use]
        pub fn new(
            name: ::std::option::Option<::std::string::String>,
            version: ::std::option::Option<::std::string::String>,
            path: ::std::path::PathBuf,
            relative_path: ::std::path::PathBuf,
        ) -> Self {
            Self::new_discovered(name, version, path, relative_path, true)
        }

        #[must_use]
        pub(crate) fn new_discovered(
            name: ::std::option::Option<::std::string::String>,
            version: ::std::option::Option<::std::string::String>,
            path: ::std::path::PathBuf,
            relative_path: ::std::path::PathBuf,
            publishable_by_default: ::std::primitive::bool,
        ) -> Self {
            Self {
                name,
                version,
                path,
                relative_path,
                is_changed: false,
                publishable_by_default,
                dependencies: ::std::collections::HashSet::new(),
            }
        }
    };
}

/// Declares a discovered package/workspace struct plus its constructors.
///
/// Five language types — `PythonPackage`, `PythonWorkspace`, `DartPackage`,
/// `DartWorkspace` and `CSharpPackage` — declared the exact same seven private
/// fields (`name`, `version`, `path`, `relative_path`, `is_changed`,
/// `publishable_by_default`, `dependencies`) and each immediately followed the
/// declaration with an inherent impl containing
/// [`impl_discovered_new!`](crate::impl_discovered_new). Those field names are
/// already hard-coded by that constructor macro, so the declarations were not
/// independently variable: this macro makes the coupling explicit and keeps the
/// layout in one place.
///
/// Node, Rust and Java are intentionally NOT expressible here — they carry
/// extra fields (`package_manager`, the workspace-inheritance trio) or lack
/// `publishable_by_default` entirely — and keep their hand-written
/// declarations.
///
/// Additional inherent methods stay in a separate `impl` block beside the
/// invocation (see `CSharpPackage`'s command-runner helpers).
///
/// ```ignore
/// changepacks_core::declare_discovered_project!(
///     /// Doc comments and other outer attributes pass through.
///     pub struct PythonPackage
/// );
/// ```
#[macro_export]
macro_rules! declare_discovered_project {
    ($(#[$meta:meta])* pub struct $name:ident) => {
        $(#[$meta])*
        #[derive(::std::fmt::Debug)]
        pub struct $name {
            name: ::std::option::Option<::std::string::String>,
            version: ::std::option::Option<::std::string::String>,
            path: ::std::path::PathBuf,
            relative_path: ::std::path::PathBuf,
            is_changed: ::std::primitive::bool,
            publishable_by_default: ::std::primitive::bool,
            dependencies: ::std::collections::HashSet<::std::string::String>,
        }

        impl $name {
            $crate::impl_discovered_new!();
        }
    };
}

/// Builds the [`Project`](crate::Project) a finder just discovered, choosing
/// the `Workspace` or `Package` variant from `$is_workspace`.
///
/// Four finders — Node, Python, Dart and Java — ended their `visit()` with the
/// same ten-line `if is_workspace { Project::Workspace(Box::new(WsCtor(..))) }
/// else { Project::Package(Box::new(PkgCtor(..))) }`, and in every copy the
/// argument list was byte-identical in both arms because the finder had
/// already hoisted the shared `name` / `version` / `path_key` bindings above
/// the branch. Only the two constructor paths and that argument list actually
/// vary, so they are what this macro takes.
///
/// Evaluation is unchanged from the hand-written shape: `$is_workspace` is
/// evaluated once, and each `$arg` is evaluated exactly once and only inside
/// the branch that is taken. A `path_key.clone()` argument therefore still
/// performs exactly one `PathBuf` allocation per visit, not two, and the
/// moved-once `name` / `version` bindings keep type-checking because only one
/// arm ever runs.
///
/// Deliberately NOT used by two finders:
/// - `crates/csharp/src/finder.rs` has no workspace variant — it always
///   constructs a `Project::Package`, so there is no branch to factor out.
/// - `crates/rust/src/finder.rs` builds its two variants from separate
///   control-flow blocks with different argument lists, not from one `if/else`
///   over a shared list.
///
/// ```ignore
/// let mut project = changepacks_core::discovered_project!(
///     is_workspace,
///     NodeWorkspace::new_discovered,
///     NodePackage::new_discovered,
///     name,
///     version,
///     path_key.clone(),
///     relative_path_key,
///     package_manager,
///     publishable_by_default,
/// );
/// ```
#[macro_export]
macro_rules! discovered_project {
    ($is_workspace:expr, $ws:path, $pkg:path, $($arg:expr),* $(,)?) => {
        if $is_workspace {
            $crate::Project::Workspace(::std::boxed::Box::new($ws($($arg),*)))
        } else {
            $crate::Project::Package(::std::boxed::Box::new($pkg($($arg),*)))
        }
    };
}

/// Generates `fn language(&self) -> Language` for a fixed language variant.
#[macro_export]
macro_rules! impl_language {
    ($lang:expr) => {
        fn language(&self) -> $crate::Language {
            $lang
        }
    };
}

/// Returns `true` when `path`'s extension matches `ext` case-insensitively
/// (ASCII only).
///
/// Mirrors the `path.extension().and_then(|e| e.to_str()).is_some_and(|e|
/// e.eq_ignore_ascii_case(ext))` idiom used across language crates so the
/// predicate lives in exactly one place. Returns `false` when the path has
/// no extension (including dotfiles such as `.json`, where
/// [`std::path::Path::extension`] returns `None`).
///
/// Public so cross-crate callers (e.g. `changepacks-csharp`,
/// `changepacks-java`, `changepacks-utils`) can reuse it via the re-export
/// from `changepacks_core::lib.rs`.
#[must_use]
pub fn has_extension_ignore_ascii_case(path: &Path, ext: &str) -> bool {
    path.extension()
        .and_then(|e| e.to_str())
        .is_some_and(|e| e.eq_ignore_ascii_case(ext))
}

/// Returns `Ok(true)` when `path` refers to an existing regular file.
///
/// Boolean shorthand over [`regular_file_metadata`], which owns the triage:
/// a missing path or directory returns `Ok(false)`, and other metadata errors
/// are propagated with the failing path in their context.
///
/// Shared between `ProjectFinder::matches_project_file` (name-based match
/// used by every language) and `CSharpProjectFinder::visit` (extension-based
/// match) so the byte-identical stat + `is_file()` fallthrough lives in ONE
/// place. Public so cross-crate callers (e.g. `changepacks-csharp`) can
/// reuse it via the re-export from `changepacks_core::lib.rs`.
///
/// # Errors
/// Propagates any [`regular_file_metadata`] error, i.e. a metadata read that
/// fails for a reason other than the path being absent.
pub async fn is_regular_file(path: &Path) -> Result<bool> {
    Ok(regular_file_metadata(path).await?.is_some())
}

/// Returns `Ok(Some(metadata))` when `path` refers to an existing regular
/// file, and `Ok(None)` when it is missing or is not a regular file.
///
/// This is the single owner of the metadata triage ladder shared by every
/// language crate: `is_file()` decides regular-vs-other,
/// [`std::io::ErrorKind::NotFound`] is normalized to "absent", and any other
/// metadata error is propagated with the failing path in its context.
///
/// [`is_regular_file`] is the boolean shorthand over this function. Callers
/// that additionally need something *from* the same
/// [`std::fs::Metadata`] — e.g. `changepacks-java` reading the Unix
/// permission bits of a `java` candidate — must use this function rather
/// than `is_regular_file` followed by their own `metadata` call, because a
/// second stat is both a wasted syscall and a TOCTOU window.
///
/// AGENTS.md rule: never blocking I/O in async — uses `tokio::fs::metadata`.
///
/// # Errors
/// Returns the underlying `io::Error`, annotated with the failing path, when
/// the metadata read fails for any reason other than
/// [`std::io::ErrorKind::NotFound`].
pub async fn regular_file_metadata(path: &Path) -> Result<Option<std::fs::Metadata>> {
    match tokio::fs::metadata(path).await {
        Ok(metadata) if metadata.is_file() => Ok(Some(metadata)),
        Ok(_) => Ok(None),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(error) => {
            Err(error).with_context(|| format!("Failed to read metadata for {}", path.display()))
        }
    }
}

/// Visitor pattern for discovering projects by walking the git tree.
///
/// Each language implements this trait to detect its project files (package.json, Cargo.toml, etc.)
/// and build a collection of projects. The `visit` method is called for each file in the git tree.
#[async_trait]
pub trait ProjectFinder: std::fmt::Debug + Send + Sync {
    fn projects(&self) -> Vec<&Project>;
    fn projects_mut(&mut self) -> Vec<&mut Project>;
    /// Number of projects held by this finder.
    ///
    /// Required rather than defaulted: a `self.projects().len()` default would
    /// allocate and immediately drop a whole `Vec<&Project>` just to read a
    /// length. Every implementor already owns an O(1), allocation-free count
    /// (the language finders get one from
    /// [`impl_projects_hashmap_accessors!`]), so the trait demands it instead
    /// of offering a lossy shortcut.
    fn project_count(&self) -> usize;
    /// Append every project held by this finder onto `out`.
    ///
    /// Exists for the same reason [`ProjectFinder::project_count`] does:
    /// callers that merge several finders into one buffer (the CLI's
    /// `collect_projects`) would otherwise pay one throwaway `Vec<&Project>`
    /// per finder — allocated by `projects()` and dropped one line later —
    /// on every `check`, `update`, `publish`, and default-changepack run.
    /// Pushing into the caller's buffer removes that per-finder allocation.
    ///
    /// The default body is the compatibility path for external implementors:
    /// it forwards to `projects()`, so an implementor that only supplies the
    /// required accessors keeps compiling and keeps identical behaviour, and
    /// merely forfeits the allocation elision. Implementors backed by a
    /// `HashMap<PathBuf, Project>` get the elided override for free from
    /// [`impl_projects_hashmap_accessors!`].
    ///
    /// Contract for overrides: append in exactly `projects()` order and never
    /// clear or reorder what `out` already holds — callers rely on the merged
    /// order for their output (e.g. `changepacks check`).
    fn extend_projects<'a>(&'a self, out: &mut Vec<&'a Project>) {
        out.extend(self.projects());
    }
    /// Mutable counterpart of [`ProjectFinder::extend_projects`]: append every
    /// project held by this finder onto `out` as `&mut Project`.
    ///
    /// Exists for the same allocation reason: `find_project_dirs`'s no-name
    /// fallback merges every finder's projects into one buffer, and
    /// `flat_map(|f| f.projects_mut())` paid one throwaway `Vec<&mut Project>`
    /// per finder — six of them on every CLI run — allocated by `projects_mut()`
    /// and dropped as soon as the flattening consumed it. Pushing into the
    /// caller's buffer removes that per-finder allocation.
    ///
    /// The default body is the compatibility path for external implementors:
    /// it forwards to `projects_mut()`, so an implementor that only supplies
    /// the required accessors keeps compiling and keeps identical behaviour,
    /// and merely forfeits the allocation elision. Implementors backed by a
    /// `HashMap<PathBuf, Project>` get the elided override for free from
    /// [`impl_projects_hashmap_accessors!`].
    ///
    /// Contract for overrides: append in exactly `projects_mut()` order and
    /// never clear or reorder what `out` already holds.
    fn extend_projects_mut<'a>(&'a mut self, out: &mut Vec<&'a mut Project>) {
        out.extend(self.projects_mut());
    }
    /// Whether a project keyed by exactly `path` has already been discovered
    /// by this finder.
    ///
    /// `path` is the manifest path a `visit()` call was handed — the same
    /// value every finder uses as its storage key — so this is the
    /// "already visited, do not re-parse" probe. It exists so the six
    /// language finders stop reaching into their private `projects` field
    /// from inside `visit()`; the gate now belongs to the trait that defines
    /// the visit protocol.
    ///
    /// The default body is the compatibility path for external implementors,
    /// exactly like [`ProjectFinder::extend_projects`]: it linearly scans
    /// `projects()` for a project whose [`Project::path`] equals `path`, so
    /// an implementor that only supplies the required accessors keeps
    /// compiling and keeps identical behaviour, and merely forfeits the
    /// hashed lookup. Implementors backed by a `HashMap<PathBuf, Project>`
    /// get the O(1) override for free from
    /// [`impl_projects_hashmap_accessors!`].
    fn contains_project(&self, path: &Path) -> bool {
        self.projects()
            .into_iter()
            .any(|project| project.path() == path)
    }
    /// Whether `visit()` should parse `path`, or bail out early.
    ///
    /// This is the two-guard prelude every language finder open-coded at the
    /// top of its `visit()`: `path` must be a manifest this finder claims AND
    /// must not have been discovered already.
    ///
    /// Guard order is deliberate and preserved from the hand-rolled copies:
    /// the name/stat gate ([`ProjectFinder::matches_project_file`]) runs
    /// FIRST and the map probe ([`ProjectFinder::contains_project`]) second.
    /// `&&` short-circuits, so a path that is not a manifest never pays for
    /// the second probe — and, more importantly, the ordering keeps the
    /// error surface unchanged: a metadata error on a recognized manifest
    /// name still propagates even when that path is already known.
    ///
    /// Only finders whose [`ProjectFinder::project_files`] uses the bare
    /// file-name form may gate on this. An extension-based finder (the
    /// `".csproj"` form) must keep its own
    /// [`has_extension_ignore_ascii_case`] + [`is_regular_file`] check and
    /// call [`ProjectFinder::contains_project`] directly, for the reason
    /// spelled out on [`ProjectFinder::matches_project_file`].
    ///
    /// # Errors
    /// Propagates whatever [`ProjectFinder::matches_project_file`] returns.
    ///
    /// Written in the boxed-future shape `#[async_trait]` would produce rather
    /// than as a defaulted `async fn`, for the same reason
    /// [`impl_publish_flows!`] is: the spans `#[async_trait]` puts on a
    /// *defaulted* body are not attributed back to this file by `llvm-cov`, so
    /// such a default reads as permanently unexecuted in coverage even while
    /// tests drive every branch of it. This shape is object safe, stays
    /// overridable by the `#[async_trait]` impls in the language crates, and is
    /// measurable. The three defaults below follow the same rule.
    fn should_visit_manifest<'life0, 'life1, 'async_trait>(
        &'life0 self,
        path: &'life1 Path,
    ) -> ::core::pin::Pin<
        ::std::boxed::Box<
            dyn ::core::future::Future<Output = Result<bool>> + ::core::marker::Send + 'async_trait,
        >,
    >
    where
        'life0: 'async_trait,
        'life1: 'async_trait,
        Self: ::core::marker::Sync + 'async_trait,
    {
        ::std::boxed::Box::pin(async move {
            Ok(self.matches_project_file(path).await? && !self.contains_project(path))
        })
    }
    /// The manifest patterns this finder claims, in one of TWO forms.
    ///
    /// 1. A bare **file name** (`"package.json"`, `"Cargo.toml"`,
    ///    `"pyproject.toml"`, `"pubspec.yaml"`, `"build.gradle.kts"`). Five of
    ///    the six language finders use only this form.
    /// 2. A leading-dot **extension** (`".csproj"`), used when the manifest
    ///    name varies per project. `CSharpProjectFinder` is the only
    ///    in-tree implementor of this form.
    ///
    /// Only the discovery walk understands both: `find_project_dirs`'s
    /// `project_files_can_visit_path` (in `changepacks-utils`) first compares
    /// the entry to `path.file_name()` and, on a miss, retries any entry that
    /// starts with `.` as a case-insensitive extension match.
    ///
    /// The defaulted [`ProjectFinder::matches_project_file`] deliberately
    /// implements ONLY form 1 — it compares `path.file_name()` against this
    /// list — so an extension entry such as `".csproj"` can never match there
    /// (`Path::new("App.csproj").file_name()` is `"App.csproj"`, never
    /// `".csproj"`). An implementor that returns extension entries therefore
    /// MUST NOT gate `visit()` on `matches_project_file`; it must do its own
    /// extension check with [`has_extension_ignore_ascii_case`] plus
    /// [`is_regular_file`], exactly as `CSharpProjectFinder::visit` does.
    ///
    /// The two forms also differ in case sensitivity: a file-name entry is
    /// compared byte-for-byte, while an extension entry matches
    /// case-insensitively (`App.CSPROJ` is accepted).
    fn project_files(&self) -> &[&str];
    /// # Errors
    /// Returns error if the file visitation fails.
    async fn visit(&mut self, path: &Path, relative_path: &Path) -> Result<()>;
    /// Whether `path` is a project manifest file recognized by this finder.
    ///
    /// Returns `false` for directories and files whose name is not in
    /// `project_files()`. Used by language-specific `visit()` implementations
    /// to gate manifest parsing on file-name matching.
    ///
    /// This gate implements ONLY the bare-file-name form of
    /// [`ProjectFinder::project_files`]. A leading-dot extension entry such as
    /// `".csproj"` can never match here, because `path.file_name()` yields the
    /// whole name (`"App.csproj"`) and never the extension alone. That is why
    /// `CSharpProjectFinder` gates `visit()` on
    /// [`has_extension_ignore_ascii_case`] + [`is_regular_file`] instead of
    /// calling this method — any future extension-based finder must do the
    /// same.
    ///
    /// Check order is name-first, stat-last: on a monorepo with N tracked
    /// files where only K match any recognized manifest name (typically
    /// K ≪ N), the previous stat-then-name shape issued 5 × N async
    /// `tokio::fs::metadata` syscalls across every non-CSharp language
    /// finder invocation. Reversing the order collapses that to ~K stats
    /// total. Missing/non-UTF-8 file names cannot possibly match ASCII
    /// manifest names anyway, so returning `Ok(false)` early is
    /// semantically identical to the previous `with_context` error paths
    /// — which were unreachable for git-index-derived paths.
    ///
    /// # Errors
    /// Returns an error when metadata for a recognized manifest path cannot be
    /// read for a reason other than the path not existing.
    fn matches_project_file<'life0, 'life1, 'async_trait>(
        &'life0 self,
        path: &'life1 Path,
    ) -> ::core::pin::Pin<
        ::std::boxed::Box<
            dyn ::core::future::Future<Output = Result<bool>> + ::core::marker::Send + 'async_trait,
        >,
    >
    where
        'life0: 'async_trait,
        'life1: 'async_trait,
        Self: ::core::marker::Sync + 'async_trait,
    {
        ::std::boxed::Box::pin(async move {
            let Some(name_os) = path.file_name() else {
                return Ok(false);
            };
            let Some(name) = name_os.to_str() else {
                return Ok(false);
            };
            if !self.project_files().contains(&name) {
                return Ok(false);
            }
            is_regular_file(path).await
        })
    }
    /// Mark every project against every path in `paths` from ONE
    /// `projects_mut()` call.
    ///
    /// The driver dispatches every changed file to every finder. Rebuilding
    /// the `Vec<&mut Project>` via `projects_mut()` once per file would cost
    /// `F` changed files × `M` finders fresh Vec allocations. Collecting the
    /// paths once and looping project-major here collapses that to one Vec per
    /// finder (`M` total).
    ///
    /// The project-major / path-major order flip is behavior-preserving:
    /// [`Project::check_changed`] is monotonic — it early-returns once the
    /// project is already changed and only ever sets `changed = true` via the
    /// pure, stateless `should_mark_changed`. A project ends up changed iff
    /// *any* path matches, an order-independent logical OR, so visiting all
    /// paths for one project before moving to the next yields an identical
    /// result to a path-major traversal.
    ///
    /// # Errors
    /// Returns error if checking changed status fails for any project.
    fn check_changed_many(&mut self, paths: &[PathBuf]) -> Result<()> {
        for project in self.projects_mut() {
            for path in paths {
                project.check_changed(path)?;
                // Early break: check_changed is monotonic, so once changed, remaining paths are redundant.
                if project.is_changed() {
                    break;
                }
            }
        }
        Ok(())
    }
    /// Post-visit processing hook for resolving deferred state (e.g., workspace-inherited versions).
    /// Called once after all `visit()` calls complete.
    /// # Errors
    /// Returns error if finalization fails.
    fn finalize<'life0, 'async_trait>(
        &'life0 mut self,
    ) -> ::core::pin::Pin<
        ::std::boxed::Box<
            dyn ::core::future::Future<Output = Result<()>> + ::core::marker::Send + 'async_trait,
        >,
    >
    where
        'life0: 'async_trait,
        Self: ::core::marker::Send + 'async_trait,
    {
        ::std::boxed::Box::pin(async move { Ok(()) })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_support::{MockPackage, MockWorkspace};
    use crate::{Package, Workspace};
    use async_trait::async_trait;
    use rstest::rstest;
    use std::path::PathBuf;

    // `Path::new(".json").extension()` returns `None` in Rust — dotfiles have
    // no extension — so `has_extension_ignore_ascii_case(Path::new(".json"), "json")`
    // is `false`. This matches the behaviour of every call site that wraps a
    // bare filename with `Path::new(file_name)`.
    #[rstest]
    #[case("foo.json", "json", true)]
    #[case("foo.JSON", "json", true)]
    #[case("foo.Json", "json", true)]
    #[case("foo", "json", false)]
    #[case(".json", "json", false)]
    #[case("foo.jsonx", "json", false)]
    fn test_has_extension_ignore_ascii_case(
        #[case] file: &str,
        #[case] ext: &str,
        #[case] expected: bool,
    ) {
        assert_eq!(
            has_extension_ignore_ascii_case(Path::new(file), ext),
            expected,
            "has_extension_ignore_ascii_case(Path::new({file:?}), {ext:?})"
        );
    }

    // `add_dependency` now probes `contains` before allocating. These cases
    // lock the observable contract the probe must not change: a repeated name
    // is still stored exactly once, and distinct names all still land.
    #[test]
    fn test_add_dependency_deduplicates_repeated_names() {
        let mut package = MockPackage::same_path("pkg", "/project/package.json");

        // The duplicate path: the same name arrives from two manifest sections.
        package.add_dependency("serde");
        package.add_dependency("serde");
        package.add_dependency("serde");

        assert_eq!(
            package.dependencies().len(),
            1,
            "repeated add_dependency must keep exactly one entry"
        );
        assert!(package.dependencies().contains("serde"));

        // Distinct names still insert normally (the miss path is unchanged).
        package.add_dependency("tokio");
        package.add_dependency("anyhow");
        package.add_dependency("tokio");

        let mut names = package.dependencies().iter().cloned().collect::<Vec<_>>();
        names.sort();
        assert_eq!(names, vec!["anyhow", "serde", "tokio"]);
    }

    #[test]
    fn test_add_dependency_deduplicates_on_workspace_too() {
        // The macro backs both the Package and the Workspace impls of all six
        // language crates, so pin the behaviour at the Workspace surface as well.
        let mut workspace = MockWorkspace::same_path("root", "/project/package.json");

        workspace.add_dependency("left-pad");
        workspace.add_dependency("left-pad");

        assert_eq!(workspace.dependencies().len(), 1);
        assert!(workspace.dependencies().contains("left-pad"));
    }

    #[derive(Debug)]
    struct MockProjectFinder {
        projects: Vec<Project>,
    }

    impl MockProjectFinder {
        fn new() -> Self {
            Self { projects: vec![] }
        }

        fn with_package(mut self, package: MockPackage) -> Self {
            self.projects.push(Project::Package(Box::new(package)));
            self
        }

        fn with_workspace(mut self, workspace: MockWorkspace) -> Self {
            self.projects.push(Project::Workspace(Box::new(workspace)));
            self
        }
    }

    #[async_trait]
    impl ProjectFinder for MockProjectFinder {
        fn projects(&self) -> Vec<&Project> {
            self.projects.iter().collect()
        }

        fn projects_mut(&mut self) -> Vec<&mut Project> {
            self.projects.iter_mut().collect()
        }

        fn project_count(&self) -> usize {
            self.projects.len()
        }

        fn project_files(&self) -> &[&str] {
            &["package.json"]
        }

        async fn visit(&mut self, _path: &Path, _relative_path: &Path) -> Result<()> {
            Ok(())
        }
    }

    /// HashMap-backed finder that takes its accessors from
    /// [`impl_projects_hashmap_accessors!`], so the macro's `extend_projects`
    /// override is exercised inside `core` (the six language finders use the
    /// exact same expansion).
    #[derive(Debug)]
    struct HashMapProjectFinder {
        projects: std::collections::HashMap<PathBuf, Project>,
    }

    impl HashMapProjectFinder {
        fn with_packages(names: &[(&str, &str)]) -> Self {
            let mut projects = std::collections::HashMap::new();
            for (name, path) in names {
                projects.insert(
                    PathBuf::from(*path),
                    Project::Package(Box::new(MockPackage::same_path(name, path))),
                );
            }
            Self { projects }
        }
    }

    #[async_trait]
    impl ProjectFinder for HashMapProjectFinder {
        crate::impl_projects_hashmap_accessors!();

        fn project_files(&self) -> &[&str] {
            &["package.json"]
        }

        async fn visit(&mut self, _path: &Path, _relative_path: &Path) -> Result<()> {
            Ok(())
        }
    }

    // Accepts both `&[&Project]` and `&[&mut Project]` buffers: std provides
    // `Borrow<T>` for `&T` and `&mut T` alike, so the shared/mutable
    // `extend_projects` twins can assert against one helper.
    fn project_names<P: std::borrow::Borrow<Project>>(projects: &[P]) -> Vec<String> {
        projects
            .iter()
            .map(|project| project.borrow().name().unwrap_or_default().to_string())
            .collect()
    }

    // The defaulted `extend_projects` body is the compatibility path for
    // external implementors: `MockProjectFinder` does NOT override it, so this
    // pins that the default appends exactly `projects()`, in `projects()`
    // order, without disturbing what the buffer already holds.
    #[test]
    fn test_extend_projects_default_matches_projects_and_preserves_buffer() {
        let finder = MockProjectFinder::new()
            .with_package(MockPackage::same_path("pkg1", "/project1/package.json"))
            .with_workspace(MockWorkspace::same_path("root", "/project2/package.json"))
            .with_package(MockPackage::same_path("pkg2", "/project3/package.json"));

        let seed = MockProjectFinder::new()
            .with_package(MockPackage::same_path("seed", "/seed/package.json"));
        let mut out = seed.projects();
        finder.extend_projects(&mut out);

        let mut expected = vec!["seed".to_string()];
        expected.extend(project_names(&finder.projects()));
        assert_eq!(project_names(&out), expected);
    }

    #[test]
    fn test_extend_projects_default_on_empty_finder_is_a_no_op() {
        let finder = MockProjectFinder::new();
        let mut out: Vec<&Project> = Vec::new();
        finder.extend_projects(&mut out);
        assert!(out.is_empty());
    }

    // Mutable twin of the test above: `MockProjectFinder` does NOT override
    // `extend_projects_mut`, so this pins that the default appends exactly
    // `projects_mut()`, in `projects_mut()` order, without disturbing what the
    // buffer already holds — the contract `find_project_dirs`'s no-name
    // fallback relies on when it merges every finder into one buffer.
    #[test]
    fn test_extend_projects_mut_default_matches_projects_and_preserves_buffer() {
        let mut finder = MockProjectFinder::new()
            .with_package(MockPackage::same_path("pkg1", "/project1/package.json"))
            .with_workspace(MockWorkspace::same_path("root", "/project2/package.json"))
            .with_package(MockPackage::same_path("pkg2", "/project3/package.json"));

        let mut seed = MockProjectFinder::new()
            .with_package(MockPackage::same_path("seed", "/seed/package.json"));
        let mut out = seed.projects_mut();
        finder.extend_projects_mut(&mut out);
        let names = project_names(&out);
        drop(out);

        let mut expected = vec!["seed".to_string()];
        expected.extend(project_names(&finder.projects()));
        assert_eq!(names, expected);
    }

    #[test]
    fn test_extend_projects_mut_default_on_empty_finder_is_a_no_op() {
        let mut finder = MockProjectFinder::new();
        let mut out: Vec<&mut Project> = Vec::new();
        finder.extend_projects_mut(&mut out);
        assert!(out.is_empty());
    }

    // The macro override skips the intermediate Vec that `projects()` builds;
    // both must still yield the same projects in the same `HashMap::values()`
    // order, so a caller can swap one for the other without reordering output.
    #[test]
    fn test_extend_projects_macro_override_matches_projects_order() {
        let finder = HashMapProjectFinder::with_packages(&[
            ("pkg1", "/project1/package.json"),
            ("pkg2", "/project2/package.json"),
            ("pkg3", "/project3/package.json"),
        ]);

        let mut out: Vec<&Project> = Vec::new();
        finder.extend_projects(&mut out);

        assert_eq!(out.len(), finder.project_count());
        assert_eq!(project_names(&out), project_names(&finder.projects()));
    }

    // Same equivalence for the mutable override: `HashMap::values_mut()` and
    // `HashMap::values()` walk one unmodified map in the same order, so the
    // elided body must yield exactly what `projects_mut()` would have.
    #[test]
    fn test_extend_projects_mut_macro_override_matches_projects_order() {
        let mut finder = HashMapProjectFinder::with_packages(&[
            ("pkg1", "/project1/package.json"),
            ("pkg2", "/project2/package.json"),
            ("pkg3", "/project3/package.json"),
        ]);

        let mut out: Vec<&mut Project> = Vec::new();
        finder.extend_projects_mut(&mut out);
        let out_len = out.len();
        let names = project_names(&out);
        drop(out);

        assert_eq!(out_len, finder.project_count());
        assert_eq!(names, project_names(&finder.projects_mut()));
    }

    // The borrows handed out must alias the finder's own storage: mutating a
    // project through the merged buffer has to be visible on the finder
    // afterwards, which is exactly what the no-name `set_name` fallback does.
    #[test]
    fn test_extend_projects_mut_yields_borrows_that_mutate_the_finder() {
        let mut finder = HashMapProjectFinder::with_packages(&[("pkg1", "/project1/package.json")]);

        let mut out: Vec<&mut Project> = Vec::new();
        finder.extend_projects_mut(&mut out);
        for project in &mut out {
            project.set_name("renamed".to_string());
        }
        drop(out);

        assert_eq!(project_names(&finder.projects()), vec!["renamed"]);
    }

    // `contains_project` has the same two-body shape as `extend_projects`: a
    // defaulted linear scan for external implementors and a hashed override
    // from the macro. `MockProjectFinder` does NOT override it, so this pins
    // the compatibility path — hit on the exact stored manifest path, miss on
    // an unknown one and on a merely-similar one.
    #[test]
    fn test_contains_project_default_scans_projects_by_path() {
        let finder = MockProjectFinder::new()
            .with_package(MockPackage::same_path("pkg1", "/project1/package.json"))
            .with_workspace(MockWorkspace::same_path("root", "/project2/package.json"));

        assert!(finder.contains_project(Path::new("/project1/package.json")));
        // Workspace projects count too, not just packages.
        assert!(finder.contains_project(Path::new("/project2/package.json")));
        assert!(!finder.contains_project(Path::new("/project3/package.json")));
        // The probe keys on the whole manifest path, never on the directory.
        assert!(!finder.contains_project(Path::new("/project1")));
    }

    #[test]
    fn test_contains_project_default_on_empty_finder_is_always_false() {
        let finder = MockProjectFinder::new();
        assert!(!finder.contains_project(Path::new("/project1/package.json")));
    }

    // The macro override must answer identically to the default for every
    // probe — that equivalence is what lets the six language finders swap
    // their open-coded `self.projects.contains_key(path)` for the trait
    // method without changing behaviour.
    #[test]
    fn test_contains_project_macro_override_matches_default_answers() {
        let entries = [
            ("pkg1", "/project1/package.json"),
            ("pkg2", "/project2/package.json"),
        ];
        let hashed = HashMapProjectFinder::with_packages(&entries);
        let mut scanned = MockProjectFinder::new();
        for (name, path) in entries {
            scanned = scanned.with_package(MockPackage::same_path(name, path));
        }

        for probe in [
            "/project1/package.json",
            "/project2/package.json",
            "/project3/package.json",
            "/project1",
            "",
        ] {
            assert_eq!(
                hashed.contains_project(Path::new(probe)),
                scanned.contains_project(Path::new(probe)),
                "hashed and scanned answers diverged for {probe:?}"
            );
        }
    }

    // `should_visit_manifest` is the consolidated two-guard prelude. Its
    // documented order is name/stat gate FIRST, already-discovered probe
    // SECOND, and it returns `true` only when both agree the manifest is new.
    #[tokio::test]
    async fn test_should_visit_manifest_accepts_new_recognized_manifest() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let manifest = temp_dir.path().join("package.json");
        std::fs::write(&manifest, "{}").unwrap();

        let finder = MockProjectFinder::new();
        assert!(finder.should_visit_manifest(&manifest).await.unwrap());
    }

    // The duplicate-visit half: same manifest, but already discovered.
    #[tokio::test]
    async fn test_should_visit_manifest_rejects_already_discovered_manifest() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let manifest = temp_dir.path().join("package.json");
        std::fs::write(&manifest, "{}").unwrap();

        let finder = MockProjectFinder::new()
            .with_package(MockPackage::same_path("pkg", manifest.to_str().unwrap()));
        assert!(
            !finder.should_visit_manifest(&manifest).await.unwrap(),
            "a manifest already in the finder must not be visited twice"
        );
    }

    // The name/stat half: an unrecognized name and a directory that merely
    // shares a manifest name are both rejected before anything is parsed.
    #[tokio::test]
    async fn test_should_visit_manifest_rejects_non_manifest_and_directory() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let other = temp_dir.path().join("Cargo.toml");
        std::fs::write(&other, "[package]\n").unwrap();
        let dir_path = temp_dir.path().join("package.json");
        std::fs::create_dir(&dir_path).unwrap();

        let finder = MockProjectFinder::new();
        assert!(!finder.should_visit_manifest(&other).await.unwrap());
        assert!(!finder.should_visit_manifest(&dir_path).await.unwrap());
    }

    // Equivalence with the hand-rolled prelude the language finders used to
    // open-code: `matches_project_file(path)? && !contains_project(path)`.
    #[tokio::test]
    async fn test_should_visit_manifest_equals_the_open_coded_two_guard_prelude() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let manifest = temp_dir.path().join("package.json");
        std::fs::write(&manifest, "{}").unwrap();
        let unrecognized = temp_dir.path().join("Cargo.toml");
        std::fs::write(&unrecognized, "[package]\n").unwrap();
        let missing = temp_dir.path().join("nested").join("package.json");

        let known = MockProjectFinder::new()
            .with_package(MockPackage::same_path("pkg", manifest.to_str().unwrap()));
        let empty = MockProjectFinder::new();

        for finder in [&known, &empty] {
            for probe in [&manifest, &unrecognized, &missing] {
                let open_coded = finder.matches_project_file(probe).await.unwrap()
                    && !finder.contains_project(probe);
                assert_eq!(
                    finder.should_visit_manifest(probe).await.unwrap(),
                    open_coded,
                    "consolidated gate diverged from the open-coded prelude for {}",
                    probe.display()
                );
            }
        }
    }

    #[test]
    fn test_extend_projects_macro_override_preserves_existing_buffer_contents() {
        let first = HashMapProjectFinder::with_packages(&[("pkg1", "/project1/package.json")]);
        let second = HashMapProjectFinder::with_packages(&[("pkg2", "/project2/package.json")]);

        // Mirrors the CLI's `collect_projects`: one buffer, several finders.
        let mut out: Vec<&Project> = Vec::new();
        first.extend_projects(&mut out);
        second.extend_projects(&mut out);

        assert_eq!(project_names(&out), vec!["pkg1", "pkg2"]);
    }

    #[test]
    fn test_extend_projects_mut_macro_override_preserves_existing_buffer_contents() {
        let mut first = HashMapProjectFinder::with_packages(&[("pkg1", "/project1/package.json")]);
        let mut second = HashMapProjectFinder::with_packages(&[("pkg2", "/project2/package.json")]);

        // Mirrors `find_project_dirs`'s no-name fallback: one buffer, several finders.
        let mut out: Vec<&mut Project> = Vec::new();
        first.extend_projects_mut(&mut out);
        second.extend_projects_mut(&mut out);

        assert_eq!(project_names(&out), vec!["pkg1", "pkg2"]);
    }

    #[test]
    fn test_project_finder_check_changed() {
        let package = MockPackage::same_path("test", "/project/package.json");
        let mut finder = MockProjectFinder::new().with_package(package);

        // Check a file that's in the project directory
        finder
            .check_changed_many(&[PathBuf::from("/project/src/index.js")])
            .unwrap();

        // The project should be marked as changed
        assert!(finder.projects()[0].is_changed());
    }

    #[test]
    fn test_project_finder_check_changed_multiple_projects() {
        let package1 = MockPackage::same_path("pkg1", "/project1/package.json");
        let package2 = MockPackage::same_path("pkg2", "/project2/package.json");
        let mut finder = MockProjectFinder::new()
            .with_package(package1)
            .with_package(package2);

        // Check a file in project1 only
        finder
            .check_changed_many(&[PathBuf::from("/project1/src/index.js")])
            .unwrap();

        // Only project1 should be changed
        assert!(finder.projects()[0].is_changed());
        assert!(!finder.projects()[1].is_changed());
    }

    #[test]
    fn test_project_finder_check_changed_many() {
        let package1 = MockPackage::same_path("pkg1", "/project1/package.json");
        let package2 = MockPackage::same_path("pkg2", "/project2/package.json");
        let workspace = MockWorkspace::same_path("root", "/project3/package.json");
        let mut finder = MockProjectFinder::new()
            .with_package(package1)
            .with_package(package2)
            .with_workspace(workspace);

        // One batch: a file under project1 and a file under project3 (the
        // workspace); nothing under project2. `check_changed_many` must mark
        // exactly project1 and project3 — a project is marked changed iff any
        // path matches it, proving the project-major loop order is
        // behavior-preserving across both Package and Workspace variants.
        let paths = [
            PathBuf::from("/project1/src/index.js"),
            PathBuf::from("/project3/lib/mod.rs"),
        ];
        finder.check_changed_many(&paths).unwrap();

        assert!(finder.projects()[0].is_changed());
        assert!(!finder.projects()[1].is_changed());
        assert!(finder.projects()[2].is_changed());
    }

    #[test]
    fn test_project_finder_check_changed_many_matches_per_file_traversal() {
        // The same inputs fed one-at-a-time (each path its own single-element
        // batch, mirroring a per-file traversal) and fed together in ONE batch
        // must land the two finders in an identical changed-state, locking the
        // order/batch equivalence the driver relies on.
        let paths = [
            PathBuf::from("/project1/src/index.js"),
            PathBuf::from("/project2/README.md"),
        ];

        let mut per_path = MockProjectFinder::new()
            .with_package(MockPackage::same_path("pkg1", "/project1/package.json"))
            .with_package(MockPackage::same_path("pkg2", "/project2/package.json"));
        for path in &paths {
            per_path
                .check_changed_many(std::slice::from_ref(path))
                .unwrap();
        }

        let mut batched = MockProjectFinder::new()
            .with_package(MockPackage::same_path("pkg1", "/project1/package.json"))
            .with_package(MockPackage::same_path("pkg2", "/project2/package.json"));
        batched.check_changed_many(&paths).unwrap();

        assert_eq!(
            per_path.projects()[0].is_changed(),
            batched.projects()[0].is_changed()
        );
        assert_eq!(
            per_path.projects()[1].is_changed(),
            batched.projects()[1].is_changed()
        );
        assert!(batched.projects()[0].is_changed());
        assert!(batched.projects()[1].is_changed());
    }

    #[test]
    fn test_project_finder_with_workspace() {
        let workspace = MockWorkspace::same_path("root", "/project/package.json");
        let mut finder = MockProjectFinder::new().with_workspace(workspace);

        finder
            .check_changed_many(&[PathBuf::from("/project/src/index.js")])
            .unwrap();

        assert!(finder.projects()[0].is_changed());
    }

    // Every other `check_changed_many` test ends in `unwrap`, so the `?` on
    // `project.check_changed(path)` inside the defaulted body was never
    // exercised on its failing branch. The only way that call can fail is
    // `should_mark_changed` finding no parent directory for the project
    // manifest, so a project rooted at `/` — whose `Path::parent()` is `None`
    // on both Windows and Unix — reaches it. The batch loop must surface that
    // error instead of swallowing it and reporting the project as unchanged.
    #[test]
    fn test_project_finder_check_changed_many_propagates_check_changed_error() {
        let mut finder = MockProjectFinder::new().with_package(MockPackage::same_path("root", "/"));

        let error = finder
            .check_changed_many(&[PathBuf::from("/src/index.js")])
            .expect_err("a manifest without a parent directory must fail the batch");

        let chain = format!("{error:#}");
        assert!(
            chain.contains("Parent not found"),
            "error chain should carry the missing-parent context, got: {chain}"
        );
        assert!(
            !finder.projects()[0].is_changed(),
            "a project whose check_changed failed must not be reported as changed"
        );
    }

    #[test]
    fn project_finder_entry_points_are_included_in_coverage() {
        assert!(
            !include_str!("project_finder.rs")
                .contains(concat!("#[cfg(not(", "tarpaulin_include))]"))
        );
    }

    #[tokio::test]
    async fn test_default_project_finder_finalize_is_covered_no_op() {
        let mut finder = MockProjectFinder::new();
        let result = finder.finalize().await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_is_regular_file_with_existing_file() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let file_path = temp_dir.path().join("test.txt");
        std::fs::write(&file_path, "test content").unwrap();

        let result = is_regular_file(&file_path).await;
        assert!(result.unwrap());
    }

    #[tokio::test]
    async fn test_is_regular_file_with_directory() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let dir_path = temp_dir.path().join("subdir");
        std::fs::create_dir(&dir_path).unwrap();

        let result = is_regular_file(&dir_path).await;
        assert!(!result.unwrap());
    }

    #[tokio::test]
    async fn test_is_regular_file_with_missing_path() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let missing_path = temp_dir.path().join("nonexistent.txt");

        let result = is_regular_file(&missing_path).await;
        assert!(!result.unwrap());
    }

    #[tokio::test]
    async fn test_is_regular_file_propagates_metadata_error_with_path_context() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        #[cfg(windows)]
        let invalid_path = temp_dir.path().join("invalid\0path");
        #[cfg(unix)]
        let invalid_path = {
            use std::os::unix::fs::symlink;

            let path = temp_dir.path().join("metadata-loop");
            symlink(&path, &path).unwrap();
            path
        };

        let error = is_regular_file(&invalid_path)
            .await
            .expect_err("metadata errors other than NotFound must be propagated");
        let chain = format!("{error:#}");
        assert!(
            chain.contains(&invalid_path.display().to_string()),
            "error chain should name the path whose metadata failed, got: {chain}"
        );
    }

    // `regular_file_metadata` is the ladder `is_regular_file` and the Java
    // executable probe both sit on, and it is the only one of the two that
    // hands the caller the stat'ed `Metadata`. These cases pin that extra
    // guarantee: the returned metadata must describe the file itself, and the
    // non-file exits must stay indistinguishable `None`s.
    #[tokio::test]
    async fn test_regular_file_metadata_returns_metadata_for_existing_file() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let file_path = temp_dir.path().join("test.txt");
        std::fs::write(&file_path, "test content").unwrap();

        let metadata = regular_file_metadata(&file_path)
            .await
            .unwrap()
            .expect("an existing regular file must yield its metadata");
        assert!(metadata.is_file());
        assert_eq!(metadata.len(), "test content".len() as u64);
    }

    #[tokio::test]
    async fn test_regular_file_metadata_returns_none_for_directory_and_missing_path() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let dir_path = temp_dir.path().join("subdir");
        std::fs::create_dir(&dir_path).unwrap();

        assert!(regular_file_metadata(&dir_path).await.unwrap().is_none());
        assert!(
            regular_file_metadata(&temp_dir.path().join("nonexistent.txt"))
                .await
                .unwrap()
                .is_none()
        );
    }

    #[tokio::test]
    async fn test_regular_file_metadata_propagates_error_with_path_context() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        #[cfg(windows)]
        let invalid_path = temp_dir.path().join("invalid\0path");
        #[cfg(unix)]
        let invalid_path = {
            use std::os::unix::fs::symlink;

            let path = temp_dir.path().join("metadata-loop");
            symlink(&path, &path).unwrap();
            path
        };

        let error = regular_file_metadata(&invalid_path)
            .await
            .expect_err("metadata errors other than NotFound must be propagated");
        let chain = format!("{error:#}");
        assert!(
            chain.contains(&format!(
                "Failed to read metadata for {}",
                invalid_path.display()
            )),
            "error chain should carry the shared metadata context, got: {chain}"
        );
    }

    // `matches_project_file` is the defaulted gate every non-CSharp language
    // finder calls before parsing a manifest. `MockProjectFinder::project_files`
    // returns exactly `["package.json"]`, so these cases pin all four exits of
    // its documented name-first / stat-last order.

    // Exit 4 (the only `true`): recognized name AND a real regular file.
    #[tokio::test]
    async fn test_matches_project_file_accepts_recognized_regular_file() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let manifest = temp_dir.path().join("package.json");
        std::fs::write(&manifest, "{}").unwrap();

        let finder = MockProjectFinder::new();
        assert!(
            finder.matches_project_file(&manifest).await.unwrap(),
            "a real file named package.json must be recognized"
        );
    }

    // Exit 4 again, negative half: the name matches but the entry is a
    // DIRECTORY, so the stat must veto it. This is why the stat cannot simply
    // be dropped once the name check is in place.
    #[tokio::test]
    async fn test_matches_project_file_rejects_directory_with_recognized_name() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let dir_path = temp_dir.path().join("package.json");
        std::fs::create_dir(&dir_path).unwrap();

        let finder = MockProjectFinder::new();
        assert!(
            !finder.matches_project_file(&dir_path).await.unwrap(),
            "a directory named package.json must not be treated as a manifest"
        );
    }

    // Exit 3: an unrecognized name is rejected even though the file really
    // exists — the name guard, not the stat, is what filters it out.
    #[tokio::test]
    async fn test_matches_project_file_rejects_unrecognized_name() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let other = temp_dir.path().join("Cargo.toml");
        std::fs::write(&other, "[package]\n").unwrap();

        let finder = MockProjectFinder::new();
        assert!(
            !finder.matches_project_file(&other).await.unwrap(),
            "Cargo.toml is not in this finder's project_files()"
        );
    }

    // Exit 1: `file_name()` is `None` for a path ending in `..`, even though
    // that path resolves to an existing directory. The early return must fire
    // before any stat.
    #[tokio::test]
    async fn test_matches_project_file_rejects_path_without_file_name() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let parent_ref = temp_dir.path().join("..");
        assert!(parent_ref.file_name().is_none());

        let finder = MockProjectFinder::new();
        assert!(
            !finder.matches_project_file(&parent_ref).await.unwrap(),
            "a path with no file name cannot match a manifest name"
        );
    }

    // Exit 2: `to_str()` is `None` for a non-UTF-8 file name. Such a name
    // cannot equal any ASCII manifest name, so the guard must short-circuit to
    // `Ok(false)` before any stat — exactly what the method doc reasons about.
    // The path deliberately does not exist: the early return fires first.
    #[tokio::test]
    async fn test_matches_project_file_rejects_non_utf8_file_name() {
        #[cfg(unix)]
        let name: std::ffi::OsString = {
            use std::os::unix::ffi::OsStrExt;
            std::ffi::OsStr::from_bytes(b"\xFF\xFEpackage.json").to_os_string()
        };
        #[cfg(windows)]
        let name: std::ffi::OsString = {
            use std::os::windows::ffi::OsStringExt;
            // Unpaired high surrogate — unrepresentable in UTF-8.
            std::ffi::OsString::from_wide(&[0xD800, u16::from(b'x')])
        };

        // Stay honest if a platform ever normalizes the name away.
        assert!(
            Path::new(&name)
                .file_name()
                .and_then(std::ffi::OsStr::to_str)
                .is_none(),
            "fixture must really be a non-UTF-8 file name"
        );

        let temp_dir = tempfile::TempDir::new().unwrap();
        let path = temp_dir.path().join(&name);

        let finder = MockProjectFinder::new();
        assert!(
            !finder.matches_project_file(&path).await.unwrap(),
            "a non-UTF-8 file name cannot match an ASCII manifest name"
        );
    }

    /// Finder that returns the leading-dot EXTENSION form of
    /// [`ProjectFinder::project_files`], the same shape `CSharpProjectFinder`
    /// uses.
    #[derive(Debug)]
    struct ExtensionProjectFinder;

    #[async_trait]
    impl ProjectFinder for ExtensionProjectFinder {
        fn projects(&self) -> Vec<&Project> {
            vec![]
        }

        fn projects_mut(&mut self) -> Vec<&mut Project> {
            vec![]
        }

        fn project_count(&self) -> usize {
            0
        }

        fn project_files(&self) -> &[&str] {
            &[".csproj"]
        }

        async fn visit(&mut self, _path: &Path, _relative_path: &Path) -> Result<()> {
            Ok(())
        }
    }

    // Pins the documented half of the dual contract: the defaulted
    // `matches_project_file` implements ONLY the bare-file-name form, so an
    // extension entry can never match through it — not even for a real
    // `.csproj` file on disk, in any casing. This is exactly why
    // `CSharpProjectFinder::visit` gates on `has_extension_ignore_ascii_case`
    // + `is_regular_file` instead of calling this method; if that ever
    // changed, C# discovery would silently stop finding projects.
    #[tokio::test]
    async fn test_matches_project_file_never_matches_an_extension_entry() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let finder = ExtensionProjectFinder;

        for name in ["App.csproj", "App.CSPROJ"] {
            let manifest = temp_dir.path().join(name);
            std::fs::write(&manifest, "<Project/>").unwrap();

            assert!(
                !finder.matches_project_file(&manifest).await.unwrap(),
                "{name} must not match through the file-name-only gate"
            );
            // The extension-aware check is the one that accepts it.
            assert!(has_extension_ignore_ascii_case(&manifest, "csproj"));
            assert!(is_regular_file(&manifest).await.unwrap());
        }
    }

    // Recognized name, nothing on disk: `is_regular_file` maps NotFound to
    // `Ok(false)` rather than an error, so the gate stays quiet for deleted
    // manifests still listed in the git index.
    #[tokio::test]
    async fn test_matches_project_file_rejects_missing_manifest() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let missing = temp_dir.path().join("package.json");

        let finder = MockProjectFinder::new();
        assert!(
            !finder.matches_project_file(&missing).await.unwrap(),
            "a package.json that does not exist must not match"
        );
    }
}