wsb 0.253.6349

Workspace tools for every project under $PRJ: git across submodules, template stamping, GitHub, and the workbench
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
use crate::prelude::*;
use r2d2::PooledConnection;
use r2d2_sqlite::SqliteConnectionManager;
use regex::Regex;
use rusqlite::params;
use std::fs;

/// Resolve the path where wsb.db lives: the most senior git repo root.
/// Falls back to `repo_root` itself if no git hierarchy is found.
fn db_root_for(repo_root: &Path) -> PathBuf {
    crate::workspace::find_super_root_or_project(repo_root)
}

fn db_path_for(repo_root: &Path) -> PathBuf {
    db_root_for(repo_root).join(".wsb/wsb.db")
}

#[derive(Debug, Serialize, Deserialize)]
pub struct StateConfig {
    pub version: u32,
    pub enabled: bool,
    pub version_file: String,
    #[serde(default = "default_auto_detect")]
    pub auto_detect_project_files: bool,
    #[serde(default)]
    pub project_files: Vec<String>,
}

fn default_auto_detect() -> bool {
    true
}

impl Default for StateConfig {
    fn default() -> Self {
        Self {
            version: 1,
            enabled: true,
            version_file: "version.txt".to_string(),
            auto_detect_project_files: true,
            project_files: Vec::new(),
        }
    }
}

impl StateConfig {
    pub fn load(repo_root: &Path) -> Result<Self> {
        if tokio::runtime::Handle::try_current().is_ok() {
            anyhow::bail!("StateConfig::load cannot be called from an async runtime; use StateConfig::load_async");
        }
        let db_path = db_path_for(repo_root);
        let rt = tokio::runtime::Runtime::new()?;
        rt.block_on(async { load_state_config_from_db(&db_path, repo_root).await })
    }

    pub fn save(&self, repo_root: &Path) -> Result<()> {
        if tokio::runtime::Handle::try_current().is_ok() {
            anyhow::bail!("StateConfig::save cannot be called from an async runtime; use StateConfig::save_async");
        }
        let db_path = db_path_for(repo_root);
        let rt = tokio::runtime::Runtime::new()?;
        rt.block_on(async { save_state_config_to_db(&db_path, self).await })
    }

    pub async fn load_async(repo_root: &Path) -> Result<Self> {
        let db_path = db_path_for(repo_root);
        load_state_config_from_db(&db_path, repo_root).await
    }

    pub async fn save_async(&self, repo_root: &Path) -> Result<()> {
        let db_path = db_path_for(repo_root);
        save_state_config_to_db(&db_path, self).await
    }
}

pub fn calculate_workspace_version(repo_root: &Path) -> Result<VersionInfo> {
    calculate_workspace_version_cached(repo_root, &crate::state::RunCache::new())
}

/// The same, reusing the commit and tag counts a run has already taken.
///
/// A recursive update calculates a version per repository, and every one of
/// them counts the commits of every repository *under* it — so a 43-repository
/// fleet did roughly 130 history walks for 43 repositories' worth of history.
/// An update does not commit, so each of those counts is one answer per run.
pub fn calculate_workspace_version_cached(
    repo_root: &Path,
    cache: &crate::state::RunCache,
) -> Result<VersionInfo> {
    if tokio::runtime::Handle::try_current().is_ok() {
        anyhow::bail!(
            "calculate_workspace_version cannot be called from an async runtime; use calculate_workspace_version_async"
        );
    }
    let rt = tokio::runtime::Runtime::new()?;
    rt.block_on(calculate_workspace_version_async_cached(repo_root, cache))
}

pub async fn calculate_workspace_version_async(repo_root: &Path) -> Result<VersionInfo> {
    calculate_workspace_version_async_cached(repo_root, &crate::state::RunCache::new()).await
}

/// The same, reusing what a run has already counted.
pub async fn calculate_workspace_version_async_cached(
    repo_root: &Path,
    cache: &crate::state::RunCache,
) -> Result<VersionInfo> {
    let major_version = load_project_major_version_async(repo_root).await?;
    VersionInfo::calculate_with_major_in_repo_cached(major_version, repo_root, cache)
}

async fn load_project_major_version_async(repo_root: &Path) -> Result<u32> {
    let db_path = db_path_for(repo_root);
    if let Some(parent) = db_path.parent() {
        fs::create_dir_all(parent)?;
    }
    let service = open_initialized_state_db(&db_path).await?;

    let major_from_db = tokio::task::spawn_blocking({
        let service = service.clone();
        move || {
            let conn = service.get_connection()?;
            let result: Result<i64, rusqlite::Error> =
                conn.query_row("SELECT major_version FROM projects LIMIT 1", [], |row| {
                    row.get::<usize, i64>(0)
                });
            Ok::<Option<u32>, anyhow::Error>(result.ok().map(|v| v as u32))
        }
    })
    .await??;

    if let Some(major) = major_from_db {
        return Ok(major);
    }

    // No project row in DB — fall back to version.txt at project root.
    // If version.txt doesn't exist either, fail hard: we have no version source.
    read_major_version_from_file(repo_root).ok_or_else(|| {
        anyhow::anyhow!(
            "No project row in database and no version.txt found at {}. \
             Run 'wsb init' or 'wsb update' to initialize version tracking.",
            repo_root.display()
        )
    })
}

#[derive(Debug, Clone)]
pub struct VersionInfo {
    pub major_version: String,
    pub minor_version: u32,
    pub patch_version: u32,
    pub full_version: String,
}

#[derive(Debug, Clone)]
pub struct VersionCalculationInfo {
    pub major_version: u32,
    pub total_commits: u32,
    pub changes_since_release: u32,
    pub last_release_tag: Option<String>,
    pub git_root: Option<PathBuf>,
    pub calculation_method: String,
}

impl VersionInfo {
    /// The version of the project at `repo_root`: the declared major, the
    /// commits under it, and the file changes since its last release tag.
    pub fn calculate_with_major_in_repo(major: u32, repo_root: &Path) -> Result<Self> {
        Self::calculate_with_major_in_repo_cached(major, repo_root, &crate::state::RunCache::new())
    }

    pub fn calculate_with_major_in_repo_cached(
        major: u32,
        repo_root: &Path,
        cache: &crate::state::RunCache,
    ) -> Result<Self> {
        let (mut minor_version, mut patch_version) = version_counts(repo_root, major, cache)?;

        // Count every submodule at every depth, not just the superproject's direct
        // children, so a nested chain contributes its full history to the version.
        let tree = crate::fleet::git::SubmoduleTree::discover_allow_empty(repo_root)?;
        for node in tree.top_down() {
            // An uninitialized submodule has no history on disk to count. That is a
            // defined state, unlike a checked-out repository we fail to read.
            if !node.initialized {
                continue;
            }
            let (commits, changes) = version_counts(&node.abs_path, major, cache)?;
            minor_version += commits;
            patch_version += changes;
        }

        let full_version = format!("{}.{}.{}", major, minor_version, patch_version);
        let major_version = format!("v{}", major);

        Ok(Self {
            major_version,
            minor_version,
            patch_version,
            full_version,
        })
    }


    /// How the version of the project at `repo_root` was arrived at.
    pub fn get_calculation_info_in_repo(
        major: u32,
        repo_root: &Path,
    ) -> Result<VersionCalculationInfo> {
        let cache = crate::state::RunCache::new();
        let (total_commits, changes_since_release) = version_counts(repo_root, major, &cache)?;
        let last_release_tag = release_tags_in_repo(repo_root, major, &cache)?.first().cloned();
        let git_root = get_git_root_in_repo(repo_root).ok();

        Ok(VersionCalculationInfo {
            major_version: major,
            total_commits,
            changes_since_release,
            last_release_tag,
            git_root,
            calculation_method: "Database major + git commits + changes since release".to_string(),
        })
    }
}

pub fn validate_git_tag(tag: &str) -> Result<()> {
    if tag.is_empty() {
        anyhow::bail!("Tag cannot be empty");
    }
    if tag.chars().any(|c| c.is_whitespace()) {
        anyhow::bail!("Tag cannot contain whitespace: '{}'", tag);
    }
    let invalid_chars = ['~', '^', ':', '?', '*', '[', '\\'];
    for c in invalid_chars {
        if tag.contains(c) {
            anyhow::bail!("Tag contains invalid git ref character '{}': '{}'", c, tag);
        }
    }
    if tag.contains("..") {
        anyhow::bail!("Tag cannot contain '..': '{}'", tag);
    }
    if tag.contains("@{") {
        anyhow::bail!("Tag cannot contain '@{{}}': '{}'", tag);
    }
    if tag.contains("//") {
        anyhow::bail!("Tag cannot contain '//': '{}'", tag);
    }
    if tag.starts_with('.') || tag.starts_with('/') {
        anyhow::bail!("Tag cannot start with '.' or '/': '{}'", tag);
    }
    if tag.ends_with('.') || tag.ends_with('/') || tag.ends_with(".lock") {
        anyhow::bail!("Tag cannot end with '.', '/', or '.lock': '{}'", tag);
    }
    Ok(())
}

/// Write `version_info` into the project at `repo_root`, and stamp the
/// manifests that carry a version of their own.
///
/// `repo_root` is named rather than taken from the current directory, because
/// a recursive update visits every repository in the fleet without ever
/// changing directory: the current-directory version of this wrote all 34
/// submodule versions into the SUPERPROJECT's `version.txt`, one over the
/// next, and left every submodule's own file untouched — which quietly
/// defeated the whole reason the walk goes children-first.
pub fn update_version_file_in_repo(
    version_info: &VersionInfo,
    config: &StateConfig,
    repo_root: &Path,
) -> Result<bool> {
    if config.version_file.is_empty() {
        info!("No version file configured, skipping version file update");
        return Ok(false);
    }

    let version_file_path = if Path::new(&config.version_file).is_absolute() {
        PathBuf::from(&config.version_file)
    } else {
        repo_root.join(&config.version_file)
    };
    let current_version_content = if version_file_path.exists() {
        fs::read_to_string(&version_file_path)
            .unwrap_or_default()
            .trim()
            .to_string()
    } else {
        String::new()
    };

    if current_version_content == version_info.full_version {
        info!(
            "Version {} is already up to date",
            version_info.full_version
        );
        return Ok(false);
    }

    fs::write(
        &version_file_path,
        format!("{}\n", version_info.full_version),
    )
    .with_context(|| format!("Failed to write version to {}", version_file_path.display()))?;

    if config.auto_detect_project_files {
        match detect_project_files(repo_root) {
            Ok(project_files) => {
                if !project_files.is_empty() {
                    match update_project_files(version_info, &project_files) {
                        Ok(updated_files) => {
                            if !updated_files.is_empty() {
                                info!("Updated project files: {}", updated_files.join(", "));
                            }
                        }
                        Err(e) => {
                            warn!("Failed to update some project files: {}", e);
                            crate::errln!("Warning: Failed to update some project files: {}", e);
                        }
                    }
                }
            }
            Err(e) => {
                warn!("Failed to detect project files: {}", e);
                crate::errln!("Warning: Failed to detect project files: {}", e);
            }
        }
    }

    if !config.project_files.is_empty() {
        let manual_files: Vec<ProjectFile> = config
            .project_files
            .iter()
            .filter_map(|file_path| {
                let full_path = repo_root.join(file_path);
                if full_path.exists() {
                    detect_file_type(&full_path).map(|file_type| ProjectFile {
                        path: full_path,
                        file_type,
                    })
                } else {
                    crate::errln!("Warning: Configured project file not found: {}", file_path);
                    None
                }
            })
            .collect();

        if !manual_files.is_empty() {
            match update_project_files(version_info, &manual_files) {
                Ok(updated_files) => {
                    if !updated_files.is_empty() {
                        crate::outln!(
                            "Updated configured project files: {}",
                            updated_files.join(", ")
                        );
                    }
                }
                Err(e) => {
                    crate::errln!("Warning: Failed to update configured project files: {}", e);
                }
            }
        }
    }

    Ok(true)
}

fn detect_file_type(path: &Path) -> Option<ProjectFileType> {
    let filename = path.file_name()?.to_str()?;
    match filename {
        "Cargo.toml" => Some(ProjectFileType::CargoToml),
        "package.json" => Some(ProjectFileType::PackageJson),
        "pyproject.toml" => Some(ProjectFileType::PyprojectToml),
        "setup.py" => Some(ProjectFileType::SetupPy),
        "composer.json" => Some(ProjectFileType::ComposerJson),
        "pubspec.yaml" => Some(ProjectFileType::PubspecYaml),
        "pom.xml" => Some(ProjectFileType::PomXml),
        "build.gradle" => Some(ProjectFileType::BuildGradle),
        "build.gradle.kts" => Some(ProjectFileType::BuildGradleKts),
        "CMakeLists.txt" => Some(ProjectFileType::CMakeLists),
        "Package.swift" => Some(ProjectFileType::PackageSwift),
        "go.mod" => Some(ProjectFileType::GoMod),
        "mix.exs" => Some(ProjectFileType::MixExs),
        "build.sbt" => Some(ProjectFileType::BuildSbt),
        "shard.yml" => Some(ProjectFileType::ShardYml),
        "Project.toml" => Some(ProjectFileType::JuliaProject),
        _ => {
            if let Some(extension) = path.extension().and_then(|ext| ext.to_str()) {
                match extension {
                    "json" => Some(ProjectFileType::PackageJson),
                    "gemspec" => Some(ProjectFileType::Gemspec),
                    "csproj" => Some(ProjectFileType::Csproj),
                    _ => None,
                }
            } else {
                None
            }
        }
    }
}

/// Whether `repo_root` is a git repository.
///
/// There is no current-directory spelling of this. `wsb update --recursive`
/// runs 34 updates from one working directory, and a check that asked about
/// the directory the command was typed in answered for the superproject every
/// time.
pub fn is_git_repository_in(repo_root: &Path) -> bool {
    crate::git_backend::is_git_repository(repo_root)
}

/// The root of the repository containing `repo_root`.
pub fn get_git_root_in_repo(repo_root: &Path) -> Result<PathBuf> {
    crate::git_backend::repo_root(repo_root)
}

#[derive(Debug, Clone)]
pub struct ProjectFile {
    pub path: PathBuf,
    pub file_type: ProjectFileType,
}

#[derive(Debug, Clone, PartialEq)]
pub enum ProjectFileType {
    CargoToml,
    PackageJson,
    PyprojectToml,
    SetupPy,
    ComposerJson,
    PubspecYaml,
    PomXml,
    BuildGradle,
    BuildGradleKts,
    CMakeLists,
    PackageSwift,
    Gemspec,
    Csproj,
    GoMod,
    MixExs,
    BuildSbt,
    ShardYml,
    JuliaProject,
}

impl ProjectFileType {
    pub fn file_name(&self) -> &'static str {
        match self {
            ProjectFileType::CargoToml => "Cargo.toml",
            ProjectFileType::PackageJson => "package.json",
            ProjectFileType::PyprojectToml => "pyproject.toml",
            ProjectFileType::SetupPy => "setup.py",
            ProjectFileType::ComposerJson => "composer.json",
            ProjectFileType::PubspecYaml => "pubspec.yaml",
            ProjectFileType::PomXml => "pom.xml",
            ProjectFileType::BuildGradle => "build.gradle",
            ProjectFileType::BuildGradleKts => "build.gradle.kts",
            ProjectFileType::CMakeLists => "CMakeLists.txt",
            ProjectFileType::PackageSwift => "Package.swift",
            ProjectFileType::Gemspec => "*.gemspec",
            ProjectFileType::Csproj => "*.csproj",
            ProjectFileType::GoMod => "go.mod",
            ProjectFileType::MixExs => "mix.exs",
            ProjectFileType::BuildSbt => "build.sbt",
            ProjectFileType::ShardYml => "shard.yml",
            ProjectFileType::JuliaProject => "Project.toml",
        }
    }
}

pub fn detect_project_files(repo_root: &Path) -> Result<Vec<ProjectFile>> {
    let mut project_files = Vec::new();

    let exact_file_types = [
        ProjectFileType::CargoToml,
        ProjectFileType::PackageJson,
        ProjectFileType::PyprojectToml,
        ProjectFileType::SetupPy,
        ProjectFileType::ComposerJson,
        ProjectFileType::PubspecYaml,
        ProjectFileType::PomXml,
        ProjectFileType::BuildGradle,
        ProjectFileType::BuildGradleKts,
        ProjectFileType::CMakeLists,
        ProjectFileType::PackageSwift,
        ProjectFileType::GoMod,
        ProjectFileType::MixExs,
        ProjectFileType::BuildSbt,
        ProjectFileType::ShardYml,
        ProjectFileType::JuliaProject,
    ];

    for file_type in &exact_file_types {
        let file_path = repo_root.join(file_type.file_name());
        if file_path.exists() {
            project_files.push(ProjectFile {
                path: file_path,
                file_type: file_type.clone(),
            });
        }
    }

    if let Ok(entries) = std::fs::read_dir(repo_root) {
        for entry in entries.filter_map(|e| e.ok()) {
            let path = entry.path();
            if path.is_file() {
                if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
                    match ext {
                        "gemspec" => {
                            project_files.push(ProjectFile {
                                path,
                                file_type: ProjectFileType::Gemspec,
                            });
                        }
                        "csproj" => {
                            project_files.push(ProjectFile {
                                path,
                                file_type: ProjectFileType::Csproj,
                            });
                        }
                        _ => {}
                    }
                }
            }
        }
    }

    Ok(project_files)
}

pub fn update_project_files(
    version_info: &VersionInfo,
    project_files: &[ProjectFile],
) -> Result<Vec<String>> {
    let mut updated_files = Vec::new();

    for project_file in project_files {
        match update_project_file(version_info, project_file) {
            Ok(()) => {
                updated_files.push(project_file.path.display().to_string());
            }
            Err(e) => {
                crate::errln!(
                    "Warning: Failed to update {}: {}",
                    project_file.path.display(),
                    e
                );
            }
        }
    }

    Ok(updated_files)
}

pub fn update_project_file(version_info: &VersionInfo, project_file: &ProjectFile) -> Result<()> {
    let content = fs::read_to_string(&project_file.path)
        .with_context(|| format!("Failed to read {}", project_file.path.display()))?;

    let updated_content = match project_file.file_type {
        ProjectFileType::CargoToml => update_cargo_toml(&content, &version_info.full_version)?,
        ProjectFileType::PackageJson => update_package_json(&content, &version_info.full_version)?,
        ProjectFileType::PyprojectToml => {
            update_pyproject_toml(&content, &version_info.full_version)?
        }
        ProjectFileType::SetupPy => update_setup_py(&content, &version_info.full_version)?,
        ProjectFileType::ComposerJson => {
            update_composer_json(&content, &version_info.full_version)?
        }
        ProjectFileType::PubspecYaml => update_pubspec_yaml(&content, &version_info.full_version)?,
        ProjectFileType::PomXml => update_pom_xml(&content, &version_info.full_version)?,
        ProjectFileType::BuildGradle => update_build_gradle(&content, &version_info.full_version)?,
        ProjectFileType::BuildGradleKts => {
            update_build_gradle_kts(&content, &version_info.full_version)?
        }
        ProjectFileType::CMakeLists => update_cmake_lists(&content, &version_info.full_version)?,
        ProjectFileType::PackageSwift => {
            update_package_swift(&content, &version_info.full_version)?
        }
        ProjectFileType::Gemspec => update_gemspec(&content, &version_info.full_version)?,
        ProjectFileType::Csproj => update_csproj(&content, &version_info.full_version)?,
        ProjectFileType::GoMod => update_go_mod(&content, &version_info.full_version)?,
        ProjectFileType::MixExs => update_mix_exs(&content, &version_info.full_version)?,
        ProjectFileType::BuildSbt => update_build_sbt(&content, &version_info.full_version)?,
        ProjectFileType::ShardYml => update_shard_yml(&content, &version_info.full_version)?,
        ProjectFileType::JuliaProject => {
            update_julia_project(&content, &version_info.full_version)?
        }
    };

    fs::write(&project_file.path, updated_content)
        .with_context(|| format!("Failed to write updated {}", project_file.path.display()))?;

    Ok(())
}

fn update_cargo_toml(content: &str, version: &str) -> Result<String> {
    let mut parsed: toml::Value = content.parse().context("Failed to parse Cargo.toml")?;

    if let Some(package) = parsed.get_mut("package").and_then(|p| p.as_table_mut()) {
        package.insert(
            "version".to_string(),
            toml::Value::String(version.to_string()),
        );
    }

    Ok(toml::to_string(&parsed)?)
}

fn update_package_json(content: &str, version: &str) -> Result<String> {
    let mut parsed: serde_json::Value =
        serde_json::from_str(content).context("Failed to parse package.json")?;

    if let Some(obj) = parsed.as_object_mut() {
        obj.insert(
            "version".to_string(),
            serde_json::Value::String(version.to_string()),
        );
    }

    Ok(serde_json::to_string_pretty(&parsed)?)
}

fn update_pyproject_toml(content: &str, version: &str) -> Result<String> {
    let mut parsed: toml::Value = content.parse().context("Failed to parse pyproject.toml")?;

    if let Some(tool) = parsed.get_mut("tool") {
        if let Some(poetry) = tool.get_mut("poetry").and_then(|p| p.as_table_mut()) {
            poetry.insert(
                "version".to_string(),
                toml::Value::String(version.to_string()),
            );
        }
    }

    if let Some(project) = parsed.get_mut("project").and_then(|p| p.as_table_mut()) {
        project.insert(
            "version".to_string(),
            toml::Value::String(version.to_string()),
        );
    }

    Ok(toml::to_string(&parsed)?)
}

fn update_setup_py(content: &str, version: &str) -> Result<String> {
    let version_regex = Regex::new(r#"version\s*=\s*["'][^"']*["']"#)
        .context("Failed to create regex for setup.py")?;

    let updated = version_regex.replace_all(content, &format!(r#"version="{}""#, version));
    Ok(updated.to_string())
}

fn update_composer_json(content: &str, version: &str) -> Result<String> {
    let mut parsed: serde_json::Value =
        serde_json::from_str(content).context("Failed to parse composer.json")?;

    if let Some(obj) = parsed.as_object_mut() {
        obj.insert(
            "version".to_string(),
            serde_json::Value::String(version.to_string()),
        );
    }

    Ok(serde_json::to_string_pretty(&parsed)?)
}

fn update_pubspec_yaml(content: &str, version: &str) -> Result<String> {
    let version_regex =
        Regex::new(r"(?m)^version:\s*.*$").context("Failed to create regex for pubspec.yaml")?;

    let updated = version_regex.replace_all(content, &format!("version: {}", version));
    Ok(updated.to_string())
}

fn update_pom_xml(content: &str, version: &str) -> Result<String> {
    let version_regex =
        Regex::new(r"<version>[^<]*</version>").context("Failed to create regex for pom.xml")?;

    let updated = version_regex.replace(content, &format!("<version>{}</version>", version));
    Ok(updated.to_string())
}

fn update_build_gradle(content: &str, version: &str) -> Result<String> {
    let version_regex = Regex::new(r#"version\s*=\s*['"][^'"]*['"]"#)
        .context("Failed to create regex for build.gradle")?;

    let updated = version_regex.replace_all(content, &format!(r#"version = '{}'"#, version));
    Ok(updated.to_string())
}

fn update_cmake_lists(content: &str, version: &str) -> Result<String> {
    let version_regex = Regex::new(r"(?i)project\s*\([^)]*VERSION\s+[^\s)]+")
        .context("Failed to create regex for CMakeLists.txt")?;

    let updated = version_regex.replace_all(content, |caps: &regex::Captures| {
        let matched = caps.get(0).unwrap().as_str();
        let version_part_regex = Regex::new(r"VERSION\s+[^\s)]+").unwrap();
        version_part_regex
            .replace(matched, &format!("VERSION {}", version))
            .to_string()
    });

    Ok(updated.to_string())
}

fn update_build_gradle_kts(content: &str, version: &str) -> Result<String> {
    let version_regex = Regex::new(r#"version\s*=\s*"[^"]*""#)
        .context("Failed to create regex for build.gradle.kts")?;

    let updated = version_regex.replace_all(content, &format!(r#"version = "{}""#, version));
    Ok(updated.to_string())
}

fn update_package_swift(content: &str, version: &str) -> Result<String> {
    let version_regex = Regex::new(r#"//\s*version:\s*[^\n]*"#)
        .context("Failed to create regex for Package.swift version comment")?;

    let updated = if version_regex.is_match(content) {
        version_regex
            .replace_all(content, &format!("// version: {}", version))
            .to_string()
    } else {
        let pkg_version_regex = Regex::new(r#"version\s*:\s*"[^"]*""#)
            .context("Failed to create regex for Package.swift")?;
        if pkg_version_regex.is_match(content) {
            pkg_version_regex
                .replace_all(content, &format!(r#"version: "{}""#, version))
                .to_string()
        } else {
            format!("// version: {}\n{}", version, content)
        }
    };

    Ok(updated)
}

fn update_gemspec(content: &str, version: &str) -> Result<String> {
    let version_regex = Regex::new(r#"(\w+)\.version\s*=\s*["'][^"']*["']"#)
        .context("Failed to create regex for gemspec")?;

    let updated = version_regex.replace_all(content, |caps: &regex::Captures| {
        let var_name = caps.get(1).unwrap().as_str();
        format!(r#"{}.version = "{}""#, var_name, version)
    });

    Ok(updated.to_string())
}

fn update_csproj(content: &str, version: &str) -> Result<String> {
    let version_regex = Regex::new(r"<Version>[^<]*</Version>")
        .context("Failed to create regex for csproj Version")?;

    let updated = if version_regex.is_match(content) {
        version_regex
            .replace_all(content, &format!("<Version>{}</Version>", version))
            .to_string()
    } else {
        let pkg_version_regex = Regex::new(r"<PackageVersion>[^<]*</PackageVersion>")
            .context("Failed to create regex for csproj PackageVersion")?;
        if pkg_version_regex.is_match(content) {
            pkg_version_regex
                .replace_all(
                    content,
                    &format!("<PackageVersion>{}</PackageVersion>", version),
                )
                .to_string()
        } else {
            let asm_version_regex = Regex::new(r"<AssemblyVersion>[^<]*</AssemblyVersion>")
                .context("Failed to create regex for csproj AssemblyVersion")?;
            asm_version_regex
                .replace_all(
                    content,
                    &format!("<AssemblyVersion>{}</AssemblyVersion>", version),
                )
                .to_string()
        }
    };

    Ok(updated)
}

fn update_go_mod(content: &str, version: &str) -> Result<String> {
    let version_regex = Regex::new(r"//\s*version:\s*[^\n]*")
        .context("Failed to create regex for go.mod version comment")?;

    let updated = if version_regex.is_match(content) {
        version_regex
            .replace_all(content, &format!("// version: {}", version))
            .to_string()
    } else {
        let module_regex =
            Regex::new(r"(module\s+[^\n]+)").context("Failed to create regex for go.mod module")?;
        module_regex
            .replace(content, &format!("$1\n// version: {}", version))
            .to_string()
    };

    Ok(updated)
}

fn update_mix_exs(content: &str, version: &str) -> Result<String> {
    let version_regex =
        Regex::new(r#"version:\s*"[^"]*""#).context("Failed to create regex for mix.exs")?;

    let updated = version_regex.replace_all(content, &format!(r#"version: "{}""#, version));
    Ok(updated.to_string())
}

fn update_build_sbt(content: &str, version: &str) -> Result<String> {
    let version_regex =
        Regex::new(r#"version\s*:=\s*"[^"]*""#).context("Failed to create regex for build.sbt")?;

    let updated = version_regex.replace_all(content, &format!(r#"version := "{}""#, version));
    Ok(updated.to_string())
}

fn update_shard_yml(content: &str, version: &str) -> Result<String> {
    let version_regex =
        Regex::new(r"(?m)^version:\s*.*$").context("Failed to create regex for shard.yml")?;

    let updated = version_regex.replace_all(content, &format!("version: {}", version));
    Ok(updated.to_string())
}

fn update_julia_project(content: &str, version: &str) -> Result<String> {
    let mut parsed: toml::Value = content
        .parse()
        .context("Failed to parse Julia Project.toml")?;

    if let Some(table) = parsed.as_table_mut() {
        table.insert(
            "version".to_string(),
            toml::Value::String(version.to_string()),
        );
    }

    Ok(toml::to_string(&parsed)?)
}

async fn load_state_config_from_db(
    db_path: &std::path::Path,
    project_root: &Path,
) -> Result<StateConfig> {
    let service = open_initialized_state_db(db_path).await?;

    let major_from_file = read_major_version_from_file(project_root);

    tokio::task::spawn_blocking({
        let service = service.clone();
        move || {
            let conn = service.get_connection()?;

            let mut stmt = conn.prepare(
                r#"
                SELECT version_file, auto_detect_project_files, project_files 
                FROM projects 
                LIMIT 1
                "#,
            )?;

            let mut rows = stmt.query([])?;

            if let Some(row) = rows.next()? {
                let version_file: String = row.get(0)?;
                let auto_detect: i32 = row.get(1)?;
                let project_files_json: Option<String> = row.get(2)?;

                let project_files: Vec<String> = if let Some(json_str) = project_files_json {
                    serde_json::from_str(&json_str).unwrap_or_default()
                } else {
                    Vec::new()
                };

                Ok(StateConfig {
                    version: 1,
                    enabled: true,
                    version_file,
                    auto_detect_project_files: auto_detect != 0,
                    project_files,
                })
            } else {
                let initial_major = major_from_file.unwrap_or(0);
                let default_config = StateConfig::default();
                create_default_project_with_config_sync(&conn, &default_config, initial_major)?;
                Ok(default_config)
            }
        }
    })
    .await?
}

async fn save_state_config_to_db(db_path: &std::path::Path, config: &StateConfig) -> Result<()> {
    let service = open_initialized_state_db(db_path).await?;

    let project_files_json = serde_json::to_string(&config.project_files)?;
    let auto_detect = if config.auto_detect_project_files {
        1
    } else {
        0
    };
    let version_file = config.version_file.clone();

    tokio::task::spawn_blocking({
        let service = service.clone();
        move || {
            let conn = service.get_connection()?;

            conn.execute(
                r#"
                UPDATE projects 
                SET version_file = ?1, 
                    auto_detect_project_files = ?2, 
                    project_files = ?3,
                    updated_at = datetime('now')
                WHERE id = (SELECT id FROM projects LIMIT 1)
                "#,
                params![version_file, auto_detect, project_files_json],
            )?;

            Ok(())
        }
    })
    .await?
}

async fn open_initialized_state_db(
    db_path: &Path,
) -> Result<Arc<crate::persist::global::DatabaseService>> {
    if let Some(parent) = db_path.parent() {
        fs::create_dir_all(parent)?;
    }

    let config = crate::persist::global::DatabaseConfig::new(db_path);
    let service = crate::persist::global::DatabaseService::new(&config)
        .map_err(|e| anyhow::anyhow!("Failed to create entities service: {}", e))?;

    Ok(Arc::new(service))
}

fn create_default_project_with_config_sync(
    conn: &PooledConnection<SqliteConnectionManager>,
    config: &StateConfig,
    major_version: u32,
) -> Result<()> {
    let project_files_json = serde_json::to_string(&config.project_files)?;

    conn.execute(
        r#"
        INSERT INTO projects (
            id, code, name, description, status, major_version,
            version_file, auto_detect_project_files, project_files
        ) VALUES (
            'P001', 'P001', 'Default Project', 'Auto-created project', 'active', ?4,
            ?1, ?2, ?3
        )
        "#,
        params![
            &config.version_file,
            config.auto_detect_project_files as i32,
            project_files_json,
            major_version as i32
        ],
    )?;

    Ok(())
}

/// Read the major version from `version.txt` at the given project root.
/// Returns `None` if the file doesn't exist or can't be parsed.
pub fn read_major_version_from_file(project_root: &Path) -> Option<u32> {
    let version_path = project_root.join("version.txt");
    let content = fs::read_to_string(&version_path).ok()?;
    let first_segment = content.trim().split('.').next()?;
    first_segment.trim_start_matches('v').parse().ok()
}

/// The repository's part of a version: `(commits, changes since its last
/// release)`, for the commit that holds what its working tree holds
/// (`git_backend::version_counts`).
///
/// Whether that is HEAD or the commit about to be made is whether the tree
/// holds changes a commit would record. The files an update writes are not
/// among them: they are a function of the version, so counting them would make
/// the version depend on itself — and a tree rendered against the working
/// copies (`wsb local on`) is HEAD's tree with nothing of its own in it.
fn version_counts(
    repo_root: &Path,
    major: u32,
    cache: &crate::state::RunCache,
) -> Result<(u32, u32)> {
    let tags = release_tags_in_repo(repo_root, major, cache)?;
    cache.version_counts(repo_root, major, || {
        let repo = crate::git_backend::discover_repo(repo_root)?;
        // A commit being made in this repository is a change of its own,
        // whatever it holds: its version is the one it will have once the
        // commit lands. Judged by what the tree holds alone, a commit of
        // nothing but rendered outputs — a lock catching up — was given its
        // parent's version, and every checkpoint after committed the
        // difference.
        let pending = cache.is_being_committed(repo_root) || holds_changes_of_its_own(&repo, repo_root, cache)?;
        crate::git_backend::version_counts(&repo, &tags, pending)
    })
}

/// Whether the repository holds changes a commit would record beyond the files
/// an update writes.
fn holds_changes_of_its_own(
    repo: &gix::Repository,
    repo_root: &Path,
    cache: &crate::state::RunCache,
) -> Result<bool> {
    // Both sides canonical: a submodule's repository names its working tree
    // through `core.worktree`, relative to its git directory, so the working
    // tree's path and the project's are two spellings of one directory
    // unless both are resolved. The comparison is of places, not spellings.
    let workdir = repo
        .workdir()
        .ok_or_else(|| anyhow::anyhow!("{} has no working tree", repo_root.display()))?;
    let workdir = crate::platform::canonicalize(workdir)
        .with_context(|| format!("resolving the working tree of {}", repo_root.display()))?;
    let project_root = crate::platform::canonicalize(repo_root)
        .with_context(|| format!("resolving {}", repo_root.display()))?;
    let written = update_output_paths(&project_root, &workdir, cache)?;
    let entries = crate::git_backend::status_entries(repo)?;
    Ok(entries
        .iter()
        .filter(|entry| entry.status != crate::git_backend::FileStatusKind::Ignored)
        .any(|entry| !written.contains(&workdir.join(&entry.path))))
}

/// Every file an update writes in the repository at `repo_root`, by its
/// resolved path: what a render puts there and nothing else, so a change to
/// one of them is the render's to make again.
pub fn files_an_update_writes(repo_root: &Path) -> Result<std::collections::HashSet<PathBuf>> {
    let place = crate::platform::canonicalize(repo_root)
        .with_context(|| format!("resolving {}", repo_root.display()))?;
    update_output_paths(&place, &place, &crate::state::RunCache::new())
}

/// Every file an update writes in the repository whose working tree is `workdir`
/// (the project at `project_root`, whose version file it is): each
/// template's output, the lock the render keeps in step with a manifest, and
/// the version file. Their paths, which the templates fix; their contents are a
/// function of the version.
fn update_output_paths(
    project_root: &Path,
    workdir: &Path,
    cache: &crate::state::RunCache,
) -> Result<std::collections::HashSet<PathBuf>> {
    let mut written = std::collections::HashSet::new();
    let version_file = configured_version_file(project_root)?;
    if !version_file.is_empty() {
        written.insert(if Path::new(&version_file).is_absolute() {
            PathBuf::from(&version_file)
        } else {
            project_root.join(&version_file)
        });
    }
    let templates = cache.templates_under(workdir, || {
        crate::search_backend::discover_files_with_suffix(workdir, ".wstemplate")
    })?;
    for template in templates.iter() {
        let text = template.to_string_lossy();
        let output = PathBuf::from(&text[..text.len() - ".wstemplate".len()]);
        if let Some(lock) = crate::state::wstemplate::lockfile_followed_by(&output) {
            written.insert(lock);
        }
        written.insert(output);
    }
    Ok(written)
}

/// The version file the workspace of `project_root` is configured with, read
/// as `StateConfig::load` reads it — and readable where that is not, inside
/// the async runtime every update runs in: a version is computed there, and
/// what the version is must not depend on which side of a runtime asked.
///
/// A workspace whose database has no project yet has the default, as
/// `StateConfig::load` would create it.
fn configured_version_file(project_root: &Path) -> Result<String> {
    let db_path = db_path_for(project_root);
    if !db_path.exists() {
        return Ok(StateConfig::default().version_file);
    }
    let conn = rusqlite::Connection::open_with_flags(&db_path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)
        .with_context(|| format!("opening {} to read the version file", db_path.display()))?;
    let has_projects: bool = conn.query_row(
        "SELECT EXISTS (SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'projects')",
        [],
        |row| row.get(0),
    )?;
    if !has_projects {
        return Ok(StateConfig::default().version_file);
    }
    match conn.query_row("SELECT version_file FROM projects LIMIT 1", [], |row| row.get::<_, String>(0)) {
        Ok(version_file) => Ok(version_file),
        Err(rusqlite::Error::QueryReturnedNoRows) => Ok(StateConfig::default().version_file),
        Err(e) => Err(anyhow::anyhow!("reading the version file from {}: {e}", db_path.display())),
    }
}

/// The release tags of this major, newest first.
fn release_tags_in_repo(
    repo_root: &Path,
    major: u32,
    cache: &crate::state::RunCache,
) -> Result<Vec<String>> {
    // `discover_repo`, not `open_repo`: this keeps the original resolution,
    // which finds the repository containing `repo_root` rather than insisting
    // it is one.
    let tags = cache.discovered_tags(repo_root, || {
        let repo = crate::git_backend::discover_repo(repo_root)?;
        crate::git_backend::list_tags(&repo)
    })?;
    Ok(tags
        .iter()
        .filter(|tag| tag.starts_with(&format!("v{major}.")))
        .cloned()
        .collect())
}

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

    #[test]
    fn test_state_config_default() {
        let config = StateConfig::default();
        assert_eq!(config.version, 1);
        assert!(config.enabled);
        assert_eq!(config.version_file, "version.txt");
    }

    fn create_temp_state_config_file(dir: &Path, config: &StateConfig) -> Result<()> {
        let config_path = dir.join(".state.json");
        std::fs::write(&config_path, serde_json::to_string_pretty(config)?)?;
        Ok(())
    }

    fn load_state_config_file_only(dir: &Path) -> Result<StateConfig> {
        let config_path = dir.join(".state.json");
        let content = std::fs::read_to_string(&config_path)?;
        Ok(serde_json::from_str(&content)?)
    }

    #[test]
    fn test_state_config_save_load() {
        let temp_dir = TempDir::new().unwrap();
        let config = StateConfig::default();

        create_temp_state_config_file(temp_dir.path(), &config).unwrap();
        let loaded_config = load_state_config_file_only(temp_dir.path()).unwrap();

        assert_eq!(config.version, loaded_config.version);
        assert_eq!(config.enabled, loaded_config.enabled);
        assert_eq!(config.version_file, loaded_config.version_file);
    }

    #[test]
    fn test_version_info_format() {
        let version_info = VersionInfo {
            major_version: "v1.0".to_string(),
            minor_version: 5,
            patch_version: 100,
            full_version: "1.0.5.100".to_string(),
        };

        assert_eq!(version_info.full_version, "1.0.5.100");
    }

    /// TEST11180: a directory is a git repository, or it is not, and the
    /// answer is about the directory named.
    ///
    /// The predicate used to have a current-directory spelling as well, which
    /// `wsb update --recursive` called once per repository from one working
    /// directory — so it answered for the superproject 34 times running. There
    /// is no such spelling now, and the reason it must not come back is the
    /// second assertion here: two different paths, two different answers.
    #[test]
    fn test11180_git_repository_is_answered_about_the_path_named() {
        let temp = TempDir::new().unwrap();
        let repo = temp.path().join("repo");
        let plain = temp.path().join("plain");
        std::fs::create_dir_all(&repo).unwrap();
        std::fs::create_dir_all(&plain).unwrap();
        crate::git_backend::init_repository(&repo).unwrap();

        assert!(
            is_git_repository_in(&repo),
            "a directory that was just initialised is a repository"
        );
        assert!(
            !is_git_repository_in(&plain),
            "a plain directory beside it is not, and asking about one must not answer about \
             the other"
        );
    }

    #[test]
    fn test_project_file_type_file_name() {
        assert_eq!(ProjectFileType::CargoToml.file_name(), "Cargo.toml");
        assert_eq!(ProjectFileType::PackageJson.file_name(), "package.json");
        assert_eq!(ProjectFileType::PyprojectToml.file_name(), "pyproject.toml");
        assert_eq!(ProjectFileType::SetupPy.file_name(), "setup.py");
        assert_eq!(ProjectFileType::ComposerJson.file_name(), "composer.json");
        assert_eq!(ProjectFileType::PubspecYaml.file_name(), "pubspec.yaml");
        assert_eq!(ProjectFileType::PomXml.file_name(), "pom.xml");
        assert_eq!(ProjectFileType::BuildGradle.file_name(), "build.gradle");
        assert_eq!(
            ProjectFileType::BuildGradleKts.file_name(),
            "build.gradle.kts"
        );
        assert_eq!(ProjectFileType::CMakeLists.file_name(), "CMakeLists.txt");
        assert_eq!(ProjectFileType::PackageSwift.file_name(), "Package.swift");
        assert_eq!(ProjectFileType::Gemspec.file_name(), "*.gemspec");
        assert_eq!(ProjectFileType::Csproj.file_name(), "*.csproj");
        assert_eq!(ProjectFileType::GoMod.file_name(), "go.mod");
        assert_eq!(ProjectFileType::MixExs.file_name(), "mix.exs");
        assert_eq!(ProjectFileType::BuildSbt.file_name(), "build.sbt");
        assert_eq!(ProjectFileType::ShardYml.file_name(), "shard.yml");
        assert_eq!(ProjectFileType::JuliaProject.file_name(), "Project.toml");
    }

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

        let cargo_path = temp_dir.path().join("Cargo.toml");
        assert_eq!(
            detect_file_type(&cargo_path),
            Some(ProjectFileType::CargoToml)
        );

        let package_path = temp_dir.path().join("package.json");
        assert_eq!(
            detect_file_type(&package_path),
            Some(ProjectFileType::PackageJson)
        );

        let custom_json_path = temp_dir.path().join("custom.json");
        assert_eq!(
            detect_file_type(&custom_json_path),
            Some(ProjectFileType::PackageJson)
        );

        let unknown_path = temp_dir.path().join("unknown.txt");
        assert_eq!(detect_file_type(&unknown_path), None);
    }

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

        fs::write(
            temp_dir.path().join("Cargo.toml"),
            "[package]\nname = \"test\"\nversion = \"0.1.0\"",
        )
        .unwrap();
        fs::write(
            temp_dir.path().join("package.json"),
            "{\"Name\": \"test\", \"version\": \"1.0.0\"}",
        )
        .unwrap();

        let project_files = detect_project_files(temp_dir.path()).unwrap();
        assert_eq!(project_files.len(), 2);

        let file_types: Vec<_> = project_files.iter().map(|f| &f.file_type).collect();
        assert!(file_types.contains(&&ProjectFileType::CargoToml));
        assert!(file_types.contains(&&ProjectFileType::PackageJson));
    }

    #[test]
    fn test_update_cargo_toml() {
        let content = r#"[package]
name = "test-package"
version = "0.1.0"
edition = "2021"

[dependencies]
serde = "1.0"
"#;

        let updated = update_cargo_toml(content, "1.2.3").unwrap();
        assert!(updated.contains("version = \"1.2.3\""));
        assert!(updated.contains("name = \"test-package\""));
        assert!(updated.contains("serde = \"1.0\""));
    }

    #[test]
    fn test_update_package_json() {
        let content = r#"{
  "name": "test-package",
  "version": "1.0.0",
  "description": "A test package",
  "main": "index.js"
}"#;

        let updated = update_package_json(content, "2.1.0").unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&updated).unwrap();
        assert_eq!(parsed["version"], "2.1.0");
        assert_eq!(parsed["name"], "test-package");
    }

    #[test]
    fn test_update_pyproject_toml() {
        let content = r#"[tool.poetry]
name = "test-package"
version = "0.1.0"
description = "A test package"

[project]
name = "test-package"
version = "0.1.0"
"#;

        let updated = update_pyproject_toml(content, "1.5.2").unwrap();
        assert!(updated.contains("version = \"1.5.2\""));
        let version_count = updated.matches("version = \"1.5.2\"").count();
        assert_eq!(version_count, 2);
    }

    #[test]
    fn test_update_setup_py() {
        let content = r#"from setuptools import setup

setup(
    name="test-package",
    version="0.1.0",
    description="A test package",
    author="Test Author",
    packages=["test_package"],
)
"#;

        let updated = update_setup_py(content, "2.0.1").unwrap();
        assert!(updated.contains("version=\"2.0.1\""));
        assert!(updated.contains("name=\"test-package\""));
    }

    #[test]
    fn test_update_composer_json() {
        let content = r#"{
    "name": "vendor/package",
    "version": "1.0.0",
    "description": "A test package",
    "type": "library"
}"#;

        let updated = update_composer_json(content, "1.5.0").unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&updated).unwrap();
        assert_eq!(parsed["version"], "1.5.0");
        assert_eq!(parsed["name"], "vendor/package");
    }

    #[test]
    fn test_update_pubspec_yaml() {
        let content = r#"name: test_package
description: A test Flutter package
version: 1.0.0+1
environment:
  sdk: ">=2.12.0 <4.0.0"
"#;

        let updated = update_pubspec_yaml(content, "2.1.0+5").unwrap();
        assert!(updated.contains("version: 2.1.0+5"));
        assert!(updated.contains("name: test_package"));
    }

    #[test]
    fn test_update_pom_xml() {
        let content = r#"<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>test-project</artifactId>
    <version>1.0.0</version>
    <packaging>jar</packaging>
</project>
"#;

        let updated = update_pom_xml(content, "2.3.1").unwrap();
        assert!(updated.contains("<version>2.3.1</version>"));
        assert!(updated.contains("<artifactId>test-project</artifactId>"));
    }

    #[test]
    fn test_update_build_gradle() {
        let content = r#"plugins {
    id 'java'
}

group = 'com.example'
version = '1.0.0'
sourceCompatibility = '11'

repositories {
    mavenCentral()
}
"#;

        let updated = update_build_gradle(content, "3.2.1").unwrap();
        assert!(updated.contains("version = '3.2.1'"));
        assert!(updated.contains("group = 'com.example'"));
    }

    #[test]
    fn test_update_cmake_lists() {
        let content = r#"cmake_minimum_required(VERSION 3.16)

project(TestProject
    VERSION 1.0.0
    DESCRIPTION "A test project"
    LANGUAGES CXX
)

set(CMAKE_CXX_STANDARD 17)
"#;

        let updated = update_cmake_lists(content, "2.1.5").unwrap();
        assert!(updated.contains("VERSION 2.1.5"));
        assert!(updated.contains("project(TestProject"));
    }

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

        let config = StateConfig {
            version: 1,
            enabled: true,
            version_file: "version.txt".to_string(),
            auto_detect_project_files: true,
            project_files: vec!["custom.toml".to_string()],
        };

        create_temp_state_config_file(temp_dir.path(), &config).unwrap();
        let loaded_config = load_state_config_file_only(temp_dir.path()).unwrap();

        assert_eq!(loaded_config.auto_detect_project_files, true);
        assert_eq!(loaded_config.project_files, vec!["custom.toml"]);
    }

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

        let config_content = r#"{
  "version": 1,
  "enabled": true,
  "version_file": "version.txt"
}"#;
        std::fs::write(temp_dir.path().join(".state.json"), config_content).unwrap();

        let loaded_config = load_state_config_file_only(temp_dir.path()).unwrap();
        assert_eq!(loaded_config.auto_detect_project_files, true);
        assert!(loaded_config.project_files.is_empty());
    }

    /// TEST11181: a version is written into the project named, and nowhere
    /// else — not into the current directory.
    ///
    /// `wsb update --recursive` never changes directory. When this took the
    /// destination from the process's working directory, every submodule's
    /// version went into the SUPERPROJECT's `version.txt`, one over the next,
    /// and no submodule's own file was ever written — which defeated the
    /// children-first order, since a parent then read a version nobody had
    /// updated. The second assertion is the one that would have caught it.
    #[test]
    fn test11181_a_version_is_written_into_the_project_named() {
        let temp = TempDir::new().unwrap();
        let target = temp.path().join("target");
        let elsewhere = temp.path().join("elsewhere");
        std::fs::create_dir_all(&target).unwrap();
        std::fs::create_dir_all(&elsewhere).unwrap();
        std::fs::write(target.join("version.txt"), "1.0.0\n").unwrap();
        std::fs::write(elsewhere.join("version.txt"), "9.9.9\n").unwrap();

        let config = StateConfig::default();
        let version_info = VersionInfo {
            major_version: "v1".to_string(),
            minor_version: 5,
            patch_version: 100,
            full_version: "1.5.100".to_string(),
        };

        let wrote = update_version_file_in_repo(&version_info, &config, &target).unwrap();

        assert!(wrote, "the version changed, so it must have been written");
        assert_eq!(
            fs::read_to_string(target.join("version.txt")).unwrap().trim(),
            "1.5.100"
        );
        assert_eq!(
            fs::read_to_string(elsewhere.join("version.txt")).unwrap().trim(),
            "9.9.9",
            "no other project's version file may be touched"
        );
    }

    /// TEST11182: writing a version that is already recorded changes nothing
    /// and says so.
    #[test]
    fn test11182_an_unchanged_version_is_not_rewritten() {
        let temp = TempDir::new().unwrap();
        let project = temp.path().join("project");
        std::fs::create_dir_all(&project).unwrap();
        std::fs::write(project.join("version.txt"), "1.5.100\n").unwrap();

        let config = StateConfig::default();
        let version_info = VersionInfo {
            major_version: "v1".to_string(),
            minor_version: 5,
            patch_version: 100,
            full_version: "1.5.100".to_string(),
        };

        assert!(
            !update_version_file_in_repo(&version_info, &config, &project).unwrap(),
            "the recorded version already is this one, so nothing was written"
        );
        assert_eq!(
            fs::read_to_string(project.join("version.txt")).unwrap(),
            "1.5.100\n",
            "the file must be left exactly as it was, trailing newline included"
        );
    }


    fn run_git(repo_root: &Path, args: &[&str]) {
        let repo = match args {
            ["init"] => crate::git_backend::init_repository(repo_root).unwrap(),
            _ => crate::git_backend::open_repo(repo_root).unwrap(),
        };

        match args {
            ["init"] => {}
            ["config", "user.name", name] => {
                let email = repo
                    .config_snapshot()
                    .string("user.email")
                    .map(|value| value.to_string())
                    .unwrap_or_else(|| "test@example.com".to_string());
                crate::git_backend::configure_local_user(&repo, name, &email).unwrap();
            }
            ["config", "user.email", email] => {
                let name = repo
                    .config_snapshot()
                    .string("user.name")
                    .map(|value| value.to_string())
                    .unwrap_or_else(|| "Test User".to_string());
                crate::git_backend::configure_local_user(&repo, &name, email).unwrap();
            }
            ["add", path] => {
                crate::git_backend::stage_paths(&repo, &[path.to_string()]).unwrap();
            }
            ["commit", "-m", message] => {
                crate::git_backend::commit_all(&repo, message).unwrap();
            }
            ["tag", name] => {
                crate::git_backend::create_tag(&repo, name, name).unwrap();
            }
            _ => panic!("unsupported git test helper command: {args:?}"),
        }
    }

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

        run_git(repo_root, &["init"]);
        run_git(repo_root, &["config", "user.name", "Test User"]);
        run_git(repo_root, &["config", "user.email", "test@example.com"]);

        fs::write(repo_root.join("README.md"), "hello\n").unwrap();
        run_git(repo_root, &["add", "README.md"]);
        run_git(repo_root, &["commit", "-m", "initial"]);

        let _ = StateConfig::load_async(repo_root).await.unwrap();
        let db_path = db_path_for(repo_root);

        let config = crate::persist::global::DatabaseConfig::new(&db_path);
        let service = crate::persist::global::DatabaseService::new(&config).unwrap();

        tokio::task::spawn_blocking({
            let service = service.clone();
            move || {
                let conn = service.get_connection().unwrap();
                conn.execute(
                    "UPDATE projects SET major_version = 7 WHERE id = (SELECT id FROM projects LIMIT 1)",
                    [],
                )
                .unwrap();
            }
        })
        .await
        .unwrap();

        let expected = VersionInfo::calculate_with_major_in_repo(7, repo_root).unwrap();
        let actual = calculate_workspace_version_async(repo_root).await.unwrap();

        assert_eq!(actual.major_version, "v7");
        assert_eq!(actual.full_version, expected.full_version);
    }

    #[test]
    fn test_calculate_with_major_in_repo_uses_target_repo_history() {
        let outer = TempDir::new().unwrap();
        let outer_root = outer.path();
        run_git(outer_root, &["init"]);
        crate::workspace::exclude_state_dir(outer_root).unwrap();
        run_git(outer_root, &["config", "user.name", "Test User"]);
        run_git(outer_root, &["config", "user.email", "test@example.com"]);
        fs::write(outer_root.join("README.md"), "outer\n").unwrap();
        run_git(outer_root, &["add", "README.md"]);
        run_git(outer_root, &["commit", "-m", "outer initial"]);

        let inner = TempDir::new().unwrap();
        let inner_root = inner.path();
        run_git(inner_root, &["init"]);
        crate::workspace::exclude_state_dir(inner_root).unwrap();
        run_git(inner_root, &["config", "user.name", "Test User"]);
        run_git(inner_root, &["config", "user.email", "test@example.com"]);
        fs::write(inner_root.join("README.md"), "inner\n").unwrap();
        run_git(inner_root, &["add", "README.md"]);
        run_git(inner_root, &["commit", "-m", "inner initial"]);
        fs::write(inner_root.join("CHANGELOG.md"), "more\n").unwrap();
        run_git(inner_root, &["add", "CHANGELOG.md"]);
        run_git(inner_root, &["commit", "-m", "inner second"]);

        // Hold the process directory at `outer` for both calls. If the calculation
        // ever read the current directory instead of its argument, the second call
        // would report outer's numbers and this test would catch it.
        let original_dir = std::env::current_dir().unwrap();
        std::env::set_current_dir(outer_root).unwrap();

        let outer_info = VersionInfo::calculate_with_major_in_repo(1, outer_root);
        let inner_info = VersionInfo::calculate_with_major_in_repo(1, inner_root);

        std::env::set_current_dir(&original_dir).unwrap();

        let outer_info = outer_info.unwrap();
        let inner_info = inner_info.unwrap();

        // A clean tree has HEAD's version: minor counts the commits before HEAD,
        // patch the file changes before HEAD since the last release tag (with no
        // tag, all of them). Outer's one commit has nothing before it; inner's
        // second has the first, which added one file.
        assert_eq!((outer_info.minor_version, outer_info.patch_version), (0, 0));
        assert_eq!((inner_info.minor_version, inner_info.patch_version), (1, 1));
    }

    /// TEST12553: a version survives its own commit and its own tag, files an
    /// update writes do not move it, and a change after a release does.
    ///
    /// The version is written into the commit it names, so it is computed while
    /// that commit is being made. Counted from HEAD as it stands, the commit
    /// then counted itself and its tag zeroed its changes: lungo-rs at exactly
    /// its `v1.86.160` release called itself `1.87.0`, so every render moved
    /// every version, every checkpoint committed the move, and every ship found
    /// a release due with nothing in it.
    #[test]
    fn test12553_a_version_survives_its_own_commit_and_tag() {
        let dir = TempDir::new().unwrap();
        let root = dir.path();
        run_git(root, &["init"]);
        // As every repository wsb works in has it: its state is never a change.
        crate::workspace::exclude_state_dir(root).unwrap();
        run_git(root, &["config", "user.name", "Test User"]);
        run_git(root, &["config", "user.email", "test@example.com"]);
        fs::write(root.join("README.md"), "one\n").unwrap();
        run_git(root, &["add", "README.md"]);
        run_git(root, &["commit", "-m", "first"]);
        let version = |what: &str| {
            VersionInfo::calculate_with_major_in_repo(1, root)
                .unwrap_or_else(|e| panic!("{what}: {e}"))
                .full_version
        };

        // A change on its way to being committed, and the version it is given.
        fs::write(root.join("feature.txt"), "a\n").unwrap();
        let while_committing = version("while committing");
        run_git(root, &["add", "feature.txt"]);
        run_git(root, &["commit", "-m", "feature"]);
        assert_eq!(version("committed"), while_committing, "the commit moved its own version");

        // Released at that version: the tag names it, and does not move it.
        run_git(root, &["tag", &format!("v{while_committing}")]);
        assert_eq!(version("tagged"), while_committing, "the release tag moved the version it names");

        // What an update writes is a function of the version, not a change.
        fs::write(root.join("version.txt"), format!("{while_committing}\n")).unwrap();
        fs::write(root.join("Cargo.toml.wstemplate"), "[package]\n").unwrap();
        run_git(root, &["add", "Cargo.toml.wstemplate"]);
        run_git(root, &["commit", "-m", "template"]);
        let with_template = version("with a template");
        fs::write(root.join("Cargo.toml"), "[package]\nversion = \"local\"\n").unwrap();
        assert_eq!(version("rendered"), with_template, "a rendered manifest moved the version");

        // A real change after the release moves it.
        fs::write(root.join("feature.txt"), "b\n").unwrap();
        assert_ne!(version("changed"), with_template, "a change of the tree's own did not move the version");
    }

    /// TEST12563: a submodule's version survives the files an update writes
    /// in it, and moves with a change of its own.
    ///
    /// Every repository of the workspace but its root is a submodule, whose
    /// repository names its working tree through a relative `core.worktree`
    /// in `.git/modules`; TEST12553 holds a plain repository to the same.
    #[test]
    fn test12563_a_submodule_version_survives_its_render() {
        // Real git: a submodule is laid out by `git submodule add`, which the
        // gix-backed helper above does not speak.
        let git = |dir: &Path, args: &[&str]| {
            let output = crate::git_backend::git_command()
                .args(args)
                .current_dir(dir)
                .output()
                .expect("git runs");
            assert!(
                output.status.success(),
                "git {args:?} in {}: {}",
                dir.display(),
                String::from_utf8_lossy(&output.stderr)
            );
        };
        let dir = TempDir::new().unwrap();
        let root = crate::platform::canonicalize(&dir.path()).unwrap();
        let seed = root.join("seed");
        fs::create_dir_all(&seed).unwrap();
        git(&seed, &["init", "--quiet", "-b", "main"]);
        git(&seed, &["config", "user.name", "Test User"]);
        git(&seed, &["config", "user.email", "test@example.com"]);
        fs::write(seed.join("README.md"), "one\n").unwrap();
        fs::write(seed.join("version.txt"), "1.0.0\n").unwrap();
        git(&seed, &["add", "-A"]);
        git(&seed, &["commit", "--quiet", "-m", "first"]);

        let workspace = root.join("ws");
        fs::create_dir_all(&workspace).unwrap();
        git(&workspace, &["init", "--quiet", "-b", "main"]);
        crate::workspace::exclude_state_dir(&workspace).unwrap();
        git(&workspace, &["config", "user.name", "Test User"]);
        git(&workspace, &["config", "user.email", "test@example.com"]);
        git(
            &workspace,
            &["-c", "protocol.file.allow=always", "submodule", "add", "--quiet", &seed.display().to_string(), "sub"],
        );
        git(&workspace, &["commit", "--quiet", "-m", "add sub"]);
        let sub = workspace.join("sub");
        crate::workspace::exclude_state_dir(&sub).unwrap();
        assert!(sub.join(".git").is_file(), "the submodule is not laid out as the workspace's are");

        let version = || VersionInfo::calculate_with_major_in_repo(1, &sub).unwrap().full_version;
        let committed = version();
        fs::write(sub.join("version.txt"), "1.9.9\n").unwrap();
        assert_eq!(version(), committed, "a rendered version file moved a submodule's version");
        fs::write(sub.join("README.md"), "two\n").unwrap();
        assert_ne!(version(), committed, "a change of the submodule's own did not move its version");
    }

    /// TEST12571: a commit of nothing but rendered outputs is given the
    /// version it has once it lands.
    ///
    /// The hook renders for a commit; a tree holding only update outputs —
    /// floom-uikit's lock catching up to its manifest — was judged unchanged
    /// and given its parent's version, so the commit's own version file
    /// disagreed with the commit and the next checkpoint committed the
    /// difference, for ever.
    #[test]
    fn test12571_a_commit_of_outputs_alone_gets_the_version_it_will_have() {
        let dir = TempDir::new().unwrap();
        let root = dir.path();
        run_git(root, &["init"]);
        crate::workspace::exclude_state_dir(root).unwrap();
        run_git(root, &["config", "user.name", "Test User"]);
        run_git(root, &["config", "user.email", "test@example.com"]);
        fs::write(root.join("README.md"), "one\n").unwrap();
        run_git(root, &["add", "README.md"]);
        run_git(root, &["commit", "-m", "first"]);
        fs::write(root.join("version.txt"), "rendered before\n").unwrap();
        run_git(root, &["add", "version.txt"]);
        run_git(root, &["commit", "-m", "second"]);

        // The hook's render, for a commit holding only the version file.
        fs::write(root.join("version.txt"), "rendered now\n").unwrap();
        let committing = crate::state::RunCache::new();
        committing.commit_is_being_made_in(root);
        let given = VersionInfo::calculate_with_major_in_repo_cached(1, root, &committing).unwrap().full_version;
        run_git(root, &["add", "version.txt"]);
        run_git(root, &["commit", "-m", "the render"]);
        let landed = VersionInfo::calculate_with_major_in_repo(1, root).unwrap().full_version;
        assert_eq!(given, landed, "the commit was given another version than it has");
    }

    #[test]
    fn test_update_cmake_lists_preserves_project_name() {
        let content = r#"cmake_minimum_required(VERSION 3.16)
project(MyProject VERSION 1.0.0 LANGUAGES CXX)
"#;

        let updated = update_cmake_lists(content, "2.0.0").unwrap();

        assert!(updated.contains("project(MyProject"));
        assert!(updated.contains("VERSION 2.0.0"));
        assert!(updated.contains("LANGUAGES CXX"));
    }

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

        run_git(repo_root, &["init"]);
        run_git(repo_root, &["config", "user.name", "Test User"]);
        run_git(repo_root, &["config", "user.email", "test@example.com"]);

        fs::write(repo_root.join("README.md"), "initial\n").unwrap();
        run_git(repo_root, &["add", "README.md"]);
        run_git(repo_root, &["commit", "-m", "initial commit"]);
        run_git(repo_root, &["tag", "v1.0.0"]);

        fs::write(repo_root.join("README.md"), "update\n").unwrap();
        run_git(repo_root, &["add", "README.md"]);
        run_git(repo_root, &["commit", "-m", "new feature"]);

        let _ = StateConfig::load_async(repo_root).await.unwrap();
        let db_path = db_path_for(repo_root);

        let config = crate::persist::global::DatabaseConfig::new(&db_path);
        let service = crate::persist::global::DatabaseService::new(&config).unwrap();

        tokio::task::spawn_blocking({
            let service = service.clone();
            move || {
                let conn = service.get_connection().unwrap();
                conn.execute(
                    "UPDATE projects SET major_version = 1 WHERE id = (SELECT id FROM projects LIMIT 1)",
                    [],
                )
                .unwrap();
            }
        })
        .await
        .unwrap();

        let version = calculate_workspace_version_async(repo_root).await.unwrap();

        assert_eq!(version.major_version, "v1");
        assert_eq!(version.patch_version, 1);
    }

    #[test]
    fn test_read_major_version_from_file_extracts_major_segment() {
        let temp_dir = TempDir::new().unwrap();
        let project_root = temp_dir.path();

        // No version.txt → returns None
        assert_eq!(read_major_version_from_file(project_root), None);

        // version.txt with "5.3.1" → returns 5
        fs::write(project_root.join("version.txt"), "5.3.1").unwrap();
        assert_eq!(read_major_version_from_file(project_root), Some(5));

        // version.txt with "0.0.0" → returns 0
        fs::write(project_root.join("version.txt"), "0.0.0").unwrap();
        assert_eq!(read_major_version_from_file(project_root), Some(0));

        // version.txt with "12.1.99\n" → returns 12 (trims whitespace)
        fs::write(project_root.join("version.txt"), "12.1.99\n").unwrap();
        assert_eq!(read_major_version_from_file(project_root), Some(12));

        // version.txt with "v3.0.0" → returns 3 (strips leading 'v')
        fs::write(project_root.join("version.txt"), "v3.0.0").unwrap();
        assert_eq!(read_major_version_from_file(project_root), Some(3));

        // version.txt with garbage → returns None
        fs::write(project_root.join("version.txt"), "not-a-version").unwrap();
        assert_eq!(read_major_version_from_file(project_root), None);
    }
}