cargo-cross 1.5.0

A cargo subcommand for cross-compilation, no need docker!
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
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
//! Command-line argument parsing for cargo-cross using clap

use crate::config::{
    self, supported_freebsd_versions_str, supported_glibc_versions_str,
    supported_iphone_sdk_versions_str, supported_macos_sdk_versions_str,
    DEFAULT_CROSS_MAKE_VERSION, DEFAULT_FREEBSD_VERSION, DEFAULT_GLIBC_VERSION,
    DEFAULT_IPHONE_SDK_VERSION, DEFAULT_MACOS_SDK_VERSION, DEFAULT_NDK_VERSION,
    DEFAULT_QEMU_VERSION, SUPPORTED_FREEBSD_VERSIONS, SUPPORTED_GLIBC_VERSIONS,
    SUPPORTED_IPHONE_SDK_VERSIONS, SUPPORTED_MACOS_SDK_VERSIONS,
};
use crate::error::{CrossError, Result};
use clap::builder::styling::{AnsiColor, Effects, Styles};
use clap::ArgAction;
use clap::{Args as ClapArgs, CommandFactory, FromArgMatches, Parser, Subcommand, ValueHint};
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::LazyLock;

/// Binary name from Cargo.toml (e.g., "cargo-cross")
const BIN_NAME: &str = env!("CARGO_PKG_NAME");

/// Define subcommand-related constants from a single literal
macro_rules! define_subcommand {
    ($name:literal) => {
        const SUBCOMMAND: &str = $name;
        const CARGO_DISPLAY_NAME: &str = concat!("cargo ", $name);
    };
}
define_subcommand!("cross");

/// Program name - either "cargo cross" or "cargo-cross" based on invocation style
static PROGRAM_NAME: LazyLock<&'static str> = LazyLock::new(|| {
    let args: Vec<String> = std::env::args().collect();
    let is_cargo_subcommand = std::env::var("CARGO").is_ok()
        && std::env::var("CARGO_HOME").is_ok()
        && args.get(1).map(String::as_str) == Some(SUBCOMMAND);

    if is_cargo_subcommand {
        CARGO_DISPLAY_NAME
    } else {
        BIN_NAME
    }
});

/// Get the program name for display
#[must_use]
pub fn program_name() -> &'static str {
    *PROGRAM_NAME
}

/// Custom styles for CLI help output
fn cli_styles() -> Styles {
    Styles::styled()
        .header(AnsiColor::BrightCyan.on_default() | Effects::BOLD)
        .usage(AnsiColor::BrightCyan.on_default() | Effects::BOLD)
        .literal(AnsiColor::BrightGreen.on_default())
        .placeholder(AnsiColor::BrightMagenta.on_default())
        .valid(AnsiColor::BrightGreen.on_default())
        .invalid(AnsiColor::BrightRed.on_default())
        .error(AnsiColor::BrightRed.on_default() | Effects::BOLD)
}

/// Cross-compilation tool for Rust projects
#[derive(Parser, Debug)]
#[command(name = "cargo-cross", version)]
#[command(about = "Cross-compilation tool for Rust projects, no Docker required")]
#[command(long_about = "\
Cross-compilation tool for Rust projects.

This tool provides cross-compilation support for Rust projects across multiple
platforms including Linux (musl/gnu), Windows, macOS, FreeBSD, iOS, and Android.
It automatically downloads and configures the appropriate cross-compiler toolchains.")]
#[command(propagate_version = true)]
#[command(arg_required_else_help = true)]
#[command(styles = cli_styles())]
#[command(override_usage = "cargo-cross [+toolchain] <COMMAND> [OPTIONS]")]
#[command(after_help = "\
Use 'cargo-cross <COMMAND> --help' for more information about a command.

TOOLCHAIN:
    If the first argument begins with +, it will be interpreted as a Rust toolchain
    name (such as +nightly, +stable, or +1.75.0). This follows the same convention
    as rustup and cargo.

EXAMPLES:
    cargo-cross build -t x86_64-unknown-linux-musl
    cargo-cross +nightly build -t aarch64-unknown-linux-gnu --profile release
    cargo-cross build -t '*-linux-musl' --crt-static true
    cargo-cross test -t x86_64-unknown-linux-musl -- --nocapture")]
pub struct Cli {
    #[command(subcommand)]
    pub command: CliCommand,
}

#[derive(Subcommand, Debug)]
pub enum CliCommand {
    /// Compile the current package
    #[command(visible_alias = "b")]
    #[command(long_about = "\
Compile the current package and all of its dependencies.

When no target selection options are given, this tool will build all binary
and library targets of the selected packages.")]
    Build(BuildArgs),

    /// Analyze the current package and report errors, but don't build object files
    #[command(visible_alias = "c")]
    #[command(long_about = "\
Check the current package and all of its dependencies for errors.

This will essentially compile packages without performing the final step of
code generation, which is faster than running build.")]
    Check(BuildArgs),

    /// Run a binary or example of the current package
    #[command(visible_alias = "r")]
    #[command(long_about = "\
Run a binary or example of the local package.

For cross-compilation targets, QEMU user-mode emulation is used to run the binary.")]
    Run(BuildArgs),

    /// Run the tests
    #[command(visible_alias = "t")]
    #[command(long_about = "\
Execute all unit and integration tests and build examples of a local package.

For cross-compilation targets, QEMU user-mode emulation is used to run tests.")]
    Test(BuildArgs),

    /// Run the benchmarks
    #[command(long_about = "\
Execute all benchmarks of a local package.

For cross-compilation targets, QEMU user-mode emulation is used to run benchmarks.")]
    Bench(BuildArgs),

    /// Run Clippy lints on the current package
    #[command(long_about = "\
Run Clippy on the current package and all of its dependencies.

This forwards to `cargo clippy` with the configured cross-compilation environment.")]
    Clippy(BuildArgs),

    /// Prepare and print the configured cross-compilation environment
    #[command(long_about = "\
Prepare the cross-compilation environment and print environment variables.

This is intended for use with shell evaluation, for example:
    eval \"$(cargo cross setup -t aarch64-unknown-linux-musl)\"")]
    Setup(SetupCliArgs),

    /// Execute an arbitrary command inside the configured cross-compilation environment
    #[command(long_about = "\
Prepare the cross-compilation environment and execute an arbitrary command.

This is useful for running custom tooling that should inherit the configured
compiler, linker, PATH, and cargo target environment variables.")]
    Exec(ExecCliArgs),

    /// Display all supported cross-compilation targets
    #[command(long_about = "\
Display all supported cross-compilation targets.

You can also use glob patterns with --target to match multiple targets,
for example: --target '*-linux-musl' or --target 'aarch64-*'")]
    Targets(TargetsArgs),

    /// Print version information
    Version,
}

/// Output format for targets command
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, clap::ValueEnum)]
pub enum OutputFormat {
    /// Human-readable colored text (default)
    #[default]
    Text,
    /// JSON array format
    Json,
    /// Plain text, one target per line
    Plain,
}

/// Output format for setup command
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, clap::ValueEnum)]
pub enum SetupOutputFormat {
    /// Detect the current shell from the environment, fallback to bash syntax
    #[default]
    Auto,
    /// Bash-compatible exports
    Bash,
    /// Zsh-compatible exports
    Zsh,
    /// Fish shell exports
    Fish,
    /// PowerShell environment assignments
    Powershell,
    /// Windows cmd.exe environment assignments
    Cmd,
    /// JSON object
    Json,
}

#[derive(ClapArgs, Debug, Clone)]
pub struct SetupCliArgs {
    #[command(flatten)]
    pub build: BuildArgs,

    /// Output format
    #[arg(
        short = 'f',
        long = "format",
        value_enum,
        default_value = "auto",
        help = "Output format (auto, bash, zsh, fish, powershell, cmd, json)"
    )]
    pub format: SetupOutputFormat,
}

#[derive(Debug, Clone)]
pub struct SetupArgs {
    pub args: Args,
    pub format: SetupOutputFormat,
}

#[derive(ClapArgs, Debug, Clone)]
pub struct ExecCliArgs {
    #[command(flatten)]
    pub build: BuildArgs,
}

#[derive(Debug, Clone)]
pub struct ExecArgs {
    pub args: Args,
    pub command: Vec<String>,
}

#[derive(ClapArgs, Debug, Clone, Default)]
pub struct TargetsArgs {
    /// Output format
    #[arg(
        short = 'f',
        long = "format",
        value_enum,
        default_value = "text",
        help = "Output format (text, json, plain)"
    )]
    pub format: OutputFormat,
}

#[derive(ClapArgs, Debug, Clone, Default)]
#[command(next_help_heading = "Target Selection")]
pub struct BuildArgs {
    // ===== Target Selection =====
    /// Build for the target triple(s)
    #[arg(
        short = 't',
        long = "target",
        visible_alias = "targets",
        value_delimiter = ',',
        env = "TARGETS",
        value_name = "TRIPLE",
        help = "Build for the target triple(s), comma-separated",
        long_help = "\
Build for the specified target architecture. This flag may be specified multiple
times or with comma-separated values. Supports glob patterns like '*-linux-musl'.
The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi>.
Run the 'targets' subcommand to see all supported targets.

Examples: -t x86_64-unknown-linux-musl, -t '*-linux-musl'"
    )]
    pub targets: Vec<String>,

    // ===== Feature Selection =====
    /// Space or comma separated list of features to activate
    #[arg(
        short = 'F',
        long,
        env = "FEATURES",
        value_name = "FEATURES",
        conflicts_with = "all_features",
        help_heading = "Feature Selection",
        long_help = "\
Space or comma separated list of features to activate. Features of workspace members
may be enabled with package-name/feature-name syntax. May be specified multiple times."
    )]
    pub features: Option<String>,

    /// Do not activate the `default` feature of the selected packages
    #[arg(long, env = "NO_DEFAULT_FEATURES", help_heading = "Feature Selection")]
    pub no_default_features: bool,

    /// Activate all available features of all selected packages
    #[arg(
        long,
        env = "ALL_FEATURES",
        conflicts_with = "features",
        help_heading = "Feature Selection"
    )]
    pub all_features: bool,

    // ===== Profile =====
    /// Build artifacts in release mode, with optimizations
    #[arg(
        short = 'r',
        long = "release",
        conflicts_with = "profile",
        help_heading = "Profile",
        long_help = "\
Build artifacts in release mode, with optimizations. Equivalent to --profile=release."
    )]
    pub release: bool,

    /// Build artifacts with the specified profile
    #[arg(
        long,
        default_value = "dev",
        env = "PROFILE",
        value_name = "PROFILE-NAME",
        conflicts_with = "release",
        help_heading = "Profile",
        long_help = "\
Build artifacts with the specified profile. Built-in: dev, release, test, bench.
Custom profiles can be defined in Cargo.toml. Default is 'dev'."
    )]
    pub profile: String,

    // ===== Package Selection =====
    /// Package to build (see `cargo help pkgid`)
    #[arg(
        short = 'p',
        long,
        env = "PACKAGE",
        value_name = "SPEC",
        help_heading = "Package Selection",
        long_help = "\
Build only the specified packages. This flag may be specified multiple times
and supports common Unix glob patterns like *, ?, and []."
    )]
    pub package: Option<String>,

    /// Build all members in the workspace
    #[arg(
        long,
        visible_alias = "all",
        env = "BUILD_WORKSPACE",
        help_heading = "Package Selection"
    )]
    pub workspace: bool,

    /// Exclude packages from the build (must be used with --workspace)
    #[arg(
        long,
        env = "EXCLUDE",
        value_name = "SPEC",
        requires = "workspace",
        help_heading = "Package Selection",
        long_help = "\
Exclude the specified packages. Must be used in conjunction with the --workspace flag.
This flag may be specified multiple times and supports common Unix glob patterns."
    )]
    pub exclude: Option<String>,

    /// Build only the specified binary
    #[arg(
        long = "bin",
        env = "BIN_TARGET",
        value_name = "NAME",
        help_heading = "Package Selection",
        long_help = "\
Build the specified binary. This flag may be specified multiple times
and supports common Unix glob patterns."
    )]
    pub bin_target: Option<String>,

    /// Build all binary targets
    #[arg(long = "bins", env = "BUILD_BINS", help_heading = "Package Selection")]
    pub build_bins: bool,

    /// Build only this package's library
    #[arg(long = "lib", env = "BUILD_LIB", help_heading = "Package Selection")]
    pub build_lib: bool,

    /// Build only the specified example
    #[arg(
        long = "example",
        env = "EXAMPLE_TARGET",
        value_name = "NAME",
        help_heading = "Package Selection",
        long_help = "\
Build the specified example. This flag may be specified multiple times
and supports common Unix glob patterns."
    )]
    pub example_target: Option<String>,

    /// Build all example targets
    #[arg(
        long = "examples",
        env = "BUILD_EXAMPLES",
        help_heading = "Package Selection"
    )]
    pub build_examples: bool,

    /// Build only the specified test target
    #[arg(
        long = "test",
        env = "TEST_TARGET",
        value_name = "NAME",
        help_heading = "Package Selection",
        long_help = "\
Build the specified integration test. This flag may be specified multiple times
and supports common Unix glob patterns."
    )]
    pub test_target: Option<String>,

    /// Build all test targets (includes unit tests from lib/bins)
    #[arg(
        long = "tests",
        env = "BUILD_TESTS",
        help_heading = "Package Selection",
        long_help = "\
Build all targets that have the test = true manifest flag set. By default this
includes the library and binaries built as unittests, and integration tests."
    )]
    pub build_tests: bool,

    /// Build only the specified bench target
    #[arg(
        long = "bench",
        env = "BENCH_TARGET",
        value_name = "NAME",
        help_heading = "Package Selection",
        long_help = "\
Build the specified benchmark. This flag may be specified multiple times
and supports common Unix glob patterns."
    )]
    pub bench_target: Option<String>,

    /// Build all bench targets
    #[arg(
        long = "benches",
        env = "BUILD_BENCHES",
        help_heading = "Package Selection",
        long_help = "\
Build all targets that have the bench = true manifest flag set. By default this
includes the library and binaries built as benchmarks, and bench targets."
    )]
    pub build_benches: bool,

    /// Build all targets (equivalent to --lib --bins --tests --benches --examples)
    #[arg(
        long = "all-targets",
        env = "BUILD_ALL_TARGETS",
        help_heading = "Package Selection"
    )]
    pub build_all_targets: bool,

    /// Path to Cargo.toml
    #[arg(long, env = "MANIFEST_PATH", value_name = "PATH",
          value_hint = ValueHint::FilePath, help_heading = "Package Selection",
          long_help = "\
Path to Cargo.toml. By default, Cargo searches for the Cargo.toml file
in the current directory or any parent directory.")]
    pub manifest_path: Option<PathBuf>,

    // ===== Version Options =====
    /// Glibc version for Linux GNU targets
    #[arg(long, default_value = DEFAULT_GLIBC_VERSION, env = "GLIBC_VERSION",
          value_name = "VERSION", hide_default_value = true, help_heading = "Toolchain Versions")]
    pub glibc_version: String,

    /// iPhone SDK version for iOS targets
    #[arg(long, default_value = DEFAULT_IPHONE_SDK_VERSION, env = "IPHONE_SDK_VERSION",
          value_name = "VERSION", hide_default_value = true, help_heading = "Toolchain Versions")]
    pub iphone_sdk_version: String,

    /// Override iPhoneOS SDK path (skips version lookup)
    #[arg(long, env = "IPHONE_SDK_PATH", value_name = "PATH",
          value_hint = ValueHint::DirPath, help_heading = "Toolchain Versions",
          long_help = "\
Override iPhoneOS SDK path for device targets. Skips version lookup.")]
    pub iphone_sdk_path: Option<PathBuf>,

    /// Override iPhoneSimulator SDK path
    #[arg(long, env = "IPHONE_SIMULATOR_SDK_PATH", value_name = "PATH",
          value_hint = ValueHint::DirPath, help_heading = "Toolchain Versions",
          long_help = "\
Override iPhoneSimulator SDK path for simulator targets. Skips version lookup.")]
    pub iphone_simulator_sdk_path: Option<PathBuf>,

    /// macOS SDK version for Darwin targets
    #[arg(long, default_value = DEFAULT_MACOS_SDK_VERSION, env = "MACOS_SDK_VERSION",
          value_name = "VERSION", hide_default_value = true, help_heading = "Toolchain Versions")]
    pub macos_sdk_version: String,

    /// Override macOS SDK path (skips version lookup)
    #[arg(long, env = "MACOS_SDK_PATH", value_name = "PATH",
          value_hint = ValueHint::DirPath, help_heading = "Toolchain Versions",
          long_help = "\
Override macOS SDK path directly. Skips version lookup.")]
    pub macos_sdk_path: Option<PathBuf>,

    /// FreeBSD version for FreeBSD targets
    #[arg(long, default_value = DEFAULT_FREEBSD_VERSION, env = "FREEBSD_VERSION",
          value_name = "VERSION", hide_default_value = true, help_heading = "Toolchain Versions")]
    pub freebsd_version: String,

    /// Android NDK version
    #[arg(long, default_value = DEFAULT_NDK_VERSION, env = "NDK_VERSION",
          value_name = "VERSION", hide_default_value = true, help_heading = "Toolchain Versions",
          long_help = "\
Specify Android NDK version for Android targets. Auto-downloaded from Google's official repository.")]
    pub ndk_version: String,

    /// QEMU version for user-mode emulation
    #[arg(long, default_value = DEFAULT_QEMU_VERSION, env = "QEMU_VERSION",
          value_name = "VERSION", hide_default_value = true, help_heading = "Toolchain Versions",
          long_help = "\
Specify QEMU version for user-mode emulation. Used to run cross-compiled binaries during test/run/bench.")]
    pub qemu_version: String,

    /// Cross-compiler make version
    #[arg(long, default_value = DEFAULT_CROSS_MAKE_VERSION, env = "CROSS_MAKE_VERSION",
          value_name = "VERSION", hide_default_value = true, help_heading = "Toolchain Versions",
          long_help = "\
Specify cross-compiler make version. This determines which version of cross-compilation \
toolchains will be downloaded from the upstream repository.")]
    pub cross_make_version: String,

    // ===== Directories =====
    /// Directory for cross-compiler toolchains
    #[arg(long, env = "CROSS_COMPILER_DIR", value_name = "DIR",
          value_hint = ValueHint::DirPath, help_heading = "Directories",
          long_help = "\
Directory where cross-compiler toolchains will be downloaded and stored. Defaults to temp dir.
Set this to reuse downloaded toolchains across builds.")]
    pub cross_compiler_dir: Option<PathBuf>,

    /// Directory for all generated artifacts
    #[arg(long, visible_alias = "target-dir", env = "CARGO_TARGET_DIR", value_name = "DIR",
          value_hint = ValueHint::DirPath, help_heading = "Directories",
          long_help = "\
Directory for all generated artifacts and intermediate files. Defaults to 'target'.")]
    pub cargo_target_dir: Option<PathBuf>,

    /// Copy final artifacts to this directory (unstable)
    #[arg(long, env = "ARTIFACT_DIR", value_name = "DIR",
          value_hint = ValueHint::DirPath, help_heading = "Directories",
          long_help = "\
Copy final artifacts to this directory. Unstable, requires nightly toolchain.")]
    pub artifact_dir: Option<PathBuf>,

    // ===== Compiler Options =====
    /// Override C compiler path
    #[arg(long, env = "CC", value_name = "PATH",
          value_hint = ValueHint::ExecutablePath, help_heading = "Compiler Options",
          long_help = "\
Override the C compiler path. By default, the appropriate cross-compiler is auto-configured.")]
    pub cc: Option<PathBuf>,

    /// Override C++ compiler path
    #[arg(long, env = "CXX", value_name = "PATH",
          value_hint = ValueHint::ExecutablePath, help_heading = "Compiler Options",
          long_help = "\
Override the C++ compiler path. By default, the appropriate cross-compiler is auto-configured.")]
    pub cxx: Option<PathBuf>,

    /// Override archiver (ar) path
    #[arg(long, env = "AR", value_name = "PATH",
          value_hint = ValueHint::ExecutablePath, help_heading = "Compiler Options",
          long_help = "\
Override the archiver (ar) path. By default, the appropriate archiver is auto-configured.")]
    pub ar: Option<PathBuf>,

    /// Override linker path
    #[arg(long, env = "LINKER", value_name = "PATH",
          value_hint = ValueHint::ExecutablePath, help_heading = "Compiler Options",
          long_help = "\
Override the linker path. By default, the cross-compiler is used as linker.
This option takes precedence over auto-configured linker.")]
    pub linker: Option<PathBuf>,

    /// Additional flags for C compilation
    #[arg(
        long,
        env = "CFLAGS",
        value_name = "FLAGS",
        allow_hyphen_values = true,
        help_heading = "Compiler Options",
        long_help = "\
Additional flags to pass to the C compiler. Appended to default CFLAGS.
Example: --cflags '-O2 -Wall -march=native'"
    )]
    pub cflags: Option<String>,

    /// Additional flags for C++ compilation
    #[arg(
        long,
        env = "CXXFLAGS",
        value_name = "FLAGS",
        allow_hyphen_values = true,
        help_heading = "Compiler Options",
        long_help = "\
Additional flags to pass to the C++ compiler. Appended to default CXXFLAGS.
Example: --cxxflags '-O2 -Wall -std=c++17'"
    )]
    pub cxxflags: Option<String>,

    /// Additional flags for linking
    #[arg(
        long,
        env = "LDFLAGS",
        value_name = "FLAGS",
        allow_hyphen_values = true,
        help_heading = "Compiler Options",
        long_help = "\
Additional flags to pass to the linker. Appended to default LDFLAGS.
Example: --ldflags '-L/usr/local/lib -static'"
    )]
    pub ldflags: Option<String>,

    /// C++ standard library to use
    #[arg(
        long,
        env = "CXXSTDLIB",
        value_name = "LIB",
        help_heading = "Compiler Options",
        long_help = "\
Specify the C++ standard library to use (libc++, libstdc++, etc)."
    )]
    pub cxxstdlib: Option<String>,

    /// `CMake` generator to use (like cmake -G)
    #[arg(
        long,
        short = 'G',
        env = "CMAKE_GENERATOR",
        value_name = "GENERATOR",
        help_heading = "Compiler Options",
        long_help = "\
Specify the CMake generator to use. On Windows, this overrides the auto-detection.
Common generators: Ninja, 'MinGW Makefiles', 'Unix Makefiles', 'NMake Makefiles'.
If not specified, auto-detects: Ninja > MinGW Makefiles > Unix Makefiles."
    )]
    pub cmake_generator: Option<String>,

    /// Additional RUSTFLAGS (can be repeated)
    #[arg(long = "rustflag", visible_alias = "rustflags", value_name = "FLAG",
          env = "ADDITIONAL_RUSTFLAGS", allow_hyphen_values = true,
          action = clap::ArgAction::Append, help_heading = "Compiler Options",
          long_help = "\
Additional flags to pass to rustc via RUSTFLAGS. Can be specified multiple times.
Example: --rustflag '-C target-cpu=native' --rustflag '-C lto=thin'")]
    pub rustflags: Vec<String>,

    /// Rustc wrapper program (e.g., sccache, cachepot)
    #[arg(long, env = "RUSTC_WRAPPER", value_name = "PATH",
          value_hint = ValueHint::ExecutablePath,
          conflicts_with = "enable_sccache", help_heading = "Compiler Options",
          long_help = "\
Specify a rustc wrapper program (sccache, cachepot, etc) for compilation caching.")]
    pub rustc_wrapper: Option<PathBuf>,

    /// Skip cross-compilation toolchain setup
    #[arg(
        long,
        env = "NO_TOOLCHAIN_SETUP",
        help_heading = "Compiler Options",
        long_help = "\
Skip downloading and configuring cross-compilation toolchain.
Use this when you have pre-configured system compilers or want to use
only CLI-provided compiler options (--cc, --cxx, --ar, --linker)."
    )]
    pub no_toolchain_setup: bool,

    // ===== Sccache Options =====
    /// Enable sccache for compilation caching
    #[arg(
        long,
        env = "ENABLE_SCCACHE",
        conflicts_with = "rustc_wrapper",
        help_heading = "Sccache Options",
        long_help = "\
Enable sccache as the rustc wrapper for compilation caching.
Speeds up compilation by caching previous compilations."
    )]
    pub enable_sccache: bool,

    /// Directory for sccache local disk cache
    #[arg(long, env = "SCCACHE_DIR", value_name = "DIR",
          value_hint = ValueHint::DirPath, help_heading = "Sccache Options",
          long_help = "\
Directory for sccache's local disk cache. Defaults to $HOME/.cache/sccache.")]
    pub sccache_dir: Option<PathBuf>,

    /// Maximum cache size (e.g., '10G', '500M')
    #[arg(
        long,
        env = "SCCACHE_CACHE_SIZE",
        value_name = "SIZE",
        help_heading = "Sccache Options",
        long_help = "\
Maximum size of the local disk cache (e.g., '10G', '500M'). Default is 10GB."
    )]
    pub sccache_cache_size: Option<String>,

    /// Idle timeout in seconds for sccache server
    #[arg(
        long,
        env = "SCCACHE_IDLE_TIMEOUT",
        value_name = "SECONDS",
        help_heading = "Sccache Options",
        long_help = "\
Idle timeout in seconds for the sccache server. Set to 0 to run indefinitely."
    )]
    pub sccache_idle_timeout: Option<String>,

    /// Log level for sccache (error, warn, info, debug, trace)
    #[arg(
        long,
        env = "SCCACHE_LOG",
        value_name = "LEVEL",
        help_heading = "Sccache Options",
        long_help = "\
Log level for sccache. Valid: error, warn, info, debug, trace"
    )]
    pub sccache_log: Option<String>,

    /// Run sccache without the daemon (single process mode)
    #[arg(
        long,
        env = "SCCACHE_NO_DAEMON",
        help_heading = "Sccache Options",
        long_help = "\
Run sccache without daemon (single-process mode). May be slower but avoids daemon startup issues."
    )]
    pub sccache_no_daemon: bool,

    /// Enable sccache direct mode (bypass preprocessor)
    #[arg(
        long,
        env = "SCCACHE_DIRECT",
        help_heading = "Sccache Options",
        long_help = "\
Enable sccache direct mode. Caches based on source file content directly, bypassing preprocessor."
    )]
    pub sccache_direct: bool,

    // ===== CC Crate Options =====
    /// Disable CC crate default compiler flags
    #[arg(
        long,
        env = "CRATE_CC_NO_DEFAULTS",
        hide = true,
        help_heading = "CC Crate Options"
    )]
    pub cc_no_defaults: bool,

    /// Use shell-escaped flags for CC crate
    #[arg(
        long,
        env = "CC_SHELL_ESCAPED_FLAGS",
        hide = true,
        help_heading = "CC Crate Options"
    )]
    pub cc_shell_escaped_flags: bool,

    /// Enable CC crate debug output
    #[arg(
        long,
        env = "CC_ENABLE_DEBUG_OUTPUT",
        hide = true,
        help_heading = "CC Crate Options"
    )]
    pub cc_enable_debug: bool,

    // ===== Build Options =====
    /// Link the C runtime statically
    #[arg(long, value_parser = parse_optional_bool, env = "CRT_STATIC",
          value_name = "BOOL", num_args = 0..=1, default_missing_value = "true",
          help_heading = "Build Options",
          long_help = "\
Control whether the C runtime is statically linked. true=static (larger, portable),
false=dynamic (smaller, requires libc). Musl defaults to static, glibc to dynamic.")]
    pub crt_static: Option<bool>,

    /// Abort immediately on panic (smaller binary, implies --build-std)
    #[arg(
        long,
        env = "PANIC_IMMEDIATE_ABORT",
        help_heading = "Build Options",
        long_help = "\
Use panic=abort and remove panic formatting code for smaller binaries.
Requires nightly and implies --build-std. Stack traces will not be available."
    )]
    pub panic_immediate_abort: bool,

    /// Debug formatting mode (full, shallow, none) - requires nightly
    #[arg(long, value_name = "MODE", hide = true, help_heading = "Build Options")]
    pub fmt_debug: Option<String>,

    /// Location detail mode - requires nightly
    #[arg(long, value_name = "MODE", hide = true, help_heading = "Build Options")]
    pub location_detail: Option<String>,

    /// Build the standard library from source
    #[arg(long, value_parser = parse_build_std, env = "BUILD_STD",
          value_name = "CRATES", help_heading = "Build Options",
          num_args = 0..=1, default_missing_value = "true",
          long_help = "\
Build the standard library from source (requires nightly). Without arguments, builds 'std'.
Use 'true' for full std or specify crates like 'core,alloc'. Required for unsupported targets or panic=abort.")]
    pub build_std: Option<String>,

    /// Features to enable when building std
    #[arg(
        long,
        env = "BUILD_STD_FEATURES",
        value_name = "FEATURES",
        requires = "build_std",
        help_heading = "Build Options",
        long_help = "\
Space-separated features for std. Common: panic_immediate_abort, optimize_for_size"
    )]
    pub build_std_features: Option<String>,

    /// Trim paths in compiler output for reproducible builds
    #[arg(
        long,
        visible_alias = "trim-paths",
        env = "CARGO_TRIM_PATHS",
        value_name = "VALUE",
        num_args = 0..=1,
        default_missing_value = "true",
        help_heading = "Build Options",
        long_help = "\
Control how paths are trimmed in compiler output for reproducible builds.
Valid: true, macro, diagnostics, object, all, none (default: false)"
    )]
    pub cargo_trim_paths: Option<String>,

    /// Disable metadata embedding (requires nightly)
    #[arg(
        long,
        env = "NO_EMBED_METADATA",
        hide = true,
        help_heading = "Build Options"
    )]
    pub no_embed_metadata: bool,

    /// Set `RUSTC_BOOTSTRAP` for using nightly features on stable
    #[arg(
        long,
        env = "RUSTC_BOOTSTRAP",
        value_name = "VALUE",
        num_args = 0..=1,
        default_missing_value = "1",
        hide = true,
        help_heading = "Build Options"
    )]
    pub rustc_bootstrap: Option<String>,

    // ===== Output Options =====
    /// Use verbose output (-v, -vv for very verbose)
    #[arg(short = 'v', long = "verbose", action = clap::ArgAction::Count,
          env = "VERBOSE_LEVEL", conflicts_with = "quiet",
          help_heading = "Output Options",
          long_help = "\
Use verbose output. -v=commands/warnings, -vv=+deps/build scripts, -vvv=max verbosity")]
    pub verbose_level: u8,

    /// Do not print cargo log messages
    #[arg(
        short = 'q',
        long,
        env = "QUIET",
        conflicts_with = "verbose_level",
        help_heading = "Output Options",
        long_help = "\
Do not print cargo log messages. Shows only errors and warnings."
    )]
    pub quiet: bool,

    /// Diagnostic message format
    #[arg(
        long,
        env = "MESSAGE_FORMAT",
        value_name = "FMT",
        help_heading = "Output Options",
        long_help = "\
Output format for diagnostics. Valid: human (default), short, json"
    )]
    pub message_format: Option<String>,

    /// Control when colored output is used
    #[arg(
        long,
        env = "COLOR",
        value_name = "WHEN",
        help_heading = "Output Options",
        long_help = "\
Control when colored output is used. Valid: auto (default), always, never"
    )]
    pub color: Option<String>,

    /// Output the build plan in JSON (requires nightly)
    #[arg(long, env = "BUILD_PLAN", hide = true, help_heading = "Output Options")]
    pub build_plan: bool,

    /// Timing output formats (html, json)
    #[arg(long, env = "TIMINGS", value_name = "FMTS",
          num_args = 0..=1, default_missing_value = "true",
          help_heading = "Output Options",
          long_help = "\
Output timing information. --timings=HTML report, --timings=json for JSON. Saved to target/cargo-timings/.")]
    pub timings: Option<String>,

    // ===== Dependency Options =====
    /// Ignore `rust-version` specification in packages
    #[arg(
        long,
        env = "IGNORE_RUST_VERSION",
        help_heading = "Dependency Options",
        long_help = "\
Ignore rust-version specification in packages. Allows building with older Rust versions."
    )]
    pub ignore_rust_version: bool,

    /// Assert that Cargo.lock will remain unchanged
    #[arg(
        long,
        env = "LOCKED",
        help_heading = "Dependency Options",
        long_help = "\
Assert Cargo.lock will remain unchanged. Exits with error if missing or needs updating. Use in CI."
    )]
    pub locked: bool,

    /// Run without accessing the network
    #[arg(
        long,
        env = "OFFLINE",
        help_heading = "Dependency Options",
        long_help = "\
Prevent network access. Uses locally cached data. Run 'cargo fetch' first if needed."
    )]
    pub offline: bool,

    /// Require Cargo.lock and cache are up to date (implies --locked --offline)
    #[arg(
        long,
        env = "FROZEN",
        help_heading = "Dependency Options",
        long_help = "\
Equivalent to --locked --offline. Requires Cargo.lock and cache are up to date."
    )]
    pub frozen: bool,

    /// Path to Cargo.lock (unstable)
    #[arg(long, env = "LOCKFILE_PATH", value_name = "PATH",
          value_hint = ValueHint::FilePath, help_heading = "Dependency Options",
          long_help = "\
Override lockfile path from default (<workspace_root>/Cargo.lock). Requires nightly.")]
    pub lockfile_path: Option<PathBuf>,

    // ===== Build Configuration =====
    /// Number of parallel jobs to run
    #[arg(
        short = 'j',
        long,
        env = "JOBS",
        value_name = "N",
        help_heading = "Build Configuration",
        long_help = "\
Number of parallel jobs. Defaults to logical CPUs. Negative=CPUs+N. 'default' to reset."
    )]
    pub jobs: Option<String>,

    /// Build as many crates as possible, rather than aborting on first error
    #[arg(
        long,
        env = "KEEP_GOING",
        help_heading = "Build Configuration",
        long_help = "\
Build as many crates in the dependency graph as possible. Rather than aborting on the first
crate that fails to build, continue with other crates in the dependency graph."
    )]
    pub keep_going: bool,

    /// Output a future incompatibility report after the build
    #[arg(
        long,
        env = "FUTURE_INCOMPAT_REPORT",
        help_heading = "Build Configuration",
        long_help = "\
Displays a future-incompat report for any future-incompatible warnings produced during
execution of this command. See 'cargo report' for more information."
    )]
    pub future_incompat_report: bool,

    // ===== Additional Cargo Arguments =====
    /// Additional arguments to pass to cargo
    /// Note: `CARGO_ARGS` env var is handled manually in cargo.rs to support shell-style parsing
    #[arg(
        long,
        visible_alias = "args",
        value_name = "ARGS",
        hide = true,
        allow_hyphen_values = true,
        action = clap::ArgAction::Append,
        help_heading = "Additional Options"
    )]
    pub cargo_args: Vec<String>,

    /// Unstable (nightly-only) flags to Cargo
    #[arg(short = 'Z', value_name = "FLAG",
          action = clap::ArgAction::Append, help_heading = "Additional Options",
          long_help = "\
Unstable (nightly-only) flags to Cargo. Run 'cargo -Z help' for details on available flags.
Common flags: build-std, unstable-options")]
    pub cargo_z_flags: Vec<String>,

    /// Override a Cargo configuration value
    #[arg(long = "config", value_name = "KEY=VALUE",
          action = clap::ArgAction::Append, help_heading = "Additional Options",
          long_help = "\
Override a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE.
This flag may be specified multiple times.
Example: --config 'build.jobs=4' --config 'profile.release.lto=true'")]
    pub cargo_config: Vec<String>,

    /// Change to directory before doing anything
    #[arg(short = 'C', long = "directory", env = "CARGO_CWD",
          value_name = "DIR", value_hint = ValueHint::DirPath,
          help_heading = "Additional Options",
          long_help = "\
Changes the current working directory before executing any specified operations.
This affects where cargo looks for the project manifest (Cargo.toml) and .cargo/config.toml.")]
    pub cargo_cwd: Option<PathBuf>,

    /// Rust toolchain to use (alternative to +toolchain syntax)
    #[arg(
        long = "toolchain",
        env = "TOOLCHAIN",
        value_name = "TOOLCHAIN",
        help_heading = "Additional Options",
        long_help = "\
Specify the Rust toolchain to use for compilation. This is an alternative to the +toolchain
syntax (e.g., +nightly). Examples: --toolchain nightly, --toolchain stable, --toolchain 1.75.0"
    )]
    pub toolchain_option: Option<String>,

    /// GitHub mirror URL for downloading toolchains
    #[arg(long, visible_alias = "github-proxy-mirror", env = "GH_PROXY", value_name = "URL",
          value_hint = ValueHint::Url, hide_env = true,
          help_heading = "Additional Options",
          long_help = "\
Specify a GitHub mirror/proxy URL for downloading cross-compiler toolchains.
Useful in regions where GitHub access is slow or restricted.
Example: --github-proxy 'https://ghproxy.com/'")]
    pub github_proxy: Option<String>,

    /// Clean the target directory before building
    #[arg(
        long,
        env = "CLEAN_CACHE",
        help_heading = "Additional Options",
        long_help = "\
Clean the target directory before building. Equivalent to running 'cargo clean' before the build."
    )]
    pub clean_cache: bool,

    /// Disable automatic --target appending for `exec` cargo commands
    #[arg(
        long,
        env = "NO_APPEND_TARGET",
        help_heading = "Additional Options",
        long_help = "\
Disable automatic insertion of '--target <triple>' when using the 'exec' command
with a cargo invocation. By default, 'cargo cross exec --target ... -- cargo ...'
will add '--target <triple>' to the cargo command unless it is already present."
    )]
    pub no_append_target: bool,

    /// Arguments passed through to cargo (after --)
    /// Note: `CARGO_PASSTHROUGH_ARGS` env var is handled manually in cargo.rs to support shell-style parsing
    #[arg(
        last = true,
        allow_hyphen_values = true,
        value_name = "ARGS",
        help = "Arguments passed through to the underlying cargo command",
        long_help = "\
Arguments passed through to the underlying cargo command. Everything after -- is passed
directly to cargo/test runner. For test command, these are passed to the test binary.
Examples: test -- --nocapture --test-threads=1, run -- --arg1 --arg2"
    )]
    pub passthrough_args: Vec<String>,
}

impl BuildArgs {
    /// Create default `BuildArgs` with proper version defaults
    #[must_use]
    pub fn default_for_host() -> Self {
        Self {
            profile: "dev".to_string(),
            glibc_version: DEFAULT_GLIBC_VERSION.to_string(),
            iphone_sdk_version: DEFAULT_IPHONE_SDK_VERSION.to_string(),
            macos_sdk_version: DEFAULT_MACOS_SDK_VERSION.to_string(),
            freebsd_version: DEFAULT_FREEBSD_VERSION.to_string(),
            ndk_version: DEFAULT_NDK_VERSION.to_string(),
            qemu_version: DEFAULT_QEMU_VERSION.to_string(),
            cross_make_version: DEFAULT_CROSS_MAKE_VERSION.to_string(),
            ..Default::default()
        }
    }
}

/// Parse optional bool value (true/false)
fn parse_optional_bool(s: &str) -> std::result::Result<bool, String> {
    match s.to_lowercase().as_str() {
        "true" | "1" | "yes" => Ok(true),
        "false" | "0" | "no" => Ok(false),
        _ => Err(format!("invalid bool value: {s}")),
    }
}

/// Parse build-std value (returns empty string for disabled, which is filtered later)
fn parse_build_std(s: &str) -> std::result::Result<String, String> {
    match s.to_lowercase().as_str() {
        "false" | "0" | "no" | "" => Ok(String::new()), // Will be converted to None later
        "true" | "1" | "yes" => Ok("true".to_string()),
        _ => Ok(s.to_string()),
    }
}

/// Cargo or internal command descriptor
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Command(String);

impl Default for Command {
    fn default() -> Self {
        Self::build()
    }
}

impl Command {
    #[must_use]
    pub fn new(name: impl Into<String>) -> Self {
        Self(name.into())
    }

    #[must_use]
    pub fn build() -> Self {
        Self::new("build")
    }

    #[must_use]
    pub fn check() -> Self {
        Self::new("check")
    }

    #[must_use]
    pub fn run() -> Self {
        Self::new("run")
    }

    #[must_use]
    pub fn test() -> Self {
        Self::new("test")
    }

    #[must_use]
    pub fn bench() -> Self {
        Self::new("bench")
    }

    #[must_use]
    pub fn clippy() -> Self {
        Self::new("clippy")
    }

    #[must_use]
    pub fn setup() -> Self {
        Self::new("setup")
    }

    #[must_use]
    pub fn exec() -> Self {
        Self::new("exec")
    }

    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    #[must_use]
    pub fn needs_runner(&self) -> bool {
        matches!(self.as_str(), "run" | "test" | "bench")
    }
}

/// Parsed and validated arguments
#[derive(Debug, Clone)]
pub struct Args {
    /// Rust toolchain to use (e.g., "nightly", "stable")
    pub toolchain: Option<String>,
    /// Cargo command to execute
    pub command: Command,
    /// Expanded target list (after glob pattern expansion)
    pub targets: Vec<String>,
    /// Skip passing --target to cargo (for host builds)
    pub no_cargo_target: bool,
    /// Cross-make version for toolchain downloads
    pub cross_make_version: String,
    /// Directory for cross-compiler toolchains
    pub cross_compiler_dir: PathBuf,
    /// All build arguments from CLI
    pub build: BuildArgs,
}

impl std::ops::Deref for Args {
    type Target = BuildArgs;

    fn deref(&self) -> &Self::Target {
        &self.build
    }
}

impl std::ops::DerefMut for Args {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.build
    }
}

impl Args {
    /// Create Args from `BuildArgs` and Command
    fn from_build_args(b: BuildArgs, command: Command, toolchain: Option<String>) -> Result<Self> {
        let cross_compiler_dir = b
            .cross_compiler_dir
            .clone()
            .unwrap_or_else(|| std::env::temp_dir().join("rust-cross-compiler"));
        let targets = expand_target_list(&b.targets)?;

        Ok(Self {
            toolchain,
            command,
            targets,
            no_cargo_target: false,
            cross_make_version: b.cross_make_version.clone(),
            cross_compiler_dir,
            build: b,
        })
    }
}

/// Result of parsing CLI arguments
pub enum ParseResult {
    /// Normal build/check/run/test/bench command
    Build(Box<Args>),
    /// Print configured environment variables
    Setup(Box<SetupArgs>),
    /// Execute an arbitrary command after environment setup
    Exec(Box<ExecArgs>),
    /// Show targets command
    ShowTargets(OutputFormat),
    /// Show version
    ShowVersion,
}

/// Remove empty environment variables that clap would incorrectly treat as having values.
/// Clap's `env = "VAR"` attribute treats empty strings as valid values, which causes
/// parsing errors for `PathBuf` and other types that don't accept empty strings.
fn sanitize_clap_env() {
    let empty_vars: Vec<_> = std::env::vars()
        .filter(|(_, v)| v.is_empty())
        .map(|(k, _)| k)
        .collect();

    for var in empty_vars {
        std::env::remove_var(&var);
    }
}

/// Parse command-line arguments
pub fn parse_args() -> Result<ParseResult> {
    let args: Vec<String> = std::env::args().collect();
    parse_args_from(args)
}

#[derive(Parser, Debug)]
#[command(name = "cargo-cross")]
#[command(styles = cli_styles())]
struct ExternalCargoCli {
    #[command(flatten)]
    build: BuildArgs,
}

/// Parse arguments from a vector (for testing)
pub fn parse_args_from(args: Vec<String>) -> Result<ParseResult> {
    use std::env;

    // Remove empty environment variables that clap would incorrectly treat as having values
    // This must be done before clap parses, as clap reads from env vars with `env = "VAR"`
    sanitize_clap_env();

    let mut toolchain: Option<String> = None;

    // When invoked as `cargo cross`, cargo sets the CARGO env var and passes
    // args as ["cargo-cross", "cross", ...]. We need to skip both.
    // When invoked directly as `cargo-cross`, only skip the program name.
    let is_cargo_subcommand = env::var("CARGO").is_ok()
        && env::var("CARGO_HOME").is_ok()
        && args.get(1).map(String::as_str) == Some(SUBCOMMAND);

    let skip_count = if is_cargo_subcommand { 2 } else { 1 };
    let mut args: Vec<String> = args.iter().skip(skip_count).cloned().collect();

    // Extract +toolchain from args (can appear at the beginning)
    // e.g., cargo cross +nightly build -t x86_64-unknown-linux-musl
    if let Some(tc) = args.first().and_then(|a| a.strip_prefix('+')) {
        toolchain = Some(tc.to_string());
        args.remove(0);
    }

    if let Some(command_name) = args.first().cloned() {
        let remaining_args: Vec<String> = args.iter().skip(1).cloned().collect();
        let help_or_version_requested = has_wrapper_help_or_version_request(&remaining_args);

        if let Some(canonical_name) = canonical_cargo_command_name(&command_name) {
            if !help_or_version_requested {
                return parse_cargo_command_args(
                    &command_name,
                    canonical_name,
                    remaining_args,
                    toolchain,
                );
            }
        }
        if should_parse_as_external_cargo_command(&command_name) {
            return parse_cargo_command_args(
                &command_name,
                &command_name,
                remaining_args,
                toolchain,
            );
        }
    }

    // Prepend program name for clap (internal name, not displayed)
    args.insert(0, BIN_NAME.to_string());

    // Build command with dynamic help text
    let cmd = build_command_with_dynamic_help();

    // Try to parse with clap using modified command
    let cli = match cmd.try_get_matches_from(&args) {
        Ok(matches) => {
            Cli::from_arg_matches(&matches).map_err(|e| CrossError::ClapError(e.to_string()))?
        }
        Err(e) => {
            // For help/version/missing subcommand, let clap print and exit
            if matches!(
                e.kind(),
                clap::error::ErrorKind::DisplayHelp
                    | clap::error::ErrorKind::DisplayVersion
                    | clap::error::ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand
            ) {
                e.exit();
            }
            // For argument errors, return Err so tests can catch them
            return Err(CrossError::ClapError(e.render().to_string()));
        }
    };

    process_cli(cli, toolchain)
}

fn has_wrapper_help_or_version_request(args: &[String]) -> bool {
    args.iter()
        .take_while(|arg| arg.as_str() != "--")
        .any(|arg| matches!(arg.as_str(), "--help" | "-h" | "--version" | "-V"))
}

/// Build the clap Command with dynamic help text based on invocation style
fn build_command_with_dynamic_help() -> clap::Command {
    let prog = program_name();

    // Build dynamic help strings
    let usage = format!("{prog} [+toolchain] <COMMAND> [OPTIONS]");
    let after_help = format!(
        "Use '{prog} <COMMAND> --help' for more information about a command.\n\n\
TOOLCHAIN:\n    \
    If the first argument begins with +, it will be interpreted as a Rust toolchain\n    \
    name (such as +nightly, +stable, or +1.75.0). This follows the same convention\n    \
    as rustup and cargo.\n\n\
EXAMPLES:\n    \
    {prog} build -t x86_64-unknown-linux-musl\n    \
    {prog} +nightly build -t aarch64-unknown-linux-gnu --profile release\n    \
    {prog} build -t '*-linux-musl' --crt-static true\n    \
    {prog} test -t x86_64-unknown-linux-musl -- --nocapture"
    );

    // Build dynamic version help texts
    let glibc_help = format!(
        "Specify glibc version for GNU libc targets. The version determines the minimum Linux kernel\n\
         version required. Lower versions provide better compatibility with older systems.\n\
         Supported: {}",
        supported_glibc_versions_str()
    );
    let freebsd_help = format!(
        "Specify FreeBSD version for FreeBSD targets. Supported: {}",
        supported_freebsd_versions_str()
    );
    let iphone_sdk_help = format!(
        "Specify iPhone SDK version for iOS targets. On Linux: uses pre-built SDK from releases.\n\
         On macOS: uses installed Xcode SDK. Supported on Linux: {}",
        supported_iphone_sdk_versions_str()
    );
    let macos_sdk_help = format!(
        "Specify macOS SDK version for Darwin targets. On Linux: uses osxcross with pre-built SDK.\n\
         On macOS: uses installed Xcode SDK. Supported on Linux: {}",
        supported_macos_sdk_versions_str()
    );

    // Get base command and modify it
    let mut cmd = Cli::command().override_usage(usage).after_help(after_help);

    // Update subcommand usage strings and version help texts
    for subcmd_name in &["build", "check", "run", "test", "bench", "clippy"] {
        let glibc_help = glibc_help.clone();
        let freebsd_help = freebsd_help.clone();
        let iphone_sdk_help = iphone_sdk_help.clone();
        let macos_sdk_help = macos_sdk_help.clone();
        cmd = cmd.mut_subcommand(*subcmd_name, |subcmd| {
            subcmd
                .override_usage(format!(
                    "{prog} [+toolchain] {subcmd_name} [OPTIONS] [-- <PASSTHROUGH_ARGS>...]"
                ))
                .mut_arg("glibc_version", |arg| arg.long_help(glibc_help))
                .mut_arg("freebsd_version", |arg| arg.long_help(freebsd_help))
                .mut_arg("iphone_sdk_version", |arg| arg.long_help(iphone_sdk_help))
                .mut_arg("macos_sdk_version", |arg| arg.long_help(macos_sdk_help))
        });
    }

    cmd
}

fn should_parse_as_external_cargo_command(command_name: &str) -> bool {
    if command_name.starts_with('-') {
        return false;
    }

    canonical_cargo_command_name(command_name).is_none()
        && is_supported_external_cargo_command(command_name)
}

fn canonical_cargo_command_name(command_name: &str) -> Option<&'static str> {
    match command_name {
        "build" | "b" => Some("build"),
        "check" | "c" => Some("check"),
        "run" | "r" => Some("run"),
        "test" | "t" => Some("test"),
        "bench" => Some("bench"),
        "clippy" => Some("clippy"),
        _ => None,
    }
}

fn is_supported_external_cargo_command(command_name: &str) -> bool {
    matches!(command_name, "doc" | "fix" | "rustc" | "rustdoc")
}

fn parse_cargo_command_args(
    display_name: &str,
    canonical_name: &str,
    args: Vec<String>,
    toolchain: Option<String>,
) -> Result<ParseResult> {
    let processed_args = preprocess_cargo_args(args);
    let mut clap_args = Vec::with_capacity(processed_args.len() + 1);
    clap_args.push(BIN_NAME.to_string());
    clap_args.extend(processed_args);

    let cmd = build_external_cargo_command_with_dynamic_help(display_name);
    let cli = match cmd.try_get_matches_from(&clap_args) {
        Ok(matches) => ExternalCargoCli::from_arg_matches(&matches)
            .map_err(|e| CrossError::ClapError(e.to_string()))?,
        Err(e) => {
            if matches!(
                e.kind(),
                clap::error::ErrorKind::DisplayHelp | clap::error::ErrorKind::DisplayVersion
            ) {
                e.exit();
            }
            return Err(CrossError::ClapError(e.render().to_string()));
        }
    };

    let args = finalize_args(cli.build, Command::new(canonical_name), toolchain)?;
    Ok(ParseResult::Build(Box::new(args)))
}

#[derive(Clone, Copy, Debug)]
struct KnownArgSpec {
    takes_value: bool,
    min_values: usize,
    max_values: usize,
    allow_hyphen_values: bool,
}

fn preprocess_cargo_args(args: Vec<String>) -> Vec<String> {
    let parser = ExternalCargoCli::command();
    let (long_args, short_args) = known_arg_maps(&parser);
    let mut processed = Vec::with_capacity(args.len());
    let mut pending_value: Option<KnownArgSpec> = None;
    let mut passthrough = false;
    let mut index = 0;

    while index < args.len() {
        let token = &args[index];

        if passthrough {
            processed.push(token.clone());
            index += 1;
            continue;
        }

        if token == "--" {
            pending_value = None;
            passthrough = true;
            processed.push(token.clone());
            index += 1;
            continue;
        }

        if matches!(token.as_str(), "--help" | "-h" | "--version" | "-V") {
            pending_value = None;
            processed.push(token.clone());
            index += 1;
            continue;
        }

        if let Some(spec) = pending_value {
            if should_consume_known_value(token, spec) {
                processed.push(token.clone());
                pending_value = None;
                index += 1;
                continue;
            }
            pending_value = None;
        }

        if let Some(spec) = classify_known_long_arg(token, &long_args) {
            processed.push(token.clone());
            pending_value = needs_following_value(token, spec);
            index += 1;
            continue;
        }

        if let Some(spec) = classify_known_short_arg(token, &short_args) {
            processed.push(token.clone());
            pending_value = needs_following_value(token, spec);
            index += 1;
            continue;
        }

        push_cargo_arg(&mut processed, token);
        if should_pair_unknown_value(token, args.get(index + 1).map(String::as_str)) {
            if let Some(value) = args.get(index + 1) {
                push_cargo_arg(&mut processed, value);
                index += 1;
            }
        }
        index += 1;
    }

    processed
}

fn known_arg_maps(
    command: &clap::Command,
) -> (HashMap<String, KnownArgSpec>, HashMap<char, KnownArgSpec>) {
    let mut long_args = HashMap::new();
    let mut short_args = HashMap::new();

    for arg in command.get_arguments() {
        if arg.is_positional() {
            continue;
        }

        let (takes_value, min_values, max_values) = infer_arg_value_shape(arg);
        let spec = KnownArgSpec {
            takes_value,
            min_values,
            max_values,
            allow_hyphen_values: arg.is_allow_hyphen_values_set(),
        };

        if let Some(long) = arg.get_long() {
            long_args.insert(long.to_string(), spec);
        }
        if let Some(aliases) = arg.get_long_and_visible_aliases() {
            for alias in aliases {
                long_args.insert(alias.to_string(), spec);
            }
        }
        if let Some(short) = arg.get_short() {
            short_args.insert(short, spec);
        }
        if let Some(aliases) = arg.get_short_and_visible_aliases() {
            for alias in aliases {
                short_args.insert(alias, spec);
            }
        }
    }

    (long_args, short_args)
}

fn infer_arg_value_shape(arg: &clap::Arg) -> (bool, usize, usize) {
    if let Some(range) = arg.get_num_args() {
        return (range.takes_values(), range.min_values(), range.max_values());
    }

    match arg.get_action() {
        ArgAction::Set | ArgAction::Append => (true, 1, 1),
        ArgAction::SetTrue
        | ArgAction::SetFalse
        | ArgAction::Count
        | ArgAction::Help
        | ArgAction::HelpShort
        | ArgAction::HelpLong
        | ArgAction::Version => (false, 0, 0),
        _ => (false, 0, 0),
    }
}

fn classify_known_long_arg(
    token: &str,
    long_args: &HashMap<String, KnownArgSpec>,
) -> Option<KnownArgSpec> {
    if !token.starts_with("--") || token == "--" {
        return None;
    }

    let name = token
        .trim_start_matches("--")
        .split_once('=')
        .map_or_else(|| token.trim_start_matches("--"), |(name, _)| name);
    long_args.get(name).copied()
}

fn classify_known_short_arg(
    token: &str,
    short_args: &HashMap<char, KnownArgSpec>,
) -> Option<KnownArgSpec> {
    if !token.starts_with('-') || token.starts_with("--") || token == "-" {
        return None;
    }

    let rest = token.strip_prefix('-')?;
    let mut chars = rest.chars();
    let first = chars.next()?;
    let spec = short_args.get(&first).copied()?;

    if spec.takes_value {
        return Some(spec);
    }

    if rest
        .chars()
        .all(|short| short_args.get(&short).is_some_and(|arg| !arg.takes_value))
    {
        return Some(spec);
    }

    None
}

fn needs_following_value(token: &str, spec: KnownArgSpec) -> Option<KnownArgSpec> {
    if !spec.takes_value || spec.max_values == 0 {
        return None;
    }

    let has_inline_value = if token.starts_with("--") {
        token.contains('=')
    } else {
        token.len() > 2
    };

    if has_inline_value {
        None
    } else {
        Some(spec)
    }
}

fn should_consume_known_value(token: &str, spec: KnownArgSpec) -> bool {
    if token == "--" {
        return false;
    }

    if spec.min_values == 0 && token.starts_with('-') && !spec.allow_hyphen_values {
        return false;
    }

    !token.starts_with('-') || spec.allow_hyphen_values || spec.min_values > 0
}

fn should_pair_unknown_value(current: &str, next: Option<&str>) -> bool {
    if current == "-" || current == "--" {
        return false;
    }

    if !(current.starts_with("--") || (current.starts_with('-') && current.len() == 2)) {
        return false;
    }

    let Some(next) = next else {
        return false;
    };

    !next.starts_with('-')
}

fn push_cargo_arg(processed: &mut Vec<String>, value: &str) {
    processed.push("--cargo-args".to_string());
    processed.push(value.to_string());
}

fn build_external_cargo_command_with_dynamic_help(command_name: &str) -> clap::Command {
    let prog = program_name();
    let after_help = format!(
        "This command forwards to 'cargo {command_name}' after configuring the\n\
cross-compilation environment.\n\n\
EXAMPLES:\n    \
{prog} {command_name} -t x86_64-unknown-linux-musl\n    \
{prog} {command_name} -t aarch64-unknown-linux-gnu -- --help"
    );

    ExternalCargoCli::command()
        .override_usage(format!(
            "{prog} [+toolchain] {command_name} [OPTIONS] [-- <PASSTHROUGH_ARGS>...]"
        ))
        .after_help(after_help)
}

fn process_cli(cli: Cli, toolchain: Option<String>) -> Result<ParseResult> {
    match cli.command {
        CliCommand::Build(args) => {
            let args = finalize_args(args, Command::build(), toolchain)?;
            Ok(ParseResult::Build(Box::new(args)))
        }
        CliCommand::Check(args) => {
            let args = finalize_args(args, Command::check(), toolchain)?;
            Ok(ParseResult::Build(Box::new(args)))
        }
        CliCommand::Run(args) => {
            let args = finalize_args(args, Command::run(), toolchain)?;
            Ok(ParseResult::Build(Box::new(args)))
        }
        CliCommand::Test(args) => {
            let args = finalize_args(args, Command::test(), toolchain)?;
            Ok(ParseResult::Build(Box::new(args)))
        }
        CliCommand::Bench(args) => {
            let args = finalize_args(args, Command::bench(), toolchain)?;
            Ok(ParseResult::Build(Box::new(args)))
        }
        CliCommand::Clippy(args) => {
            let args = finalize_args(args, Command::clippy(), toolchain)?;
            Ok(ParseResult::Build(Box::new(args)))
        }
        CliCommand::Setup(setup) => {
            let args = finalize_args(setup.build, Command::setup(), toolchain)?;
            Ok(ParseResult::Setup(Box::new(SetupArgs {
                args,
                format: setup.format,
            })))
        }
        CliCommand::Exec(exec) => {
            let mut build = exec.build;
            populate_env_arg_fallbacks(&mut build);
            let command = std::mem::take(&mut build.passthrough_args);
            if command.is_empty() {
                return Err(CrossError::InvalidArgument(
                    "exec requires a command after `--`".to_string(),
                ));
            }
            let args = finalize_args(build, Command::exec(), toolchain)?;
            Ok(ParseResult::Exec(Box::new(ExecArgs { args, command })))
        }
        CliCommand::Targets(args) => Ok(ParseResult::ShowTargets(args.format)),
        CliCommand::Version => Ok(ParseResult::ShowVersion),
    }
}

/// Check if a string is a glob pattern (contains *, ?, or [)
fn is_glob_pattern(s: &str) -> bool {
    s.contains('*') || s.contains('?') || s.contains('[')
}

/// Validate that a target triple only contains valid characters (a-z, 0-9, -, _)
fn validate_target_triple(target: &str) -> Result<()> {
    for c in target.chars() {
        if !c.is_ascii_lowercase() && !c.is_ascii_digit() && c != '-' && c != '_' {
            return Err(CrossError::InvalidTargetTriple {
                target: target.to_string(),
                char: c,
            });
        }
    }
    Ok(())
}

/// Expand target list, handling glob patterns
fn expand_target_list(targets: &[String]) -> Result<Vec<String>> {
    let mut result = Vec::new();
    for target in targets {
        // Split by comma or newline to support multiple delimiters
        for part in target.split([',', '\n']) {
            let part = part.trim();
            if part.is_empty() {
                continue;
            }
            let expanded = config::expand_targets(part);
            if expanded.is_empty() {
                // If it was a glob pattern that matched nothing, error
                if is_glob_pattern(part) {
                    return Err(CrossError::NoMatchingTargets {
                        pattern: part.to_string(),
                    });
                }
                // Not a glob pattern, validate and use as-is
                validate_target_triple(part)?;
                if !result.contains(&part.to_string()) {
                    result.push(part.to_string());
                }
            } else {
                for t in expanded {
                    let t = t.to_string();
                    if !result.contains(&t) {
                        result.push(t);
                    }
                }
            }
        }
    }
    Ok(result)
}

fn finalize_args(
    mut build_args: BuildArgs,
    command: Command,
    toolchain: Option<String>,
) -> Result<Args> {
    // Handle --release flag: set profile to "release"
    if build_args.release {
        build_args.profile = "release".to_string();
    }

    // Handle build_std: empty string means disabled (from env var "false")
    if build_args
        .build_std
        .as_ref()
        .is_some_and(std::string::String::is_empty)
    {
        build_args.build_std = None;
    }

    populate_env_arg_fallbacks(&mut build_args);

    // Merge toolchain: +toolchain syntax takes precedence over --toolchain option
    let final_toolchain = toolchain.or_else(|| build_args.toolchain_option.clone());

    let mut args = Args::from_build_args(build_args, command, final_toolchain)?;

    // Validate versions
    validate_versions(&args)?;

    // Handle empty targets - default to host
    if args.targets.is_empty() {
        let host = config::HostPlatform::detect();
        args.targets.push(host.triple);
        args.no_toolchain_setup = true;
        args.no_cargo_target = true;
    }
    // Note: "host-tuple" is handled dynamically in execute_target

    Ok(args)
}

fn populate_env_arg_fallbacks(build_args: &mut BuildArgs) {
    if build_args.cargo_args.is_empty() {
        if let Some(env_args) = parse_env_args("CARGO_ARGS") {
            build_args.cargo_args = env_args;
        }
    }
    if build_args.passthrough_args.is_empty() {
        if let Some(env_args) = parse_passthrough_env_args("CARGO_PASSTHROUGH_ARGS") {
            build_args.passthrough_args = env_args;
        }
    }
}

fn parse_passthrough_env_args(env_name: &str) -> Option<Vec<String>> {
    let mut args = parse_env_args(env_name)?;
    if args.first().is_some_and(|arg| arg == "--") {
        args.remove(0);
    }
    if args.is_empty() {
        None
    } else {
        Some(args)
    }
}

/// Parse environment variable as shell-style arguments using shlex
/// Returns None if env var is not set or empty
fn parse_env_args(env_name: &str) -> Option<Vec<String>> {
    let value = std::env::var(env_name).ok()?;
    let value = value.trim();
    if value.is_empty() {
        return None;
    }
    match shlex::split(value) {
        Some(parsed) if !parsed.is_empty() => Some(parsed),
        Some(_) => None,
        None => {
            eprintln!("Warning: Failed to parse {env_name} (mismatched quotes?): {value}");
            None
        }
    }
}

/// Validate version options
fn validate_versions(args: &Args) -> Result<()> {
    // Only validate glibc version if it's specified (non-empty)
    // Empty string means use default version, which is valid for both gnu and musl targets
    if !args.glibc_version.is_empty()
        && !SUPPORTED_GLIBC_VERSIONS.contains(&args.glibc_version.as_str())
    {
        return Err(CrossError::UnsupportedGlibcVersion {
            version: args.glibc_version.clone(),
            supported: SUPPORTED_GLIBC_VERSIONS.join(", "),
        });
    }

    let host = config::HostPlatform::detect();
    if !host.is_darwin()
        && !SUPPORTED_IPHONE_SDK_VERSIONS.contains(&args.iphone_sdk_version.as_str())
    {
        return Err(CrossError::UnsupportedIphoneSdkVersion {
            version: args.iphone_sdk_version.clone(),
            supported: SUPPORTED_IPHONE_SDK_VERSIONS.join(", "),
        });
    }

    if !host.is_darwin() && !SUPPORTED_MACOS_SDK_VERSIONS.contains(&args.macos_sdk_version.as_str())
    {
        return Err(CrossError::UnsupportedMacosSdkVersion {
            version: args.macos_sdk_version.clone(),
            supported: SUPPORTED_MACOS_SDK_VERSIONS.join(", "),
        });
    }

    if !SUPPORTED_FREEBSD_VERSIONS.contains(&args.freebsd_version.as_str()) {
        return Err(CrossError::UnsupportedFreebsdVersion {
            version: args.freebsd_version.clone(),
            supported: SUPPORTED_FREEBSD_VERSIONS.join(", "),
        });
    }

    Ok(())
}

/// Print all supported targets
pub fn print_all_targets(format: OutputFormat) {
    let mut targets: Vec<_> = config::all_targets().collect();
    targets.sort_unstable();

    match format {
        OutputFormat::Text => {
            use colored::Colorize;
            println!("{}", "Supported Rust targets:".bright_green());
            for target in &targets {
                println!("  {}", target.bright_cyan());
            }
        }
        OutputFormat::Json => {
            let json_array = serde_json::to_string(&targets).unwrap_or_else(|_| "[]".to_string());
            println!("{json_array}");
        }
        OutputFormat::Plain => {
            for target in &targets {
                println!("{target}");
            }
        }
    }

    // Output to GITHUB_OUTPUT if running in GitHub Actions
    if let Ok(github_output) = std::env::var("GITHUB_OUTPUT") {
        let json_array = serde_json::to_string(&targets).unwrap_or_else(|_| "[]".to_string());
        if let Ok(mut file) = std::fs::OpenOptions::new()
            .append(true)
            .open(&github_output)
        {
            use std::io::Write;
            let _ = writeln!(file, "all-targets={json_array}");
        }
    }
}

/// Print version information
pub fn print_version() {
    use colored::Colorize;

    let version = env!("CARGO_PKG_VERSION");
    let name = env!("CARGO_PKG_NAME");
    println!("{} {}", name.bright_green(), version.bright_cyan());
}

#[cfg(test)]
mod tests {
    use super::*;

    fn parse(args: &[&str]) -> Result<Args> {
        let args: Vec<String> = args.iter().map(std::string::ToString::to_string).collect();
        match parse_args_from(args)? {
            ParseResult::Build(args) => Ok(*args),
            ParseResult::ShowTargets(_) => panic!("unexpected ShowTargets"),
            ParseResult::Setup(_) => panic!("unexpected Setup"),
            ParseResult::Exec(_) => panic!("unexpected Exec"),
            ParseResult::ShowVersion => panic!("unexpected ShowVersion"),
        }
    }

    fn parse_setup(args: &[&str]) -> Result<SetupArgs> {
        let args: Vec<String> = args.iter().map(std::string::ToString::to_string).collect();
        match parse_args_from(args)? {
            ParseResult::Setup(args) => Ok(*args),
            _ => panic!("unexpected parse result"),
        }
    }

    fn parse_exec(args: &[&str]) -> Result<ExecArgs> {
        let args: Vec<String> = args.iter().map(std::string::ToString::to_string).collect();
        match parse_args_from(args)? {
            ParseResult::Exec(args) => Ok(*args),
            _ => panic!("unexpected parse result"),
        }
    }

    // Note: test_parse_empty_requires_subcommand removed because MissingSubcommand
    // now calls exit() which cannot be tested

    #[test]
    fn test_parse_build_command() {
        let args = parse(&["cargo-cross", "build"]).unwrap();
        assert_eq!(args.command, Command::build());
        assert_eq!(args.profile, "dev");
    }

    #[test]
    fn test_parse_check_command() {
        let args = parse(&["cargo-cross", "check"]).unwrap();
        assert_eq!(args.command, Command::check());
    }

    #[test]
    fn test_parse_clippy_command() {
        let args = parse(&["cargo-cross", "clippy"]).unwrap();
        assert_eq!(args.command, Command::clippy());
    }

    #[test]
    fn test_parse_clippy_unknown_cargo_flags() {
        let args = parse(&[
            "cargo-cross",
            "clippy",
            "--workspace",
            "--all-targets",
            "--fix",
            "--allow-dirty",
            "--target",
            "x86_64-pc-windows-msvc",
        ])
        .unwrap();
        assert!(args.workspace);
        assert!(args.build_all_targets);
        assert_eq!(
            args.cargo_args,
            vec!["--fix".to_string(), "--allow-dirty".to_string()]
        );
        assert_eq!(args.targets, vec!["x86_64-pc-windows-msvc"]);
    }

    #[test]
    fn test_parse_external_cargo_command() {
        let args = parse(&["cargo-cross", "doc"]).unwrap();
        assert_eq!(args.command, Command::new("doc"));
    }

    #[test]
    fn test_reject_non_build_like_external_cargo_command() {
        let result = parse(&["cargo-cross", "metadata"]);
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_external_command_unknown_cargo_flags() {
        let args = parse(&[
            "cargo-cross",
            "doc",
            "--workspace",
            "--open",
            "--target",
            "x86_64-unknown-linux-musl",
        ])
        .unwrap();
        assert_eq!(args.command, Command::new("doc"));
        assert!(args.workspace);
        assert_eq!(args.cargo_args, vec!["--open".to_string()]);
        assert_eq!(args.targets, vec!["x86_64-unknown-linux-musl"]);
    }

    #[test]
    fn test_parse_setup_command() {
        let args =
            parse_setup(&["cargo-cross", "setup", "-t", "x86_64-unknown-linux-musl"]).unwrap();
        assert_eq!(args.args.command, Command::setup());
        assert_eq!(args.format, SetupOutputFormat::Auto);
    }

    #[test]
    fn test_parse_setup_command_explicit_format() {
        let args = parse_setup(&[
            "cargo-cross",
            "setup",
            "-t",
            "x86_64-unknown-linux-musl",
            "--format",
            "fish",
        ])
        .unwrap();
        assert_eq!(args.format, SetupOutputFormat::Fish);
    }

    #[test]
    fn test_parse_exec_command() {
        let args = parse_exec(&[
            "cargo-cross",
            "exec",
            "-t",
            "x86_64-unknown-linux-musl",
            "--",
            "env",
            "FOO=bar",
        ])
        .unwrap();
        assert_eq!(args.args.command, Command::exec());
        assert_eq!(args.command, vec!["env", "FOO=bar"]);
    }

    #[test]
    fn test_parse_exec_command_disable_auto_target() {
        let args = parse_exec(&[
            "cargo-cross",
            "exec",
            "--no-append-target",
            "-t",
            "x86_64-unknown-linux-musl",
            "--",
            "cargo",
            "clippy",
        ])
        .unwrap();
        assert!(args.args.no_append_target);
        assert_eq!(args.command, vec!["cargo", "clippy"]);
    }

    #[test]
    fn test_parse_exec_command_from_env_passthrough() {
        std::env::set_var("CARGO_PASSTHROUGH_ARGS", "-- env FOO=bar");
        let args = parse_exec(&["cargo-cross", "exec", "-t", "x86_64-unknown-linux-musl"]).unwrap();
        assert_eq!(args.args.command, Command::exec());
        assert_eq!(args.command, vec!["env", "FOO=bar"]);
        std::env::remove_var("CARGO_PASSTHROUGH_ARGS");
    }

    #[test]
    fn test_parse_target() {
        let args = parse(&["cargo-cross", "build", "-t", "x86_64-unknown-linux-musl"]).unwrap();
        assert_eq!(args.targets, vec!["x86_64-unknown-linux-musl"]);
    }

    #[test]
    fn test_parse_multiple_targets() {
        let args = parse(&[
            "cargo-cross",
            "build",
            "-t",
            "x86_64-unknown-linux-musl,aarch64-unknown-linux-musl",
        ])
        .unwrap();
        assert_eq!(
            args.targets,
            vec!["x86_64-unknown-linux-musl", "aarch64-unknown-linux-musl"]
        );
    }

    #[test]
    fn test_parse_verbose() {
        let args = parse(&["cargo-cross", "build", "-vvv"]).unwrap();
        assert_eq!(args.verbose_level, 3);
    }

    #[test]
    fn test_parse_crt_static_flag() {
        let args = parse(&["cargo-cross", "build", "--crt-static", "true"]).unwrap();
        assert_eq!(args.crt_static, Some(true));
    }

    #[test]
    fn test_parse_crt_static_false() {
        let args = parse(&["cargo-cross", "build", "--crt-static", "false"]).unwrap();
        assert_eq!(args.crt_static, Some(false));
    }

    #[test]
    fn test_parse_crt_static_no_value() {
        // --crt-static without value should default to true
        let args = parse(&["cargo-cross", "build", "--crt-static"]).unwrap();
        assert_eq!(args.crt_static, Some(true));
    }

    #[test]
    fn test_parse_crt_static_not_provided() {
        // When --crt-static is not provided at all, value should be None
        let args = parse(&["cargo-cross", "build"]).unwrap();
        assert_eq!(args.crt_static, None);
    }

    #[test]
    fn test_parse_build_std() {
        let args = parse(&["cargo-cross", "build", "--build-std", "true"]).unwrap();
        assert_eq!(args.build_std, Some("true".to_string()));
    }

    #[test]
    fn test_parse_build_std_crates() {
        let args = parse(&["cargo-cross", "build", "--build-std", "core,alloc"]).unwrap();
        assert_eq!(args.build_std, Some("core,alloc".to_string()));
    }

    #[test]
    fn test_parse_build_std_false() {
        let args = parse(&["cargo-cross", "build", "--build-std", "false"]).unwrap();
        assert_eq!(args.build_std, None);
    }

    #[test]
    fn test_parse_build_std_no_value() {
        // --build-std without value should default to "true"
        let args = parse(&["cargo-cross", "build", "--build-std"]).unwrap();
        assert_eq!(args.build_std, Some("true".to_string()));
    }

    #[test]
    fn test_parse_features() {
        let args = parse(&["cargo-cross", "build", "--features", "foo,bar"]).unwrap();
        assert_eq!(args.features, Some("foo,bar".to_string()));
    }

    #[test]
    fn test_parse_no_default_features() {
        let args = parse(&["cargo-cross", "build", "--no-default-features"]).unwrap();
        assert!(args.no_default_features);
    }

    #[test]
    fn test_parse_profile() {
        let args = parse(&["cargo-cross", "build", "--profile", "dev"]).unwrap();
        assert_eq!(args.profile, "dev");
    }

    #[test]
    fn test_parse_jobs() {
        let args = parse(&["cargo-cross", "build", "-j", "4"]).unwrap();
        assert_eq!(args.jobs, Some("4".to_string()));
    }

    #[test]
    fn test_parse_passthrough_args() {
        let args = parse(&["cargo-cross", "build", "--", "--foo", "--bar"]).unwrap();
        assert_eq!(args.passthrough_args, vec!["--foo", "--bar"]);
    }

    #[test]
    fn test_parse_passthrough_args_from_env_with_legacy_separator() {
        std::env::set_var("CARGO_PASSTHROUGH_ARGS", "-- --foo --bar");
        let args = parse(&["cargo-cross", "build"]).unwrap();
        assert_eq!(args.passthrough_args, vec!["--foo", "--bar"]);
        std::env::remove_var("CARGO_PASSTHROUGH_ARGS");
    }

    #[test]
    fn test_parse_z_flag() {
        let args = parse(&["cargo-cross", "build", "-Z", "build-std"]).unwrap();
        assert_eq!(args.cargo_z_flags, vec!["build-std"]);
    }

    #[test]
    fn test_parse_config_flag() {
        let args = parse(&["cargo-cross", "build", "--config", "opt-level=3"]).unwrap();
        assert_eq!(args.cargo_config, vec!["opt-level=3"]);
    }

    #[test]
    fn test_targets_subcommand() {
        let args: Vec<String> = vec!["cargo-cross".to_string(), "targets".to_string()];
        match parse_args_from(args).unwrap() {
            ParseResult::ShowTargets(format) => {
                assert_eq!(format, OutputFormat::Text);
            }
            _ => panic!("expected ShowTargets"),
        }
    }

    #[test]
    fn test_targets_json_format() {
        let args: Vec<String> = vec![
            "cargo-cross".to_string(),
            "targets".to_string(),
            "--format".to_string(),
            "json".to_string(),
        ];
        match parse_args_from(args).unwrap() {
            ParseResult::ShowTargets(format) => {
                assert_eq!(format, OutputFormat::Json);
            }
            _ => panic!("expected ShowTargets"),
        }
    }

    #[test]
    fn test_targets_plain_format() {
        let args: Vec<String> = vec![
            "cargo-cross".to_string(),
            "targets".to_string(),
            "-f".to_string(),
            "plain".to_string(),
        ];
        match parse_args_from(args).unwrap() {
            ParseResult::ShowTargets(format) => {
                assert_eq!(format, OutputFormat::Plain);
            }
            _ => panic!("expected ShowTargets"),
        }
    }

    #[test]
    fn test_parse_toolchain() {
        let args = parse(&["cargo-cross", "+nightly", "build"]).unwrap();
        assert_eq!(args.toolchain, Some("nightly".to_string()));
        assert_eq!(args.command, Command::build());
    }

    #[test]
    fn test_parse_toolchain_with_target() {
        let args = parse(&[
            "cargo-cross",
            "+nightly",
            "build",
            "-t",
            "x86_64-unknown-linux-musl",
        ])
        .unwrap();
        assert_eq!(args.toolchain, Some("nightly".to_string()));
        assert_eq!(args.targets, vec!["x86_64-unknown-linux-musl"]);
    }

    // Equals syntax vs space syntax tests

    #[test]
    fn test_equals_syntax_target() {
        let args = parse(&["cargo-cross", "build", "-t=x86_64-unknown-linux-musl"]).unwrap();
        assert_eq!(args.targets, vec!["x86_64-unknown-linux-musl"]);
    }

    #[test]
    fn test_equals_syntax_long_target() {
        let args = parse(&["cargo-cross", "build", "--target=x86_64-unknown-linux-musl"]).unwrap();
        assert_eq!(args.targets, vec!["x86_64-unknown-linux-musl"]);
    }

    #[test]
    fn test_equals_syntax_profile() {
        let args = parse(&["cargo-cross", "build", "--profile=dev"]).unwrap();
        assert_eq!(args.profile, "dev");
    }

    #[test]
    fn test_equals_syntax_features() {
        let args = parse(&["cargo-cross", "build", "--features=foo,bar"]).unwrap();
        assert_eq!(args.features, Some("foo,bar".to_string()));
    }

    #[test]
    fn test_equals_syntax_short_features() {
        let args = parse(&["cargo-cross", "build", "-F=foo,bar"]).unwrap();
        assert_eq!(args.features, Some("foo,bar".to_string()));
    }

    #[test]
    fn test_equals_syntax_jobs() {
        let args = parse(&["cargo-cross", "build", "-j=8"]).unwrap();
        assert_eq!(args.jobs, Some("8".to_string()));
    }

    #[test]
    fn test_equals_syntax_crt_static() {
        let args = parse(&["cargo-cross", "build", "--crt-static=true"]).unwrap();
        assert_eq!(args.crt_static, Some(true));
    }

    #[test]
    fn test_equals_syntax_build_std() {
        let args = parse(&["cargo-cross", "build", "--build-std=core,alloc"]).unwrap();
        assert_eq!(args.build_std, Some("core,alloc".to_string()));
    }

    #[test]
    fn test_equals_syntax_manifest_path() {
        let args = parse(&[
            "cargo-cross",
            "build",
            "--manifest-path=/path/to/Cargo.toml",
        ])
        .unwrap();
        assert_eq!(
            args.manifest_path,
            Some(PathBuf::from("/path/to/Cargo.toml"))
        );
    }

    #[test]
    fn test_equals_syntax_cross_compiler_dir() {
        let args = parse(&["cargo-cross", "build", "--cross-compiler-dir=/opt/cross"]).unwrap();
        assert_eq!(args.cross_compiler_dir, PathBuf::from("/opt/cross"));
    }

    #[test]
    fn test_equals_syntax_glibc_version() {
        let args = parse(&["cargo-cross", "build", "--glibc-version=2.31"]).unwrap();
        assert_eq!(args.glibc_version, "2.31");
    }

    #[test]
    fn test_equals_syntax_cc_cxx_ar() {
        let args = parse(&[
            "cargo-cross",
            "build",
            "--cc=/usr/bin/gcc",
            "--cxx=/usr/bin/g++",
            "--ar=/usr/bin/ar",
        ])
        .unwrap();
        assert_eq!(args.cc, Some(PathBuf::from("/usr/bin/gcc")));
        assert_eq!(args.cxx, Some(PathBuf::from("/usr/bin/g++")));
        assert_eq!(args.ar, Some(PathBuf::from("/usr/bin/ar")));
    }

    #[test]
    fn test_equals_syntax_linker() {
        let args = parse(&["cargo-cross", "build", "--linker=/usr/bin/ld.lld"]).unwrap();
        assert_eq!(args.linker, Some(PathBuf::from("/usr/bin/ld.lld")));
    }

    #[test]
    fn test_equals_syntax_cflags_with_spaces() {
        let args = parse(&["cargo-cross", "build", "--cflags=-O2 -Wall -Wextra"]).unwrap();
        assert_eq!(args.cflags, Some("-O2 -Wall -Wextra".to_string()));
    }

    #[test]
    fn test_equals_syntax_ldflags() {
        let args = parse(&["cargo-cross", "build", "--ldflags=-L/usr/local/lib -static"]).unwrap();
        assert_eq!(args.ldflags, Some("-L/usr/local/lib -static".to_string()));
    }

    #[test]
    fn test_equals_syntax_rustflag() {
        let args = parse(&["cargo-cross", "build", "--rustflag=-C opt-level=3"]).unwrap();
        assert_eq!(args.rustflags, vec!["-C opt-level=3"]);
    }

    #[test]
    fn test_equals_syntax_github_proxy() {
        let args = parse(&[
            "cargo-cross",
            "build",
            "--github-proxy=https://mirror.example.com/",
        ])
        .unwrap();
        assert_eq!(
            args.github_proxy,
            Some("https://mirror.example.com/".to_string())
        );
    }

    #[test]
    fn test_equals_syntax_sccache_options() {
        let args = parse(&[
            "cargo-cross",
            "build",
            "--enable-sccache",
            "--sccache-dir=/tmp/sccache",
            "--sccache-cache-size=20G",
        ])
        .unwrap();
        assert!(args.enable_sccache);
        assert_eq!(args.sccache_dir, Some(PathBuf::from("/tmp/sccache")));
        assert_eq!(args.sccache_cache_size, Some("20G".to_string()));
    }

    #[test]
    fn test_equals_syntax_config_with_equals_in_value() {
        let args = parse(&["cargo-cross", "build", "--config=build.jobs=4"]).unwrap();
        assert_eq!(args.cargo_config, vec!["build.jobs=4"]);
    }

    #[test]
    fn test_equals_syntax_multiple_options() {
        let args = parse(&[
            "cargo-cross",
            "build",
            "-t=x86_64-unknown-linux-musl",
            "--profile=release",
            "-F=serde,json",
            "-j=8",
            "--crt-static=true",
            "--build-std=core,alloc",
        ])
        .unwrap();
        assert_eq!(args.targets, vec!["x86_64-unknown-linux-musl"]);
        assert_eq!(args.profile, "release");
        assert_eq!(args.features, Some("serde,json".to_string()));
        assert_eq!(args.jobs, Some("8".to_string()));
        assert_eq!(args.crt_static, Some(true));
        assert_eq!(args.build_std, Some("core,alloc".to_string()));
    }

    #[test]
    fn test_equals_syntax_toolchain() {
        let args = parse(&["cargo-cross", "build", "--toolchain=nightly-2024-01-01"]).unwrap();
        assert_eq!(args.toolchain, Some("nightly-2024-01-01".to_string()));
    }

    #[test]
    fn test_equals_syntax_target_dir() {
        let args = parse(&["cargo-cross", "build", "--target-dir=/tmp/target"]).unwrap();
        assert_eq!(args.cargo_target_dir, Some(PathBuf::from("/tmp/target")));
    }

    #[test]
    fn test_equals_syntax_z_flag() {
        let args = parse(&["cargo-cross", "build", "-Z=build-std"]).unwrap();
        assert_eq!(args.cargo_z_flags, vec!["build-std"]);
    }

    #[test]
    fn test_equals_syntax_directory() {
        let args = parse(&["cargo-cross", "build", "-C=/path/to/project"]).unwrap();
        assert_eq!(args.cargo_cwd, Some(PathBuf::from("/path/to/project")));
    }

    #[test]
    fn test_equals_syntax_message_format() {
        let args = parse(&["cargo-cross", "build", "--message-format=json"]).unwrap();
        assert_eq!(args.message_format, Some("json".to_string()));
    }

    #[test]
    fn test_equals_syntax_color() {
        let args = parse(&["cargo-cross", "build", "--color=always"]).unwrap();
        assert_eq!(args.color, Some("always".to_string()));
    }

    // Mixed flags and options tests

    #[test]
    fn test_mixed_crt_static_then_flag() {
        let args = parse(&[
            "cargo-cross",
            "build",
            "--crt-static",
            "true",
            "--no-default-features",
        ])
        .unwrap();
        assert_eq!(args.crt_static, Some(true));
        assert!(args.no_default_features);
    }

    #[test]
    fn test_mixed_crt_static_then_short_option() {
        let args = parse(&[
            "cargo-cross",
            "build",
            "--crt-static",
            "false",
            "-F",
            "serde",
        ])
        .unwrap();
        assert_eq!(args.crt_static, Some(false));
        assert_eq!(args.features, Some("serde".to_string()));
    }

    #[test]
    fn test_mixed_crt_static_with_target() {
        let args = parse(&[
            "cargo-cross",
            "build",
            "--crt-static",
            "true",
            "-t",
            "x86_64-unknown-linux-musl",
            "--profile",
            "release",
        ])
        .unwrap();
        assert_eq!(args.crt_static, Some(true));
        assert_eq!(args.targets, vec!["x86_64-unknown-linux-musl"]);
        assert_eq!(args.profile, "release");
    }

    #[test]
    fn test_mixed_flag_then_crt_static() {
        let args = parse(&[
            "cargo-cross",
            "build",
            "--no-default-features",
            "--crt-static",
            "true",
        ])
        .unwrap();
        assert!(args.no_default_features);
        assert_eq!(args.crt_static, Some(true));
    }

    #[test]
    fn test_mixed_multiple_flags_and_options() {
        let args = parse(&[
            "cargo-cross",
            "build",
            "-t",
            "aarch64-unknown-linux-musl",
            "--no-default-features",
            "-F",
            "serde,json",
            "--crt-static",
            "true",
            "--profile",
            "release",
            "-vv",
        ])
        .unwrap();
        assert_eq!(args.targets, vec!["aarch64-unknown-linux-musl"]);
        assert!(args.no_default_features);
        assert_eq!(args.features, Some("serde,json".to_string()));
        assert_eq!(args.crt_static, Some(true));
        assert_eq!(args.profile, "release");
        assert_eq!(args.verbose_level, 2);
    }

    // Complex option ordering tests

    #[test]
    fn test_options_before_command_style() {
        // Options can come in any order
        let args = parse(&[
            "cargo-cross",
            "build",
            "--profile",
            "dev",
            "-t",
            "x86_64-unknown-linux-musl",
            "--features",
            "foo",
        ])
        .unwrap();
        assert_eq!(args.profile, "dev");
        assert_eq!(args.targets, vec!["x86_64-unknown-linux-musl"]);
        assert_eq!(args.features, Some("foo".to_string()));
    }

    #[test]
    fn test_interleaved_short_and_long_options() {
        let args = parse(&[
            "cargo-cross",
            "build",
            "-t",
            "x86_64-unknown-linux-musl",
            "--profile",
            "release",
            "-F",
            "foo",
            "--no-default-features",
            "-j",
            "4",
            "--locked",
        ])
        .unwrap();
        assert_eq!(args.targets, vec!["x86_64-unknown-linux-musl"]);
        assert_eq!(args.profile, "release");
        assert_eq!(args.features, Some("foo".to_string()));
        assert!(args.no_default_features);
        assert_eq!(args.jobs, Some("4".to_string()));
        assert!(args.locked);
    }

    // Verbose flag variations

    #[test]
    fn test_verbose_single() {
        let args = parse(&["cargo-cross", "build", "-v"]).unwrap();
        assert_eq!(args.verbose_level, 1);
    }

    #[test]
    fn test_verbose_double() {
        let args = parse(&["cargo-cross", "build", "-vv"]).unwrap();
        assert_eq!(args.verbose_level, 2);
    }

    #[test]
    fn test_verbose_triple() {
        let args = parse(&["cargo-cross", "build", "-vvv"]).unwrap();
        assert_eq!(args.verbose_level, 3);
    }

    #[test]
    fn test_verbose_separate() {
        let args = parse(&["cargo-cross", "build", "-v", "-v", "-v"]).unwrap();
        assert_eq!(args.verbose_level, 3);
    }

    #[test]
    fn test_verbose_long_form() {
        let args = parse(&["cargo-cross", "build", "--verbose", "--verbose"]).unwrap();
        assert_eq!(args.verbose_level, 2);
    }

    #[test]
    fn test_verbose_mixed_with_options() {
        let args = parse(&[
            "cargo-cross",
            "build",
            "-v",
            "-t",
            "x86_64-unknown-linux-musl",
            "-v",
        ])
        .unwrap();
        assert_eq!(args.verbose_level, 2);
        assert_eq!(args.targets, vec!["x86_64-unknown-linux-musl"]);
    }

    // Timings option (optional value) tests

    #[test]
    fn test_timings_without_value() {
        let args = parse(&["cargo-cross", "build", "--timings"]).unwrap();
        assert_eq!(args.timings, Some("true".to_string()));
    }

    #[test]
    fn test_timings_with_value() {
        let args = parse(&["cargo-cross", "build", "--timings=html"]).unwrap();
        assert_eq!(args.timings, Some("html".to_string()));
    }

    #[test]
    fn test_timings_followed_by_flag() {
        let args = parse(&["cargo-cross", "build", "--timings", "--locked"]).unwrap();
        assert_eq!(args.timings, Some("true".to_string()));
        assert!(args.locked);
    }

    #[test]
    fn test_timings_followed_by_option() {
        let args = parse(&[
            "cargo-cross",
            "build",
            "--timings",
            "-t",
            "x86_64-unknown-linux-musl",
        ])
        .unwrap();
        assert_eq!(args.timings, Some("true".to_string()));
        assert_eq!(args.targets, vec!["x86_64-unknown-linux-musl"]);
    }

    // Multiple values / repeated options tests

    #[test]
    fn test_multiple_targets_comma_separated() {
        let args = parse(&[
            "cargo-cross",
            "build",
            "-t",
            "x86_64-unknown-linux-musl,aarch64-unknown-linux-musl,armv7-unknown-linux-musleabihf",
        ])
        .unwrap();
        assert_eq!(args.targets.len(), 3);
        assert_eq!(args.targets[0], "x86_64-unknown-linux-musl");
        assert_eq!(args.targets[1], "aarch64-unknown-linux-musl");
        assert_eq!(args.targets[2], "armv7-unknown-linux-musleabihf");
    }

    #[test]
    fn test_multiple_targets_repeated_option() {
        let args = parse(&[
            "cargo-cross",
            "build",
            "-t",
            "x86_64-unknown-linux-musl",
            "-t",
            "aarch64-unknown-linux-musl",
        ])
        .unwrap();
        assert_eq!(args.targets.len(), 2);
    }

    #[test]
    fn test_multiple_rustflags() {
        let args = parse(&[
            "cargo-cross",
            "build",
            "--rustflag",
            "-C opt-level=3",
            "--rustflag",
            "-C lto=thin",
        ])
        .unwrap();
        assert_eq!(args.rustflags.len(), 2);
        assert_eq!(args.rustflags[0], "-C opt-level=3");
        assert_eq!(args.rustflags[1], "-C lto=thin");
    }

    #[test]
    fn test_multiple_config_flags() {
        let args = parse(&[
            "cargo-cross",
            "build",
            "--config",
            "build.jobs=4",
            "--config",
            "profile.release.lto=true",
        ])
        .unwrap();
        assert_eq!(args.cargo_config.len(), 2);
    }

    #[test]
    fn test_multiple_z_flags() {
        let args = parse(&[
            "cargo-cross",
            "build",
            "-Z",
            "build-std",
            "-Z",
            "unstable-options",
        ])
        .unwrap();
        assert_eq!(args.cargo_z_flags.len(), 2);
    }

    // Hyphen values tests (for compiler flags)

    #[test]
    fn test_cflags_with_hyphen() {
        let args = parse(&["cargo-cross", "build", "--cflags", "-O2 -Wall"]).unwrap();
        assert_eq!(args.cflags, Some("-O2 -Wall".to_string()));
    }

    #[test]
    fn test_ldflags_with_hyphen() {
        let args = parse(&["cargo-cross", "build", "--ldflags", "-L/usr/local/lib"]).unwrap();
        assert_eq!(args.ldflags, Some("-L/usr/local/lib".to_string()));
    }

    #[test]
    fn test_rustflag_with_hyphen() {
        let args = parse(&["cargo-cross", "build", "--rustflag", "-C target-cpu=native"]).unwrap();
        assert_eq!(args.rustflags, vec!["-C target-cpu=native"]);
    }

    // Passthrough arguments tests

    #[test]
    fn test_passthrough_single() {
        let args = parse(&["cargo-cross", "build", "--", "--nocapture"]).unwrap();
        assert_eq!(args.passthrough_args, vec!["--nocapture"]);
    }

    #[test]
    fn test_passthrough_multiple() {
        let args = parse(&[
            "cargo-cross",
            "test",
            "--",
            "--nocapture",
            "--test-threads=1",
        ])
        .unwrap();
        assert_eq!(
            args.passthrough_args,
            vec!["--nocapture", "--test-threads=1"]
        );
    }

    #[test]
    fn test_passthrough_with_hyphen_values() {
        let args = parse(&["cargo-cross", "build", "--", "-v", "--foo", "-bar"]).unwrap();
        assert_eq!(args.passthrough_args, vec!["-v", "--foo", "-bar"]);
    }

    #[test]
    fn test_passthrough_after_options() {
        let args = parse(&[
            "cargo-cross",
            "build",
            "-t",
            "x86_64-unknown-linux-musl",
            "--profile",
            "release",
            "--",
            "--foo",
            "--bar",
        ])
        .unwrap();
        assert_eq!(args.targets, vec!["x86_64-unknown-linux-musl"]);
        assert_eq!(args.profile, "release");
        assert_eq!(args.passthrough_args, vec!["--foo", "--bar"]);
    }

    // Alias tests

    #[test]
    fn test_alias_targets() {
        let args = parse(&[
            "cargo-cross",
            "build",
            "--targets",
            "x86_64-unknown-linux-musl",
        ])
        .unwrap();
        assert_eq!(args.targets, vec!["x86_64-unknown-linux-musl"]);
    }

    #[test]
    fn test_alias_workspace_all() {
        let args = parse(&["cargo-cross", "build", "--all"]).unwrap();
        assert!(args.workspace);
    }

    #[test]
    fn test_alias_rustflags() {
        let args = parse(&["cargo-cross", "build", "--rustflags", "-C lto"]).unwrap();
        assert_eq!(args.rustflags, vec!["-C lto"]);
    }

    #[test]
    fn test_alias_trim_paths() {
        let args = parse(&["cargo-cross", "build", "--trim-paths", "all"]).unwrap();
        assert_eq!(args.cargo_trim_paths, Some("all".to_string()));
    }

    #[test]
    fn test_trim_paths_no_value() {
        // --trim-paths without value should default to "true"
        let args = parse(&["cargo-cross", "build", "--trim-paths"]).unwrap();
        assert_eq!(args.cargo_trim_paths, Some("true".to_string()));
    }

    #[test]
    fn test_cargo_trim_paths_no_value() {
        // --cargo-trim-paths without value should default to "true"
        let args = parse(&["cargo-cross", "build", "--cargo-trim-paths"]).unwrap();
        assert_eq!(args.cargo_trim_paths, Some("true".to_string()));
    }

    #[test]
    fn test_rustc_bootstrap_no_value() {
        // --rustc-bootstrap without value should default to "1"
        let args = parse(&["cargo-cross", "build", "--rustc-bootstrap"]).unwrap();
        assert_eq!(args.rustc_bootstrap, Some("1".to_string()));
    }

    #[test]
    fn test_rustc_bootstrap_with_value() {
        let args = parse(&["cargo-cross", "build", "--rustc-bootstrap", "mycrate"]).unwrap();
        assert_eq!(args.rustc_bootstrap, Some("mycrate".to_string()));
    }

    // Command alias tests

    #[test]
    fn test_command_alias_b() {
        let args = parse(&["cargo-cross", "b"]).unwrap();
        assert_eq!(args.command, Command::build());
    }

    #[test]
    fn test_command_alias_c() {
        let args = parse(&["cargo-cross", "c"]).unwrap();
        assert_eq!(args.command, Command::check());
    }

    #[test]
    fn test_command_alias_r() {
        let args = parse(&["cargo-cross", "r"]).unwrap();
        assert_eq!(args.command, Command::run());
    }

    #[test]
    fn test_command_alias_t() {
        let args = parse(&["cargo-cross", "t"]).unwrap();
        assert_eq!(args.command, Command::test());
    }

    // Requires relationship tests

    #[test]
    fn test_requires_exclude_needs_workspace() {
        let result = parse(&["cargo-cross", "build", "--exclude", "foo"]);
        assert!(
            result.is_err() || {
                // clap exits on error, so we might not get here
                false
            }
        );
    }

    #[test]
    fn test_requires_exclude_with_workspace() {
        let args = parse(&["cargo-cross", "build", "--workspace", "--exclude", "foo"]).unwrap();
        assert!(args.workspace);
        assert_eq!(args.exclude, Some("foo".to_string()));
    }

    #[test]
    fn test_requires_build_std_features_with_build_std() {
        let args = parse(&[
            "cargo-cross",
            "build",
            "--build-std",
            "core,alloc",
            "--build-std-features",
            "panic_immediate_abort",
        ])
        .unwrap();
        assert_eq!(args.build_std, Some("core,alloc".to_string()));
        assert_eq!(
            args.build_std_features,
            Some("panic_immediate_abort".to_string())
        );
    }

    // Conflicts relationship tests

    #[test]
    fn test_conflicts_quiet_verbose() {
        let result = parse(&["cargo-cross", "build", "--quiet", "--verbose"]);
        // This should fail due to conflict
        assert!(
            result.is_err() || {
                // clap exits, checking we don't panic
                false
            }
        );
    }

    #[test]
    fn test_conflicts_features_all_features() {
        let result = parse(&[
            "cargo-cross",
            "build",
            "--features",
            "foo",
            "--all-features",
        ]);
        assert!(result.is_err());
    }

    #[test]
    fn test_no_toolchain_setup() {
        let args = parse(&["cargo-cross", "build", "--no-toolchain-setup"]).unwrap();
        assert!(args.no_toolchain_setup);
    }

    #[test]
    fn test_linker_with_no_toolchain_setup() {
        // --linker and --no-toolchain-setup can be used together
        let args = parse(&[
            "cargo-cross",
            "build",
            "--linker",
            "/usr/bin/ld",
            "--no-toolchain-setup",
        ])
        .unwrap();
        assert!(args.no_toolchain_setup);
        assert_eq!(args.linker, Some(PathBuf::from("/usr/bin/ld")));
    }

    // Complex real-world scenario tests

    #[test]
    fn test_real_world_linux_musl_build() {
        let args = parse(&[
            "cargo-cross",
            "+nightly",
            "build",
            "-t",
            "x86_64-unknown-linux-musl",
            "--profile",
            "release",
            "--crt-static",
            "true",
            "--no-default-features",
            "-F",
            "serde,json",
            "-j",
            "8",
            "--locked",
        ])
        .unwrap();
        assert_eq!(args.toolchain, Some("nightly".to_string()));
        assert_eq!(args.command, Command::build());
        assert_eq!(args.targets, vec!["x86_64-unknown-linux-musl"]);
        assert_eq!(args.profile, "release");
        assert_eq!(args.crt_static, Some(true));
        assert!(args.no_default_features);
        assert_eq!(args.features, Some("serde,json".to_string()));
        assert_eq!(args.jobs, Some("8".to_string()));
        assert!(args.locked);
    }

    #[test]
    fn test_real_world_multi_target_build() {
        let args = parse(&[
            "cargo-cross",
            "build",
            "-t",
            "x86_64-unknown-linux-musl,aarch64-unknown-linux-musl",
            "--profile",
            "release",
            "--build-std",
            "core,alloc",
            "--build-std-features",
            "panic_immediate_abort",
            "-vv",
        ])
        .unwrap();
        assert_eq!(args.targets.len(), 2);
        assert_eq!(args.build_std, Some("core,alloc".to_string()));
        assert_eq!(
            args.build_std_features,
            Some("panic_immediate_abort".to_string())
        );
        assert_eq!(args.verbose_level, 2);
    }

    #[test]
    fn test_real_world_test_with_passthrough() {
        let args = parse(&[
            "cargo-cross",
            "test",
            "-t",
            "x86_64-unknown-linux-musl",
            "--",
            "--nocapture",
            "--test-threads=1",
        ])
        .unwrap();
        assert_eq!(args.command, Command::test());
        assert_eq!(args.targets, vec!["x86_64-unknown-linux-musl"]);
        assert_eq!(
            args.passthrough_args,
            vec!["--nocapture", "--test-threads=1"]
        );
    }

    #[test]
    fn test_real_world_with_compiler_options() {
        let args = parse(&[
            "cargo-cross",
            "build",
            "-t",
            "aarch64-unknown-linux-musl",
            "--cc",
            "/opt/cross/bin/aarch64-linux-musl-gcc",
            "--cxx",
            "/opt/cross/bin/aarch64-linux-musl-g++",
            "--ar",
            "/opt/cross/bin/aarch64-linux-musl-ar",
            "--cflags",
            "-O2 -march=armv8-a",
        ])
        .unwrap();
        assert_eq!(args.targets, vec!["aarch64-unknown-linux-musl"]);
        assert!(args.cc.is_some());
        assert!(args.cxx.is_some());
        assert!(args.ar.is_some());
        assert_eq!(args.cflags, Some("-O2 -march=armv8-a".to_string()));
    }

    #[test]
    fn test_real_world_sccache_build() {
        let args = parse(&[
            "cargo-cross",
            "build",
            "-t",
            "x86_64-unknown-linux-musl",
            "--enable-sccache",
            "--sccache-dir",
            "/tmp/sccache",
            "--sccache-cache-size",
            "10G",
        ])
        .unwrap();
        assert!(args.enable_sccache);
        assert_eq!(args.sccache_dir, Some(PathBuf::from("/tmp/sccache")));
        assert_eq!(args.sccache_cache_size, Some("10G".to_string()));
    }

    #[test]
    fn test_real_world_workspace_build() {
        let args = parse(&[
            "cargo-cross",
            "build",
            "--workspace",
            "--exclude",
            "test-crate",
            "-t",
            "x86_64-unknown-linux-musl",
            "--profile",
            "release",
        ])
        .unwrap();
        assert!(args.workspace);
        assert_eq!(args.exclude, Some("test-crate".to_string()));
        assert_eq!(args.targets, vec!["x86_64-unknown-linux-musl"]);
    }

    // Edge case tests

    #[test]
    fn test_edge_case_equals_in_value() {
        let args = parse(&[
            "cargo-cross",
            "build",
            "--config",
            "build.rustflags=['-C', 'opt-level=3']",
        ])
        .unwrap();
        assert_eq!(
            args.cargo_config,
            vec!["build.rustflags=['-C', 'opt-level=3']"]
        );
    }

    #[test]
    fn test_edge_case_empty_passthrough() {
        let args = parse(&["cargo-cross", "build", "--"]).unwrap();
        assert!(args.passthrough_args.is_empty());
    }

    #[test]
    fn test_edge_case_target_with_numbers() {
        let args = parse(&[
            "cargo-cross",
            "build",
            "-t",
            "armv7-unknown-linux-musleabihf",
        ])
        .unwrap();
        assert_eq!(args.targets, vec!["armv7-unknown-linux-musleabihf"]);
    }

    #[test]
    fn test_edge_case_all_bool_options() {
        let args = parse(&[
            "cargo-cross",
            "build",
            "--no-default-features",
            "--workspace",
            "--bins",
            "--lib",
            "--examples",
            "--tests",
            "--benches",
            "--all-targets",
            "--locked",
            "--offline",
            "--keep-going",
        ])
        .unwrap();
        assert!(args.no_default_features);
        assert!(args.workspace);
        assert!(args.build_bins);
        assert!(args.build_lib);
        assert!(args.build_examples);
        assert!(args.build_tests);
        assert!(args.build_benches);
        assert!(args.build_all_targets);
        assert!(args.locked);
        assert!(args.offline);
        assert!(args.keep_going);
    }

    #[test]
    fn test_edge_case_mixed_equals_and_space() {
        let args = parse(&[
            "cargo-cross",
            "build",
            "-t=x86_64-unknown-linux-musl",
            "--profile",
            "release",
            "-F=serde",
            "--crt-static",
            "true",
        ])
        .unwrap();
        assert_eq!(args.targets, vec!["x86_64-unknown-linux-musl"]);
        assert_eq!(args.profile, "release");
        assert_eq!(args.features, Some("serde".to_string()));
        assert_eq!(args.crt_static, Some(true));
    }

    #[test]
    fn test_edge_case_directory_option() {
        let args = parse(&[
            "cargo-cross",
            "build",
            "-C",
            "/path/to/project",
            "-t",
            "x86_64-unknown-linux-musl",
        ])
        .unwrap();
        assert_eq!(args.cargo_cwd, Some(PathBuf::from("/path/to/project")));
    }

    #[test]
    fn test_edge_case_manifest_path() {
        let args = parse(&[
            "cargo-cross",
            "build",
            "--manifest-path",
            "/path/to/Cargo.toml",
        ])
        .unwrap();
        assert_eq!(
            args.manifest_path,
            Some(PathBuf::from("/path/to/Cargo.toml"))
        );
    }

    // Cargo cross invocation style tests

    #[test]
    fn test_cargo_cross_style_build() {
        let args: Vec<String> = vec![
            "cargo-cross".to_string(),
            "cross".to_string(),
            "build".to_string(),
            "-t".to_string(),
            "x86_64-unknown-linux-musl".to_string(),
        ];
        match parse_args_from(args).unwrap() {
            ParseResult::Build(args) => {
                assert_eq!(args.command, Command::build());
                assert_eq!(args.targets, vec!["x86_64-unknown-linux-musl"]);
            }
            _ => panic!("expected Build"),
        }
    }

    #[test]
    fn test_cargo_cross_style_with_toolchain() {
        let args: Vec<String> = vec![
            "cargo-cross".to_string(),
            "cross".to_string(),
            "+nightly".to_string(),
            "build".to_string(),
        ];
        match parse_args_from(args).unwrap() {
            ParseResult::Build(args) => {
                assert_eq!(args.toolchain, Some("nightly".to_string()));
                assert_eq!(args.command, Command::build());
            }
            _ => panic!("expected Build"),
        }
    }

    #[test]
    fn test_cargo_cross_style_targets() {
        let args: Vec<String> = vec![
            "cargo-cross".to_string(),
            "cross".to_string(),
            "targets".to_string(),
        ];
        match parse_args_from(args).unwrap() {
            ParseResult::ShowTargets(_) => {}
            _ => panic!("expected ShowTargets"),
        }
    }

    // New alias and option tests

    #[test]
    fn test_github_proxy_mirror_alias() {
        let args = parse(&[
            "cargo-cross",
            "build",
            "--github-proxy-mirror",
            "https://mirror.example.com/",
        ])
        .unwrap();
        assert_eq!(
            args.github_proxy,
            Some("https://mirror.example.com/".to_string())
        );
    }

    #[test]
    fn test_github_proxy_original() {
        let args = parse(&[
            "cargo-cross",
            "build",
            "--github-proxy",
            "https://proxy.example.com/",
        ])
        .unwrap();
        assert_eq!(
            args.github_proxy,
            Some("https://proxy.example.com/".to_string())
        );
    }

    #[test]
    fn test_release_flag_short() {
        let args = parse(&["cargo-cross", "build", "-r"]).unwrap();
        assert!(args.release);
        assert_eq!(args.profile, "release");
    }

    #[test]
    fn test_release_flag_long() {
        let args = parse(&["cargo-cross", "build", "--release"]).unwrap();
        assert!(args.release);
        assert_eq!(args.profile, "release");
    }

    #[test]
    fn test_toolchain_option() {
        let args = parse(&["cargo-cross", "build", "--toolchain", "nightly"]).unwrap();
        assert_eq!(args.toolchain, Some("nightly".to_string()));
    }

    #[test]
    fn test_toolchain_option_with_version() {
        let args = parse(&["cargo-cross", "build", "--toolchain", "1.75.0"]).unwrap();
        assert_eq!(args.toolchain, Some("1.75.0".to_string()));
    }

    #[test]
    fn test_toolchain_plus_syntax_takes_precedence() {
        let args = parse(&["cargo-cross", "+nightly", "build", "--toolchain", "stable"]).unwrap();
        // +nightly syntax takes precedence over --toolchain
        assert_eq!(args.toolchain, Some("nightly".to_string()));
    }

    #[test]
    fn test_target_dir_alias() {
        let args = parse(&["cargo-cross", "build", "--target-dir", "/tmp/target"]).unwrap();
        assert_eq!(args.cargo_target_dir, Some(PathBuf::from("/tmp/target")));
    }

    #[test]
    fn test_cargo_target_dir_original() {
        let args = parse(&["cargo-cross", "build", "--cargo-target-dir", "/tmp/target"]).unwrap();
        assert_eq!(args.cargo_target_dir, Some(PathBuf::from("/tmp/target")));
    }

    #[test]
    fn test_args_alias() {
        let args = parse(&["cargo-cross", "build", "--args", "--verbose"]).unwrap();
        assert_eq!(args.cargo_args, vec!["--verbose"]);
    }

    #[test]
    fn test_cargo_args_original() {
        let args = parse(&["cargo-cross", "build", "--cargo-args", "--verbose"]).unwrap();
        assert_eq!(args.cargo_args, vec!["--verbose"]);
    }

    #[test]
    fn test_cargo_args_multiple() {
        let args = parse(&[
            "cargo-cross",
            "build",
            "--cargo-args",
            "--verbose",
            "--cargo-args",
            "--locked",
        ])
        .unwrap();
        assert_eq!(args.cargo_args, vec!["--verbose", "--locked"]);
    }

    // Target validation tests

    #[test]
    fn test_invalid_target_triple_uppercase() {
        let result = parse(&["cargo-cross", "build", "-t", "X86_64-unknown-linux-musl"]);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            matches!(err, CrossError::InvalidTargetTriple { target, char } if target == "X86_64-unknown-linux-musl" && char == 'X')
        );
    }

    #[test]
    fn test_glob_pattern_matches_target() {
        // x86_64*unknown-linux-musl matches x86_64-unknown-linux-musl (glob * matches -)
        let args = parse(&["cargo-cross", "build", "-t", "x86_64*unknown-linux-musl"]).unwrap();
        assert!(args
            .targets
            .contains(&"x86_64-unknown-linux-musl".to_string()));
    }

    #[test]
    fn test_invalid_target_triple_slash() {
        // Slash is not a glob character, so it should fail validation as invalid character
        let result = parse(&["cargo-cross", "build", "-t", "x86_64/unknown-linux-musl"]);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            matches!(err, CrossError::InvalidTargetTriple { target, char } if target == "x86_64/unknown-linux-musl" && char == '/')
        );
    }

    #[test]
    fn test_invalid_target_triple_dot() {
        let result = parse(&["cargo-cross", "build", "-t", "x86_64.unknown-linux-musl"]);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            matches!(err, CrossError::InvalidTargetTriple { target, char } if target == "x86_64.unknown-linux-musl" && char == '.')
        );
    }

    #[test]
    fn test_no_matching_targets_glob() {
        let result = parse(&["cargo-cross", "build", "-t", "*mingw*"]);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(matches!(
            err,
            CrossError::NoMatchingTargets { pattern } if pattern == "*mingw*"
        ));
    }

    #[test]
    fn test_no_matching_targets_glob_complex() {
        let result = parse(&["cargo-cross", "build", "-t", "*nonexistent-platform*"]);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(matches!(
            err,
            CrossError::NoMatchingTargets { pattern } if pattern == "*nonexistent-platform*"
        ));
    }

    #[test]
    fn test_valid_target_triple_with_numbers() {
        let args = parse(&[
            "cargo-cross",
            "build",
            "-t",
            "armv7-unknown-linux-gnueabihf",
        ])
        .unwrap();
        assert_eq!(args.targets, vec!["armv7-unknown-linux-gnueabihf"]);
    }

    #[test]
    fn test_valid_target_triple_underscore() {
        let args = parse(&["cargo-cross", "build", "-t", "x86_64_unknown_linux_musl"]).unwrap();
        assert_eq!(args.targets, vec!["x86_64_unknown_linux_musl"]);
    }

    #[test]
    fn test_valid_glob_pattern_matches() {
        let args = parse(&["cargo-cross", "build", "-t", "*-linux-musl"]).unwrap();
        assert!(!args.targets.is_empty());
        for target in &args.targets {
            assert!(target.ends_with("-linux-musl"));
        }
    }

    #[test]
    fn test_is_glob_pattern() {
        assert!(is_glob_pattern("*-linux-musl"));
        assert!(is_glob_pattern("x86_64-*-linux"));
        assert!(is_glob_pattern("x86_64-?-linux"));
        assert!(is_glob_pattern("[ab]-linux"));
        assert!(!is_glob_pattern("x86_64-unknown-linux-musl"));
        assert!(!is_glob_pattern("aarch64-linux-android"));
    }

    #[test]
    fn test_validate_target_triple() {
        assert!(validate_target_triple("x86_64-unknown-linux-musl").is_ok());
        assert!(validate_target_triple("aarch64-unknown-linux-gnu").is_ok());
        assert!(validate_target_triple("armv7-unknown-linux-gnueabihf").is_ok());
        assert!(validate_target_triple("i686-pc-windows-msvc").is_ok());
        assert!(validate_target_triple("x86_64-pc-windows-msvc").is_ok());
        assert!(validate_target_triple("X86_64-unknown-linux-musl").is_err()); // uppercase X
        assert!(validate_target_triple("x86_64*linux").is_err()); // special char *
        assert!(validate_target_triple("x86_64.linux").is_err()); // special char .
        assert!(validate_target_triple("x86_64 linux").is_err()); // space
    }

    // Short argument concatenation tests (no separator between flag and value)

    #[test]
    fn test_short_concat_features() {
        let args = parse(&["cargo-cross", "build", "-Ffoo,bar"]).unwrap();
        assert_eq!(args.features, Some("foo,bar".to_string()));
    }

    #[test]
    fn test_short_concat_jobs() {
        let args = parse(&["cargo-cross", "build", "-j4"]).unwrap();
        assert_eq!(args.jobs, Some("4".to_string()));
    }

    #[test]
    fn test_short_concat_package() {
        let args = parse(&["cargo-cross", "build", "-pmypackage"]).unwrap();
        assert_eq!(args.package, Some("mypackage".to_string()));
    }

    #[test]
    fn test_short_concat_target() {
        let args = parse(&["cargo-cross", "build", "-tx86_64-unknown-linux-musl"]).unwrap();
        assert_eq!(args.targets, vec!["x86_64-unknown-linux-musl"]);
    }

    #[test]
    fn test_short_concat_z_flag() {
        let args = parse(&["cargo-cross", "build", "-Zbuild-std"]).unwrap();
        assert_eq!(args.cargo_z_flags, vec!["build-std"]);
    }

    #[test]
    fn test_short_concat_directory() {
        let args = parse(&["cargo-cross", "build", "-C/path/to/project"]).unwrap();
        assert_eq!(args.cargo_cwd, Some(PathBuf::from("/path/to/project")));
    }

    #[test]
    fn test_short_concat_multiple() {
        let args = parse(&[
            "cargo-cross",
            "build",
            "-tx86_64-unknown-linux-musl",
            "-Ffoo,bar",
            "-j8",
            "-pmypkg",
        ])
        .unwrap();
        assert_eq!(args.targets, vec!["x86_64-unknown-linux-musl"]);
        assert_eq!(args.features, Some("foo,bar".to_string()));
        assert_eq!(args.jobs, Some("8".to_string()));
        assert_eq!(args.package, Some("mypkg".to_string()));
    }

    #[test]
    fn test_short_concat_mixed_with_space() {
        let args = parse(&[
            "cargo-cross",
            "build",
            "-j4",
            "-t",
            "x86_64-unknown-linux-musl",
            "-Fbar",
        ])
        .unwrap();
        assert_eq!(args.jobs, Some("4".to_string()));
        assert_eq!(args.targets, vec!["x86_64-unknown-linux-musl"]);
        assert_eq!(args.features, Some("bar".to_string()));
    }

    // Tests for parse_env_args (shell-style argument parsing from env vars)

    #[test]
    fn test_parse_env_args_not_set() {
        std::env::remove_var("TEST_PARSE_ENV_ARGS_NOT_SET");
        let result = parse_env_args("TEST_PARSE_ENV_ARGS_NOT_SET");
        assert!(result.is_none());
    }

    #[test]
    fn test_parse_env_args_empty() {
        std::env::set_var("TEST_PARSE_ENV_ARGS_EMPTY", "");
        let result = parse_env_args("TEST_PARSE_ENV_ARGS_EMPTY");
        assert!(result.is_none());
        std::env::remove_var("TEST_PARSE_ENV_ARGS_EMPTY");
    }

    #[test]
    fn test_parse_env_args_simple() {
        std::env::set_var("TEST_PARSE_ENV_ARGS_SIMPLE", "--verbose --locked");
        let result = parse_env_args("TEST_PARSE_ENV_ARGS_SIMPLE");
        assert_eq!(
            result,
            Some(vec!["--verbose".to_string(), "--locked".to_string()])
        );
        std::env::remove_var("TEST_PARSE_ENV_ARGS_SIMPLE");
    }

    #[test]
    fn test_parse_env_args_with_single_quotes() {
        std::env::set_var(
            "TEST_PARSE_ENV_ARGS_SINGLE_QUOTES",
            "--config 'build.jobs=4' --verbose",
        );
        let result = parse_env_args("TEST_PARSE_ENV_ARGS_SINGLE_QUOTES");
        assert_eq!(
            result,
            Some(vec![
                "--config".to_string(),
                "build.jobs=4".to_string(),
                "--verbose".to_string()
            ])
        );
        std::env::remove_var("TEST_PARSE_ENV_ARGS_SINGLE_QUOTES");
    }

    #[test]
    fn test_parse_env_args_with_double_quotes() {
        std::env::set_var(
            "TEST_PARSE_ENV_ARGS_DOUBLE_QUOTES",
            "--message-format \"json with spaces\"",
        );
        let result = parse_env_args("TEST_PARSE_ENV_ARGS_DOUBLE_QUOTES");
        assert_eq!(
            result,
            Some(vec![
                "--message-format".to_string(),
                "json with spaces".to_string()
            ])
        );
        std::env::remove_var("TEST_PARSE_ENV_ARGS_DOUBLE_QUOTES");
    }

    #[test]
    fn test_parse_env_args_complex() {
        std::env::set_var(
            "TEST_PARSE_ENV_ARGS_COMPLEX",
            "--config 'key=\"value with spaces\"' --verbose",
        );
        let result = parse_env_args("TEST_PARSE_ENV_ARGS_COMPLEX");
        assert_eq!(
            result,
            Some(vec![
                "--config".to_string(),
                "key=\"value with spaces\"".to_string(),
                "--verbose".to_string()
            ])
        );
        std::env::remove_var("TEST_PARSE_ENV_ARGS_COMPLEX");
    }

    #[test]
    fn test_parse_env_args_whitespace_only() {
        std::env::set_var("TEST_PARSE_ENV_ARGS_WHITESPACE", "   ");
        let result = parse_env_args("TEST_PARSE_ENV_ARGS_WHITESPACE");
        assert!(result.is_none());
        std::env::remove_var("TEST_PARSE_ENV_ARGS_WHITESPACE");
    }

    #[test]
    fn test_musl_target_with_default_glibc() {
        // musl targets should work with default (empty) glibc version
        let args = parse(&[
            "cargo-cross",
            "build",
            "-t",
            "aarch64_be-unknown-linux-musl",
        ])
        .unwrap();
        assert_eq!(args.targets, vec!["aarch64_be-unknown-linux-musl"]);
        assert_eq!(args.glibc_version, ""); // default is empty string
    }
}