changepacks-java 0.3.3

Java/Gradle project support for changepacks
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
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
use anyhow::{Context, Result};
use async_trait::async_trait;
use changepacks_core::{Project, ProjectFinder, manifest_parent_dir};
#[cfg(test)]
use std::process::Stdio;
use std::{
    collections::HashMap,
    ffi::{OsStr, OsString},
    path::{Path, PathBuf},
};
use tokio::process::Command;

use crate::{
    gradle_dependency_lexer::extract_gradle_project_dependencies,
    gradle_metadata::{GradleProperties, GradleWrapperMetadata, get_gradle_metadata},
    package::GradlePackage,
    read_gradle_build_file,
    version_lexer::gradle_dialect_for,
    workspace::GradleWorkspace,
};

/// Manifest filenames this finder recognizes. Static because the list is
/// compile-time constant — no per-instance heap `Vec` is needed and the
/// `ProjectFinder::project_files` return type (`&[&str]`) already accepts
/// a `&'static [&'static str]`.
const PROJECT_FILES: &[&str] = &["build.gradle.kts", "build.gradle"];

/// OS-specific Java executable filename, used by `which_java_in` and
/// `java_home_has_java` to avoid repeating the `cfg!(windows)` branch.
#[cfg(windows)]
const JAVA_EXECUTABLE: &str = "java.exe";
#[cfg(not(windows))]
const JAVA_EXECUTABLE: &str = "java";

#[derive(Debug, Default)]
pub struct GradleProjectFinder {
    projects: HashMap<PathBuf, Project>,
    java_available: Option<bool>,
    metadata_by_wrapper: HashMap<PathBuf, GradleWrapperMetadata>,
    /// Raw `gradlew_dir` (as returned by `find_gradlew`) to its canonicalized
    /// form. Every subproject of a Gradle monorepo resolves to the SAME wrapper
    /// root, so without this cache each visited manifest repeats an identical
    /// `canonicalize` syscall just to build the `metadata_by_wrapper` key.
    wrapper_dir_canonical: HashMap<PathBuf, PathBuf>,
}

impl GradleProjectFinder {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Resolve the repository-bounded Gradle wrapper for `manifest_path` and make
    /// sure this finder holds that wrapper's batched metadata.
    ///
    /// Owns the three cache-shaped steps of discovery: the bounded `find_gradlew`
    /// ancestor walk, the `wrapper_dir_canonical` memoization of the wrapper root,
    /// and the one-shot `metadata_by_wrapper` fill. Returns the normalized wrapper
    /// root (the `metadata_by_wrapper` key) together with the wrapper path, which
    /// the caller still needs for its error context.
    async fn resolve_wrapper_metadata(
        &mut self,
        manifest_path: &Path,
        project_dir: &Path,
        relative_path: &Path,
        java_available: bool,
    ) -> Result<(PathBuf, PathBuf)> {
        // Bound the gradlew search to the repository root: `relative_path` is
        // the build file's path relative to the git repo root, so its component
        // count equals the number of directories from `project_dir` up to and
        // INCLUDING the repo root (root project: `build.gradle.kts` → count 1 →
        // check `project_dir` only). This stops the ancestor walk at the repo
        // boundary so an out-of-repo `gradlew` is never discovered or executed.
        // Mirrors the C# finder's `is_workspace` bound.
        let max_depth = relative_path.components().count();

        let (gradlew, gradlew_dir) = find_gradlew(project_dir, max_depth)
            .await?
            .with_context(|| gradlew_not_found(manifest_path))?;
        // Sibling subprojects all report the same `gradlew_dir`, so canonicalize
        // it once per wrapper root instead of once per manifest.
        let normalized_wrapper_dir = if let Some(cached) =
            self.wrapper_dir_canonical.get(&gradlew_dir)
        {
            cached.clone()
        } else {
            let normalized = tokio::fs::canonicalize(&gradlew_dir)
                .await
                .with_context(|| {
                    format!(
                        "Failed to normalize Gradle wrapper root '{}' for '{}'",
                        gradlew_dir.display(),
                        manifest_path.display()
                    )
                })?;
            self.wrapper_dir_canonical
                .insert(gradlew_dir.clone(), normalized.clone());
            normalized
        };

        if !self
            .metadata_by_wrapper
            .contains_key(&normalized_wrapper_dir)
        {
            let metadata = get_gradle_metadata(&gradlew, &gradlew_dir, java_available).await?;
            self.metadata_by_wrapper
                .insert(normalized_wrapper_dir.clone(), metadata);
        }

        Ok((normalized_wrapper_dir, gradlew))
    }

    /// Look up the metadata record Gradle emitted for one project directory.
    ///
    /// The two lookups fail for structurally different reasons and therefore
    /// carry distinct contexts: the first means this wrapper root produced no
    /// batch at all, the second means the batch exists but never mentioned this
    /// project directory. The wrapper record is handed back alongside the
    /// project's Gradle path and properties because the caller resolves
    /// dependency project names against that same record and must not repeat
    /// the lookup.
    fn gradle_project_metadata<'a>(
        &'a self,
        normalized_wrapper_dir: &Path,
        project_dir: &Path,
        normalized_project_dir: &Path,
        gradlew: &Path,
    ) -> Result<(&'a GradleWrapperMetadata, String, GradleProperties)> {
        let wrapper_metadata = self
            .metadata_by_wrapper
            .get(normalized_wrapper_dir)
            .with_context(|| {
                format!(
                    "missing Gradle metadata batch for wrapper root '{}' (wrapper '{}') while resolving project directory '{}'",
                    normalized_wrapper_dir.display(),
                    gradlew.display(),
                    project_dir.display()
                )
            })?;
        let metadata = wrapper_metadata
            .by_project_dir
            .get(normalized_project_dir)
            .with_context(|| {
                format!(
                    "missing Gradle metadata record for project directory '{}' (normalized: '{}') in the batch emitted by wrapper '{}'",
                    project_dir.display(),
                    normalized_project_dir.display(),
                    gradlew.display()
                )
            })?;
        Ok((
            wrapper_metadata,
            metadata.project_path.clone(),
            metadata.properties.clone(),
        ))
    }

    /// Map the `project(":a:b")` dependency paths lexed out of a build file to
    /// the project names Gradle reported for them.
    ///
    /// A miss means the build file references a project the wrapper never
    /// emitted, so the error names every field needed to locate the mismatch.
    fn dependency_project_names<'a>(
        project_names_by_path: &'a HashMap<String, String>,
        dependencies: &[&str],
        name: Option<&str>,
        project_path: &str,
        manifest_path: &Path,
        gradlew: &Path,
    ) -> Result<Vec<&'a str>> {
        dependencies
            .iter()
            .map(|dependency_path| {
                project_names_by_path
                    .get(*dependency_path)
                    .map(String::as_str)
                    .with_context(|| {
                        format!(
                            "Gradle dependency project path '{}' declared by project '{}' (Gradle path '{}', manifest '{}') is missing from metadata emitted by wrapper '{}'",
                            dependency_path,
                            name.unwrap_or("<unnamed>"),
                            project_path,
                            manifest_path.display(),
                            gradlew.display()
                        )
                    })
            })
            .collect::<Result<Vec<_>>>()
    }
}

/// Whether `path` is an existing regular file that could be the `java`
/// executable (on Unix: with at least one exec bit set).
///
/// The missing/non-regular/other-error triage is delegated to
/// [`changepacks_core::regular_file_metadata`], which is also what
/// [`changepacks_core::is_regular_file`] is built on, so the ladder and its
/// `Failed to read metadata for ...` context live in exactly one place. That
/// helper hands back the very [`std::fs::Metadata`] it stat'ed, so the Unix
/// permission check costs no second syscall.
async fn is_java_executable_candidate(path: &Path) -> Result<bool> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;

        Ok(changepacks_core::regular_file_metadata(path)
            .await?
            .is_some_and(|metadata| metadata.permissions().mode() & 0o111 != 0))
    }
    #[cfg(not(unix))]
    {
        // No exec bit to inspect: being a regular file is the whole test, and
        // `is_regular_file` is the same `regular_file_metadata` ladder.
        changepacks_core::is_regular_file(path).await
    }
}

/// Core logic for finding `java` in a given PATH value.
///
/// Scans the split paths for a `java` / `java.exe` executable.
/// Returns `None` if `path_var` is `None` or empty.
///
/// Metadata errors other than missing candidates are propagated.
///
/// This function is testable without mutating process env.
async fn which_java_in(path_var: Option<&OsStr>) -> Result<Option<PathBuf>> {
    let Some(path_var) = path_var else {
        return Ok(None);
    };
    if path_var.is_empty() {
        return Ok(None);
    }
    for dir in std::env::split_paths(path_var) {
        let candidate = dir.join(JAVA_EXECUTABLE);
        if is_java_executable_candidate(&candidate).await? {
            return Ok(Some(candidate));
        }
    }
    Ok(None)
}

async fn java_home_has_java(java_home: Option<&OsStr>) -> Result<bool> {
    let Some(java_home) = java_home else {
        return Ok(false);
    };
    if java_home.is_empty() {
        return Ok(false);
    }

    let candidate = Path::new(java_home).join("bin").join(JAVA_EXECUTABLE);
    is_java_executable_candidate(&candidate).await
}

/// The platform-appropriate Gradle wrapper filename.
fn gradle_wrapper_name(windows: bool) -> &'static str {
    if windows { "gradlew.bat" } else { "gradlew" }
}

/// Single source of truth for the "wrapper missing" error message.
///
/// Both the discovery path (`GradleProjectFinder::visit`) and the publish path
/// (`run_gradle_publish`) fail here, and each names the offending manifest the
/// same way every other fallible step in those functions does. The leading
/// sentence is a stability contract: `crates/java/src/lib.rs` and
/// `crates/java/src/package.rs` assert on
/// `.contains("Gradle wrapper (gradlew) not found")`, so the prefix must stay
/// byte-identical and the manifest path is appended after it.
fn gradlew_not_found(manifest: &Path) -> String {
    format!(
        "Gradle wrapper (gradlew) not found for '{}'. \
         Ensure the project root contains gradlew or gradlew.bat.",
        manifest.display()
    )
}

async fn find_gradlew(start_dir: &Path, max_depth: usize) -> Result<Option<(PathBuf, PathBuf)>> {
    find_gradlew_named(start_dir, max_depth, gradle_wrapper_name(cfg!(windows))).await
}

/// Find gradlew executable by walking up the directory tree.
///
/// In multi-module Gradle builds, `gradlew` lives at the root while subprojects
/// only contain `build.gradle.kts`. This function searches upward from `start_dir`
/// until it finds `gradlew` (Unix) or `gradlew.bat` (Windows).
///
/// The ancestor walk is BOUNDED to the repository root by `max_depth`: the
/// caller passes `relative_path.components().count()` — the number of
/// directories from the project dir up to and INCLUDING the repo root — so
/// `start_dir.ancestors().take(max_depth)` stops AT the repository root and
/// never touches the drive root, the user's home dir, or a sibling checkout.
/// An out-of-repo `gradlew` must never be discovered (and then executed):
/// project discovery is git-scoped, so a stray wrapper ABOVE the repo root
/// must not be picked up and run. Mirrors the git-scoped bounds the sibling
/// C# finder applies in `is_workspace` and the Rust finder applies in its
/// version-inheritance walk.
///
/// Returns `(gradlew_path, gradlew_dir)`, or `None` if not found within the bound.
async fn find_gradlew_named(
    start_dir: &Path,
    max_depth: usize,
    gradlew_name: &str,
) -> Result<Option<(PathBuf, PathBuf)>> {
    // `Path::ancestors()` yields `[start_dir, parent, …, root]`; `take(max_depth)`
    // caps the climb at the repository root so the walk never leaves the repo
    // and can never adopt an out-of-repo wrapper.
    for current in start_dir.ancestors().take(max_depth) {
        let gradlew = current.join(gradlew_name);
        // Reject directories while continuing the bounded search; propagate
        // metadata failures other than a missing wrapper candidate.
        if changepacks_core::is_regular_file(&gradlew).await? {
            return Ok(Some((gradlew, current.to_path_buf())));
        }
    }
    Ok(None)
}

/// Run a built-in Gradle publish task through the repository-bounded wrapper.
///
/// The wrapper and task are passed as OS arguments rather than interpolated
/// into a shell command, so paths containing spaces or shell metacharacters
/// remain intact. Configured publish commands do not use this path; their
/// existing shell semantics are preserved by the package/workspace callers.
pub(crate) async fn run_gradle_publish(
    manifest_path: &Path,
    relative_path: &Path,
    project_path: Option<&str>,
    task: &str,
    additional_args: &[OsString],
    missing_dir_ctx: &'static str,
) -> Result<changepacks_core::publish::PublishOutput> {
    let project_dir = manifest_path.parent().context(missing_dir_ctx)?;
    let max_depth = relative_path.components().count();
    let (gradlew, gradlew_dir) = find_gradlew(project_dir, max_depth)
        .await?
        .with_context(|| gradlew_not_found(manifest_path))?;
    let mut args = Vec::with_capacity(additional_args.len() + 1);
    args.push(match project_path {
        Some(project_path) => gradle_task_arg_from_project_path(project_path, task),
        None => gradle_task_arg_from_project_dir(project_dir, &gradlew_dir, task)?,
    });
    args.extend_from_slice(additional_args);
    let output = GradleCommandSpec::new(&gradlew, &gradlew_dir, args)
        .command()
        .output()
        .await
        .with_context(|| format!("Failed to execute Gradle wrapper '{}'", gradlew.display()))?;

    Ok(output.into())
}

fn gradle_subproject_path(relative: &Path) -> Result<String> {
    // Preallocate against the source path's byte length: each `:` separator we
    // push is 1 byte and maps 1:1 to a path-separator byte already counted in
    // `as_os_str().len()`, so that length is a safe upper bound for the joined
    // `:`-separated output — removing the geometric-doubling reallocations for
    // deep subprojects. Matches the preallocation policy used elsewhere in the
    // finders.
    let mut path = String::with_capacity(relative.as_os_str().len());
    for component in relative.components() {
        let value = component.as_os_str().to_str().with_context(|| {
            format!(
                "Gradle subproject path contains a non-Unicode component: {}",
                relative.display()
            )
        })?;
        if !path.is_empty() {
            path.push(':');
        }
        path.push_str(value);
    }
    Ok(path)
}

/// Returns true when a Java runtime is reachable from the supplied `JAVA_HOME`
/// and `PATH` values.
///
/// The environment read lives in [`java_is_available`] so that this decision —
/// "`JAVA_HOME` wins, otherwise fall back to a `PATH` scan" — can be exercised
/// for both outcomes without mutating process environment, which edition 2024
/// makes `unsafe` and `[workspace.lints.rust] unsafe_code = "deny"` forbids.
/// Same split as `run_publish_command`'s env shim in `changepacks-core`.
async fn java_is_available_in(java_home: Option<&OsStr>, path: Option<&OsStr>) -> Result<bool> {
    if java_home_has_java(java_home).await? {
        return Ok(true);
    }
    Ok(which_java_in(path).await?.is_some())
}

/// Returns true when a Java runtime is available via `JAVA_HOME` or PATH.
async fn java_is_available() -> Result<bool> {
    let java_home = std::env::var_os("JAVA_HOME");
    let path = std::env::var_os("PATH");
    java_is_available_in(java_home.as_deref(), path.as_deref()).await
}

fn gradle_task_arg_from_project_path(project_path: &str, task: &str) -> OsString {
    if project_path == ":" {
        OsString::from(task)
    } else {
        OsString::from(format!("{project_path}:{task}"))
    }
}

fn gradle_task_arg_from_project_dir(
    project_dir: &Path,
    gradlew_dir: &Path,
    task: &str,
) -> Result<OsString> {
    if gradlew_dir == project_dir {
        return Ok(OsString::from(task));
    }

    let relative = project_dir
        .strip_prefix(gradlew_dir)
        .context("Failed to compute subproject path")?;
    let gradle_path = gradle_subproject_path(relative)?;
    Ok(OsString::from(format!(":{gradle_path}:{task}")))
}

/// Argument/working-directory bundle for one Gradle wrapper invocation.
///
/// Shared by `finder.rs` (publish tasks) and `gradle_metadata.rs` (batched
/// metadata discovery), so it stays here as `pub(crate)`.
#[derive(Debug)]
pub(crate) struct GradleCommandSpec {
    program: OsString,
    args: Vec<OsString>,
    current_dir: PathBuf,
}

impl GradleCommandSpec {
    pub(crate) fn new(gradlew: &Path, gradlew_dir: &Path, gradle_args: Vec<OsString>) -> Self {
        Self::for_platform(gradlew, gradlew_dir, gradle_args, cfg!(windows))
    }

    /// Build the spec for an explicitly named platform.
    ///
    /// `windows` is a parameter rather than a `cfg!(windows)` read so both
    /// layouts — the wrapper as the program on Windows, `sh <wrapper>`
    /// elsewhere — stay reachable from a single host, mirroring
    /// [`gradle_wrapper_name`]. A `cfg!` read here would leave whichever arm
    /// does not match the build target permanently unexecuted.
    fn for_platform(
        gradlew: &Path,
        gradlew_dir: &Path,
        gradle_args: Vec<OsString>,
        windows: bool,
    ) -> Self {
        let mut args = Vec::with_capacity(gradle_args.len() + usize::from(!windows));
        let program = if windows {
            gradlew.as_os_str().to_owned()
        } else {
            args.push(gradlew.as_os_str().to_owned());
            OsString::from("sh")
        };
        args.extend(gradle_args);

        Self {
            program,
            args,
            current_dir: gradlew_dir.to_path_buf(),
        }
    }

    pub(crate) fn command(&self) -> Command {
        let mut command = Command::new(&self.program);
        command
            .args(&self.args)
            .current_dir(&self.current_dir)
            .kill_on_drop(true);
        command
    }
}

#[async_trait]
impl ProjectFinder for GradleProjectFinder {
    changepacks_core::impl_projects_hashmap_accessors!();

    fn project_files(&self) -> &[&str] {
        PROJECT_FILES
    }

    async fn visit(&mut self, path: &Path, relative_path: &Path) -> Result<()> {
        // Parse this manifest if it is a recognized project file not already
        // visited. Both guards live in `ProjectFinder::should_visit_manifest`
        // (name/stat gate first, already-discovered map probe second) so the
        // prelude is written once for every file-name-based finder.
        if !self.should_visit_manifest(path).await? {
            return Ok(());
        }

        let project_dir = manifest_parent_dir(path)?;

        let java_available = if let Some(value) = self.java_available {
            value
        } else {
            let value = java_is_available().await?;
            self.java_available = Some(value);
            value
        };

        // Read Gradle build file first (fail fast if unreadable)
        let content = read_gradle_build_file(path).await?;
        let dependencies = extract_gradle_project_dependencies(&content, gradle_dialect_for(path));

        let (normalized_wrapper_dir, gradlew) = self
            .resolve_wrapper_metadata(path, project_dir, relative_path, java_available)
            .await?;

        let normalized_project_dir =
            tokio::fs::canonicalize(project_dir)
                .await
                .with_context(|| {
                    format!(
                        "Failed to normalize Gradle project directory '{}' for '{}'",
                        project_dir.display(),
                        path.display()
                    )
                })?;
        let (wrapper_metadata, project_path, properties) = self.gradle_project_metadata(
            &normalized_wrapper_dir,
            project_dir,
            &normalized_project_dir,
            &gradlew,
        )?;
        let GradleProperties {
            name,
            version,
            has_subprojects,
            has_publish_task,
            has_publish_to_maven_local_task,
        } = properties;

        // Use directory name as fallback for project name
        let name = name.or_else(|| {
            project_dir
                .file_name()
                .and_then(|n| n.to_str())
                .map(std::string::ToString::to_string)
        });

        let dependency_names = Self::dependency_project_names(
            &wrapper_metadata.project_names_by_path,
            &dependencies,
            name.as_deref(),
            &project_path,
            path,
            &gradlew,
        )?;

        // Workspace detection: gradlew reports non-empty subprojects list.
        // Previous approach (checking for settings.gradle.kts existence) caused
        // false positives in composite builds and subprojects with IDE-generated files.
        let is_workspace = has_subprojects;

        // Hoist the map key allocation out of both arms: the old shape
        // built a `(PathBuf, Project)` tuple, which forced each branch
        // to call `path.to_path_buf()` TWICE (once for the tuple slot,
        // once again for `*::new`). One shared `path_key` + one
        // `.clone()` into the constructor cuts 4 `PathBuf` allocs to 2.
        let path_key = path.to_path_buf();
        let relative_path_key = relative_path.to_path_buf();
        let mut project = changepacks_core::discovered_project!(
            is_workspace,
            GradleWorkspace::new_with_project_path_and_publish_tasks,
            GradlePackage::new_with_project_path_and_publish_tasks,
            name,
            version,
            path_key.clone(),
            relative_path_key,
            Some(project_path),
            has_publish_task,
            has_publish_to_maven_local_task,
        );

        for dependency in dependency_names {
            project.add_dependency(dependency);
        }

        self.projects.insert(path_key, project);
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::gradle_metadata::GRADLE_METADATA_PREFIX;
    use changepacks_core::{Project, UpdateType};
    use changepacks_utils::{apply_reverse_dependencies, sort_by_dependencies};
    use rstest::rstest;
    use std::collections::HashSet;
    use std::fs;
    use tempfile::TempDir;

    fn finder_with_java_available() -> GradleProjectFinder {
        GradleProjectFinder {
            java_available: Some(true),
            ..GradleProjectFinder::default()
        }
    }

    async fn dependencies_for_manifest(manifest_name: &str, content: &str) -> HashSet<String> {
        let temp_dir = TempDir::new().unwrap();
        let project_dir = temp_dir.path().join("project");
        tokio::fs::create_dir_all(&project_dir).await.unwrap();
        let manifest = project_dir.join(manifest_name);
        tokio::fs::write(&manifest, content).await.unwrap();
        let dependency_paths =
            super::extract_gradle_project_dependencies(content, gradle_dialect_for(&manifest));
        let mut records = vec![metadata_record(&project_dir, ":", "project", false)];
        for (index, dependency_path) in dependency_paths.iter().enumerate() {
            let dependency_dir = project_dir.join(format!("dependency-{index}"));
            tokio::fs::create_dir_all(&dependency_dir).await.unwrap();
            let dependency_name = dependency_path.rsplit(':').next().unwrap();
            records.push(metadata_record(
                &dependency_dir,
                dependency_path,
                dependency_name,
                false,
            ));
        }
        create_metadata_gradlew(&project_dir, &records).await;

        let mut finder = finder_with_java_available();
        finder
            .visit(&manifest, &PathBuf::from("project").join(manifest_name))
            .await
            .unwrap();
        let dependencies = finder.projects()[0].dependencies().clone();

        temp_dir.close().unwrap();
        dependencies
    }

    #[test]
    fn test_gradle_wrapper_name_selects_platform_variant() {
        assert_eq!(gradle_wrapper_name(false), "gradlew");
        assert_eq!(gradle_wrapper_name(true), "gradlew.bat");
    }

    #[tokio::test]
    async fn test_find_gradlew_accepts_both_wrapper_filenames_and_respects_bound() {
        for wrapper_name in ["gradlew", "gradlew.bat"] {
            let temp_dir = TempDir::new().unwrap();
            let repo = temp_dir.path().join("repo");
            let project = repo.join("nested");
            fs::create_dir_all(&project).unwrap();
            fs::write(repo.join(wrapper_name), "wrapper").unwrap();
            fs::write(
                temp_dir.path().join(if wrapper_name == "gradlew" {
                    "gradlew.bat"
                } else {
                    "gradlew"
                }),
                "out-of-repo decoy",
            )
            .unwrap();

            let found = find_gradlew_named(&project, 2, wrapper_name)
                .await
                .unwrap()
                .unwrap();

            assert_eq!(found.0, repo.join(wrapper_name));
            assert_eq!(found.1, repo);
        }
    }

    // Both `GradleProjectFinder::new()` and `GradleProjectFinder::default()`
    // must yield the same empty finder that recognizes both Kotlin and
    // Groovy Gradle manifests.
    #[rstest]
    #[case(GradleProjectFinder::new())]
    #[case(GradleProjectFinder::default())]
    fn test_gradle_project_finder_construction(#[case] finder: GradleProjectFinder) {
        assert_eq!(
            finder.project_files(),
            &["build.gradle.kts", "build.gradle"]
        );
        assert_eq!(finder.projects().len(), 0);
    }

    #[derive(Clone, Copy)]
    struct MockGradlew<'a> {
        name: &'a str,
        version: &'a str,
        subprojects: &'a str,
        has_publish_task: bool,
        has_publish_to_maven_local_task: bool,
    }

    impl<'a> MockGradlew<'a> {
        fn package(name: &'a str, version: &'a str) -> Self {
            Self {
                name,
                version,
                subprojects: "[]",
                has_publish_task: true,
                has_publish_to_maven_local_task: true,
            }
        }

        fn workspace(name: &'a str, version: &'a str, subprojects: &'a str) -> Self {
            Self {
                name,
                version,
                subprojects,
                has_publish_task: true,
                has_publish_to_maven_local_task: true,
            }
        }

        fn with_publish_tasks(
            mut self,
            has_publish_task: bool,
            has_publish_to_maven_local_task: bool,
        ) -> Self {
            self.has_publish_task = has_publish_task;
            self.has_publish_to_maven_local_task = has_publish_to_maven_local_task;
            self
        }
    }

    /// Create a mock gradlew in the given directory that emits batched metadata.
    fn create_mock_gradlew(dir: &Path, mock: MockGradlew<'_>) {
        let record = format!(
            "{GRADLE_METADATA_PREFIX}{{\"projectDir\":{},\"projectPath\":\":\",\"name\":{},\"version\":{},\"aggregate\":{},\"hasPublishTask\":{},\"hasPublishToMavenLocalTask\":{}}}",
            json_string(dir.to_string_lossy().as_ref()),
            json_string(mock.name),
            json_string(mock.version),
            mock.subprojects != "[]",
            mock.has_publish_task,
            mock.has_publish_to_maven_local_task,
        );
        if cfg!(windows) {
            fs::write(
                dir.join("gradlew.bat"),
                format!("@echo off\r\necho {record}\r\n"),
            )
            .unwrap();
        } else {
            let gradlew_path = dir.join("gradlew");
            fs::write(
                &gradlew_path,
                format!("#!/bin/sh\nprintf '%s\\n' '{record}'\n"),
            )
            .unwrap();
            #[cfg(unix)]
            make_executable(&gradlew_path);
        }
    }

    /// Text the failing wrapper writes to its stderr. Asserting on this exact
    /// marker is what proves the `; stderr: ...` suffix of the metadata-failure
    /// message carries the WRAPPER's own diagnostics, rather than some
    /// incidental text that would also satisfy a bare "`is_err`" check.
    const FAILING_GRADLEW_STDERR_MARKER: &str = "changepacks-gradle-failure-marker";

    /// Create a wrapper that runs successfully but exits non-zero after writing
    /// to stderr — the shape of an ordinary failing Gradle build, as opposed to
    /// a wrapper that cannot be spawned at all.
    fn create_failing_gradlew(dir: &Path) {
        if cfg!(windows) {
            fs::write(
                dir.join("gradlew.bat"),
                format!("@echo off\r\n(echo {FAILING_GRADLEW_STDERR_MARKER})>&2\r\nexit /b 1\r\n"),
            )
            .unwrap();
        } else {
            let gradlew_path = dir.join("gradlew");
            fs::write(
                &gradlew_path,
                format!("#!/bin/sh\necho '{FAILING_GRADLEW_STDERR_MARKER}' >&2\nexit 1\n"),
            )
            .unwrap();
            #[cfg(unix)]
            make_executable(&gradlew_path);
        }
    }

    /// Render `value` as a JSON string literal (quotes included), escaping every
    /// character JSON requires instead of the handful a hand-rolled escaper covers.
    fn json_string(value: &str) -> String {
        serde_json::Value::String(value.to_owned()).to_string()
    }

    fn create_counting_multi_project_gradlew(
        dir: &Path,
        root_project_dir: &Path,
        child_project_dir: &Path,
        child_project_path: &str,
        emit_child_record: bool,
    ) -> PathBuf {
        let invocation_count = dir.join("wrapper-invocations.txt");
        let prefix = GRADLE_METADATA_PREFIX;
        let root_record = format!(
            "{prefix}{{\"projectDir\":{},\"projectPath\":\":\",\"name\":\"root project\",\"version\":\"1.2.3\",\"aggregate\":true,\"hasPublishTask\":true,\"hasPublishToMavenLocalTask\":true}}",
            json_string(root_project_dir.to_string_lossy().as_ref())
        );
        let child_record = format!(
            "{prefix}{{\"projectDir\":{},\"projectPath\":{},\"name\":\"child project\",\"version\":\"2.3.4\",\"aggregate\":false,\"hasPublishTask\":true,\"hasPublishToMavenLocalTask\":true}}",
            json_string(child_project_dir.to_string_lossy().as_ref()),
            json_string(child_project_path),
        );
        let batch_records = if emit_child_record {
            format!(
                "echo {root_record}\r\necho unrelated __CHANGEPACKS_GRADLE_METADATA text\r\necho {child_record}\r\n"
            )
        } else {
            format!("echo {root_record}\r\n")
        };
        let unix_batch_records = if emit_child_record {
            format!(
                "printf '%s\\n' '{root_record}' 'unrelated __CHANGEPACKS_GRADLE_METADATA text' '{child_record}'"
            )
        } else {
            format!("printf '%s\\n' '{root_record}'")
        };

        if cfg!(windows) {
            fs::write(
                dir.join("gradlew.bat"),
                format!(
                    "@echo off\r\n\
                     type nul >\"metadata-command-args.txt\"\r\n\
                     for %%A in (%*) do echo %%~A>>\"metadata-command-args.txt\"\r\n\
                     set count=0\r\n\
                     if exist \"wrapper-invocations.txt\" set /p count=<\"wrapper-invocations.txt\"\r\n\
                     set /a count+=1\r\n\
                     >\"wrapper-invocations.txt\" echo %count%\r\n\
                     {batch_records}\
                     exit /b 0\r\n"
                ),
            )
            .unwrap();
        } else {
            let gradlew_path = dir.join("gradlew");
            fs::write(
                &gradlew_path,
                format!(
                    "#!/bin/sh\n\
                     : > metadata-command-args.txt\n\
                     for arg in \"$@\"; do printf '%s\\n' \"$arg\" >> metadata-command-args.txt; done\n\
                     count=$(cat wrapper-invocations.txt 2>/dev/null || printf 0)\n\
                     count=$((count + 1))\n\
                     printf '%s\\n' \"$count\" > wrapper-invocations.txt\n\
                     {unix_batch_records}\n"
                ),
            )
            .unwrap();
            #[cfg(unix)]
            make_executable(&gradlew_path);
        }

        invocation_count
    }

    fn metadata_record(
        project_dir: &Path,
        project_path: &str,
        name: &str,
        aggregate: bool,
    ) -> String {
        format!(
            "{GRADLE_METADATA_PREFIX}{{\"projectDir\":{},\"projectPath\":{},\"name\":{},\"version\":\"1.0.0\",\"aggregate\":{aggregate},\"hasPublishTask\":true,\"hasPublishToMavenLocalTask\":true}}",
            json_string(project_dir.to_string_lossy().as_ref()),
            json_string(project_path),
            json_string(name),
        )
    }

    async fn create_metadata_gradlew(dir: &Path, records: &[String]) {
        if cfg!(windows) {
            let mut output = String::new();
            for record in records {
                output.push_str("echo ");
                output.push_str(record);
                output.push_str("\r\n");
            }
            tokio::fs::write(
                dir.join("gradlew.bat"),
                format!("@echo off\r\n{output}exit /b 0\r\n"),
            )
            .await
            .unwrap();
        } else {
            let mut output = String::new();
            for record in records {
                output.push_str("printf '%s\\n' '");
                output.push_str(record);
                output.push_str("'\n");
            }
            let gradlew = dir.join("gradlew");
            tokio::fs::write(&gradlew, format!("#!/bin/sh\n{output}"))
                .await
                .unwrap();
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;

                tokio::fs::set_permissions(&gradlew, fs::Permissions::from_mode(0o755))
                    .await
                    .unwrap();
            }
        }
    }

    #[tokio::test]
    async fn test_gradle_metadata_command_disables_lazy_and_cached_configuration() {
        let temp_dir = TempDir::new().unwrap();
        let repo = temp_dir.path().join("repo");
        let child_dir = repo.join("child");
        fs::create_dir_all(&child_dir).unwrap();
        let root_manifest = repo.join("build.gradle.kts");
        fs::write(&root_manifest, "plugins { java }\n").unwrap();
        create_counting_multi_project_gradlew(&repo, &repo, &child_dir, ":module one", true);

        let mut finder = finder_with_java_available();
        finder
            .visit(&root_manifest, Path::new("build.gradle.kts"))
            .await
            .unwrap();

        let actual = fs::read_to_string(repo.join("metadata-command-args.txt"))
            .unwrap()
            .lines()
            .map(std::string::ToString::to_string)
            .collect::<Vec<_>>();
        let init_script = actual
            .iter()
            .find(|argument| argument.ends_with(".gradle"))
            .unwrap()
            .clone();
        assert_eq!(
            actual,
            vec![
                "-Dorg.gradle.configureondemand=false".to_string(),
                "-Dorg.gradle.configuration-cache=false".to_string(),
                "--init-script".to_string(),
                init_script,
                "--quiet".to_string(),
                "help".to_string(),
            ]
        );

        temp_dir.close().unwrap();
    }

    #[tokio::test]
    async fn test_gradle_finder_batches_metadata_per_wrapper_root() {
        let temp_dir = TempDir::new().unwrap();
        let repo = temp_dir.path().join("repo with spaces");
        let child_dir = repo.join("module one");
        fs::create_dir_all(&child_dir).unwrap();
        let root_manifest = repo.join("build.gradle.kts");
        let child_manifest = child_dir.join("build.gradle.kts");
        fs::write(&root_manifest, "plugins { java }\n").unwrap();
        fs::write(&child_manifest, "plugins { java }\n").unwrap();
        let invocation_count =
            create_counting_multi_project_gradlew(&repo, &repo, &child_dir, ":module one", true);

        let mut finder = finder_with_java_available();
        finder
            .visit(&root_manifest, Path::new("build.gradle.kts"))
            .await
            .unwrap();
        finder
            .visit(
                &child_manifest,
                Path::new("module one").join("build.gradle.kts").as_path(),
            )
            .await
            .unwrap();

        let projects = finder.projects();
        assert_eq!(projects.len(), 2);
        let root = projects
            .iter()
            .copied()
            .find(|project| project.name() == Some("root project"))
            .unwrap();
        let child = projects
            .iter()
            .copied()
            .find(|project| project.name() == Some("child project"))
            .unwrap();
        assert!(matches!(root, Project::Workspace(_)));
        assert_eq!(root.version(), Some("1.2.3"));
        assert!(matches!(child, Project::Package(_)));
        assert_eq!(child.version(), Some("2.3.4"));
        assert_eq!(fs::read_to_string(invocation_count).unwrap().trim(), "1");

        temp_dir.close().unwrap();
    }

    #[tokio::test]
    async fn test_gradle_finder_canonicalizes_shared_wrapper_root_once() {
        let temp_dir = TempDir::new().unwrap();
        let repo = temp_dir.path().join("repo with spaces");
        let alpha_dir = repo.join("alpha");
        let beta_dir = repo.join("beta");
        fs::create_dir_all(&alpha_dir).unwrap();
        fs::create_dir_all(&beta_dir).unwrap();
        let root_manifest = repo.join("build.gradle.kts");
        let alpha_manifest = alpha_dir.join("build.gradle.kts");
        let beta_manifest = beta_dir.join("build.gradle.kts");
        for manifest in [&root_manifest, &alpha_manifest, &beta_manifest] {
            fs::write(manifest, "plugins { java }\n").unwrap();
        }
        create_metadata_gradlew(
            &repo,
            &[
                metadata_record(&repo, ":", "root project", true),
                metadata_record(&alpha_dir, ":alpha", "alpha", false),
                metadata_record(&beta_dir, ":beta", "beta", false),
            ],
        )
        .await;

        let mut finder = finder_with_java_available();
        for (manifest, relative) in [
            (&root_manifest, PathBuf::from("build.gradle.kts")),
            (&alpha_manifest, Path::new("alpha").join("build.gradle.kts")),
            (&beta_manifest, Path::new("beta").join("build.gradle.kts")),
        ] {
            finder.visit(manifest, &relative).await.unwrap();
        }

        // One wrapper root shared by three manifests: exactly one canonicalize
        // result is cached, and it is the canonical repository root.
        let normalized_repo = tokio::fs::canonicalize(&repo).await.unwrap();
        assert_eq!(
            finder.wrapper_dir_canonical.values().collect::<Vec<_>>(),
            vec![&normalized_repo]
        );
        assert_eq!(
            finder.metadata_by_wrapper.keys().collect::<Vec<_>>(),
            vec![&normalized_repo]
        );

        // Both siblings still resolve their own metadata record through that
        // single shared wrapper root.
        let mut names = finder
            .projects()
            .iter()
            .map(|project| project.name().unwrap().to_string())
            .collect::<Vec<_>>();
        names.sort();
        assert_eq!(names, vec!["alpha", "beta", "root project"]);
        for name in ["alpha", "beta"] {
            let project = finder
                .projects()
                .iter()
                .copied()
                .find(|project| project.name() == Some(name))
                .unwrap();
            assert!(matches!(project, Project::Package(_)));
            assert_eq!(project.version(), Some("1.0.0"));
        }

        temp_dir.close().unwrap();
    }

    #[tokio::test]
    async fn test_gradle_finder_publish_uses_metadata_project_path_for_exact_argv() {
        let temp_dir = TempDir::new().unwrap();
        let repo = temp_dir.path().join("repo with spaces");
        let child_dir = repo.join("generated-backend");
        fs::create_dir_all(&child_dir).unwrap();
        let child_manifest = child_dir.join("build.gradle.kts");
        fs::write(&child_manifest, "plugins { java }\n").unwrap();
        create_counting_multi_project_gradlew(&repo, &repo, &child_dir, ":api", true);

        let mut finder = finder_with_java_available();
        finder
            .visit(
                &child_manifest,
                Path::new("generated-backend/build.gradle.kts"),
            )
            .await
            .unwrap();
        let project = finder.projects()[0];

        let output = project
            .publish(&changepacks_core::Config::default())
            .await
            .unwrap();
        assert!(output.success, "stderr: {}", output.stderr);
        let publish_args = fs::read_to_string(repo.join("metadata-command-args.txt"))
            .unwrap()
            .lines()
            .map(std::string::ToString::to_string)
            .collect::<Vec<_>>();
        assert_eq!(publish_args, [":api:publish"]);

        let dry_run = project
            .dry_run_publish(&changepacks_core::Config::default())
            .await
            .unwrap()
            .unwrap();
        assert!(dry_run.success, "stderr: {}", dry_run.stderr);
        let dry_run_args = fs::read_to_string(repo.join("metadata-command-args.txt"))
            .unwrap()
            .lines()
            .map(std::string::ToString::to_string)
            .collect::<Vec<_>>();
        assert_eq!(dry_run_args.len(), 2, "args: {dry_run_args:?}");
        assert_eq!(dry_run_args[0], ":api:publishToMavenLocal");
        assert!(dry_run_args[1].starts_with("-Dmaven.repo.local="));

        temp_dir.close().unwrap();
    }

    #[tokio::test]
    async fn test_gradle_finder_carries_package_publish_task_availability() {
        let temp_dir = TempDir::new().unwrap();
        let manifest = temp_dir.path().join("build.gradle.kts");
        fs::write(&manifest, "plugins { java }\n").unwrap();
        create_mock_gradlew(
            temp_dir.path(),
            MockGradlew::package("remote-only", "1.0.0").with_publish_tasks(true, false),
        );

        let mut finder = finder_with_java_available();
        finder
            .visit(&manifest, Path::new("build.gradle.kts"))
            .await
            .unwrap();

        let project = finder.projects()[0];
        assert!(matches!(project, Project::Package(_)));
        assert!(project.is_publishable_by_default());
        assert!(!project.is_dry_run_publishable_by_default());
    }

    #[tokio::test]
    async fn test_gradle_finder_carries_workspace_publish_task_availability() {
        let temp_dir = TempDir::new().unwrap();
        let manifest = temp_dir.path().join("build.gradle.kts");
        fs::write(&manifest, "plugins { java }\n").unwrap();
        create_mock_gradlew(
            temp_dir.path(),
            MockGradlew::workspace("local-only", "1.0.0", "[project ':child']")
                .with_publish_tasks(false, true),
        );

        let mut finder = finder_with_java_available();
        finder
            .visit(&manifest, Path::new("build.gradle.kts"))
            .await
            .unwrap();

        let project = finder.projects()[0];
        assert!(matches!(project, Project::Workspace(_)));
        assert!(!project.is_publishable_by_default());
        assert!(project.is_dry_run_publishable_by_default());
    }

    #[tokio::test]
    async fn test_gradle_finder_errors_when_batch_metadata_record_is_missing() {
        let temp_dir = TempDir::new().unwrap();
        let repo = temp_dir.path().join("repo");
        let child_dir = repo.join("module one");
        fs::create_dir_all(&child_dir).unwrap();
        let root_manifest = repo.join("build.gradle.kts");
        let child_manifest = child_dir.join("build.gradle.kts");
        fs::write(&root_manifest, "plugins { java }\n").unwrap();
        fs::write(&child_manifest, "plugins { java }\n").unwrap();
        create_counting_multi_project_gradlew(&repo, &repo, &child_dir, ":module one", false);

        let mut finder = finder_with_java_available();
        finder
            .visit(&root_manifest, Path::new("build.gradle.kts"))
            .await
            .unwrap();
        let error = finder
            .visit(
                &child_manifest,
                Path::new("module one").join("build.gradle.kts").as_path(),
            )
            .await
            .unwrap_err();

        assert!(error.to_string().contains("missing Gradle metadata record"));
        assert!(
            error
                .to_string()
                .contains(child_dir.to_string_lossy().as_ref())
        );
        assert!(
            error.to_string().contains(
                repo.join(gradle_wrapper_name(cfg!(windows)))
                    .to_string_lossy()
                    .as_ref()
            )
        );

        temp_dir.close().unwrap();
    }

    /// The wrapper-record miss and the project-record miss are structurally
    /// different failures, so they must not collapse into one indistinguishable
    /// message.
    #[tokio::test]
    async fn test_gradle_project_metadata_distinguishes_wrapper_and_project_misses() {
        let wrapper_dir = PathBuf::from("repo");
        let gradlew = wrapper_dir.join(gradle_wrapper_name(cfg!(windows)));
        let project_dir = wrapper_dir.join("module one");

        // Wrapper batch present, but it holds no record for the queried project.
        let mut finder = finder_with_java_available();
        finder.metadata_by_wrapper.insert(
            wrapper_dir.clone(),
            GradleWrapperMetadata {
                by_project_dir: HashMap::new(),
                project_names_by_path: HashMap::new(),
            },
        );

        let project_miss = finder
            .gradle_project_metadata(&wrapper_dir, &project_dir, &project_dir, &gradlew)
            .unwrap_err()
            .to_string();
        assert!(
            project_miss.contains("missing Gradle metadata record for project directory"),
            "unexpected error: {project_miss}"
        );
        assert!(project_miss.contains("in the batch emitted by wrapper"));
        assert!(project_miss.contains(project_dir.to_string_lossy().as_ref()));
        assert!(project_miss.contains(gradlew.to_string_lossy().as_ref()));

        // No batch at all was recorded for this wrapper root.
        let unknown_wrapper_dir = PathBuf::from("other-repo");
        let wrapper_miss = finder
            .gradle_project_metadata(&unknown_wrapper_dir, &project_dir, &project_dir, &gradlew)
            .unwrap_err()
            .to_string();
        assert!(
            wrapper_miss.contains("missing Gradle metadata batch for wrapper root"),
            "unexpected error: {wrapper_miss}"
        );
        assert!(wrapper_miss.contains(unknown_wrapper_dir.to_string_lossy().as_ref()));
        assert!(wrapper_miss.contains(gradlew.to_string_lossy().as_ref()));

        assert_ne!(project_miss, wrapper_miss);
    }

    #[test]
    fn test_gradle_publish_task_args_for_root_project() {
        let args = [
            gradle_task_arg_from_project_path(":", "publish"),
            gradle_task_arg_from_project_path(":", "publishToMavenLocal"),
        ];

        assert_eq!(
            args,
            [
                OsString::from("publish"),
                OsString::from("publishToMavenLocal")
            ]
        );
    }

    #[test]
    fn test_gradle_publish_task_args_for_ordinary_nested_project() {
        let args = [
            gradle_task_arg_from_project_path(":libs:core", "publish"),
            gradle_task_arg_from_project_path(":libs:core", "publishToMavenLocal"),
        ];

        assert_eq!(
            args,
            [
                OsString::from(":libs:core:publish"),
                OsString::from(":libs:core:publishToMavenLocal")
            ]
        );
    }

    #[test]
    fn test_gradle_publish_task_args_for_filesystem_remapped_project() {
        let filesystem_path = gradle_subproject_path(Path::new("generated/backend")).unwrap();
        assert_eq!(filesystem_path, "generated:backend");
        assert_ne!(format!(":{filesystem_path}"), ":api");

        let args = [
            gradle_task_arg_from_project_path(":api", "publish"),
            gradle_task_arg_from_project_path(":api", "publishToMavenLocal"),
        ];

        assert_eq!(
            args,
            [
                OsString::from(":api:publish"),
                OsString::from(":api:publishToMavenLocal")
            ]
        );
    }

    #[test]
    fn test_gradle_task_arg_from_project_dir_for_wrapper_root_project() {
        let root = Path::new("/repo");

        let arg = gradle_task_arg_from_project_dir(root, root, "publish").unwrap();

        assert_eq!(arg, OsString::from("publish"));
    }

    #[test]
    fn test_gradle_task_arg_from_project_dir_for_nested_project() {
        let arg =
            gradle_task_arg_from_project_dir(Path::new("/repo/sub"), Path::new("/repo"), "publish")
                .unwrap();

        assert_eq!(arg, OsString::from(":sub:publish"));
    }

    #[test]
    fn test_gradle_task_arg_from_project_dir_for_deeply_nested_project() {
        let arg = gradle_task_arg_from_project_dir(
            Path::new("/repo/libs/core"),
            Path::new("/repo"),
            "publishToMavenLocal",
        )
        .unwrap();

        assert_eq!(arg, OsString::from(":libs:core:publishToMavenLocal"));
    }

    #[test]
    fn test_gradle_task_arg_from_project_dir_rejects_non_descendant_project() {
        let error = gradle_task_arg_from_project_dir(
            Path::new("/elsewhere/sub"),
            Path::new("/repo"),
            "publish",
        )
        .unwrap_err();

        assert!(
            error
                .to_string()
                .contains("Failed to compute subproject path"),
            "unexpected error: {error}"
        );
    }

    #[test]
    fn test_gradle_command_spec_matches_active_platform_layout() {
        let gradlew = Path::new("repo").join(if cfg!(windows) {
            "gradlew.bat"
        } else {
            "gradlew"
        });
        let args = vec![OsString::from("--quiet"), OsString::from("help")];

        let spec = GradleCommandSpec::new(&gradlew, Path::new("repo"), args);

        if cfg!(windows) {
            assert_eq!(spec.program, gradlew.as_os_str());
            assert_eq!(
                spec.args,
                vec![OsString::from("--quiet"), OsString::from("help")]
            );
        } else {
            assert_eq!(spec.program, OsString::from("sh"));
            assert_eq!(spec.args[0], gradlew.as_os_str());
            assert_eq!(
                spec.args[1..],
                [OsString::from("--quiet"), OsString::from("help")]
            );
        }
        assert_eq!(spec.current_dir, PathBuf::from("repo"));
    }

    #[tokio::test]
    async fn test_gradle_command_stops_wrapper_when_wait_future_is_dropped() {
        let temp_dir = TempDir::new().unwrap();
        let started = temp_dir.path().join("started.marker");
        let completed = temp_dir.path().join("completed.marker");
        let gradlew = temp_dir.path().join(gradle_wrapper_name(cfg!(windows)));

        if cfg!(windows) {
            fs::write(
                &gradlew,
                "@echo off\r\necho started>started.marker\r\npowershell -NoProfile -Command \"Start-Sleep -Milliseconds 400\"\r\necho completed>completed.marker\r\n",
            )
            .unwrap();
        } else {
            fs::write(
                &gradlew,
                "#!/bin/sh\nprintf started > started.marker\nsleep 0.4\nprintf completed > completed.marker\n",
            )
            .unwrap();
            #[cfg(unix)]
            make_executable(&gradlew);
        }

        let spec = GradleCommandSpec::new(&gradlew, temp_dir.path(), Vec::new());
        let mut command = spec.command();
        command.stdout(Stdio::null()).stderr(Stdio::null());
        let mut child = command.spawn().unwrap();
        let wait_task = tokio::spawn(async move { child.wait().await });

        tokio::time::timeout(std::time::Duration::from_secs(2), async {
            while !started.exists() {
                tokio::time::sleep(std::time::Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("fake Gradle wrapper did not start");

        wait_task.abort();
        let _ = wait_task.await;
        tokio::time::sleep(std::time::Duration::from_millis(700)).await;

        assert!(
            !completed.exists(),
            "dropping a Gradle wait future left its wrapper running"
        );
    }

    #[cfg(unix)]
    fn make_executable(path: &Path) {
        use std::os::unix::fs::PermissionsExt;

        fs::set_permissions(path, fs::Permissions::from_mode(0o755)).unwrap();
    }

    #[tokio::test]
    async fn test_gradle_project_finder_visit_kts_package() {
        let temp_dir = TempDir::new().unwrap();
        let project_dir = temp_dir.path().join("myproject");
        fs::create_dir_all(&project_dir).unwrap();

        let build_gradle = project_dir.join("build.gradle.kts");
        fs::write(
            &build_gradle,
            r#"
plugins {
    id("java")
}

group = "com.example"
version = "1.0.0"
"#,
        )
        .unwrap();

        create_mock_gradlew(&project_dir, MockGradlew::package("myproject", "1.0.0"));

        let mut finder = finder_with_java_available();
        finder
            .visit(&build_gradle, &PathBuf::from("myproject/build.gradle.kts"))
            .await
            .unwrap();

        let projects = finder.projects();
        assert_eq!(projects.len(), 1);
        match projects[0] {
            Project::Package(pkg) => {
                assert_eq!(pkg.name(), Some("myproject"));
                assert_eq!(pkg.version(), Some("1.0.0"));
            }
            Project::Workspace(_) => panic!("Expected Package"),
        }

        temp_dir.close().unwrap();
    }

    #[tokio::test]
    async fn test_gradle_project_finder_visit_groovy_package() {
        let temp_dir = TempDir::new().unwrap();
        let project_dir = temp_dir.path().join("groovyproject");
        fs::create_dir_all(&project_dir).unwrap();

        let build_gradle = project_dir.join("build.gradle");
        fs::write(
            &build_gradle,
            r"
plugins {
    id 'java'
}

group = 'com.example'
version = '2.0.0'
",
        )
        .unwrap();

        create_mock_gradlew(&project_dir, MockGradlew::package("groovyproject", "2.0.0"));

        let mut finder = finder_with_java_available();
        finder
            .visit(&build_gradle, &PathBuf::from("groovyproject/build.gradle"))
            .await
            .unwrap();

        let projects = finder.projects();
        assert_eq!(projects.len(), 1);
        match projects[0] {
            Project::Package(pkg) => {
                assert_eq!(pkg.name(), Some("groovyproject"));
                assert_eq!(pkg.version(), Some("2.0.0"));
            }
            Project::Workspace(_) => panic!("Expected Package"),
        }

        temp_dir.close().unwrap();
    }

    #[tokio::test]
    async fn test_gradle_project_finder_visit_workspace() {
        let temp_dir = TempDir::new().unwrap();
        let project_dir = temp_dir.path().join("multiproject");
        fs::create_dir_all(&project_dir).unwrap();

        let build_gradle = project_dir.join("build.gradle.kts");
        fs::write(
            &build_gradle,
            r#"
plugins {
    id("java")
}

group = "com.example"
version = "1.0.0"
"#,
        )
        .unwrap();

        // Mock Gradle metadata reports subprojects (this is what makes it a workspace).
        create_mock_gradlew(
            &project_dir,
            MockGradlew::workspace(
                "multiproject",
                "1.0.0",
                "[project ':subproject1', project ':subproject2']",
            ),
        );

        let mut finder = finder_with_java_available();
        finder
            .visit(
                &build_gradle,
                &PathBuf::from("multiproject/build.gradle.kts"),
            )
            .await
            .unwrap();

        let projects = finder.projects();
        assert_eq!(projects.len(), 1);
        match projects[0] {
            Project::Workspace(ws) => {
                assert_eq!(ws.name(), Some("multiproject"));
                assert_eq!(ws.version(), Some("1.0.0"));
            }
            Project::Package(_) => panic!("Expected Workspace"),
        }

        temp_dir.close().unwrap();
    }

    #[tokio::test]
    async fn test_gradle_project_finder_settings_file_does_not_make_workspace() {
        // Regression: settings.gradle.kts presence alone must NOT classify as Workspace.
        // Only evaluated Gradle metadata determines workspace status.
        let temp_dir = TempDir::new().unwrap();
        let project_dir = temp_dir.path().join("myproject");
        fs::create_dir_all(&project_dir).unwrap();

        let build_gradle = project_dir.join("build.gradle.kts");
        fs::write(&build_gradle, "version = \"1.0.0\"\n").unwrap();

        // settings.gradle.kts exists and metadata reports no subprojects, so this is a package.
        fs::write(
            project_dir.join("settings.gradle.kts"),
            "rootProject.name = \"myproject\"\n",
        )
        .unwrap();

        create_mock_gradlew(&project_dir, MockGradlew::package("myproject", "1.0.0"));

        let mut finder = finder_with_java_available();
        finder
            .visit(&build_gradle, &PathBuf::from("myproject/build.gradle.kts"))
            .await
            .unwrap();

        let projects = finder.projects();
        assert_eq!(projects.len(), 1);
        match projects[0] {
            Project::Package(_) => {} // correct: subprojects: [] → Package
            Project::Workspace(_) => panic!("Expected Package, not Workspace"),
        }

        temp_dir.close().unwrap();
    }

    #[tokio::test]
    async fn test_gradle_project_finder_empty_subprojects_is_package() {
        // A project with gradlew but subprojects: [] is a Package, not Workspace
        let temp_dir = TempDir::new().unwrap();
        let project_dir = temp_dir.path().join("standalone");
        fs::create_dir_all(&project_dir).unwrap();

        let build_gradle = project_dir.join("build.gradle.kts");
        fs::write(&build_gradle, "version = \"1.0.0\"\n").unwrap();

        create_mock_gradlew(&project_dir, MockGradlew::package("standalone", "1.0.0"));

        let mut finder = finder_with_java_available();
        finder
            .visit(&build_gradle, &PathBuf::from("standalone/build.gradle.kts"))
            .await
            .unwrap();

        let projects = finder.projects();
        assert_eq!(projects.len(), 1);
        match projects[0] {
            Project::Package(pkg) => {
                assert_eq!(pkg.name(), Some("standalone"));
            }
            Project::Workspace(_) => panic!("Expected Package, not Workspace"),
        }

        temp_dir.close().unwrap();
    }

    #[tokio::test]
    async fn test_gradle_project_finder_visit_non_gradle_file() {
        let temp_dir = TempDir::new().unwrap();
        let other_file = temp_dir.path().join("other.txt");
        fs::write(&other_file, "some content").unwrap();

        let mut finder = finder_with_java_available();
        finder
            .visit(&other_file, &PathBuf::from("other.txt"))
            .await
            .unwrap();

        assert_eq!(finder.projects().len(), 0);

        temp_dir.close().unwrap();
    }

    #[tokio::test]
    async fn test_gradle_project_finder_visit_duplicate() {
        let temp_dir = TempDir::new().unwrap();
        let project_dir = temp_dir.path().join("myproject");
        fs::create_dir_all(&project_dir).unwrap();

        let build_gradle = project_dir.join("build.gradle.kts");
        fs::write(&build_gradle, "version = \"1.0.0\"\n").unwrap();

        create_mock_gradlew(&project_dir, MockGradlew::package("myproject", "1.0.0"));

        let mut finder = finder_with_java_available();
        finder
            .visit(&build_gradle, &PathBuf::from("myproject/build.gradle.kts"))
            .await
            .unwrap();

        assert_eq!(finder.projects().len(), 1);

        // Visit again - should not add duplicate
        finder
            .visit(&build_gradle, &PathBuf::from("myproject/build.gradle.kts"))
            .await
            .unwrap();

        assert_eq!(finder.projects().len(), 1);

        temp_dir.close().unwrap();
    }

    #[tokio::test]
    async fn test_gradle_project_finder_projects_mut() {
        let temp_dir = TempDir::new().unwrap();
        let project_dir = temp_dir.path().join("myproject");
        fs::create_dir_all(&project_dir).unwrap();

        let build_gradle = project_dir.join("build.gradle.kts");
        fs::write(&build_gradle, "version = \"1.0.0\"\n").unwrap();

        create_mock_gradlew(&project_dir, MockGradlew::package("myproject", "1.0.0"));

        let mut finder = finder_with_java_available();
        finder
            .visit(&build_gradle, &PathBuf::from("myproject/build.gradle.kts"))
            .await
            .unwrap();

        let mut_projects = finder.projects_mut();
        assert_eq!(mut_projects.len(), 1);

        temp_dir.close().unwrap();
    }

    #[tokio::test]
    async fn test_find_gradlew_in_same_dir() {
        let temp_dir = TempDir::new().unwrap();

        if cfg!(windows) {
            fs::write(temp_dir.path().join("gradlew.bat"), "@echo off").unwrap();
        } else {
            fs::write(temp_dir.path().join("gradlew"), "#!/bin/sh").unwrap();
        }

        // Root project: the build file sits AT the repo root, so `visit`
        // computes `max_depth = 1` and the walk scans only `temp_dir`.
        let result = find_gradlew(temp_dir.path(), 1).await.unwrap();
        assert!(result.is_some());
        let (_, gradlew_dir) = result.unwrap();
        assert_eq!(gradlew_dir, temp_dir.path());

        temp_dir.close().unwrap();
    }

    #[tokio::test]
    async fn test_find_gradlew_in_parent_dir() {
        let temp_dir = TempDir::new().unwrap();
        let subproject = temp_dir.path().join("libs").join("core");
        fs::create_dir_all(&subproject).unwrap();

        // gradlew at root, not in subproject
        if cfg!(windows) {
            fs::write(temp_dir.path().join("gradlew.bat"), "@echo off").unwrap();
        } else {
            fs::write(temp_dir.path().join("gradlew"), "#!/bin/sh").unwrap();
        }

        // Subproject `libs/core` is two directories below the repo root, so
        // its build file is `libs/core/build.gradle.kts` (3 components) →
        // `max_depth = 3`. The walk scans `libs/core`, `libs`, then `temp_dir`
        // (the repo root), where the wrapper lives.
        let result = find_gradlew(&subproject, 3).await.unwrap();
        assert!(result.is_some());
        let (_, gradlew_dir) = result.unwrap();
        assert_eq!(gradlew_dir, temp_dir.path().to_path_buf());

        temp_dir.close().unwrap();
    }

    #[tokio::test]
    async fn test_find_gradlew_not_found() {
        let temp_dir = TempDir::new().unwrap();
        let subdir = temp_dir.path().join("no_gradlew_here");
        fs::create_dir_all(&subdir).unwrap();

        // No gradlew in `subdir` or its parent. The walk is now BOUNDED to
        // `max_depth`, so with depth 2 it scans only `subdir` and `temp_dir`
        // and stops — it can no longer climb to the filesystem root and pick
        // up an out-of-repo wrapper, so it reliably returns `None`.
        let result = find_gradlew(&subdir, 2).await.unwrap();
        assert!(result.is_none());

        temp_dir.close().unwrap();
    }

    /// Regression: a decoy `gradlew` ABOVE the repository root must NOT be
    /// discovered (and later executed) when resolving a subproject's wrapper.
    /// The ancestor walk is bounded by `max_depth` (the caller passes
    /// `relative_path.components().count()`), so it scans only the manifest's
    /// in-repo ancestors — down to the repo root — and never reaches the
    /// out-of-repo directory holding the stray wrapper. Project discovery is
    /// git-scoped; a `gradlew` in the user's home dir, the drive root, or a
    /// sibling checkout must not be picked up and run. Against the old
    /// unbounded walk (`loop { current.pop() }` to the filesystem root) this
    /// decoy WAS found, so this test fails there and passes only once the walk
    /// is bounded. Complements `test_find_gradlew_in_parent_dir`, which pins
    /// that an IN-repo ancestor `gradlew` is still found.
    #[tokio::test]
    async fn test_find_gradlew_ignores_gradlew_above_repo_root() {
        let temp_dir = TempDir::new().unwrap();
        // The simulated repo root is a nested subdir; the decoy wrapper lives
        // one level ABOVE it (outside the repo).
        let repo_root = temp_dir.path().join("repo");
        let sub = repo_root.join("sub");
        fs::create_dir_all(&sub).unwrap();

        // Decoy gradlew ABOVE the repo root — must be ignored. (`gradlew.bat`
        // on Windows, `gradlew` elsewhere, matching `create_mock_gradlew`.)
        if cfg!(windows) {
            fs::write(temp_dir.path().join("gradlew.bat"), "@echo off").unwrap();
        } else {
            fs::write(temp_dir.path().join("gradlew"), "#!/bin/sh").unwrap();
        }

        // `relative_path` is repo-root-relative with 2 components
        // (`sub/build.gradle.kts`), so the walk scans `<repo_root>/sub` and
        // `<repo_root>` — never `temp_dir`, where the decoy wrapper lives.
        let result = find_gradlew(&sub, 2).await.unwrap();
        assert!(
            result.is_none(),
            "expected a decoy gradlew above the repo root to be ignored, got {result:?}"
        );

        temp_dir.close().unwrap();
    }

    /// Regression: the DISCOVERY-side wrapper lookup must name the offending
    /// manifest. `find_gradlew` returning `Ok(None)` is covered by
    /// `test_find_gradlew_not_found`, but `GradleProjectFinder::visit` turning
    /// that `None` into a user-facing error was untested, so a message that
    /// dropped the manifest path (as the old hard-coded literal did) went
    /// unnoticed. Asserts BOTH halves of the contract: the stable leading
    /// sentence that `lib.rs` / `package.rs` match with `.contains(..)`, and
    /// the interpolated manifest path.
    #[tokio::test]
    async fn test_gradle_project_finder_visit_missing_wrapper_names_manifest() {
        let temp_dir = TempDir::new().unwrap();
        let project_dir = temp_dir.path().join("myproject");
        fs::create_dir_all(&project_dir).unwrap();

        let build_gradle = project_dir.join("build.gradle.kts");
        fs::write(&build_gradle, "version = \"1.0.0\"\n").unwrap();

        // Deliberately NO gradlew/gradlew.bat: the bounded ancestor walk
        // (`max_depth = 2` from `myproject/build.gradle.kts`) scans only
        // `project_dir` and `temp_dir`, both freshly created and wrapper-free.

        let mut finder = finder_with_java_available();
        let error = finder
            .visit(&build_gradle, &PathBuf::from("myproject/build.gradle.kts"))
            .await
            .unwrap_err();

        let flattened = error
            .chain()
            .map(ToString::to_string)
            .collect::<Vec<_>>()
            .join(": ");
        assert!(
            flattened.contains("Gradle wrapper (gradlew) not found"),
            "{flattened}"
        );
        assert!(
            flattened.contains(&build_gradle.display().to_string()),
            "{flattened}"
        );

        temp_dir.close().unwrap();
    }

    #[test]
    fn test_gradle_subproject_path_root() {
        assert_eq!(gradle_subproject_path(Path::new("")).unwrap(), "");
    }

    #[test]
    fn test_gradle_subproject_path_single_component() {
        assert_eq!(gradle_subproject_path(Path::new("app")).unwrap(), "app");
    }

    #[test]
    fn test_gradle_subproject_path_nested_unicode() {
        let relative = Path::new("라이브러리").join("핵심");

        assert_eq!(
            gradle_subproject_path(&relative).unwrap(),
            "라이브러리:핵심"
        );
    }

    #[tokio::test]
    async fn test_gradle_finder_resolves_project_path_to_evaluated_name_for_graph_edges() {
        let temp_dir = TempDir::new().unwrap();
        let repo = temp_dir.path().join("repo");
        let dependency_dir = repo.join("generated-backend");
        tokio::fs::create_dir_all(&dependency_dir).await.unwrap();
        let dependent_manifest = repo.join("build.gradle.kts");
        let dependency_manifest = dependency_dir.join("build.gradle.kts");
        tokio::fs::write(
            &dependent_manifest,
            "dependencies { implementation(project(\":api\")) }\n",
        )
        .await
        .unwrap();
        tokio::fs::write(&dependency_manifest, "plugins { java }\n")
            .await
            .unwrap();
        create_metadata_gradlew(
            &repo,
            &[
                metadata_record(&repo, ":", "service-suite", true),
                metadata_record(&dependency_dir, ":api", "published-api", false),
            ],
        )
        .await;

        let mut finder = finder_with_java_available();
        finder
            .visit(&dependent_manifest, Path::new("build.gradle.kts"))
            .await
            .unwrap();
        finder
            .visit(
                &dependency_manifest,
                Path::new("generated-backend/build.gradle.kts"),
            )
            .await
            .unwrap();

        let projects = finder.projects();
        let dependent = projects
            .iter()
            .copied()
            .find(|project| project.name() == Some("service-suite"))
            .unwrap();
        let dependency = projects
            .iter()
            .copied()
            .find(|project| project.name() == Some("published-api"))
            .unwrap();
        assert_eq!(
            dependent.dependencies(),
            &HashSet::from(["published-api".to_string()])
        );

        let sorted = sort_by_dependencies(vec![dependent, dependency]).unwrap();
        assert_eq!(
            sorted
                .iter()
                .map(|project| project.name().unwrap())
                .collect::<Vec<_>>(),
            vec!["published-api", "service-suite"]
        );

        let mut update_map = HashMap::from([(
            PathBuf::from("generated-backend/build.gradle.kts"),
            (UpdateType::Minor, Vec::new()),
        )]);
        apply_reverse_dependencies(&mut update_map, &[dependency, dependent], &repo).unwrap();
        assert_eq!(
            update_map[&PathBuf::from("build.gradle.kts")].0,
            UpdateType::Patch
        );
    }

    #[tokio::test]
    async fn test_gradle_finder_errors_when_dependency_path_is_missing_from_wrapper_metadata() {
        let temp_dir = TempDir::new().unwrap();
        let repo = temp_dir.path().join("repo");
        tokio::fs::create_dir_all(&repo).await.unwrap();
        let manifest = repo.join("build.gradle.kts");
        tokio::fs::write(
            &manifest,
            "dependencies { implementation(project(\":missing\")) }\n",
        )
        .await
        .unwrap();
        create_metadata_gradlew(
            &repo,
            &[metadata_record(&repo, ":", "service-suite", false)],
        )
        .await;

        let error = finder_with_java_available()
            .visit(&manifest, Path::new("build.gradle.kts"))
            .await
            .unwrap_err();
        let message = error.to_string();

        assert!(message.contains(":missing"), "{message}");
        assert!(message.contains("service-suite"), "{message}");
        assert!(message.contains("gradlew"), "{message}");
    }

    #[tokio::test]
    async fn test_gradle_finder_errors_when_wrapper_metadata_duplicates_project_path() {
        let temp_dir = TempDir::new().unwrap();
        let repo = temp_dir.path().join("repo");
        let first_dir = repo.join("first");
        let second_dir = repo.join("second");
        tokio::fs::create_dir_all(&first_dir).await.unwrap();
        tokio::fs::create_dir_all(&second_dir).await.unwrap();
        let manifest = repo.join("build.gradle.kts");
        tokio::fs::write(&manifest, "plugins { java }\n")
            .await
            .unwrap();
        create_metadata_gradlew(
            &repo,
            &[
                metadata_record(&repo, ":", "service-suite", true),
                metadata_record(&first_dir, ":api", "first-api", false),
                metadata_record(&second_dir, ":api", "second-api", false),
            ],
        )
        .await;

        let error = finder_with_java_available()
            .visit(&manifest, Path::new("build.gradle.kts"))
            .await
            .unwrap_err();
        let message = error.to_string();

        assert!(message.contains("Duplicate Gradle metadata project path ':api'"));
        assert!(message.contains("first-api"));
        assert!(message.contains("second-api"));
        assert!(message.contains("gradlew"));
    }

    #[tokio::test]
    async fn test_gradle_finder_errors_when_wrapper_metadata_directory_does_not_exist() {
        let temp_dir = TempDir::new().unwrap();
        let repo = temp_dir.path().join("repo");
        tokio::fs::create_dir_all(&repo).await.unwrap();
        let manifest = repo.join("build.gradle.kts");
        tokio::fs::write(&manifest, "plugins { java }\n")
            .await
            .unwrap();
        let missing_dir = repo.join("never-created");
        create_metadata_gradlew(
            &repo,
            &[
                metadata_record(&repo, ":", "service-suite", true),
                metadata_record(&missing_dir, ":ghost", "ghost-api", false),
            ],
        )
        .await;

        let error = finder_with_java_available()
            .visit(&manifest, Path::new("build.gradle.kts"))
            .await
            .unwrap_err();
        let message = format!("{error:#}");

        assert!(
            message.contains("Failed to normalize Gradle metadata directory"),
            "{message}"
        );
        assert!(message.contains(":ghost"), "{message}");
        assert!(message.contains("never-created"), "{message}");
    }

    #[tokio::test]
    async fn test_gradle_finder_uses_manifest_dialect_for_slashes() {
        let kotlin = dependencies_for_manifest(
            "build.gradle.kts",
            r#"
val first = 12 / 3
dependencies { implementation(project(":real-kotlin")) }
val second = 20 / 4
"#,
        )
        .await;
        assert_eq!(kotlin, HashSet::from(["real-kotlin".to_string()]));

        let groovy = dependencies_for_manifest(
            "build.gradle",
            r#"
def decoy = /project(":slashy-decoy")/
def first = 12 / 3
dependencies { implementation(project(":real-groovy")) }
def second = 20 / 4
"#,
        )
        .await;
        assert_eq!(groovy, HashSet::from(["real-groovy".to_string()]));
    }

    #[tokio::test]
    async fn test_gradle_finder_dependencies_drive_topological_and_reverse_edges() {
        let temp_dir = TempDir::new().unwrap();
        let core_dir = temp_dir.path().join("core");
        let app_dir = temp_dir.path().join("app");
        tokio::fs::create_dir_all(&core_dir).await.unwrap();
        tokio::fs::create_dir_all(&app_dir).await.unwrap();

        let core_manifest = core_dir.join("build.gradle.kts");
        let app_manifest = app_dir.join("build.gradle.kts");
        tokio::fs::write(&core_manifest, "plugins { java }\n")
            .await
            .unwrap();
        tokio::fs::write(
            &app_manifest,
            r#"dependencies {
    implementation(project(configuration = "default", path = ":modules:core"))
}
"#,
        )
        .await
        .unwrap();
        create_metadata_gradlew(
            temp_dir.path(),
            &[
                metadata_record(&core_dir, ":modules:core", "core", false),
                metadata_record(&app_dir, ":app", "app", false),
            ],
        )
        .await;

        let mut finder = finder_with_java_available();
        finder
            .visit(&core_manifest, Path::new("core/build.gradle.kts"))
            .await
            .unwrap();
        finder
            .visit(&app_manifest, Path::new("app/build.gradle.kts"))
            .await
            .unwrap();

        let projects = finder.projects();
        let core = projects
            .iter()
            .copied()
            .find(|project| project.name() == Some("core"))
            .unwrap();
        let app = projects
            .iter()
            .copied()
            .find(|project| project.name() == Some("app"))
            .unwrap();
        assert_eq!(app.dependencies().len(), 1);
        assert!(app.dependencies().contains("core"));

        let sorted = sort_by_dependencies(vec![app, core]).unwrap();
        assert_eq!(
            sorted
                .iter()
                .map(|project| project.name().unwrap())
                .collect::<Vec<_>>(),
            vec!["core", "app"]
        );

        let mut update_map = HashMap::from([(
            PathBuf::from("core/build.gradle.kts"),
            (UpdateType::Minor, Vec::new()),
        )]);
        apply_reverse_dependencies(&mut update_map, &[core, app], temp_dir.path()).unwrap();
        assert_eq!(
            update_map[&PathBuf::from("app/build.gradle.kts")].0,
            UpdateType::Patch
        );

        temp_dir.close().unwrap();
    }

    #[tokio::test]
    async fn test_gradle_finder_ignores_project_configuration_edge_that_would_form_cycle() {
        let temp_dir = TempDir::new().unwrap();
        let core_dir = temp_dir.path().join("core");
        let app_dir = temp_dir.path().join("app");
        tokio::fs::create_dir_all(&core_dir).await.unwrap();
        tokio::fs::create_dir_all(&app_dir).await.unwrap();

        let core_manifest = core_dir.join("build.gradle.kts");
        let app_manifest = app_dir.join("build.gradle.kts");
        tokio::fs::write(
            &core_manifest,
            r#"project(":app") {
    description = "configuration only"
}
"#,
        )
        .await
        .unwrap();
        tokio::fs::write(
            &app_manifest,
            r#"dependencies {
    implementation(project(":core"))
}
"#,
        )
        .await
        .unwrap();
        create_metadata_gradlew(
            temp_dir.path(),
            &[
                metadata_record(&core_dir, ":core", "core", false),
                metadata_record(&app_dir, ":app", "app", false),
            ],
        )
        .await;

        let mut finder = finder_with_java_available();
        finder
            .visit(&core_manifest, Path::new("core/build.gradle.kts"))
            .await
            .unwrap();
        finder
            .visit(&app_manifest, Path::new("app/build.gradle.kts"))
            .await
            .unwrap();

        let projects = finder.projects();
        let core = projects
            .iter()
            .copied()
            .find(|project| project.name() == Some("core"))
            .unwrap();
        let app = projects
            .iter()
            .copied()
            .find(|project| project.name() == Some("app"))
            .unwrap();
        assert!(core.dependencies().is_empty());
        assert_eq!(app.dependencies(), &HashSet::from(["core".to_string()]));

        let sorted = sort_by_dependencies(vec![app, core]).unwrap();
        assert_eq!(
            sorted
                .iter()
                .map(|project| project.name().unwrap())
                .collect::<Vec<_>>(),
            vec!["core", "app"]
        );

        temp_dir.close().unwrap();
    }

    #[cfg(unix)]
    #[test]
    fn test_gradle_subproject_path_rejects_non_unicode_component() {
        use std::ffi::OsString;
        use std::os::unix::ffi::OsStringExt;

        let invalid = PathBuf::from(OsString::from_vec(vec![0x66, 0x80, 0x6f]));

        assert!(gradle_subproject_path(&invalid).is_err());
    }

    #[tokio::test]
    async fn test_which_java_in_none() {
        let result = which_java_in(None).await.unwrap();
        assert!(result.is_none());
    }

    #[tokio::test]
    async fn test_which_java_in_empty() {
        let empty = std::ffi::OsStr::new("");
        let result = which_java_in(Some(empty)).await.unwrap();
        assert!(result.is_none());
    }

    #[tokio::test]
    async fn test_which_java_in_with_java_executable() {
        let temp_dir = TempDir::new().unwrap();
        let java_name = if cfg!(windows) { "java.exe" } else { "java" };
        let java_path = temp_dir.path().join(java_name);
        fs::write(&java_path, "").unwrap();

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            fs::set_permissions(&java_path, fs::Permissions::from_mode(0o755)).unwrap();
        }

        let path_var = temp_dir.path().as_os_str();
        let result = which_java_in(Some(path_var)).await.unwrap();
        assert!(result.is_some());
        assert_eq!(result.unwrap().file_name().unwrap(), java_name);

        temp_dir.close().unwrap();
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn test_which_java_in_rejects_non_executable_file() {
        use std::os::unix::fs::PermissionsExt;

        let temp_dir = TempDir::new().unwrap();
        let java_path = temp_dir.path().join("java");
        fs::write(&java_path, "").unwrap();

        fs::set_permissions(&java_path, fs::Permissions::from_mode(0o644)).unwrap();

        let result = which_java_in(Some(temp_dir.path().as_os_str()))
            .await
            .unwrap();
        assert!(result.is_none());

        temp_dir.close().unwrap();
    }

    #[tokio::test]
    async fn test_which_java_in_without_java() {
        let temp_dir = TempDir::new().unwrap();
        // Create a directory but no java executable
        fs::create_dir_all(temp_dir.path().join("subdir")).unwrap();

        let path_var = temp_dir.path().as_os_str();
        let result = which_java_in(Some(path_var)).await.unwrap();
        assert!(result.is_none());

        temp_dir.close().unwrap();
    }

    #[tokio::test]
    async fn test_java_home_has_java_rejects_empty_value() {
        assert!(!java_home_has_java(None).await.unwrap());
        assert!(
            !java_home_has_java(Some(std::ffi::OsStr::new("")))
                .await
                .unwrap()
        );
    }

    #[tokio::test]
    async fn test_java_home_has_java_rejects_invalid_home() {
        let temp_dir = TempDir::new().unwrap();
        let invalid_home = temp_dir.path().join("missing-java");
        fs::create_dir_all(&invalid_home).unwrap();

        assert!(
            !java_home_has_java(Some(invalid_home.as_os_str()))
                .await
                .unwrap()
        );

        temp_dir.close().unwrap();
    }

    #[tokio::test]
    async fn test_java_home_has_java_accepts_bin_java() {
        let temp_dir = TempDir::new().unwrap();
        let java_name = if cfg!(windows) { "java.exe" } else { "java" };
        let java_path = temp_dir.path().join("bin").join(java_name);
        fs::create_dir_all(java_path.parent().unwrap()).unwrap();
        fs::write(&java_path, "").unwrap();

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            fs::set_permissions(&java_path, fs::Permissions::from_mode(0o755)).unwrap();
        }

        assert!(
            java_home_has_java(Some(temp_dir.path().as_os_str()))
                .await
                .unwrap()
        );

        temp_dir.close().unwrap();
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn test_java_home_has_java_rejects_non_executable_file() {
        use std::os::unix::fs::PermissionsExt;

        let temp_dir = TempDir::new().unwrap();
        let java_path = temp_dir.path().join("bin").join("java");
        fs::create_dir_all(java_path.parent().unwrap()).unwrap();
        fs::write(&java_path, "").unwrap();

        fs::set_permissions(&java_path, fs::Permissions::from_mode(0o644)).unwrap();

        assert!(
            !java_home_has_java(Some(temp_dir.path().as_os_str()))
                .await
                .unwrap()
        );

        temp_dir.close().unwrap();
    }

    #[tokio::test]
    async fn test_gradle_project_finder_visit_name_fallback_to_dir() {
        // When gradlew returns name: unspecified, visit() falls back to directory name (line 173).
        let temp_dir = TempDir::new().unwrap();
        let project_dir = temp_dir.path().join("my-fallback-project");
        fs::create_dir_all(&project_dir).unwrap();

        let build_gradle = project_dir.join("build.gradle.kts");
        fs::write(&build_gradle, "version = \"1.0.0\"\n").unwrap();

        // Mock gradlew that returns unspecified name (filtered to None)
        create_mock_gradlew(&project_dir, MockGradlew::package("unspecified", "1.0.0"));

        let mut finder = finder_with_java_available();
        finder
            .visit(
                &build_gradle,
                &PathBuf::from("my-fallback-project/build.gradle.kts"),
            )
            .await
            .unwrap();

        let projects = finder.projects();
        assert_eq!(projects.len(), 1);
        match projects[0] {
            Project::Package(pkg) => {
                // name fell back to directory name
                assert_eq!(pkg.name(), Some("my-fallback-project"));
                assert_eq!(pkg.version(), Some("1.0.0"));
            }
            Project::Workspace(_) => panic!("Expected Package"),
        }

        temp_dir.close().unwrap();
    }

    #[tokio::test]
    async fn test_gradle_project_finder_visit_fails_when_gradlew_fails() {
        let temp_dir = TempDir::new().unwrap();
        let project_dir = temp_dir.path().join("my-project");
        fs::create_dir_all(&project_dir).unwrap();

        let build_gradle = project_dir.join("build.gradle.kts");
        fs::write(&build_gradle, "plugins { id 'java' }").unwrap();

        create_failing_gradlew(&project_dir);

        let mut finder = finder_with_java_available();
        let error = finder
            .visit(&build_gradle, &PathBuf::from("my-project/build.gradle.kts"))
            .await
            .unwrap_err();

        // Visit propagates the batched metadata discovery failure verbatim, so
        // pin all three parts of that message: the stable headline, the wrapper
        // root it names, and the `; stderr: ...` suffix that only appears when
        // the wrapper actually wrote diagnostics (the empty-stderr branch emits
        // no suffix at all).
        let flattened = error
            .chain()
            .map(ToString::to_string)
            .collect::<Vec<_>>()
            .join(": ");
        assert!(
            flattened.contains("Gradle metadata discovery failed"),
            "{flattened}"
        );
        assert!(
            flattened.contains(&project_dir.display().to_string()),
            "{flattened}"
        );
        assert!(
            flattened.contains(&format!("; stderr: {FAILING_GRADLEW_STDERR_MARKER}")),
            "{flattened}"
        );
        // No projects should be added when gradlew fails
        assert_eq!(finder.project_count(), 0);

        temp_dir.close().unwrap();
    }

    /// Write a wrapper that emits `record` and then deletes `victim_dir`
    /// (relative to the wrapper root it is executed in), reproducing a project
    /// directory that disappears while Gradle is still evaluating the build.
    fn create_self_destructing_gradlew(dir: &Path, victim_dir: &str, record: &str) {
        if cfg!(windows) {
            fs::write(
                dir.join("gradlew.bat"),
                format!(
                    "@echo off\r\necho {record}\r\nrmdir /s /q \"{victim_dir}\"\r\nexit /b 0\r\n"
                ),
            )
            .unwrap();
        } else {
            let gradlew_path = dir.join("gradlew");
            fs::write(
                &gradlew_path,
                format!("#!/bin/sh\nprintf '%s\\n' '{record}'\nrm -rf '{victim_dir}'\n"),
            )
            .unwrap();
            #[cfg(unix)]
            make_executable(&gradlew_path);
        }
    }

    /// `java_is_available` is the only caller that reads the ambient
    /// `JAVA_HOME` / `PATH`; everything below it takes those values as
    /// parameters. Pin that it is exactly the disjunction of its two probes
    /// over the very same ambient values, so swapping the operator, dropping
    /// the `PATH` fallback, or reading the wrong variable is caught.
    ///
    /// Only the arm matching this machine's environment executes: reaching the
    /// other one would require mutating the process environment, which is
    /// `unsafe` under edition 2024 and denied by `[workspace.lints.rust]`.
    #[tokio::test]
    async fn test_java_is_available_matches_its_java_home_and_path_probes() {
        let java_home = std::env::var_os("JAVA_HOME");
        let path = std::env::var_os("PATH");
        let via_java_home = java_home_has_java(java_home.as_deref()).await.unwrap();
        let via_path = which_java_in(path.as_deref()).await.unwrap().is_some();

        let available = java_is_available().await.unwrap();

        assert_eq!(available, via_java_home || via_path);
    }

    /// The wrapper must reach the OS exactly once: Windows spawns
    /// `gradlew.bat` as the program, every other platform spawns `sh` with the
    /// wrapper as its leading argument. Dropping it would run bare `sh`, and
    /// duplicating it would make Gradle treat the wrapper path as a task name,
    /// so the count is the invariant rather than either platform's layout.
    #[test]
    fn test_gradle_command_spec_passes_wrapper_exactly_once() {
        let gradlew_dir = Path::new("repo with spaces");
        let gradlew = gradlew_dir.join(gradle_wrapper_name(cfg!(windows)));

        let spec = GradleCommandSpec::new(&gradlew, gradlew_dir, vec![OsString::from("help")]);

        let mentions = std::iter::once(&spec.program)
            .chain(spec.args.iter())
            .filter(|value| value.as_os_str() == gradlew.as_os_str())
            .count();
        assert_eq!(mentions, 1);
        assert_eq!(spec.args.last(), Some(&OsString::from("help")));
        if cfg!(windows) {
            assert_eq!(spec.program, gradlew.as_os_str());
        } else {
            assert_eq!(spec.program, OsString::from("sh"));
        }
    }

    /// Both wrapper layouts, from either host. `new` reads `cfg!(windows)`, so
    /// on any single machine one of these arms would never run; taking the
    /// platform as a parameter is what keeps the Windows layout exercised on
    /// the Linux coverage runner and vice versa.
    #[rstest]
    #[case(true, "gradlew.bat")]
    #[case(false, "gradlew")]
    fn test_gradle_command_spec_for_platform_builds_both_layouts(
        #[case] windows: bool,
        #[case] expected_wrapper: &str,
    ) {
        let gradlew_dir = Path::new("repo");
        let gradlew = gradlew_dir.join(gradle_wrapper_name(windows));
        assert_eq!(gradlew.file_name().unwrap(), expected_wrapper);

        let spec = GradleCommandSpec::for_platform(
            &gradlew,
            gradlew_dir,
            vec![OsString::from("help")],
            windows,
        );

        if windows {
            assert_eq!(spec.program, gradlew.as_os_str());
            assert_eq!(spec.args, vec![OsString::from("help")]);
        } else {
            assert_eq!(spec.program, OsString::from("sh"));
            assert_eq!(
                spec.args,
                vec![gradlew.as_os_str().to_owned(), OsString::from("help")]
            );
        }
        assert_eq!(spec.current_dir, gradlew_dir);
    }

    /// Create an executable `java` (`java.exe` on Windows) inside `dir`, the
    /// shape both `java_home_has_java` (as `<home>/bin/java`) and
    /// `which_java_in` (as `<path entry>/java`) accept.
    fn create_java_executable(dir: &Path) {
        #[cfg(unix)]
        use std::os::unix::fs::PermissionsExt;

        fs::create_dir_all(dir).unwrap();
        let java_path = dir.join(if cfg!(windows) { "java.exe" } else { "java" });
        fs::write(&java_path, "").unwrap();
        #[cfg(unix)]
        fs::set_permissions(&java_path, fs::Permissions::from_mode(0o755)).unwrap();
    }

    /// `JAVA_HOME` short-circuits the search: with a usable `bin/java` there,
    /// an empty PATH must still report Java as available.
    #[tokio::test]
    async fn test_java_is_available_in_short_circuits_on_java_home() {
        let temp_dir = TempDir::new().unwrap();
        create_java_executable(&temp_dir.path().join("bin"));

        assert!(
            java_is_available_in(Some(temp_dir.path().as_os_str()), Some(OsStr::new("")))
                .await
                .unwrap()
        );
    }

    /// A `JAVA_HOME` without `bin/java` must not end the search — the PATH
    /// fallback still finds a runtime.
    #[tokio::test]
    async fn test_java_is_available_in_falls_back_to_path() {
        let temp_dir = TempDir::new().unwrap();
        let java_home = temp_dir.path().join("home-without-java");
        let path_entry = temp_dir.path().join("path-entry");
        fs::create_dir_all(&java_home).unwrap();
        create_java_executable(&path_entry);

        assert!(
            java_is_available_in(Some(java_home.as_os_str()), Some(path_entry.as_os_str()))
                .await
                .unwrap()
        );
    }

    /// Neither probe finds a runtime, so the disjunction is false.
    #[tokio::test]
    async fn test_java_is_available_in_reports_absent_runtime() {
        let temp_dir = TempDir::new().unwrap();
        let java_home = temp_dir.path().join("home-without-java");
        let path_entry = temp_dir.path().join("path-without-java");
        fs::create_dir_all(&java_home).unwrap();
        fs::create_dir_all(&path_entry).unwrap();

        assert!(
            !java_is_available_in(Some(java_home.as_os_str()), Some(path_entry.as_os_str()))
                .await
                .unwrap()
        );
    }

    /// `visit` normalizes the project directory with its OWN context, separate
    /// from the wrapper-root and metadata-directory normalizations that run
    /// before it. The wrapper deletes the project directory as it runs — after
    /// the manifest has been read and the wrapper located, and while still
    /// emitting a valid record for the (surviving) repository root — so the
    /// project-directory normalization is the only step left that can fail.
    #[tokio::test]
    async fn test_gradle_finder_errors_when_project_directory_disappears_before_normalization() {
        let temp_dir = TempDir::new().unwrap();
        let repo = temp_dir.path().join("repo");
        let module_dir = repo.join("module");
        tokio::fs::create_dir_all(&module_dir).await.unwrap();
        let manifest = module_dir.join("build.gradle.kts");
        tokio::fs::write(&manifest, "plugins { java }\n")
            .await
            .unwrap();
        create_self_destructing_gradlew(
            &repo,
            "module",
            &metadata_record(&repo, ":", "root project", true),
        );

        let error = finder_with_java_available()
            .visit(
                &manifest,
                Path::new("module").join("build.gradle.kts").as_path(),
            )
            .await
            .unwrap_err();
        let message = format!("{error:#}");

        assert!(
            message.contains("Failed to normalize Gradle project directory"),
            "{message}"
        );
        assert!(
            message.contains(&module_dir.display().to_string()),
            "{message}"
        );
        assert!(
            message.contains(&manifest.display().to_string()),
            "{message}"
        );

        temp_dir.close().unwrap();
    }

    /// Two records that carry DIFFERENT Gradle paths but the SAME project
    /// directory collide on the `by_project_dir` key. That is a distinct
    /// failure from the duplicate-project-path collision pinned above — it
    /// survives the `project_names_by_path` guard entirely — so it must report
    /// the directory and both offending Gradle paths.
    #[tokio::test]
    async fn test_gradle_finder_errors_when_wrapper_metadata_duplicates_normalized_directory() {
        let temp_dir = TempDir::new().unwrap();
        let repo = temp_dir.path().join("repo");
        let shared_dir = repo.join("shared");
        tokio::fs::create_dir_all(&shared_dir).await.unwrap();
        let manifest = repo.join("build.gradle.kts");
        tokio::fs::write(&manifest, "plugins { java }\n")
            .await
            .unwrap();
        create_metadata_gradlew(
            &repo,
            &[
                metadata_record(&repo, ":", "root project", true),
                metadata_record(&shared_dir, ":alpha", "alpha", false),
                metadata_record(&shared_dir, ":beta", "beta", false),
            ],
        )
        .await;

        let error = finder_with_java_available()
            .visit(&manifest, Path::new("build.gradle.kts"))
            .await
            .unwrap_err();
        let message = format!("{error:#}");

        assert!(
            message.contains("Duplicate Gradle metadata records for normalized directory"),
            "{message}"
        );
        assert!(message.contains("shared"), "{message}");
        assert!(message.contains(":alpha"), "{message}");
        assert!(message.contains(":beta"), "{message}");
        assert!(message.contains("gradlew"), "{message}");

        temp_dir.close().unwrap();
    }
}