agpm-cli 0.4.8

AGent Package Manager - A Git-based package manager for coding agents
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
//! Git operations wrapper for AGPM
//!
//! This module provides a safe, async wrapper around the system `git` command, serving as
//! the foundation for AGPM's distributed package management capabilities. Unlike libraries
//! that use embedded Git implementations (like `libgit2`), this module leverages the system's
//! installed Git binary to ensure maximum compatibility with existing Git configurations,
//! authentication methods, and platform-specific optimizations.
//!
//! # Design Philosophy: CLI-Based Git Integration
//!
//! AGPM follows the same approach as Cargo with `git-fetch-with-cli`, using the system's
//! `git` command rather than an embedded Git library. This design choice provides several
//! critical advantages:
//!
//! - **Authentication Compatibility**: Seamlessly works with SSH agents, credential helpers,
//!   Git configuration, and platform-specific authentication (Windows Credential Manager,
//!   macOS Keychain, Linux credential stores)
//! - **Feature Completeness**: Access to all Git features without library limitations
//! - **Platform Integration**: Leverages platform-optimized Git builds and configurations
//! - **Security**: Benefits from system Git's security updates and hardening
//! - **Debugging**: Uses familiar Git commands for troubleshooting and logging
//!
//! # Core Features
//!
//! ## Asynchronous Operations
//! All Git operations are async and built on Tokio, enabling:
//! - Non-blocking I/O for better performance
//! - Concurrent repository operations
//! - Progress reporting during long operations
//! - Graceful cancellation support
//!
//! ## Worktree Support for Parallel Operations
//! Advanced Git worktree integration for safe parallel package installation:
//! - **Bare repository cloning**: Creates repositories optimized for worktrees
//! - **Parallel worktree creation**: Multiple versions checked out simultaneously
//! - **Per-worktree locking**: Individual worktree creation locks prevent conflicts
//! - **Command-level concurrency**: Parallelism controlled by `--max-parallel` flag
//! - **Automatic cleanup**: Efficient worktree lifecycle management
//! - **Conflict-free operations**: Each dependency gets its own isolated working directory
//!
//! ## Progress Reporting
//! User feedback during:
//! - Repository cloning with transfer progress
//! - Fetch operations with network activity
//! - Large repository operations
//!
//! ## Authentication Handling
//! Supports multiple authentication methods through URL-based configuration:
//! - HTTPS with embedded tokens: `https://token@github.com/user/repo.git`
//! - SSH with key-based authentication: `git@github.com:user/repo.git`
//! - System credential helpers and Git configuration
//! - Platform-specific credential storage
//!
//! ## Cross-Platform Compatibility
//! Tested and optimized for:
//! - **Windows**: Handles path length limits, `PowerShell` vs CMD differences
//! - **macOS**: Integrates with Keychain and Xcode command line tools
//! - **Linux**: Works with various distributions and Git installations
//!
//! # Security Considerations
//!
//! ## Command Injection Prevention
//! All Git operations use proper argument passing to prevent injection attacks:
//! - Arguments passed as separate parameters, not shell strings
//! - URL validation before Git operations
//! - Path sanitization for repository locations
//!
//! ## Authentication Security
//! - Credentials never logged or exposed in error messages
//! - Authentication URLs are stripped from public error output
//! - Supports secure credential storage via system Git configuration
//!
//! ## Network Security
//! - HTTPS verification enabled by default
//! - Support for custom CA certificates via Git configuration
//! - Timeout handling for network operations
//!
//! # Performance Characteristics
//!
//! ## Network Operations
//! - Async I/O prevents blocking during network operations
//! - Parallel fetch operations for multiple repositories
//! - Efficient progress reporting without polling
//!
//! ## Local Operations
//! - Direct file system access for repository validation
//! - Optimized branch/tag listing with minimal Git calls
//! - Efficient checkout operations with proper reset handling
//!
//! # Error Handling Strategy
//!
//! The module provides rich error context through [`AgpmError`] variants:
//! - Network failures with retry suggestions
//! - Authentication errors with configuration guidance
//! - Repository format errors with recovery steps
//! - Platform-specific error translation
//!
//! # Usage Examples
//!
//! ## Basic Repository Operations
//! ```rust,no_run
//! use agpm_cli::git::GitRepo;
//! use std::env;
//!
//! # async fn example() -> anyhow::Result<()> {
//! // Use platform-appropriate temp directory
//! let temp_dir = env::temp_dir();
//! let repo_path = temp_dir.join("repo");
//!
//! // Clone a repository
//! let repo = GitRepo::clone(
//!     "https://github.com/example/repo.git",
//!     &repo_path
//! ).await?;
//!
//! // Fetch updates from remote
//! repo.fetch(None).await?;
//!
//! // Checkout a specific version
//! repo.checkout("v1.2.3").await?;
//!
//! // List available tags
//! let tags = repo.list_tags().await?;
//! println!("Available versions: {:?}", tags);
//! # Ok(())
//! # }
//! ```
//!
//! ## Authentication with URLs
//! ```rust,no_run
//! use agpm_cli::git::GitRepo;
//! use std::env;
//!
//! # async fn auth_example() -> anyhow::Result<()> {
//! // Use platform-appropriate temp directory
//! let temp_dir = env::temp_dir();
//! let repo_path = temp_dir.join("private-repo");
//!
//! // Clone with authentication embedded in URL
//! let repo = GitRepo::clone(
//!     "https://token:ghp_xxxx@github.com/private/repo.git",
//!     &repo_path
//! ).await?;
//!
//! // Fetch with different authentication URL
//! let auth_url = "https://oauth2:token@github.com/private/repo.git";
//! repo.fetch(Some(auth_url)).await?;
//! # Ok(())
//! # }
//! ```
//!
//! ## Repository Validation
//! ```rust,no_run
//! use agpm_cli::git::{GitRepo, ensure_git_available, is_valid_git_repo};
//! use std::env;
//!
//! # async fn validation_example() -> anyhow::Result<()> {
//! // Ensure Git is installed
//! ensure_git_available()?;
//!
//! // Verify repository URL before cloning
//! GitRepo::verify_url("https://github.com/example/repo.git").await?;
//!
//! // Check if directory is a valid Git repository
//! let temp_dir = env::temp_dir();
//! let path = temp_dir.join("repo");
//! if is_valid_git_repo(&path) {
//!     let repo = GitRepo::new(&path);
//!     let url = repo.get_remote_url().await?;
//!     println!("Repository URL: {}", url);
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ## Worktree-based Parallel Operations
//! ```rust,no_run
//! use agpm_cli::git::GitRepo;
//! use std::env;
//!
//! # async fn worktree_example() -> anyhow::Result<()> {
//! // Use platform-appropriate temp directory
//! let temp_dir = env::temp_dir();
//! let cache_dir = temp_dir.join("cache");
//! let bare_path = cache_dir.join("repo.git");
//!
//! // Clone repository as bare for worktree use
//! let bare_repo = GitRepo::clone_bare(
//!     "https://github.com/example/repo.git",
//!     &bare_path
//! ).await?;
//!
//! // Create multiple worktrees for parallel processing
//! let work1 = temp_dir.join("work1");
//! let work2 = temp_dir.join("work2");
//! let work3 = temp_dir.join("work3");
//!
//! let worktree1 = bare_repo.create_worktree(&work1, Some("v1.0.0")).await?;
//! let worktree2 = bare_repo.create_worktree(&work2, Some("v2.0.0")).await?;
//! let worktree3 = bare_repo.create_worktree(&work3, Some("main")).await?;
//!
//! // Each worktree can be used independently and concurrently
//! // Process files from worktree1 at v1.0.0
//! // Process files from worktree2 at v2.0.0  
//! // Process files from worktree3 at latest main
//!
//! // Clean up when done
//! bare_repo.remove_worktree(&work1).await?;
//! bare_repo.remove_worktree(&work2).await?;
//! bare_repo.remove_worktree(&work3).await?;
//! # Ok(())
//! # }
//! ```
//!
//! # Platform-Specific Considerations
//!
//! ## Windows
//! - Uses `git.exe` or `git.cmd` detection via PATH
//! - Handles long path names (>260 characters)
//! - Works with Windows Credential Manager
//! - Supports both CMD and `PowerShell` environments
//!
//! ## macOS
//! - Integrates with Xcode Command Line Tools Git
//! - Supports Keychain authentication
//! - Handles case-sensitive vs case-insensitive filesystems
//!
//! ## Linux
//! - Works with package manager installed Git
//! - Supports various credential helpers
//! - Handles different filesystem permissions
//!
//! # Integration with AGPM
//!
//! This module integrates with other AGPM components:
//! - [`crate::source`] - Repository source management
//! - [`crate::manifest`] - Manifest-based dependency resolution
//! - [`crate::lockfile`] - Lockfile generation with commit hashes
//! - [`crate::utils::progress`] - User progress feedback
//! - [`crate::core::AgpmError`] - Centralized error handling
//!
//! [`AgpmError`]: crate::core::AgpmError

pub mod command_builder;
#[cfg(test)]
mod tests;

use crate::core::AgpmError;
use crate::git::command_builder::GitCommand;
use anyhow::{Context, Result};
use std::path::{Path, PathBuf};

/// A Git repository handle providing async operations via CLI commands.
///
/// `GitRepo` represents a local Git repository and provides methods for common
/// Git operations such as cloning, fetching, checking out specific references,
/// and querying repository state. All operations are performed asynchronously
/// using the system's `git` command rather than an embedded Git library.
///
/// # Design Principles
///
/// - **CLI-based**: Uses system `git` command for maximum compatibility
/// - **Async**: All operations are non-blocking and support cancellation
/// - **Progress-aware**: Integration with progress reporting for long operations
/// - **Error-rich**: Detailed error information with context and suggestions
/// - **Cross-platform**: Tested on Windows, macOS, and Linux
///
/// # Repository State
///
/// The struct holds minimal state (just the repository path) and queries Git
/// directly for current information. This ensures consistency with external
/// Git operations and avoids state synchronization issues.
///
/// # Examples
///
/// ```rust,no_run
/// use agpm_cli::git::GitRepo;
/// use std::path::Path;
///
/// # async fn example() -> anyhow::Result<()> {
/// // Create handle for existing repository
/// let repo = GitRepo::new("/path/to/existing/repo");
///
/// // Verify it's a valid Git repository
/// if repo.is_git_repo() {
///     let tags = repo.list_tags().await?;
///     repo.checkout("main").await?;
/// }
/// # Ok(())
/// # }
/// ```
///
/// # Thread Safety
///
/// `GitRepo` is `Send` and `Sync`, allowing it to be used across async tasks.
/// However, concurrent Git operations on the same repository may conflict
/// at the Git level (e.g., simultaneous checkouts).
#[derive(Debug)]
pub struct GitRepo {
    /// The local filesystem path to the Git repository.
    ///
    /// This path should point to the root directory of a Git repository
    /// (the directory containing `.git/` subdirectory).
    path: PathBuf,
}

impl GitRepo {
    /// Creates a new `GitRepo` instance for an existing local repository.
    ///
    /// This constructor does not verify that the path contains a valid Git repository.
    /// Use [`is_git_repo`](#method.is_git_repo) or [`ensure_valid_git_repo`] to validate
    /// the repository before performing Git operations.
    ///
    /// # Arguments
    ///
    /// * `path` - The filesystem path to the Git repository root directory
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::git::GitRepo;
    /// use std::path::Path;
    ///
    /// // Create repository handle
    /// let repo = GitRepo::new("/path/to/repo");
    ///
    /// // Verify it's valid before operations
    /// if repo.is_git_repo() {
    ///     println!("Valid Git repository at: {:?}", repo.path());
    /// }
    /// ```
    ///
    /// # See Also
    ///
    /// * [`clone`](#method.clone) - For creating repositories by cloning from remote
    /// * [`is_git_repo`](#method.is_git_repo) - For validating repository state
    pub fn new(path: impl AsRef<Path>) -> Self {
        Self {
            path: path.as_ref().to_path_buf(),
        }
    }

    /// Clones a Git repository from a remote URL to a local path.
    ///
    /// This method performs a full clone operation, downloading the entire repository
    /// history to the target directory. The operation is async and supports progress
    /// reporting for large repositories.
    ///
    /// # Arguments
    ///
    /// * `url` - The remote repository URL (HTTPS, SSH, or file://)
    /// * `target` - The local directory where the repository will be cloned
    /// * `progress` - Optional progress bar for user feedback
    ///
    /// # Authentication
    ///
    /// Authentication can be provided in several ways:
    /// - **HTTPS with tokens**: `https://token:value@github.com/user/repo.git`
    /// - **SSH keys**: Handled by system SSH agent and Git configuration
    /// - **Credential helpers**: System Git credential managers
    ///
    /// # Supported URL Formats
    ///
    /// - `https://github.com/user/repo.git` - HTTPS
    /// - `git@github.com:user/repo.git` - SSH
    /// - `file:///path/to/repo.git` - Local file system
    /// - `https://user:token@github.com/user/repo.git` - HTTPS with auth
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use agpm_cli::git::GitRepo;
    /// use std::env;
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// let temp_dir = env::temp_dir();
    ///
    /// // Clone public repository
    /// let repo = GitRepo::clone(
    ///     "https://github.com/rust-lang/git2-rs.git",
    ///     temp_dir.join("git2-rs")
    /// ).await?;
    ///
    /// // Clone another repository
    /// let repo = GitRepo::clone(
    ///     "https://github.com/example/repository.git",
    ///     temp_dir.join("example-repo")
    /// ).await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`AgpmError::GitCloneFailed`] if:
    /// - The URL is invalid or unreachable
    /// - Authentication fails
    /// - The target directory already exists and is not empty
    /// - Network connectivity issues
    /// - Insufficient disk space
    ///
    /// # Security
    ///
    /// URLs are validated and sanitized before passing to Git. Authentication
    /// tokens in URLs are never logged or exposed in error messages.
    ///
    /// [`AgpmError::GitCloneFailed`]: crate::core::AgpmError::GitCloneFailed
    pub async fn clone(url: &str, target: impl AsRef<Path>) -> Result<Self> {
        let target_path = target.as_ref();

        // Use command builder for consistent clone operations
        let mut cmd = GitCommand::clone(url, target_path);

        // For file:// URLs, clone with all branches to ensure commit availability
        if url.starts_with("file://") {
            cmd = GitCommand::new()
                .args(["clone", "--progress", "--no-single-branch", "--recurse-submodules", url])
                .arg(target_path.display().to_string());
        }

        // Execute will handle error context properly
        cmd.execute().await?;

        Ok(Self::new(target_path))
    }

    /// Fetches updates from the remote repository without modifying the working tree.
    ///
    /// This operation downloads new commits, branches, and tags from the remote
    /// repository but does not modify the current branch or working directory.
    /// It's equivalent to `git fetch --all --tags`.
    ///
    /// # Arguments
    ///
    /// * `auth_url` - Optional URL with authentication for private repositories
    /// * `progress` - Optional progress bar for network operation feedback
    ///
    /// # Authentication URL
    ///
    /// The `auth_url` parameter allows fetching from repositories that require
    /// different authentication than the original clone URL. This is useful when:
    /// - Using rotating tokens or credentials
    /// - Accessing private repositories through different auth methods
    /// - Working with multiple authentication contexts
    ///
    /// # Local Repository Optimization
    ///
    /// For local repositories (file:// URLs), fetch is automatically skipped
    /// as local repositories don't require network synchronization.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::git::GitRepo;
    /// use std::env;
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// let temp_dir = env::temp_dir();
    /// let repo_path = temp_dir.join("repo");
    /// let repo = GitRepo::new(&repo_path);
    ///
    /// // Basic fetch from configured remote
    /// repo.fetch(None).await?;
    ///
    /// // Fetch with authentication
    /// let auth_url = "https://token:ghp_xxxx@github.com/user/repo.git";
    /// repo.fetch(Some(auth_url)).await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`AgpmError::GitCommandError`] if:
    /// - Network connectivity fails
    /// - Authentication is rejected
    /// - The remote repository is unavailable
    /// - The local repository is in an invalid state
    ///
    /// # Performance
    ///
    /// Fetch operations are optimized to:
    /// - Skip unnecessary work for local repositories
    /// - Provide progress feedback for large transfers
    /// - Use efficient Git transfer protocols
    ///
    /// [`AgpmError::GitCommandError`]: crate::core::AgpmError::GitCommandError
    pub async fn fetch(&self, auth_url: Option<&str>) -> Result<()> {
        // Note: file:// URLs are local repositories, but we still need to fetch
        // from them to get updates from the source repository

        // Use git fetch with authentication from global config URL if provided
        if let Some(url) = auth_url {
            // Temporarily update the remote URL with auth for this fetch
            GitCommand::set_remote_url(url).current_dir(&self.path).execute_success().await?;
        }

        // Now fetch with the potentially updated URL
        GitCommand::fetch().current_dir(&self.path).execute_success().await?;

        Ok(())
    }

    /// Checks out a specific Git reference (branch, tag, or commit hash).
    ///
    /// This operation switches the repository's working directory to match the
    /// specified reference. It performs a hard reset before checkout to ensure
    /// a clean state, discarding any local modifications.
    ///
    /// # Arguments
    ///
    /// * `ref_name` - The Git reference to checkout (branch, tag, or commit)
    ///
    /// # Reference Resolution Strategy
    ///
    /// The method attempts to resolve references in the following order:
    /// 1. **Direct reference**: Exact match for tags, branches, or commit hashes
    /// 2. **Remote branch**: Tries `origin/{ref_name}` for remote branches
    /// 3. **Error**: If neither resolution succeeds, returns an error
    ///
    /// # Supported Reference Types
    ///
    /// - **Tags**: `v1.0.0`, `release-2023-01`, etc.
    /// - **Branches**: `main`, `develop`, `feature/new-ui`, etc.
    /// - **Commit hashes**: `abc123def`, `1234567890abcdef` (full or abbreviated)
    /// - **Remote branches**: Automatically tries `origin/{branch_name}`
    ///
    /// # State Management
    ///
    /// Before checkout, the method performs:
    /// 1. **Hard reset**: `git reset --hard HEAD` to discard local changes
    /// 2. **Clean checkout**: Switches to the target reference
    /// 3. **Detached HEAD**: For tags/commits (normal Git behavior)
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::git::GitRepo;
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// let repo = GitRepo::new("/path/to/repo");
    ///
    /// // Checkout a specific version tag
    /// repo.checkout("v1.2.3").await?;
    ///
    /// // Checkout a branch
    /// repo.checkout("main").await?;
    ///
    /// // Checkout a commit hash
    /// repo.checkout("abc123def456").await?;
    ///
    /// // Checkout remote branch
    /// repo.checkout("feature/experimental").await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Data Loss Warning
    ///
    /// **This operation discards uncommitted changes.** The hard reset before
    /// checkout ensures a clean state but will permanently lose any local
    /// modifications. This behavior is intentional for AGPM's package management
    /// use case where clean, reproducible states are required.
    ///
    /// # Errors
    ///
    /// Returns [`AgpmError::GitCheckoutFailed`] if:
    /// - The reference doesn't exist in the repository
    /// - The repository is in an invalid state
    /// - File system permissions prevent checkout
    /// - The working directory is locked by another process
    ///
    /// # Performance
    ///
    /// Checkout operations are optimized for:
    /// - Fast switching between cached references
    /// - Minimal file system operations
    /// - Efficient handling of large repositories
    ///
    /// [`AgpmError::GitCheckoutFailed`]: crate::core::AgpmError::GitCheckoutFailed
    pub async fn checkout(&self, ref_name: &str) -> Result<()> {
        // Reset to clean state before checkout
        let reset_result = GitCommand::reset_hard().current_dir(&self.path).execute().await;

        if let Err(e) = reset_result {
            // Only warn if it's not a detached HEAD situation (which is normal)
            let error_str = e.to_string();
            if !error_str.contains("HEAD detached") {
                eprintln!("Warning: git reset failed: {error_str}");
            }
        }

        // Check if this ref exists as a remote branch
        // If it does, always use -B to ensure we get the latest
        let remote_ref = format!("origin/{ref_name}");
        let check_remote =
            GitCommand::verify_ref(&remote_ref).current_dir(&self.path).execute().await;

        if check_remote.is_ok() {
            // Remote branch exists, use -B to force update to latest
            if GitCommand::checkout_branch(ref_name, &remote_ref)
                .current_dir(&self.path)
                .execute_success()
                .await
                .is_ok()
            {
                return Ok(());
            }
        }

        // Not a remote branch, try direct checkout (works for tags and commits)
        GitCommand::checkout(ref_name).current_dir(&self.path).execute_success().await.map_err(
            |e| {
                // If it's already a GitCheckoutFailed error, return as-is
                // Otherwise wrap it
                if let Some(agpm_err) = e.downcast_ref::<AgpmError>()
                    && matches!(agpm_err, AgpmError::GitCheckoutFailed { .. })
                {
                    return e;
                }
                AgpmError::GitCheckoutFailed {
                    reference: ref_name.to_string(),
                    reason: e.to_string(),
                }
                .into()
            },
        )
    }

    /// Lists all tags in the repository, sorted by Git's default ordering.
    ///
    /// This method retrieves all Git tags from the local repository using
    /// `git tag -l`. Tags are returned as strings in Git's natural ordering,
    /// which may not be semantic version order.
    ///
    /// # Return Value
    ///
    /// Returns a `Vec<String>` containing all tag names. Empty if no tags exist.
    /// Tags are returned exactly as they appear in Git (no prefix stripping).
    ///
    /// # Repository Validation
    ///
    /// The method validates that:
    /// - The repository path exists on the filesystem
    /// - The directory contains a `.git` subdirectory
    /// - The repository is in a valid state for Git operations
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::git::GitRepo;
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// let repo = GitRepo::new("/path/to/repo");
    ///
    /// // Get all available tags
    /// let tags = repo.list_tags().await?;
    /// for tag in tags {
    ///     println!("Available version: {}", tag);
    /// }
    ///
    /// // Check for specific tag
    /// let tags = repo.list_tags().await?;
    /// if tags.contains(&"v1.0.0".to_string()) {
    ///     repo.checkout("v1.0.0").await?;
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Version Parsing
    ///
    /// For semantic version ordering, consider using the `semver` crate:
    ///
    /// ```rust,no_run
    /// # use anyhow::Result;
    /// use semver::Version;
    /// use agpm_cli::git::GitRepo;
    ///
    /// # async fn version_example() -> Result<()> {
    /// let repo = GitRepo::new("/path/to/repo");
    /// let tags = repo.list_tags().await?;
    ///
    /// // Parse and sort semantic versions
    /// let mut versions: Vec<Version> = tags
    ///     .iter()
    ///     .filter_map(|tag| tag.strip_prefix('v'))
    ///     .filter_map(|v| Version::parse(v).ok())
    ///     .collect();
    /// versions.sort();
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`AgpmError::GitCommandError`] if:
    /// - The repository path doesn't exist
    /// - The directory is not a valid Git repository
    /// - Git command execution fails
    /// - File system permissions prevent access
    ///
    /// # Performance
    ///
    /// This operation is relatively fast as it only reads Git's tag database
    /// without network access. For repositories with thousands of tags,
    /// consider filtering or pagination if memory usage is a concern.
    ///
    /// [`AgpmError::GitCommandError`]: crate::core::AgpmError::GitCommandError
    pub async fn list_tags(&self) -> Result<Vec<String>> {
        // Check if the directory exists and is a git repo
        if !self.path.exists() {
            return Err(anyhow::anyhow!("Repository path does not exist: {:?}", self.path));
        }

        // Check if it's a git repository (either regular or bare)
        // Regular repos have .git directory, bare repos have HEAD file
        if !self.path.join(".git").exists() && !self.path.join("HEAD").exists() {
            return Err(anyhow::anyhow!("Not a git repository: {:?}", self.path));
        }

        let stdout = GitCommand::list_tags()
            .current_dir(&self.path)
            .execute_stdout()
            .await
            .context(format!("Failed to list git tags in {:?}", self.path))?;

        Ok(stdout
            .lines()
            .filter(|line| !line.is_empty())
            .map(std::string::ToString::to_string)
            .collect())
    }

    /// Retrieves the URL of the remote 'origin' repository.
    ///
    /// This method queries the Git repository for the URL associated with the
    /// 'origin' remote, which is typically the source repository from which
    /// the local repository was cloned.
    ///
    /// # Return Value
    ///
    /// Returns the origin URL as configured in the repository's Git configuration.
    /// The URL format depends on how the repository was cloned:
    /// - HTTPS: `https://github.com/user/repo.git`
    /// - SSH: `git@github.com:user/repo.git`
    /// - File: `file:///path/to/repo.git`
    ///
    /// # Authentication Handling
    ///
    /// The returned URL reflects the repository's configured origin, which may
    /// or may not include authentication information depending on the original
    /// clone method and Git configuration.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::git::GitRepo;
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// let repo = GitRepo::new("/path/to/repo");
    ///
    /// // Get the origin URL
    /// let url = repo.get_remote_url().await?;
    /// println!("Repository origin: {}", url);
    ///
    /// // Check if it's a specific platform
    /// if url.contains("github.com") {
    ///     println!("This is a GitHub repository");
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # URL Processing
    ///
    /// For processing the URL further, consider using [`parse_git_url`]:
    ///
    /// ```rust,no_run
    /// use agpm_cli::git::{GitRepo, parse_git_url};
    ///
    /// # async fn parse_example() -> anyhow::Result<()> {
    /// let repo = GitRepo::new("/path/to/repo");
    /// let url = repo.get_remote_url().await?;
    ///
    /// // Parse into owner and repository name
    /// let (owner, name) = parse_git_url(&url)?;
    /// println!("Owner: {}, Repository: {}", owner, name);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`AgpmError::GitCommandError`] if:
    /// - No 'origin' remote is configured
    /// - The repository is not a valid Git repository
    /// - Git command execution fails
    /// - File system access is denied
    ///
    /// # Security
    ///
    /// The returned URL may contain authentication information if it was
    /// configured that way. Be cautious when logging or displaying URLs
    /// that might contain sensitive tokens or credentials.
    ///
    /// [`parse_git_url`]: fn.parse_git_url.html
    /// [`AgpmError::GitCommandError`]: crate::core::AgpmError::GitCommandError
    pub async fn get_remote_url(&self) -> Result<String> {
        GitCommand::remote_url().current_dir(&self.path).execute_stdout().await
    }

    /// Checks if the directory contains a valid Git repository.\n    ///
    /// This method detects both regular and bare Git repositories:\n    /// - **Regular repositories**: Have a `.git` subdirectory\n    /// - **Bare repositories**: Have a `HEAD` file in the root\n    ///
    /// Bare repositories are commonly used for:\n    /// - Serving repositories (like GitHub/GitLab)\n    /// - Cache storage in package managers\n    /// - Worktree sources for parallel operations\n    ///
    /// # Return Value\n    ///
    /// - `true` if the directory is a valid Git repository (regular or bare)\n    /// - `false` if neither `.git` directory nor `HEAD` file exists\n    ///
    /// # Performance\n    ///
    /// This method is intentionally synchronous and lightweight for efficiency.\n    /// It performs at most two filesystem checks without spawning async tasks or\n    /// executing Git commands.\n    ///
    /// # Examples\n    ///
    /// ```rust,no_run
    /// use agpm_cli::git::GitRepo;
    ///
    /// // Regular repository
    /// let repo = GitRepo::new("/path/to/regular/repo");
    /// if repo.is_git_repo() {
    ///     println!("Valid Git repository detected");
    /// }
    ///
    /// // Bare repository
    /// let bare_repo = GitRepo::new("/path/to/repo.git");
    /// if bare_repo.is_git_repo() {
    ///     println!("Valid bare Git repository detected");
    /// }
    ///
    /// // Use before async operations
    /// # async fn async_example() -> anyhow::Result<()> {
    /// let repo = GitRepo::new("/path/to/repo");
    /// if repo.is_git_repo() {
    ///     let tags = repo.list_tags().await?;
    ///     // Process tags...
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Validation Scope
    ///
    /// This method only checks for the presence of Git repository markers. It does not:
    /// - Validate Git repository integrity
    /// - Check for repository corruption
    /// - Verify specific Git version compatibility
    /// - Test network connectivity to remotes
    ///
    /// For more thorough validation, use Git operations that will fail with\n    /// detailed error information if the repository is corrupted.
    ///
    /// # Alternative
    ///
    /// For error-based validation with detailed context, use [`ensure_valid_git_repo`]:
    ///
    /// ```rust,no_run
    /// use agpm_cli::git::ensure_valid_git_repo;
    /// use std::path::Path;
    ///
    /// # fn example() -> anyhow::Result<()> {
    /// let path = Path::new("/path/to/repo");
    /// ensure_valid_git_repo(path)?; // Returns detailed error if invalid
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`ensure_valid_git_repo`]: fn.ensure_valid_git_repo.html
    #[must_use]
    pub fn is_git_repo(&self) -> bool {
        is_git_repository(&self.path)
    }

    /// Returns the filesystem path to the Git repository.
    ///
    /// This method provides access to the repository's root directory path
    /// as configured when the `GitRepo` instance was created.
    ///
    /// # Return Value
    ///
    /// Returns a reference to the [`Path`] representing the repository's
    /// root directory (the directory containing the `.git` subdirectory).
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::git::GitRepo;
    /// use std::path::Path;
    ///
    /// let repo = GitRepo::new("/home/user/my-project");
    /// let path = repo.path();
    ///
    /// println!("Repository path: {}", path.display());
    /// assert_eq!(path, Path::new("/home/user/my-project"));
    ///
    /// // Use for file operations within the repository
    /// let readme_path = path.join("README.md");
    /// if readme_path.exists() {
    ///     println!("Repository has a README file");
    /// }
    /// ```
    ///
    /// # File System Operations
    ///
    /// The returned path can be used for various filesystem operations:
    ///
    /// ```rust,no_run
    /// use agpm_cli::git::GitRepo;
    ///
    /// # fn example() -> std::io::Result<()> {
    /// let repo = GitRepo::new("/path/to/repo");
    /// let repo_path = repo.path();
    ///
    /// // Check repository contents
    /// for entry in std::fs::read_dir(repo_path)? {
    ///     let entry = entry?;
    ///     println!("Found: {}", entry.file_name().to_string_lossy());
    /// }
    ///
    /// // Access specific files
    /// let manifest_path = repo_path.join("Cargo.toml");
    /// if manifest_path.exists() {
    ///     println!("Rust project detected");
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Path Validity
    ///
    /// The returned path reflects the value provided during construction and
    /// may not exist or may not be a valid Git repository. Use [`is_git_repo`]
    /// to validate the repository state.
    ///
    /// [`is_git_repo`]: #method.is_git_repo
    #[must_use]
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Verifies that a Git repository URL is accessible without performing a full clone.
    ///
    /// This static method performs a lightweight check to determine if a repository
    /// URL is valid and accessible. It uses `git ls-remote` for remote repositories
    /// or filesystem checks for local paths.
    ///
    /// # Arguments
    ///
    /// * `url` - The repository URL to verify
    ///
    /// # Verification Methods
    ///
    /// - **Local repositories** (`file://` URLs): Checks if the path exists
    /// - **Remote repositories**: Uses `git ls-remote --heads` to test connectivity
    /// - **Authentication**: Leverages system Git configuration and credential helpers
    ///
    /// # Supported URL Types
    ///
    /// - `https://github.com/user/repo.git` - HTTPS with optional authentication
    /// - `git@github.com:user/repo.git` - SSH with key-based authentication
    /// - `file:///path/to/repo` - Local filesystem repositories
    /// - `https://token:value@host.com/repo.git` - HTTPS with embedded credentials
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use agpm_cli::git::GitRepo;
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// // Verify public repository
    /// GitRepo::verify_url("https://github.com/rust-lang/git2-rs.git").await?;
    ///
    /// // Verify before cloning
    /// let url = "https://github.com/user/private-repo.git";
    /// match GitRepo::verify_url(url).await {
    ///     Ok(_) => {
    ///         let repo = GitRepo::clone(url, "/tmp/repo").await?;
    ///         println!("Repository cloned successfully");
    ///     }
    ///     Err(e) => {
    ///         eprintln!("Repository not accessible: {}", e);
    ///     }
    /// }
    ///
    /// // Verify local repository
    /// GitRepo::verify_url("file:///home/user/local-repo").await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Performance Benefits
    ///
    /// This method is much faster than attempting a full clone because it:
    /// - Only queries repository metadata (refs and heads)
    /// - Transfers minimal data over the network
    /// - Avoids creating local filesystem structures
    /// - Provides quick feedback on accessibility
    ///
    /// # Authentication Testing
    ///
    /// The verification process tests the complete authentication chain:
    /// - Credential helper invocation
    /// - SSH key validation (for SSH URLs)
    /// - Token validation (for HTTPS URLs)
    /// - Network connectivity and DNS resolution
    ///
    /// # Use Cases
    ///
    /// - **Pre-flight checks**: Validate URLs before expensive clone operations
    /// - **Dependency validation**: Ensure all repository sources are accessible
    /// - **Configuration testing**: Verify authentication setup
    /// - **Network diagnostics**: Test connectivity to repository hosts
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - **Network issues**: DNS resolution, connectivity, timeouts
    /// - **Authentication failures**: Invalid credentials, expired tokens
    /// - **Repository issues**: Repository doesn't exist, access denied
    /// - **Local path issues**: File doesn't exist (for `file://` URLs)
    /// - **URL format issues**: Malformed or unsupported URL schemes
    ///
    /// # Security
    ///
    /// This method respects the same security boundaries as Git operations:
    /// - Uses system Git configuration and security settings
    /// - Never bypasses authentication requirements
    /// - Doesn't cache or expose authentication credentials
    /// - Follows Git's SSL/TLS verification policies
    pub async fn verify_url(url: &str) -> Result<()> {
        // For file:// URLs, just check if the path exists
        if url.starts_with("file://") {
            let path = url.strip_prefix("file://").unwrap();
            return if std::path::Path::new(path).exists() {
                Ok(())
            } else {
                Err(anyhow::anyhow!("Local path does not exist: {path}"))
            };
        }

        // For all other URLs, use ls-remote to verify
        GitCommand::ls_remote(url)
            .execute_success()
            .await
            .context("Failed to verify remote repository")
    }

    /// Fetch updates for a bare repository with logging context.
    async fn ensure_bare_repo_has_refs_with_context(&self, context: Option<&str>) -> Result<()> {
        // Try to fetch to ensure we have refs
        let mut fetch_cmd = GitCommand::fetch().current_dir(&self.path);

        if let Some(ctx) = context {
            fetch_cmd = fetch_cmd.with_context(ctx);
        }

        let fetch_result = fetch_cmd.execute_success().await;

        if fetch_result.is_err() {
            // If fetch fails, it might be because there's no remote
            // Just check if we have any refs at all
            let mut check_cmd =
                GitCommand::new().args(["show-ref", "--head"]).current_dir(&self.path);

            if let Some(ctx) = context {
                check_cmd = check_cmd.with_context(ctx);
            }

            check_cmd
                .execute_success()
                .await
                .map_err(|e| anyhow::anyhow!("Bare repository has no refs available: {e}"))?;
        }

        Ok(())
    }

    /// Clone a repository as a bare repository (no working directory).
    ///
    /// Bare repositories are optimized for use as a source for worktrees,
    /// allowing multiple concurrent checkouts without conflicts.
    ///
    /// # Arguments
    ///
    /// * `url` - The remote repository URL
    /// * `target` - The local directory where the bare repository will be stored
    /// * `progress` - Optional progress bar for user feedback
    ///
    /// # Returns
    ///
    /// Returns a new `GitRepo` instance pointing to the bare repository
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use agpm_cli::git::GitRepo;
    /// use std::env;
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// let temp_dir = env::temp_dir();
    /// let bare_repo = GitRepo::clone_bare(
    ///     "https://github.com/example/repo.git",
    ///     temp_dir.join("repo.git")
    /// ).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn clone_bare(url: &str, target: impl AsRef<Path>) -> Result<Self> {
        Self::clone_bare_with_context(url, target, None).await
    }

    /// Clone a repository as a bare repository with logging context.
    ///
    /// Bare repositories are optimized for use as a source for worktrees,
    /// allowing multiple concurrent checkouts without conflicts.
    ///
    /// # Arguments
    ///
    /// * `url` - The remote repository URL
    /// * `target` - The local directory where the bare repository will be stored
    /// * `progress` - Optional progress bar for user feedback
    /// * `context` - Optional context for logging (e.g., dependency name)
    ///
    /// # Returns
    ///
    /// Returns a new `GitRepo` instance pointing to the bare repository
    pub async fn clone_bare_with_context(
        url: &str,
        target: impl AsRef<Path>,
        context: Option<&str>,
    ) -> Result<Self> {
        let target_path = target.as_ref();

        let mut cmd = GitCommand::clone_bare(url, target_path);

        if let Some(ctx) = context {
            cmd = cmd.with_context(ctx);
        }

        cmd.execute_success().await?;

        let repo = Self::new(target_path);

        // Configure the fetch refspec to ensure all branches are fetched as remote tracking branches
        // This is crucial for file:// URLs and ensures we can resolve origin/branch after fetching
        let _ = GitCommand::new()
            .args(["config", "remote.origin.fetch", "+refs/heads/*:refs/remotes/origin/*"])
            .current_dir(repo.path())
            .execute_success()
            .await;

        // Ensure the bare repo has refs available for worktree creation
        // Also needs context for the fetch operation
        repo.ensure_bare_repo_has_refs_with_context(context).await.ok();

        Ok(repo)
    }

    /// Create a new worktree from this repository.
    ///
    /// Worktrees allow multiple working directories to be checked out from
    /// a single repository, enabling parallel operations on different versions.
    ///
    /// # Arguments
    ///
    /// * `worktree_path` - The path where the worktree will be created
    /// * `reference` - Optional Git reference (branch/tag/commit) to checkout
    ///
    /// # Returns
    ///
    /// Returns a new `GitRepo` instance pointing to the worktree
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::git::GitRepo;
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// let bare_repo = GitRepo::new("/path/to/bare.git");
    ///
    /// // Create worktree with specific version
    /// let worktree = bare_repo.create_worktree(
    ///     "/tmp/worktree1",
    ///     Some("v1.0.0")
    /// ).await?;
    ///
    /// // Create worktree with default branch
    /// let worktree2 = bare_repo.create_worktree(
    ///     "/tmp/worktree2",
    ///     None
    /// ).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn create_worktree(
        &self,
        worktree_path: impl AsRef<Path>,
        reference: Option<&str>,
    ) -> Result<Self> {
        self.create_worktree_with_context(worktree_path, reference, None).await
    }

    /// Create a new worktree from this repository with logging context.
    ///
    /// Worktrees allow multiple working directories to be checked out from
    /// a single repository, enabling parallel operations on different versions.
    ///
    /// # Arguments
    ///
    /// * `worktree_path` - The path where the worktree will be created
    /// * `reference` - Optional Git reference (branch/tag/commit) to checkout
    /// * `context` - Optional context for logging (e.g., dependency name)
    ///
    /// # Returns
    ///
    /// Returns a new `GitRepo` instance pointing to the worktree
    pub async fn create_worktree_with_context(
        &self,
        worktree_path: impl AsRef<Path>,
        reference: Option<&str>,
        context: Option<&str>,
    ) -> Result<Self> {
        let worktree_path = worktree_path.as_ref();

        // Ensure parent directory exists
        if let Some(parent) = worktree_path.parent() {
            tokio::fs::create_dir_all(parent).await.with_context(|| {
                format!("Failed to create parent directory for worktree: {parent:?}")
            })?;
        }

        // Retry logic for worktree creation to handle concurrent operations
        let max_retries = 3;
        let mut retry_count = 0;

        loop {
            // For bare repositories, we may need to handle the case where no default branch exists yet
            // If no reference provided, try to use the default branch
            let default_branch = if reference.is_none() && retry_count == 0 {
                // Try to get the default branch
                GitCommand::new()
                    .args(["symbolic-ref", "refs/remotes/origin/HEAD"])
                    .current_dir(&self.path)
                    .execute_stdout()
                    .await
                    .ok()
                    .and_then(|s| s.strip_prefix("refs/remotes/origin/").map(String::from))
                    .or_else(|| Some("main".to_string()))
            } else {
                None
            };

            let effective_ref = if let Some(ref branch) = default_branch {
                Some(branch.as_str())
            } else {
                reference
            };

            let mut cmd =
                GitCommand::worktree_add(worktree_path, effective_ref).current_dir(&self.path);

            if let Some(ctx) = context {
                cmd = cmd.with_context(ctx);
            }

            let result = cmd.execute_success().await;

            match result {
                Ok(()) => {
                    // Initialize and update submodules in the new worktree
                    let worktree_repo = Self::new(worktree_path);

                    // Initialize submodules
                    let mut init_cmd =
                        GitCommand::new().args(["submodule", "init"]).current_dir(worktree_path);

                    if let Some(ctx) = context {
                        init_cmd = init_cmd.with_context(ctx);
                    }

                    // Ignore errors - if there are no submodules, this will fail
                    let _ = init_cmd.execute_success().await;

                    // Update submodules
                    let mut update_cmd = GitCommand::new()
                        .args(["submodule", "update", "--recursive"])
                        .current_dir(worktree_path);

                    if let Some(ctx) = context {
                        update_cmd = update_cmd.with_context(ctx);
                    }

                    // Ignore errors - if there are no submodules, this will fail
                    let _ = update_cmd.execute_success().await;

                    return Ok(worktree_repo);
                }
                Err(e) => {
                    let error_str = e.to_string();

                    // Check if this is a concurrent access issue
                    if error_str.contains("already exists")
                        || error_str.contains("is already checked out")
                        || error_str.contains("fatal: could not create directory")
                    {
                        retry_count += 1;
                        if retry_count >= max_retries {
                            return Err(e).with_context(|| {
                                format!(
                                    "Failed to create worktree at {} from {} after {} retries",
                                    worktree_path.display(),
                                    self.path.display(),
                                    max_retries
                                )
                            });
                        }

                        // Wait a bit before retrying
                        tokio::time::sleep(tokio::time::Duration::from_millis(100 * retry_count))
                            .await;
                        continue;
                    }

                    // Handle stale registration: "missing but already registered worktree"
                    if error_str.contains("missing but already registered worktree") {
                        // Prune stale admin entries, then retry (once) with --force
                        let _ = self.prune_worktrees().await;

                        // Retry with --force
                        let worktree_path_str = worktree_path.display().to_string();
                        let mut args = vec![
                            "worktree".to_string(),
                            "add".to_string(),
                            "--force".to_string(),
                            worktree_path_str,
                        ];
                        if let Some(r) = effective_ref {
                            args.push(r.to_string());
                        }

                        let mut force_cmd = GitCommand::new().args(args).current_dir(&self.path);
                        if let Some(ctx) = context {
                            force_cmd = force_cmd.with_context(ctx);
                        }

                        match force_cmd.execute_success().await {
                            Ok(()) => {
                                // Initialize and update submodules in the new worktree
                                let worktree_repo = Self::new(worktree_path);

                                let mut init_cmd = GitCommand::new()
                                    .args(["submodule", "init"])
                                    .current_dir(worktree_path);
                                if let Some(ctx) = context {
                                    init_cmd = init_cmd.with_context(ctx);
                                }
                                let _ = init_cmd.execute_success().await;

                                let mut update_cmd = GitCommand::new()
                                    .args(["submodule", "update", "--recursive"])
                                    .current_dir(worktree_path);
                                if let Some(ctx) = context {
                                    update_cmd = update_cmd.with_context(ctx);
                                }
                                let _ = update_cmd.execute_success().await;

                                return Ok(worktree_repo);
                            }
                            Err(e2) => {
                                // Fall through to other recovery paths with the original error context
                                // but include the forced attempt error as context
                                return Err(e).with_context(|| {
                                    format!(
                                        "Failed to create worktree at {} from {} (forced add failed: {})",
                                        worktree_path.display(),
                                        self.path.display(),
                                        e2
                                    )
                                });
                            }
                        }
                    }

                    // If no reference was provided and the command failed, it might be because
                    // the bare repo doesn't have a default branch set. Try with explicit HEAD
                    if reference.is_none() && retry_count == 0 {
                        let mut head_cmd = GitCommand::worktree_add(worktree_path, Some("HEAD"))
                            .current_dir(&self.path);

                        if let Some(ctx) = context {
                            head_cmd = head_cmd.with_context(ctx);
                        }

                        let head_result = head_cmd.execute_success().await;

                        match head_result {
                            Ok(()) => {
                                // Initialize and update submodules in the new worktree
                                let worktree_repo = Self::new(worktree_path);

                                // Initialize submodules
                                let mut init_cmd = GitCommand::new()
                                    .args(["submodule", "init"])
                                    .current_dir(worktree_path);

                                if let Some(ctx) = context {
                                    init_cmd = init_cmd.with_context(ctx);
                                }

                                // Ignore errors - if there are no submodules, this will fail
                                let _ = init_cmd.execute_success().await;

                                // Update submodules
                                let mut update_cmd = GitCommand::new()
                                    .args(["submodule", "update", "--recursive"])
                                    .current_dir(worktree_path);

                                if let Some(ctx) = context {
                                    update_cmd = update_cmd.with_context(ctx);
                                }

                                // Ignore errors - if there are no submodules, this will fail
                                let _ = update_cmd.execute_success().await;

                                return Ok(worktree_repo);
                            }
                            Err(head_err) => {
                                // If HEAD also fails, return the original error
                                return Err(e).with_context(|| {
                                    format!(
                                        "Failed to create worktree at {} from {} (also tried HEAD: {})",
                                        worktree_path.display(),
                                        self.path.display(),
                                        head_err
                                    )
                                });
                            }
                        }
                    }

                    // Check if the error is likely due to an invalid reference
                    let error_str = e.to_string();
                    if let Some(ref_name) = reference
                        && (error_str.contains("pathspec")
                            || error_str.contains("not found")
                            || error_str.contains("ambiguous")
                            || error_str.contains("invalid")
                            || error_str.contains("unknown revision"))
                    {
                        return Err(anyhow::anyhow!(
                            "Invalid version or reference '{ref_name}': Failed to checkout reference - the specified version/tag/branch does not exist in the repository"
                        ));
                    }

                    return Err(e).with_context(|| {
                        format!(
                            "Failed to create worktree at {} from {}",
                            worktree_path.display(),
                            self.path.display()
                        )
                    });
                }
            }
        }
    }

    /// Remove a worktree associated with this repository.
    ///
    /// This removes the worktree and its administrative files, but preserves
    /// the bare repository for future use.
    ///
    /// # Arguments
    ///
    /// * `worktree_path` - The path to the worktree to remove
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::git::GitRepo;
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// let bare_repo = GitRepo::new("/path/to/bare.git");
    /// bare_repo.remove_worktree("/tmp/worktree1").await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn remove_worktree(&self, worktree_path: impl AsRef<Path>) -> Result<()> {
        let worktree_path = worktree_path.as_ref();

        GitCommand::worktree_remove(worktree_path)
            .current_dir(&self.path)
            .execute_success()
            .await
            .with_context(|| format!("Failed to remove worktree at {}", worktree_path.display()))?;

        // Also try to remove the directory if it still exists
        if worktree_path.exists() {
            tokio::fs::remove_dir_all(worktree_path).await.ok(); // Ignore errors as git worktree remove may have already cleaned it
        }

        Ok(())
    }

    /// List all worktrees associated with this repository.
    ///
    /// Returns a list of paths to existing worktrees.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::git::GitRepo;
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// let bare_repo = GitRepo::new("/path/to/bare.git");
    /// let worktrees = bare_repo.list_worktrees().await?;
    /// for worktree in worktrees {
    ///     println!("Worktree: {}", worktree.display());
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn list_worktrees(&self) -> Result<Vec<PathBuf>> {
        let output = GitCommand::worktree_list().current_dir(&self.path).execute_stdout().await?;

        let mut worktrees = Vec::new();
        let mut current_worktree: Option<PathBuf> = None;

        for line in output.lines() {
            if line.starts_with("worktree ") {
                if let Some(path) = line.strip_prefix("worktree ") {
                    current_worktree = Some(PathBuf::from(path));
                }
            } else if line == "bare" {
                // Skip bare repository entry
                current_worktree = None;
            } else if line.is_empty()
                && current_worktree.is_some()
                && let Some(path) = current_worktree.take()
            {
                worktrees.push(path);
            }
        }

        // Add the last worktree if there is one
        if let Some(path) = current_worktree {
            worktrees.push(path);
        }

        Ok(worktrees)
    }

    /// Prune stale worktree administrative files.
    ///
    /// This cleans up worktree entries that no longer have a corresponding
    /// working directory on disk.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::git::GitRepo;
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// let bare_repo = GitRepo::new("/path/to/bare.git");
    /// bare_repo.prune_worktrees().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn prune_worktrees(&self) -> Result<()> {
        GitCommand::worktree_prune()
            .current_dir(&self.path)
            .execute_success()
            .await
            .with_context(|| "Failed to prune worktrees")?;

        Ok(())
    }

    /// Check if this repository is a bare repository.
    ///
    /// Bare repositories don't have a working directory and are optimized
    /// for use as a source for worktrees.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::git::GitRepo;
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// let repo = GitRepo::new("/path/to/repo.git");
    /// if repo.is_bare().await? {
    ///     println!("This is a bare repository");
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn is_bare(&self) -> Result<bool> {
        let output = GitCommand::new()
            .args(["config", "--get", "core.bare"])
            .current_dir(&self.path)
            .execute_stdout()
            .await?;

        Ok(output.trim() == "true")
    }

    /// Get the current commit SHA of the repository.
    ///
    /// Returns the full 40-character SHA-1 hash of the current HEAD commit.
    /// This is useful for recording exact versions in lockfiles.
    ///
    /// # Returns
    ///
    /// The full commit hash as a string.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The repository is not valid
    /// - HEAD is not pointing to a valid commit
    /// - Git command fails
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use agpm_cli::git::GitRepo;
    /// # async fn example() -> anyhow::Result<()> {
    /// let repo = GitRepo::new("/path/to/repo");
    /// let commit = repo.get_current_commit().await?;
    /// println!("Current commit: {}", commit);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_current_commit(&self) -> Result<String> {
        GitCommand::current_commit()
            .current_dir(&self.path)
            .execute_stdout()
            .await
            .context("Failed to get current commit")
    }

    /// Resolves a Git reference (tag, branch, commit) to its full SHA-1 hash.
    ///
    /// This method is central to AGPM's optimization strategy - by resolving all
    /// version specifications to SHAs upfront, we can:
    /// - Create worktrees keyed by SHA for maximum reuse
    /// - Avoid redundant checkouts for the same commit
    /// - Ensure deterministic, reproducible installations
    ///
    /// # Arguments
    ///
    /// * `ref_spec` - The Git reference to resolve (tag, branch, short/full SHA, or None for HEAD)
    ///
    /// # Returns
    ///
    /// Returns the full 40-character SHA-1 hash of the resolved reference.
    ///
    /// # Resolution Strategy
    ///
    /// 1. If `ref_spec` is None or "HEAD", resolves to current HEAD commit
    /// 2. If already a full SHA (40 hex chars), returns it unchanged
    /// 3. Otherwise uses `git rev-parse` to resolve:
    ///    - Tags (e.g., "v1.0.0")
    ///    - Branches (e.g., "main", "origin/main")
    ///    - Short SHAs (e.g., "abc123")
    ///    - Symbolic refs (e.g., "HEAD~1")
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use agpm_cli::git::GitRepo;
    /// # async fn example() -> anyhow::Result<()> {
    /// let repo = GitRepo::new("/path/to/repo");
    ///
    /// // Resolve a tag
    /// let sha = repo.resolve_to_sha(Some("v1.2.3")).await?;
    /// assert_eq!(sha.len(), 40);
    ///
    /// // Resolve HEAD
    /// let head_sha = repo.resolve_to_sha(None).await?;
    ///
    /// // Already a full SHA - returned as-is
    /// let full_sha = "a".repeat(40);
    /// let resolved = repo.resolve_to_sha(Some(&full_sha)).await?;
    /// assert_eq!(resolved, full_sha);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The reference doesn't exist in the repository
    /// - The repository is invalid or corrupted
    /// - Git command execution fails
    pub async fn resolve_to_sha(&self, ref_spec: Option<&str>) -> Result<String> {
        let reference = ref_spec.unwrap_or("HEAD");

        // Optimization: if it's already a full SHA, return it directly
        if reference.len() == 40 && reference.chars().all(|c| c.is_ascii_hexdigit()) {
            return Ok(reference.to_string());
        }

        // For branch names, try to resolve origin/branch first to get the latest from remote
        // This ensures we get the most recent commit after a fetch
        let ref_to_resolve = if !reference.contains('/') && reference != "HEAD" {
            // Looks like a branch name (not a tag or special ref)
            // Try origin/branch first
            let origin_ref = format!("origin/{reference}");
            if GitCommand::rev_parse(&origin_ref)
                .current_dir(&self.path)
                .execute_stdout()
                .await
                .is_ok()
            {
                origin_ref
            } else {
                // Fallback to the original reference (might be a tag or local branch)
                reference.to_string()
            }
        } else {
            reference.to_string()
        };

        // Use rev-parse to get the full SHA
        let sha = GitCommand::rev_parse(&ref_to_resolve)
            .current_dir(&self.path)
            .execute_stdout()
            .await
            .with_context(|| format!("Failed to resolve reference '{reference}' to SHA"))?;

        // Ensure we have a full SHA (sometimes rev-parse can return short SHAs)
        if sha.len() < 40 {
            // Request the full SHA explicitly
            let full_sha = GitCommand::new()
                .args(["rev-parse", "--verify", &format!("{reference}^{{commit}}")])
                .current_dir(&self.path)
                .execute_stdout()
                .await
                .with_context(|| format!("Failed to get full SHA for reference '{reference}'"))?;
            Ok(full_sha)
        } else {
            Ok(sha)
        }
    }

    pub async fn get_current_branch(&self) -> Result<String> {
        let branch = GitCommand::current_branch()
            .current_dir(&self.path)
            .execute_stdout()
            .await
            .context("Failed to get current branch")?;

        if branch.is_empty() {
            // Fallback for very old Git or repos without commits
            Ok("master".to_string())
        } else {
            Ok(branch)
        }
    }

    /// Gets the default branch name for the repository.
    ///
    /// For bare repositories, this queries `refs/remotes/origin/HEAD` to find
    /// the default branch. For non-bare repositories, it returns the current branch.
    ///
    /// # Returns
    ///
    /// The default branch name (e.g., "main", "master") without the "refs/heads/" prefix.
    ///
    /// # Errors
    ///
    /// Returns an error if Git commands fail or the default branch cannot be determined.
    pub async fn get_default_branch(&self) -> Result<String> {
        // Try to get the symbolic ref for origin/HEAD (works for bare repos)
        let result = GitCommand::new()
            .args(["symbolic-ref", "refs/remotes/origin/HEAD"])
            .current_dir(&self.path)
            .execute_stdout()
            .await;

        if let Ok(symbolic_ref) = result {
            // Parse "refs/remotes/origin/main" -> "main"
            if let Some(branch) = symbolic_ref.strip_prefix("refs/remotes/origin/") {
                return Ok(branch.to_string());
            }
        }

        // Fallback: try to get current branch (for non-bare repos)
        self.get_current_branch().await
    }
}

// Module-level helper functions for Git environment management and URL processing

/// Checks if Git is installed and accessible on the system.
///
/// This function verifies that the system's `git` command is available in the PATH
/// and responds to version queries. It's a prerequisite check for all Git operations
/// in AGPM.
///
/// # Return Value
///
/// - `true` if Git is installed and responding to `--version` commands
/// - `false` if Git is not found, not in PATH, or not executable
///
/// # Implementation Details
///
/// The function uses [`get_git_command()`] to determine the appropriate Git command
/// for the current platform, then executes `git --version` to verify functionality.
///
/// # Platform Differences
///
/// - **Windows**: Checks for `git.exe`, `git.cmd`, or `git.bat` in PATH
/// - **Unix-like**: Checks for `git` command in PATH
/// - **All platforms**: Respects PATH environment variable ordering
///
/// # Examples
///
/// ```rust,no_run
/// use agpm_cli::git::is_git_installed;
///
/// if is_git_installed() {
///     println!("Git is available - proceeding with repository operations");
/// } else {
///     eprintln!("Error: Git is not installed or not in PATH");
///     std::process::exit(1);
/// }
/// ```
///
/// # Usage in AGPM
///
/// This function is typically called during:
/// - Application startup to validate prerequisites
/// - Before any Git operations to provide clear error messages
/// - In CI/CD pipelines to verify build environment
///
/// # Alternative
///
/// For error-based validation with detailed context, use [`ensure_git_available()`]:
///
/// ```rust,no_run
/// use agpm_cli::git::ensure_git_available;
///
/// # fn example() -> anyhow::Result<()> {
/// ensure_git_available()?; // Throws AgpmError::GitNotFound if not available
/// # Ok(())
/// # }
/// ```
///
/// [`get_git_command()`]: crate::utils::platform::get_git_command
/// [`ensure_git_available()`]: fn.ensure_git_available.html
#[must_use]
pub fn is_git_installed() -> bool {
    // For synchronous checking, we still use std::process::Command directly
    std::process::Command::new(crate::utils::platform::get_git_command())
        .arg("--version")
        .output()
        .map(|output| output.status.success())
        .unwrap_or(false)
}

/// Ensures Git is available on the system or returns a detailed error.
///
/// This function validates that Git is installed and accessible, providing a
/// [`AgpmError::GitNotFound`] with actionable guidance if Git is unavailable.
/// It's the error-throwing equivalent of [`is_git_installed()`].
///
/// # Return Value
///
/// - `Ok(())` if Git is properly installed and accessible
/// - `Err(AgpmError::GitNotFound)` if Git is not available
///
/// # Error Context
///
/// The returned error includes:
/// - Clear description of the missing Git requirement
/// - Platform-specific installation instructions
/// - Troubleshooting guidance for common PATH issues
///
/// # Examples
///
/// ```rust,no_run
/// use agpm_cli::git::ensure_git_available;
///
/// # fn example() -> anyhow::Result<()> {
/// // Validate Git before starting operations
/// ensure_git_available()?;
///
/// // Git is guaranteed to be available beyond this point
/// println!("Git is available - proceeding with operations");
/// # Ok(())
/// # }
/// ```
///
/// # Error Handling
///
/// ```rust,no_run
/// use agpm_cli::git::ensure_git_available;
/// use agpm_cli::core::AgpmError;
///
/// match ensure_git_available() {
///     Ok(_) => println!("Git is ready"),
///     Err(e) => {
///         if let Some(AgpmError::GitNotFound) = e.downcast_ref::<AgpmError>() {
///             eprintln!("Please install Git to continue");
///             // Show platform-specific installation instructions
///         }
///     }
/// }
/// ```
///
/// # Usage Pattern
///
/// Typically called at the start of Git-dependent operations:
///
/// ```rust,no_run
/// use agpm_cli::git::{ensure_git_available, GitRepo};
/// use std::env;
///
/// # async fn git_operation() -> anyhow::Result<()> {
/// // Validate prerequisites first
/// ensure_git_available()?;
///
/// // Then proceed with Git operations
/// let temp_dir = env::temp_dir();
/// let repo = GitRepo::clone(
///     "https://github.com/example/repo.git",
///     temp_dir.join("repo")
/// ).await?;
/// # Ok(())
/// # }
/// ```
///
/// [`AgpmError::GitNotFound`]: crate::core::AgpmError::GitNotFound
/// [`is_git_installed()`]: fn.is_git_installed.html
pub fn ensure_git_available() -> Result<()> {
    if !is_git_installed() {
        return Err(AgpmError::GitNotFound.into());
    }
    Ok(())
}

/// Checks if a path contains a Git repository (regular or bare).
///
/// This function detects both types of Git repositories:
/// - **Regular repositories**: Contain a `.git` subdirectory
/// - **Bare repositories**: Contain a `HEAD` file in the root
///
/// # Arguments
///
/// * `path` - The path to check for a Git repository
///
/// # Returns
///
/// * `true` if the path is a valid Git repository (regular or bare)
/// * `false` if neither repository marker exists
///
/// # Examples
///
/// ```rust,no_run
/// use std::path::Path;
/// use agpm_cli::git::is_git_repository;
///
/// // Check a regular repository
/// let repo_path = Path::new("/path/to/repo");
/// if is_git_repository(repo_path) {
///     println!("Found Git repository");
/// }
///
/// // Check a bare repository
/// let bare_path = Path::new("/path/to/repo.git");
/// if is_git_repository(bare_path) {
///     println!("Found bare Git repository");
/// }
/// ```
///
/// # Performance
///
/// This is a lightweight synchronous check that performs at most two
/// filesystem operations to determine repository type.
#[must_use]
pub fn is_git_repository(path: &Path) -> bool {
    // Check for regular repository (.git directory) or bare repository (HEAD file)
    path.join(".git").exists() || path.join("HEAD").exists()
}

/// Checks if a directory contains a valid Git repository.
///
/// This function performs the same validation as [`GitRepo::is_git_repo()`] but
/// operates on an arbitrary path without requiring a `GitRepo` instance. It's
/// useful for validating paths before creating repository handles.
///
/// # Arguments
///
/// * `path` - The directory path to check for Git repository validity
///
/// # Return Value
///
/// - `true` if the path contains a `.git` subdirectory
/// - `false` if the `.git` subdirectory is missing or the path doesn't exist
///
/// # Examples
///
/// ```rust,no_run
/// use agpm_cli::git::is_valid_git_repo;
/// use std::path::Path;
///
/// let path = Path::new("/home/user/my-project");
///
/// if is_valid_git_repo(path) {
///     println!("Found Git repository at: {}", path.display());
/// } else {
///     println!("Not a Git repository: {}", path.display());
/// }
/// ```
///
/// # Use Cases
///
/// - **Path validation**: Check directories before creating `GitRepo` instances
/// - **Discovery**: Scan directories to find Git repositories
/// - **Conditional logic**: Branch behavior based on repository presence
/// - **Bulk operations**: Filter lists of paths to Git repositories only
///
/// # Batch Processing Example
///
/// ```rust,no_run
/// use agpm_cli::git::is_valid_git_repo;
/// use std::fs;
/// use std::path::Path;
///
/// # fn example() -> std::io::Result<()> {
/// let search_dir = Path::new("/home/user/projects");
///
/// // Find all Git repositories in a directory
/// for entry in fs::read_dir(search_dir)? {
///     let path = entry?.path();
///     if path.is_dir() && is_valid_git_repo(&path) {
///         println!("Found repository: {}", path.display());
///     }
/// }
/// # Ok(())
/// # }
/// ```
///
/// # Validation Scope
///
/// This function only verifies the presence of a `.git` directory and does not:
/// - Check repository integrity or corruption
/// - Validate Git version compatibility  
/// - Test network connectivity to remotes
/// - Verify specific repository content or structure
///
/// # Performance
///
/// This is a lightweight, synchronous operation that performs a single
/// filesystem check. It's suitable for bulk validation scenarios.
///
/// [`GitRepo::is_git_repo()`]: struct.GitRepo.html#method.is_git_repo
#[must_use]
pub fn is_valid_git_repo(path: &Path) -> bool {
    is_git_repository(path)
}

/// Ensures a directory contains a valid Git repository or returns a detailed error.
///
/// This function validates that the specified path contains a Git repository,
/// providing a [`AgpmError::GitRepoInvalid`] with actionable guidance if the
/// validation fails. It's the error-throwing equivalent of [`is_valid_git_repo()`].
///
/// # Arguments
///
/// * `path` - The directory path to validate as a Git repository
///
/// # Return Value
///
/// - `Ok(())` if the path contains a valid `.git` directory
/// - `Err(AgpmError::GitRepoInvalid)` if the path is not a Git repository
///
/// # Error Context
///
/// The returned error includes:
/// - The specific path that failed validation
/// - Clear description of what constitutes a valid Git repository
/// - Suggestions for initializing or cloning repositories
///
/// # Examples
///
/// ```rust,no_run
/// use agpm_cli::git::ensure_valid_git_repo;
/// use std::path::Path;
///
/// # fn example() -> anyhow::Result<()> {
/// let path = Path::new("/home/user/my-project");
///
/// // Validate before operations
/// ensure_valid_git_repo(path)?;
///
/// // Path is guaranteed to be a Git repository beyond this point
/// println!("Validated Git repository at: {}", path.display());
/// # Ok(())
/// # }
/// ```
///
/// # Error Handling Pattern
///
/// ```rust,no_run
/// use agpm_cli::git::ensure_valid_git_repo;
/// use agpm_cli::core::AgpmError;
/// use std::path::Path;
///
/// let path = Path::new("/some/directory");
///
/// match ensure_valid_git_repo(path) {
///     Ok(_) => println!("Valid repository found"),
///     Err(e) => {
///         if let Some(AgpmError::GitRepoInvalid { path }) = e.downcast_ref::<AgpmError>() {
///             eprintln!("Directory {} is not a Git repository", path);
///             eprintln!("Try: git clone <url> {} or git init {}", path, path);
///         }
///     }
/// }
/// ```
///
/// # Integration with `GitRepo`
///
/// This function provides validation before creating `GitRepo` instances:
///
/// ```rust,no_run
/// use agpm_cli::git::{ensure_valid_git_repo, GitRepo};
/// use std::path::Path;
///
/// # async fn validated_repo_operations() -> anyhow::Result<()> {
/// let path = Path::new("/path/to/repo");
///
/// // Validate first
/// ensure_valid_git_repo(path)?;
///
/// // Then create repository handle
/// let repo = GitRepo::new(path);
/// let tags = repo.list_tags().await?;
/// # Ok(())
/// # }
/// ```
///
/// # Use Cases
///
/// - **Precondition validation**: Ensure paths are Git repositories before operations
/// - **Error-first APIs**: Provide detailed errors rather than boolean returns
/// - **Pipeline validation**: Fail fast in processing pipelines
/// - **User feedback**: Give actionable error messages with suggestions
///
/// [`AgpmError::GitRepoInvalid`]: crate::core::AgpmError::GitRepoInvalid
/// [`is_valid_git_repo()`]: fn.is_valid_git_repo.html
pub fn ensure_valid_git_repo(path: &Path) -> Result<()> {
    if !is_valid_git_repo(path) {
        return Err(AgpmError::GitRepoInvalid {
            path: path.display().to_string(),
        }
        .into());
    }
    Ok(())
}

/// Parses a Git URL into owner and repository name components.
///
/// This function extracts the repository owner (user/organization) and repository
/// name from various Git URL formats. It handles the most common Git URL patterns
/// used across different hosting platforms and local repositories.
///
/// # Arguments
///
/// * `url` - The Git repository URL to parse
///
/// # Return Value
///
/// Returns a tuple `(owner, repository_name)` where:
/// - `owner` is the user, organization, or "local" for local repositories
/// - `repository_name` is the repository name (with `.git` suffix removed)
///
/// # Supported URL Formats
///
/// ## HTTPS URLs
/// - `https://github.com/rust-lang/cargo.git` → `("rust-lang", "cargo")`
/// - `https://gitlab.com/group/project.git` → `("group", "project")
/// - `https://bitbucket.org/user/repo.git` → `("user", "repo")
///
/// ## SSH URLs
/// - `git@github.com:rust-lang/cargo.git` → `("rust-lang", "cargo")`
/// - `git@gitlab.com:group/project.git` → `("group", "project")`
///
/// ## Local URLs
/// - `file:///path/to/repo.git` → `("local", "repo")`
/// - `/absolute/path/to/repo` → `("local", "repo")`
/// - `./relative/path/repo.git` → `("local", "repo")`
///
///
/// # Examples
///
/// ```rust,no_run
/// use agpm_cli::git::parse_git_url;
///
/// # fn example() -> anyhow::Result<()> {
/// // Parse GitHub URL
/// let (owner, repo) = parse_git_url("https://github.com/rust-lang/cargo.git")?;
/// assert_eq!(owner, "rust-lang");
/// assert_eq!(repo, "cargo");
///
/// // Parse SSH URL
/// let (owner, repo) = parse_git_url("git@github.com:user/project.git")?;
/// assert_eq!(owner, "user");
/// assert_eq!(repo, "project");
///
/// // Parse local repository
/// let (owner, repo) = parse_git_url("/home/user/my-repo")?;
/// assert_eq!(owner, "local");
/// assert_eq!(repo, "my-repo");
/// # Ok(())
/// # }
/// ```
///
/// # Use Cases
///
/// - **Cache directory naming**: Generate consistent cache paths
/// - **Repository identification**: Create unique identifiers for repositories
/// - **Metadata extraction**: Extract repository information for display
/// - **Path generation**: Create filesystem-safe directory names
///
/// # Cache Integration Example
///
/// ```rust,no_run
/// use agpm_cli::git::parse_git_url;
/// use std::path::PathBuf;
///
/// # fn cache_example() -> anyhow::Result<()> {
/// let url = "https://github.com/rust-lang/cargo.git";
/// let (owner, repo) = parse_git_url(url)?;
///
/// // Create cache directory path
/// let cache_path = PathBuf::from("/home/user/.agpm/cache")
///     .join(&owner)
///     .join(&repo);
///     
/// println!("Cache location: {}", cache_path.display());
/// // Output: Cache location: /home/user/.agpm/cache/rust-lang/cargo
/// # Ok(())
/// # }
/// ```
///
/// # Authentication Handling
///
/// The parser handles URLs with embedded authentication but extracts only
/// the repository components:
///
/// ```rust,no_run
/// use agpm_cli::git::parse_git_url;
///
/// # fn auth_example() -> anyhow::Result<()> {
/// // Authentication is ignored in parsing
/// let (owner, repo) = parse_git_url("https://token:value@github.com/user/repo.git")?;
/// assert_eq!(owner, "user");
/// assert_eq!(repo, "repo");
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Returns an error if:
/// - The URL format is not recognized
/// - The URL doesn't contain sufficient path components
/// - The URL structure doesn't match expected patterns
///
/// # Platform Considerations
///
/// The parser handles platform-specific path formats:
/// - Windows: Supports backslash separators in local paths
/// - Unix: Handles standard forward slash separators
/// - All platforms: Normalizes path separators internally
pub fn parse_git_url(url: &str) -> Result<(String, String)> {
    // Handle file:// URLs
    if url.starts_with("file://") {
        let path = url.trim_start_matches("file://");
        if let Some(last_slash) = path.rfind('/') {
            let repo_name = &path[last_slash + 1..];
            let repo_name = repo_name.trim_end_matches(".git");
            return Ok(("local".to_string(), repo_name.to_string()));
        }
    }

    // Handle plain local paths (absolute or relative)
    if url.starts_with('/') || url.starts_with("./") || url.starts_with("../") {
        if let Some(last_slash) = url.rfind('/') {
            let repo_name = &url[last_slash + 1..];
            let repo_name = repo_name.trim_end_matches(".git");
            return Ok(("local".to_string(), repo_name.to_string()));
        }
        let repo_name = url.trim_end_matches(".git");
        return Ok(("local".to_string(), repo_name.to_string()));
    }

    // Handle SSH URLs like git@github.com:user/repo.git
    if url.contains('@')
        && url.contains(':')
        && !url.starts_with("ssh://")
        && let Some(colon_pos) = url.find(':')
    {
        let path = &url[colon_pos + 1..];
        let path = path.trim_end_matches(".git");
        if let Some(slash_pos) = path.find('/') {
            return Ok((path[..slash_pos].to_string(), path[slash_pos + 1..].to_string()));
        }
    }

    // Handle HTTPS URLs
    if url.contains("github.com") || url.contains("gitlab.com") || url.contains("bitbucket.org") {
        let parts: Vec<&str> = url.split('/').collect();
        if parts.len() >= 2 {
            let repo = parts[parts.len() - 1].trim_end_matches(".git");
            let owner = parts[parts.len() - 2];
            return Ok((owner.to_string(), repo.to_string()));
        }
    }

    Err(anyhow::anyhow!("Could not parse repository owner and name from URL"))
}

/// Strips authentication information from a Git URL for safe display or logging.
///
/// This function removes sensitive authentication tokens, usernames, and passwords
/// from Git URLs while preserving the repository location information. It's essential
/// for security when logging or displaying URLs that might contain credentials.
///
/// # Arguments
///
/// * `url` - The Git URL that may contain authentication information
///
/// # Return Value
///
/// Returns the URL with authentication components removed:
/// - HTTPS URLs: Removes `user:token@` prefix
/// - SSH URLs: Returned unchanged (no embedded auth to strip)
/// - Other formats: Returned unchanged if no auth detected
///
/// # Security Purpose
///
/// This function prevents accidental credential exposure in:
/// - Log files and console output
/// - Error messages shown to users
/// - Debug information and stack traces
/// - Documentation and examples
///
/// # Supported Authentication Formats
///
/// ## HTTPS with Tokens
/// - `https://token@github.com/user/repo.git` → `https://github.com/user/repo.git`
/// - `https://user:pass@gitlab.com/repo.git` → `https://gitlab.com/repo.git`
/// - `https://oauth2:token@bitbucket.org/repo.git` → `https://bitbucket.org/repo.git`
///
/// ## Preserved Formats
/// - `git@github.com:user/repo.git` → `git@github.com:user/repo.git` (unchanged)
/// - `https://github.com/user/repo.git` → `https://github.com/user/repo.git` (no auth)
/// - `file:///path/to/repo` → `file:///path/to/repo` (unchanged)
///
/// # Examples
///
/// ```rust,no_run
/// use agpm_cli::git::strip_auth_from_url;
///
/// # fn example() -> anyhow::Result<()> {
/// // Strip token from HTTPS URL
/// let clean_url = strip_auth_from_url("https://ghp_token123@github.com/user/repo.git")?;
/// assert_eq!(clean_url, "https://github.com/user/repo.git");
///
/// // Strip user:password authentication
/// let clean_url = strip_auth_from_url("https://user:secret@gitlab.com/project.git")?;
/// assert_eq!(clean_url, "https://gitlab.com/project.git");
///
/// // URLs without auth are unchanged
/// let clean_url = strip_auth_from_url("https://github.com/public/repo.git")?;
/// assert_eq!(clean_url, "https://github.com/public/repo.git");
/// # Ok(())
/// # }
/// ```
///
/// # Safe Logging Pattern
///
/// ```rust,no_run
/// use agpm_cli::git::strip_auth_from_url;
/// use anyhow::Result;
///
/// fn log_repository_operation(url: &str, operation: &str) -> Result<()> {
///     let safe_url = strip_auth_from_url(url)?;
///     println!("Performing {} on repository: {}", operation, safe_url);
///     // Logs: "Performing clone on repository: https://github.com/user/repo.git"
///     // Instead of exposing: "https://token:secret@github.com/user/repo.git"
///     Ok(())
/// }
/// ```
///
/// # Error Context Integration
///
/// ```rust,no_run
/// use agpm_cli::git::strip_auth_from_url;
/// use agpm_cli::core::AgpmError;
///
/// # async fn operation_example(url: &str) -> anyhow::Result<()> {
/// match some_git_operation(url).await {
///     Ok(result) => Ok(result),
///     Err(e) => {
///         let safe_url = strip_auth_from_url(url)?;
///         eprintln!("Git operation failed for repository: {}", safe_url);
///         Err(e)
///     }
/// }
/// # }
/// # async fn some_git_operation(url: &str) -> anyhow::Result<()> { Ok(()) }
/// ```
///
/// # Implementation Details
///
/// The function uses careful parsing to distinguish between:
/// - Authentication `@` symbols (before the hostname)
/// - Email address `@` symbols in commit information (preserved)
/// - Path components that might contain `@` symbols (preserved)
///
/// # Edge Cases Handled
///
/// - URLs with multiple `@` symbols (only strips auth prefix)
/// - URLs with no authentication (returned unchanged)
/// - Malformed URLs (best-effort processing)
/// - Non-HTTP protocols (returned unchanged)
///
/// # Security Note
///
/// This function is for **display/logging safety only**. The original authenticated
/// URL should still be used for actual Git operations. Never use the stripped URL
/// for authentication-required operations.
pub fn strip_auth_from_url(url: &str) -> Result<String> {
    if url.starts_with("https://") || url.starts_with("http://") {
        // Find the @ symbol that marks the end of authentication
        if let Some(at_pos) = url.find('@') {
            let protocol_end = if url.starts_with("https://") {
                "https://".len()
            } else {
                "http://".len()
            };

            // Check if @ is part of auth (comes before first /)
            let first_slash = url[protocol_end..].find('/').map(|p| p + protocol_end);
            if first_slash.is_none() || at_pos < first_slash.unwrap() {
                // Extract protocol and the part after @
                let protocol = &url[..protocol_end];
                let after_auth = &url[at_pos + 1..];
                return Ok(format!("{protocol}{after_auth}"));
            }
        }
    }

    // Return URL as-is if no auth found or not HTTP(S)
    Ok(url.to_string())
}