wsb 0.275.7622

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
use crate::prelude::*;
use regex::Regex;
use std::fs;

use wsb_prj::settings::{RepoSettings, VersionSettings};

/// The version of the repository wsb manages at `repo_root`: its committed
/// major, the commits under it, and the changes since its last release tag.
pub fn calculate_repo_version(repo_root: &Path) -> Result<VersionInfo> {
    calculate_repo_version_cached(repo_root, &crate::state::RunCache::new())
}

/// The version an update gives the repository wsb manages at `repo_root`:
/// its calculated version, carrying its suffix — or `override_suffix`, when
/// one is given and not empty.
pub fn stamped_version(
    repo_root: &Path,
    settings: &RepoSettings,
    cache: &crate::state::RunCache,
    override_suffix: Option<&str>,
) -> Result<VersionInfo> {
    let mut info = VersionInfo::calculate_with_major_in_repo_cached(settings.version.major, repo_root, cache)?;
    info.full_version =
        settings.full_version(&info.major_version, info.minor_version, info.patch_version, override_suffix);
    Ok(info)
}

/// 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_repo_version_cached(repo_root: &Path, cache: &crate::state::RunCache) -> Result<VersionInfo> {
    let settings = RepoSettings::require(repo_root)?;
    VersionInfo::calculate_with_major_in_repo_cached(settings.version.major, repo_root, cache)
}

#[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: "committed major (.wsb/repo.json) + 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: &VersionSettings,
    repo_root: &Path,
) -> Result<bool> {
    let version_file_path = repo_root.join(&config.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.detect_manifests {
        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.manifests.is_empty() {
        let manual_files: Vec<ProjectFile> = config
            .manifests
            .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()))?;
    // The lock that records the manifest's version moves with it, as it does
    // for a rendered manifest: a manifest bumped beside a lock naming the
    // previous version is a commit `cargo build --locked` refuses.
    crate::state::wstemplate::follow_into_lockfile(&project_file.path, &updated_content)?;

    Ok(())
}

// Every manifest is edited where its version is written, and nowhere else:
// its comments, the order of its tables and keys, and its layout are the
// project's, and a version bump that rewrites them is a commit of noise at
// best and a manifest that lost its notes at worst.

fn update_cargo_toml(content: &str, version: &str) -> Result<String> {
    let mut document: toml_edit::DocumentMut = content.parse().context("Failed to parse Cargo.toml")?;
    if let Some(package) = document.get_mut("package").and_then(|p| p.as_table_like_mut()) {
        set_toml_version(package, version);
    }
    Ok(document.to_string())
}

/// Write `version` into a manifest's table in place, keeping the decoration
/// around a version already there. A version the table inherits
/// (`version.workspace = true`) is set where it is inherited from, not here.
fn set_toml_version(table: &mut dyn toml_edit::TableLike, version: &str) {
    match table.get_mut("version") {
        Some(item) => {
            if let Some(held) = item.as_value_mut() {
                let decor = held.decor().clone();
                *held = version.into();
                *held.decor_mut() = decor;
            }
        }
        None => {
            table.insert("version", toml_edit::value(version));
        }
    }
}

fn update_package_json(content: &str, version: &str) -> Result<String> {
    crate::state::json_edit::set_top_level_string(content, "version", version).context("Failed to update package.json")
}

fn update_pyproject_toml(content: &str, version: &str) -> Result<String> {
    let mut document: toml_edit::DocumentMut = content.parse().context("Failed to parse pyproject.toml")?;
    if let Some(poetry) = document
        .get_mut("tool")
        .and_then(|tool| tool.get_mut("poetry"))
        .and_then(|poetry| poetry.as_table_like_mut())
    {
        set_toml_version(poetry, version);
    }
    if let Some(project) = document.get_mut("project").and_then(|p| p.as_table_like_mut()) {
        // A version the build backend computes is listed as dynamic, and a
        // project that also states one is refused by every backend.
        let dynamic = project
            .get("dynamic")
            .and_then(|d| d.as_array())
            .is_some_and(|names| names.iter().any(|name| name.as_str() == Some("version")));
        if !dynamic {
            set_toml_version(project, version);
        }
    }
    Ok(document.to_string())
}

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> {
    crate::state::json_edit::set_top_level_string(content, "version", version).context("Failed to update composer.json")
}

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 document: toml_edit::DocumentMut = content.parse().context("Failed to parse Julia Project.toml")?;
    set_toml_version(document.as_table_mut(), version);
    Ok(document.to_string())
}

/// 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();
    if let Some(version_file) = configured_version_file(project_root)? {
        written.insert(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 of the repository at `project_root`, when wsb manages
/// it. A submodule wsb does not manage is still counted in its parent's
/// version, and has no version file of its own for an update to write.
fn configured_version_file(project_root: &Path) -> Result<Option<String>> {
    Ok(RepoSettings::load(project_root)?.map(|settings| settings.version.file))
}

/// 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_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\""));
    }

    /// TEST20139: a version bump changes a manifest's version and nothing
    /// else — its comments, the order of its tables and keys, its
    /// indentation and its last newline stay as the project wrote them — and
    /// leaves a version that is inherited or computed where it is set.
    ///
    /// A bump that rewrote the whole manifest dropped its comments and moved
    /// `[package]` to the end of a Cargo.toml, in a commit the hook made.
    #[test]
    fn test20139_a_version_bump_changes_only_the_version() {
        let cargo = "# The crate.\n[dependencies]\nserde = { version = \"1\", features = [\"derive\"] }\n\n[package]\nname = \"x\"\nversion = \"0.1.0\" # bumped by wsb\nedition = \"2021\"\n";
        assert_eq!(update_cargo_toml(cargo, "1.2.3").unwrap(), cargo.replace("\"0.1.0\"", "\"1.2.3\""));
        let member = "[package]\nname = \"m\"\nversion.workspace = true\n";
        assert_eq!(update_cargo_toml(member, "1.2.3").unwrap(), member, "an inherited version was overwritten");
        assert_eq!(
            update_cargo_toml("[package]\nname = \"x\"\n", "1.2.3").unwrap(),
            "[package]\nname = \"x\"\nversion = \"1.2.3\"\n"
        );

        let package = "{\n    \"name\": \"p\",\n    \"dependencies\": { \"version\": \"9\" },\n    \"files\": [\"dist\", \"lib\"],\n    \"version\": \"0.1.0\",\n    \"x\": \"\\\"q\\\"\"\n}\n";
        assert_eq!(update_package_json(package, "2.0.0").unwrap(), package.replace("\"0.1.0\"", "\"2.0.0\""));
        assert_eq!(
            update_package_json("{\n  \"name\": \"p\"\n}\n", "2.0.0").unwrap(),
            "{\n  \"version\": \"2.0.0\",\n  \"name\": \"p\"\n}\n"
        );
        assert_eq!(update_package_json("{}", "2.0.0").unwrap(), "{\"version\": \"2.0.0\"}");
        assert!(update_package_json("{\"version\": 3}", "2.0.0").is_err(), "a version that is no string was replaced");
        let composer = "{\n\t\"name\": \"v/p\",\n\t\"version\": \"1.0.0\"\n}";
        assert_eq!(update_composer_json(composer, "1.5.0").unwrap(), composer.replace("1.0.0", "1.5.0"));

        let pyproject = "[project]\nname = \"p\"\ndynamic = [\"version\"]\n\n# Poetry's copy.\n[tool.poetry]\nversion = \"0.1.0\"\n";
        assert_eq!(update_pyproject_toml(pyproject, "1.5.2").unwrap(), pyproject.replace("0.1.0", "1.5.2"));
        let julia = "name = \"J\"\n# The version.\nversion = \"0.1.0\"\n\n[deps]\nA = \"1\"\n";
        assert_eq!(update_julia_project(julia, "0.2.0").unwrap(), julia.replace("0.1.0", "0.2.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"));
    }

    /// 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 = VersionSettings::at_major(1);
        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 = VersionSettings::at_major(1);
        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:?}"),
        }
    }

    /// Make the repository at `root` one wsb manages, at major 1: its
    /// `.wsb/repo.json`, written for the caller to commit with its first
    /// commit, as `wsb init` leaves it.
    fn manage(root: &Path) {
        RepoSettings {
            name: "demo".to_string(),
            alias: "demo".to_string(),
            templates_root: ".".to_string(),
            version: VersionSettings::at_major(1),
        }
        .save(root)
        .unwrap();
    }

    /// A repository's version is made at the major its `.wsb/repo.json`
    /// commits, and a repository with none is refused rather than given one.
    #[test]
    fn test_a_repos_version_is_made_at_its_committed_major() {
        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 refused = calculate_repo_version(repo_root).expect_err("an unmanaged repository has no major");
        assert!(refused.to_string().contains("wsb init"), "{refused}");

        RepoSettings {
            name: "demo".to_string(),
            alias: "demo".to_string(),
            templates_root: ".".to_string(),
            version: VersionSettings::at_major(7),
        }
        .save(repo_root)
        .unwrap();
        let expected = VersionInfo::calculate_with_major_in_repo(7, repo_root).unwrap();
        let actual = calculate_repo_version(repo_root).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"]);
        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"]);
        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"]);
        run_git(root, &["config", "user.name", "Test User"]);
        run_git(root, &["config", "user.email", "test@example.com"]);
        // Managed, so its version file is one an update writes.
        manage(root);
        fs::write(root.join("README.md"), "one\n").unwrap();
        run_git(root, &["add", "README.md"]);
        run_git(root, &["add", ".wsb/repo.json"]);
        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 worktree 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();
        // Managed, so its version file is one an update writes.
        manage(&seed);
        git(&seed, &["add", "-A"]);
        git(&seed, &["commit", "--quiet", "-m", "first"]);

        let worktree = root.join("ws");
        fs::create_dir_all(&worktree).unwrap();
        git(&worktree, &["init", "--quiet", "-b", "main"]);
        git(&worktree, &["config", "user.name", "Test User"]);
        git(&worktree, &["config", "user.email", "test@example.com"]);
        git(
            &worktree,
            &["-c", "protocol.file.allow=always", "submodule", "add", "--quiet", &seed.display().to_string(), "sub"],
        );
        git(&worktree, &["commit", "--quiet", "-m", "add sub"]);
        let sub = worktree.join("sub");
        assert!(sub.join(".git").is_file(), "the submodule is not laid out as the worktree'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"]);
        run_git(root, &["config", "user.name", "Test User"]);
        run_git(root, &["config", "user.email", "test@example.com"]);
        manage(root);
        fs::write(root.join("README.md"), "one\n").unwrap();
        run_git(root, &["add", "README.md"]);
        run_git(root, &["add", ".wsb/repo.json"]);
        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"));
    }

    #[test]
    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"]);

        manage(repo_root);
        fs::write(repo_root.join("README.md"), "initial\n").unwrap();
        run_git(repo_root, &["add", "README.md"]);
        run_git(repo_root, &["add", ".wsb/repo.json"]);
        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 version = calculate_repo_version(repo_root).unwrap();

        // A clean tree is at HEAD's version: one commit before it, and nothing
        // changed between the release tag and HEAD's parent, which it tags.
        assert_eq!(version.major_version, "v1");
        assert_eq!((version.minor_version, version.patch_version), (1, 0));

        // A change on its way to being committed gives the version that
        // commit will have: both commits before it, and every change up to
        // HEAD since the release — the one HEAD made.
        fs::write(repo_root.join("README.md"), "again\n").unwrap();
        let pending = calculate_repo_version(repo_root).unwrap();
        assert_eq!((pending.minor_version, pending.patch_version), (2, 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);
    }
}