sr-core 7.0.0

Pure domain logic for sr
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
use std::fs;
use std::path::{Path, PathBuf};

use regex::Regex;

use crate::error::ReleaseError;

/// Trait encapsulating detection, bumping, workspace discovery, and lock file
/// association for a single ecosystem (Cargo, npm, Python, etc.).
pub trait VersionFileHandler: Send + Sync {
    /// Human-readable name, e.g. "Cargo", "npm".
    fn name(&self) -> &str;

    /// Primary manifest filenames, e.g. `["Cargo.toml"]`.
    fn manifest_names(&self) -> &[&str];

    /// Associated lock file names, e.g. `["Cargo.lock"]`.
    fn lock_file_names(&self) -> &[&str];

    /// Does this ecosystem exist in `dir`? Default: any manifest file exists.
    fn detect(&self, dir: &Path) -> bool {
        self.manifest_names()
            .iter()
            .any(|name| dir.join(name).exists())
    }

    /// Bump version in the manifest at `path`. Returns additional files that
    /// were auto-discovered and bumped (e.g. workspace members).
    fn bump(&self, path: &Path, new_version: &str) -> Result<Vec<PathBuf>, ReleaseError>;
}

// ---------------------------------------------------------------------------
// Handler implementations
// ---------------------------------------------------------------------------

struct CargoHandler;

impl VersionFileHandler for CargoHandler {
    fn name(&self) -> &str {
        "Cargo"
    }
    fn manifest_names(&self) -> &[&str] {
        &["Cargo.toml"]
    }
    fn lock_file_names(&self) -> &[&str] {
        &["Cargo.lock"]
    }
    fn bump(&self, path: &Path, new_version: &str) -> Result<Vec<PathBuf>, ReleaseError> {
        bump_cargo_toml(path, new_version)
    }
}

struct NpmHandler;

impl VersionFileHandler for NpmHandler {
    fn name(&self) -> &str {
        "npm"
    }
    fn manifest_names(&self) -> &[&str] {
        &["package.json"]
    }
    fn lock_file_names(&self) -> &[&str] {
        &["package-lock.json", "yarn.lock", "pnpm-lock.yaml"]
    }
    fn bump(&self, path: &Path, new_version: &str) -> Result<Vec<PathBuf>, ReleaseError> {
        bump_package_json(path, new_version)
    }
}

struct PyprojectHandler;

impl VersionFileHandler for PyprojectHandler {
    fn name(&self) -> &str {
        "Python"
    }
    fn manifest_names(&self) -> &[&str] {
        &["pyproject.toml"]
    }
    fn lock_file_names(&self) -> &[&str] {
        &["uv.lock", "poetry.lock"]
    }
    fn bump(&self, path: &Path, new_version: &str) -> Result<Vec<PathBuf>, ReleaseError> {
        bump_pyproject_toml(path, new_version)
    }
}

struct MavenHandler;

impl VersionFileHandler for MavenHandler {
    fn name(&self) -> &str {
        "Maven"
    }
    fn manifest_names(&self) -> &[&str] {
        &["pom.xml"]
    }
    fn lock_file_names(&self) -> &[&str] {
        &[]
    }
    fn bump(&self, path: &Path, new_version: &str) -> Result<Vec<PathBuf>, ReleaseError> {
        bump_pom_xml(path, new_version).map(|()| vec![])
    }
}

struct GradleHandler;

impl VersionFileHandler for GradleHandler {
    fn name(&self) -> &str {
        "Gradle"
    }
    fn manifest_names(&self) -> &[&str] {
        &["build.gradle", "build.gradle.kts"]
    }
    fn lock_file_names(&self) -> &[&str] {
        &[]
    }
    fn bump(&self, path: &Path, new_version: &str) -> Result<Vec<PathBuf>, ReleaseError> {
        bump_gradle(path, new_version).map(|()| vec![])
    }
}

struct GoHandler;

impl VersionFileHandler for GoHandler {
    fn name(&self) -> &str {
        "Go"
    }
    fn manifest_names(&self) -> &[&str] {
        &[]
    }
    fn lock_file_names(&self) -> &[&str] {
        &[]
    }
    /// Custom detection: scan for `*.go` files containing a `Version` variable.
    fn detect(&self, dir: &Path) -> bool {
        let Ok(entries) = fs::read_dir(dir) else {
            return false;
        };
        for entry in entries.flatten() {
            let path = entry.path();
            if path.extension().is_some_and(|e| e == "go")
                && let Ok(contents) = fs::read_to_string(&path)
                && go_version_re().is_match(&contents)
            {
                return true;
            }
        }
        false
    }
    fn bump(&self, path: &Path, new_version: &str) -> Result<Vec<PathBuf>, ReleaseError> {
        bump_go_version(path, new_version).map(|()| vec![])
    }
}

// ---------------------------------------------------------------------------
// Registry & public API
// ---------------------------------------------------------------------------

/// Return all known version-file handlers.
pub fn all_handlers() -> Vec<Box<dyn VersionFileHandler>> {
    vec![
        Box::new(CargoHandler),
        Box::new(NpmHandler),
        Box::new(PyprojectHandler),
        Box::new(MavenHandler),
        Box::new(GradleHandler),
        Box::new(GoHandler),
    ]
}

/// Auto-detect version files in a directory. Returns relative paths (relative
/// to `dir`) for every manifest whose ecosystem is detected.
///
/// For the Go handler the detected `.go` file containing the Version variable
/// is returned (not a manifest name).
pub fn detect_version_files(dir: &Path) -> Vec<String> {
    let mut files = Vec::new();
    for handler in all_handlers() {
        if !handler.detect(dir) {
            continue;
        }
        if handler.manifest_names().is_empty() {
            // Go handler: find the actual .go file with a Version var
            if let Ok(entries) = fs::read_dir(dir) {
                let re = go_version_re();
                for entry in entries.flatten() {
                    let path = entry.path();
                    if path.extension().is_some_and(|e| e == "go")
                        && let Ok(contents) = fs::read_to_string(&path)
                        && re.is_match(&contents)
                    {
                        files.push(path.file_name().unwrap().to_string_lossy().into_owned());
                    }
                }
            }
        } else {
            for name in handler.manifest_names() {
                if dir.join(name).exists() {
                    files.push((*name).to_string());
                }
            }
        }
    }
    files
}

/// Look up the handler for a given filename.
fn handler_for_file(filename: &str) -> Option<Box<dyn VersionFileHandler>> {
    for handler in all_handlers() {
        if handler.manifest_names().contains(&filename) {
            return Some(handler);
        }
    }
    // Go files: any .go extension
    if filename.ends_with(".go") {
        return Some(Box::new(GoHandler));
    }
    None
}

/// Bump the `version` field in the given manifest file.
///
/// Returns a list of additional files that were auto-discovered and bumped
/// (e.g. workspace member manifests). The caller should stage these files.
///
/// The file format is auto-detected from the filename:
/// - `Cargo.toml`          → TOML (`package.version` or `workspace.package.version`)
/// - `package.json`        → JSON (`.version`)
/// - `pyproject.toml`      → TOML (`project.version` or `tool.poetry.version`)
/// - `build.gradle`        → Gradle Groovy DSL (`version = '...'` or `version = "..."`)
/// - `build.gradle.kts`    → Gradle Kotlin DSL (`version = "..."`)
/// - `pom.xml`             → Maven (`<version>...</version>`, skipping `<parent>` block)
/// - `*.go`                → Go (`var/const Version = "..."`)
///
/// For workspace roots (Cargo, npm, uv), member manifests are auto-discovered
/// and bumped without needing to list them in `version_files`.
pub fn bump_version_file(path: &Path, new_version: &str) -> Result<Vec<PathBuf>, ReleaseError> {
    let filename = path
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or_default();

    match handler_for_file(filename) {
        Some(handler) => handler.bump(path, new_version),
        None => Err(ReleaseError::VersionBump(format!(
            "unsupported version file: {filename}"
        ))),
    }
}

/// Given a list of bumped manifest paths, discover associated lock files that exist on disk.
/// Searches the manifest's directory and ancestors (for monorepo roots).
/// Returns deduplicated paths.
pub fn discover_lock_files(bumped_files: &[String]) -> Vec<PathBuf> {
    let handlers = all_handlers();
    let mut seen = std::collections::BTreeSet::new();
    for file in bumped_files {
        let path = Path::new(file);
        let filename = path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or_default();

        // Collect lock file names from all handlers that match this manifest
        let mut lock_names: Vec<&str> = Vec::new();
        for handler in &handlers {
            if handler.manifest_names().contains(&filename) {
                lock_names.extend(handler.lock_file_names());
            }
        }

        // Search the manifest's directory and ancestors
        let mut dir = path.parent();
        while let Some(d) = dir {
            for lock_name in &lock_names {
                let lock_path = d.join(lock_name);
                if lock_path.exists() {
                    seen.insert(lock_path);
                }
            }
            dir = d.parent();
            // Stop at repo root (don't traverse beyond .git)
            if d.join(".git").exists() {
                break;
            }
        }
    }
    seen.into_iter().collect()
}

/// Returns `true` if the given filename is a supported version file.
pub fn is_supported_version_file(filename: &str) -> bool {
    handler_for_file(filename).is_some()
}

/// Compile the Go Version variable regex (used in detection).
fn go_version_re() -> Regex {
    Regex::new(r#"(?:var|const)\s+Version\s*(?:string\s*)?=\s*""#).unwrap()
}

// ---------------------------------------------------------------------------
// Private bump implementations (unchanged)
// ---------------------------------------------------------------------------

fn bump_cargo_toml(path: &Path, new_version: &str) -> Result<Vec<PathBuf>, ReleaseError> {
    let contents = read_file(path)?;
    let mut doc: toml_edit::DocumentMut = contents.parse().map_err(|e| {
        ReleaseError::VersionBump(format!("failed to parse {}: {e}", path.display()))
    })?;

    let is_workspace = doc
        .get("workspace")
        .and_then(|w| w.get("package"))
        .and_then(|p| p.get("version"))
        .is_some();

    if doc.get("package").and_then(|p| p.get("version")).is_some() {
        doc["package"]["version"] = toml_edit::value(new_version);
    } else if is_workspace {
        doc["workspace"]["package"]["version"] = toml_edit::value(new_version);

        // Also update [workspace.dependencies] entries that are internal path deps
        if let Some(deps) = doc
            .get_mut("workspace")
            .and_then(|w| w.get_mut("dependencies"))
            .and_then(|d| d.as_table_like_mut())
        {
            for (_, dep) in deps.iter_mut() {
                if let Some(tbl) = dep.as_table_like_mut()
                    && tbl.get("path").is_some()
                    && tbl.get("version").is_some()
                {
                    tbl.insert("version", toml_edit::value(new_version));
                }
            }
        }
    } else {
        return Err(ReleaseError::VersionBump(format!(
            "no version field found in {}",
            path.display()
        )));
    }

    write_file(path, &doc.to_string())?;

    // Auto-discover and bump workspace member Cargo.toml files
    let mut extra = Vec::new();
    if is_workspace {
        let members = extract_toml_string_array(&doc, &["workspace", "members"]);
        let root_dir = path.parent().unwrap_or(Path::new("."));
        for member_path in resolve_member_globs(root_dir, &members, "Cargo.toml") {
            if member_path.as_path() == path {
                continue;
            }
            match bump_cargo_member(&member_path, new_version) {
                Ok(true) => extra.push(member_path),
                Ok(false) => {}
                Err(e) => eprintln!("warning: {e}"),
            }
        }
    }

    Ok(extra)
}

/// Bump `package.version` in a workspace member Cargo.toml (skip if using `version.workspace = true`).
/// Returns `true` if the file was actually modified.
fn bump_cargo_member(path: &Path, new_version: &str) -> Result<bool, ReleaseError> {
    let contents = read_file(path)?;
    let mut doc: toml_edit::DocumentMut = contents.parse().map_err(|e| {
        ReleaseError::VersionBump(format!("failed to parse {}: {e}", path.display()))
    })?;

    // Skip members that inherit version from workspace
    let version_item = doc.get("package").and_then(|p| p.get("version"));
    match version_item {
        Some(item) if item.is_value() => {
            doc["package"]["version"] = toml_edit::value(new_version);
            write_file(path, &doc.to_string())?;
            Ok(true)
        }
        _ => Ok(false), // No version or uses workspace inheritance — skip
    }
}

fn bump_package_json(path: &Path, new_version: &str) -> Result<Vec<PathBuf>, ReleaseError> {
    let contents = read_file(path)?;
    let mut value: serde_json::Value = serde_json::from_str(&contents).map_err(|e| {
        ReleaseError::VersionBump(format!("failed to parse {}: {e}", path.display()))
    })?;

    let obj = value
        .as_object_mut()
        .ok_or_else(|| ReleaseError::VersionBump("package.json is not an object".into()))?;

    // Extract workspace patterns before mutating
    let workspace_patterns: Vec<String> = obj
        .get("workspaces")
        .and_then(|w| w.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(String::from))
                .collect()
        })
        .unwrap_or_default();

    obj.insert(
        "version".into(),
        serde_json::Value::String(new_version.into()),
    );

    let output = serde_json::to_string_pretty(&value).map_err(|e| {
        ReleaseError::VersionBump(format!("failed to serialize {}: {e}", path.display()))
    })?;

    write_file(path, &format!("{output}\n"))?;

    // Auto-discover and bump workspace member package.json files
    let mut extra = Vec::new();
    if !workspace_patterns.is_empty() {
        let root_dir = path.parent().unwrap_or(Path::new("."));
        for member_path in resolve_member_globs(root_dir, &workspace_patterns, "package.json") {
            if member_path == path {
                continue;
            }
            match bump_json_version(&member_path, new_version) {
                Ok(true) => extra.push(member_path),
                Ok(false) => {}
                Err(e) => eprintln!("warning: {e}"),
            }
        }
    }

    Ok(extra)
}

/// Bump `version` in a member package.json (skip if no version field).
/// Returns `true` if the file was actually modified.
fn bump_json_version(path: &Path, new_version: &str) -> Result<bool, ReleaseError> {
    let contents = read_file(path)?;
    let mut value: serde_json::Value = serde_json::from_str(&contents).map_err(|e| {
        ReleaseError::VersionBump(format!("failed to parse {}: {e}", path.display()))
    })?;

    let obj = match value.as_object_mut() {
        Some(o) => o,
        None => return Ok(false),
    };

    if obj.get("version").is_none() {
        return Ok(false);
    }

    obj.insert(
        "version".into(),
        serde_json::Value::String(new_version.into()),
    );

    let output = serde_json::to_string_pretty(&value).map_err(|e| {
        ReleaseError::VersionBump(format!("failed to serialize {}: {e}", path.display()))
    })?;

    write_file(path, &format!("{output}\n"))?;
    Ok(true)
}

fn bump_pyproject_toml(path: &Path, new_version: &str) -> Result<Vec<PathBuf>, ReleaseError> {
    let contents = read_file(path)?;
    let mut doc: toml_edit::DocumentMut = contents.parse().map_err(|e| {
        ReleaseError::VersionBump(format!("failed to parse {}: {e}", path.display()))
    })?;

    if doc.get("project").and_then(|p| p.get("version")).is_some() {
        doc["project"]["version"] = toml_edit::value(new_version);
    } else if doc
        .get("tool")
        .and_then(|t| t.get("poetry"))
        .and_then(|p| p.get("version"))
        .is_some()
    {
        doc["tool"]["poetry"]["version"] = toml_edit::value(new_version);
    } else {
        return Err(ReleaseError::VersionBump(format!(
            "no version field found in {}",
            path.display()
        )));
    }

    write_file(path, &doc.to_string())?;

    // Auto-discover uv workspace members
    let members = extract_toml_string_array(&doc, &["tool", "uv", "workspace", "members"]);
    let mut extra = Vec::new();
    if !members.is_empty() {
        let root_dir = path.parent().unwrap_or(Path::new("."));
        for member_path in resolve_member_globs(root_dir, &members, "pyproject.toml") {
            if member_path.as_path() == path {
                continue;
            }
            match bump_pyproject_member(&member_path, new_version) {
                Ok(true) => extra.push(member_path),
                Ok(false) => {}
                Err(e) => eprintln!("warning: {e}"),
            }
        }
    }

    Ok(extra)
}

/// Bump version in a uv workspace member pyproject.toml (skip if no version field).
/// Returns `true` if the file was actually modified.
fn bump_pyproject_member(path: &Path, new_version: &str) -> Result<bool, ReleaseError> {
    let contents = read_file(path)?;
    let mut doc: toml_edit::DocumentMut = contents.parse().map_err(|e| {
        ReleaseError::VersionBump(format!("failed to parse {}: {e}", path.display()))
    })?;

    if doc.get("project").and_then(|p| p.get("version")).is_some() {
        doc["project"]["version"] = toml_edit::value(new_version);
    } else if doc
        .get("tool")
        .and_then(|t| t.get("poetry"))
        .and_then(|p| p.get("version"))
        .is_some()
    {
        doc["tool"]["poetry"]["version"] = toml_edit::value(new_version);
    } else {
        return Ok(false); // No version field — skip
    }

    write_file(path, &doc.to_string())?;
    Ok(true)
}

fn bump_gradle(path: &Path, new_version: &str) -> Result<(), ReleaseError> {
    let contents = read_file(path)?;
    let re = Regex::new(r#"(version\s*=\s*["'])([^"']*)(["'])"#).unwrap();
    if !re.is_match(&contents) {
        return Err(ReleaseError::VersionBump(format!(
            "no version assignment found in {}",
            path.display()
        )));
    }
    let result = re.replacen(&contents, 1, format!("${{1}}{new_version}${{3}}"));
    write_file(path, &result)
}

fn bump_pom_xml(path: &Path, new_version: &str) -> Result<(), ReleaseError> {
    let contents = read_file(path)?;

    // Determine search start: skip past </parent> if present, else after </modelVersion>
    let search_start = if let Some(pos) = contents.find("</parent>") {
        pos + "</parent>".len()
    } else if let Some(pos) = contents.find("</modelVersion>") {
        pos + "</modelVersion>".len()
    } else {
        0
    };

    let rest = &contents[search_start..];
    let re = Regex::new(r"<version>[^<]*</version>").unwrap();
    if let Some(m) = re.find(rest) {
        let replacement = format!("<version>{new_version}</version>");
        let mut result = String::with_capacity(contents.len());
        result.push_str(&contents[..search_start + m.start()]);
        result.push_str(&replacement);
        result.push_str(&contents[search_start + m.end()..]);
        write_file(path, &result)
    } else {
        Err(ReleaseError::VersionBump(format!(
            "no <version> element found in {}",
            path.display()
        )))
    }
}

fn bump_go_version(path: &Path, new_version: &str) -> Result<(), ReleaseError> {
    let contents = read_file(path)?;
    let re = Regex::new(r#"((?:var|const)\s+Version\s*(?:string\s*)?=\s*")([^"]*)(")"#).unwrap();
    if !re.is_match(&contents) {
        return Err(ReleaseError::VersionBump(format!(
            "no Version variable found in {}",
            path.display()
        )));
    }
    let result = re.replacen(&contents, 1, format!("${{1}}{new_version}${{3}}"));
    write_file(path, &result)
}

/// Extract a string array from a nested TOML path (e.g. `["workspace", "members"]`).
fn extract_toml_string_array(doc: &toml_edit::DocumentMut, keys: &[&str]) -> Vec<String> {
    let mut item: Option<&toml_edit::Item> = None;
    for key in keys {
        item = match item {
            None => doc.get(key),
            Some(parent) => parent.get(key),
        };
        if item.is_none() {
            return vec![];
        }
    }
    item.and_then(|v| v.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(String::from))
                .collect()
        })
        .unwrap_or_default()
}

/// Resolve workspace member glob patterns into manifest file paths.
/// Each glob is resolved relative to `root_dir`, and `manifest_name` is appended
/// to each matched directory (e.g. "Cargo.toml", "package.json", "pyproject.toml").
fn resolve_member_globs(root_dir: &Path, patterns: &[String], manifest_name: &str) -> Vec<PathBuf> {
    let mut paths = Vec::new();
    for pattern in patterns {
        let full_pattern = root_dir.join(pattern).to_string_lossy().into_owned();
        let Ok(entries) = glob::glob(&full_pattern) else {
            continue;
        };
        for entry in entries.flatten() {
            let manifest = if entry.is_dir() {
                entry.join(manifest_name)
            } else {
                continue;
            };
            if manifest.exists() {
                paths.push(manifest);
            }
        }
    }
    paths
}

fn read_file(path: &Path) -> Result<String, ReleaseError> {
    fs::read_to_string(path)
        .map_err(|e| ReleaseError::VersionBump(format!("failed to read {}: {e}", path.display())))
}

fn write_file(path: &Path, contents: &str) -> Result<(), ReleaseError> {
    fs::write(path, contents)
        .map_err(|e| ReleaseError::VersionBump(format!("failed to write {}: {e}", path.display())))
}

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

    #[test]
    fn bump_cargo_toml_package_version() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("Cargo.toml");
        fs::write(
            &path,
            r#"[package]
name = "my-crate"
version = "0.1.0"
edition = "2021"

[dependencies]
serde = "1"
"#,
        )
        .unwrap();

        bump_version_file(&path, "1.2.3").unwrap();

        let contents = fs::read_to_string(&path).unwrap();
        assert!(contents.contains("version = \"1.2.3\""));
        assert!(contents.contains("name = \"my-crate\""));
        assert!(contents.contains("serde = \"1\""));
    }

    #[test]
    fn bump_cargo_toml_workspace_version() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("Cargo.toml");
        fs::write(
            &path,
            r#"[workspace]
members = ["crates/*"]

[workspace.package]
version = "0.0.1"
edition = "2021"
"#,
        )
        .unwrap();

        bump_version_file(&path, "2.0.0").unwrap();

        let contents = fs::read_to_string(&path).unwrap();
        assert!(contents.contains("version = \"2.0.0\""));
        assert!(contents.contains("members = [\"crates/*\"]"));
    }

    #[test]
    fn bump_package_json_version() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("package.json");
        fs::write(
            &path,
            r#"{
  "name": "my-pkg",
  "version": "0.0.0",
  "description": "test"
}"#,
        )
        .unwrap();

        bump_version_file(&path, "3.1.0").unwrap();

        let contents = fs::read_to_string(&path).unwrap();
        let value: serde_json::Value = serde_json::from_str(&contents).unwrap();
        assert_eq!(value["version"], "3.1.0");
        assert_eq!(value["name"], "my-pkg");
        assert_eq!(value["description"], "test");
        assert!(contents.ends_with('\n'));
    }

    #[test]
    fn bump_pyproject_toml_project_version() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("pyproject.toml");
        fs::write(
            &path,
            r#"[project]
name = "my-project"
version = "0.1.0"
description = "A test project"
"#,
        )
        .unwrap();

        bump_version_file(&path, "1.0.0").unwrap();

        let contents = fs::read_to_string(&path).unwrap();
        assert!(contents.contains("version = \"1.0.0\""));
        assert!(contents.contains("name = \"my-project\""));
    }

    #[test]
    fn bump_pyproject_toml_poetry_version() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("pyproject.toml");
        fs::write(
            &path,
            r#"[tool.poetry]
name = "my-poetry-project"
version = "0.2.0"
description = "A poetry project"
"#,
        )
        .unwrap();

        bump_version_file(&path, "0.3.0").unwrap();

        let contents = fs::read_to_string(&path).unwrap();
        assert!(contents.contains("version = \"0.3.0\""));
        assert!(contents.contains("name = \"my-poetry-project\""));
    }

    #[test]
    fn bump_unknown_file_returns_error() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("unknown.txt");
        fs::write(&path, "version = 1").unwrap();

        let err = bump_version_file(&path, "1.0.0").unwrap_err();
        assert!(matches!(err, ReleaseError::VersionBump(_)));
        assert!(err.to_string().contains("unsupported"));
    }

    #[test]
    fn bump_build_gradle_version() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("build.gradle");
        fs::write(
            &path,
            r#"plugins {
    id 'java'
}

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

dependencies {
    implementation 'org.slf4j:slf4j-api:2.0.0'
}
"#,
        )
        .unwrap();

        bump_version_file(&path, "2.0.0").unwrap();

        let contents = fs::read_to_string(&path).unwrap();
        assert!(contents.contains("version = '2.0.0'"));
        assert!(contents.contains("group = 'com.example'"));
        // dependency version must not change
        assert!(contents.contains("slf4j-api:2.0.0"));
    }

    #[test]
    fn bump_build_gradle_kts_version() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("build.gradle.kts");
        fs::write(
            &path,
            r#"plugins {
    kotlin("jvm") version "1.9.0"
}

group = "com.example"
version = "1.0.0"

dependencies {
    implementation("org.slf4j:slf4j-api:2.0.0")
}
"#,
        )
        .unwrap();

        bump_version_file(&path, "3.0.0").unwrap();

        let contents = fs::read_to_string(&path).unwrap();
        assert!(contents.contains("version = \"3.0.0\""));
        assert!(contents.contains("group = \"com.example\""));
    }

    #[test]
    fn bump_pom_xml_version() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("pom.xml");
        fs::write(
            &path,
            r#"<?xml version="1.0" encoding="UTF-8"?>
<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>my-app</artifactId>
    <version>1.0.0</version>
</project>
"#,
        )
        .unwrap();

        bump_version_file(&path, "2.0.0").unwrap();

        let contents = fs::read_to_string(&path).unwrap();
        assert!(contents.contains("<version>2.0.0</version>"));
        assert!(contents.contains("<groupId>com.example</groupId>"));
    }

    #[test]
    fn bump_pom_xml_with_parent_version() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("pom.xml");
        fs::write(
            &path,
            r#"<?xml version="1.0" encoding="UTF-8"?>
<project>
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.example</groupId>
        <artifactId>parent</artifactId>
        <version>5.0.0</version>
    </parent>
    <artifactId>my-app</artifactId>
    <version>1.0.0</version>
</project>
"#,
        )
        .unwrap();

        bump_version_file(&path, "2.0.0").unwrap();

        let contents = fs::read_to_string(&path).unwrap();
        // Parent version must NOT be changed
        assert!(contents.contains("<version>5.0.0</version>"));
        // Project version must be changed
        assert!(contents.contains("<version>2.0.0</version>"));
        // Verify there are exactly two <version> tags with expected values
        let version_count: Vec<&str> = contents.matches("<version>").collect();
        assert_eq!(version_count.len(), 2);
    }

    #[test]
    fn bump_cargo_toml_workspace_dependencies_with_path() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("Cargo.toml");
        fs::write(
            &path,
            r#"[workspace]
members = ["crates/*"]

[workspace.package]
version = "0.1.0"
edition = "2021"

[workspace.dependencies]
# Internal crates
sr-core = { path = "crates/sr-core", version = "0.1.0" }
sr-git = { path = "crates/sr-git", version = "0.1.0" }
# External dep should not change
serde = { version = "1", features = ["derive"] }
"#,
        )
        .unwrap();

        bump_version_file(&path, "2.0.0").unwrap();

        let contents = fs::read_to_string(&path).unwrap();
        let doc: toml_edit::DocumentMut = contents.parse().unwrap();

        // workspace.package.version should be bumped
        assert_eq!(
            doc["workspace"]["package"]["version"].as_str().unwrap(),
            "2.0.0"
        );
        // Internal path deps should have their version bumped
        assert_eq!(
            doc["workspace"]["dependencies"]["sr-core"]["version"]
                .as_str()
                .unwrap(),
            "2.0.0"
        );
        assert_eq!(
            doc["workspace"]["dependencies"]["sr-git"]["version"]
                .as_str()
                .unwrap(),
            "2.0.0"
        );
        // External dep version must NOT change
        assert_eq!(
            doc["workspace"]["dependencies"]["serde"]["version"]
                .as_str()
                .unwrap(),
            "1"
        );
    }

    #[test]
    fn bump_go_version_var() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("version.go");
        fs::write(
            &path,
            r#"package main

var Version = "1.0.0"

func main() {}
"#,
        )
        .unwrap();

        bump_version_file(&path, "2.0.0").unwrap();

        let contents = fs::read_to_string(&path).unwrap();
        assert!(contents.contains(r#"var Version = "2.0.0""#));
    }

    #[test]
    fn bump_go_version_const() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("version.go");
        fs::write(
            &path,
            r#"package main

const Version string = "0.5.0"

func main() {}
"#,
        )
        .unwrap();

        bump_version_file(&path, "0.6.0").unwrap();

        let contents = fs::read_to_string(&path).unwrap();
        assert!(contents.contains(r#"const Version string = "0.6.0""#));
    }

    // --- workspace auto-discovery tests ---

    #[test]
    fn bump_cargo_workspace_discovers_members() {
        let dir = tempfile::tempdir().unwrap();

        // Create workspace root
        let root = dir.path().join("Cargo.toml");
        fs::write(
            &root,
            r#"[workspace]
members = ["crates/*"]

[workspace.package]
version = "1.0.0"
edition = "2021"

[workspace.dependencies]
my-core = { path = "crates/core", version = "1.0.0" }
"#,
        )
        .unwrap();

        // Create member with hardcoded version
        fs::create_dir_all(dir.path().join("crates/core")).unwrap();
        let member = dir.path().join("crates/core/Cargo.toml");
        fs::write(
            &member,
            r#"[package]
name = "my-core"
version = "1.0.0"
edition = "2021"
"#,
        )
        .unwrap();

        // Create member that uses workspace inheritance (should be skipped)
        fs::create_dir_all(dir.path().join("crates/cli")).unwrap();
        let inherited_member = dir.path().join("crates/cli/Cargo.toml");
        fs::write(
            &inherited_member,
            r#"[package]
name = "my-cli"
version.workspace = true
edition.workspace = true
"#,
        )
        .unwrap();

        let extra = bump_version_file(&root, "2.0.0").unwrap();

        // Root should be bumped
        let root_contents = fs::read_to_string(&root).unwrap();
        assert!(root_contents.contains("version = \"2.0.0\""));

        // Workspace dep should be bumped
        let doc: toml_edit::DocumentMut = root_contents.parse().unwrap();
        assert_eq!(
            doc["workspace"]["dependencies"]["my-core"]["version"]
                .as_str()
                .unwrap(),
            "2.0.0"
        );

        // Member with hardcoded version should be bumped
        let member_contents = fs::read_to_string(&member).unwrap();
        assert!(member_contents.contains("version = \"2.0.0\""));

        // Member with workspace inheritance should NOT be modified
        let inherited_contents = fs::read_to_string(&inherited_member).unwrap();
        assert!(inherited_contents.contains("version.workspace = true"));

        // Only the hardcoded member should be in extra
        assert_eq!(extra.len(), 1);
        assert_eq!(extra[0], member);
    }

    #[test]
    fn bump_npm_workspace_discovers_members() {
        let dir = tempfile::tempdir().unwrap();

        // Create root package.json with workspaces
        let root = dir.path().join("package.json");
        fs::write(
            &root,
            r#"{
  "name": "my-monorepo",
  "version": "1.0.0",
  "workspaces": ["packages/*"]
}"#,
        )
        .unwrap();

        // Create member
        fs::create_dir_all(dir.path().join("packages/core")).unwrap();
        let member = dir.path().join("packages/core/package.json");
        fs::write(
            &member,
            r#"{
  "name": "@my/core",
  "version": "1.0.0"
}"#,
        )
        .unwrap();

        // Create member without version (should be skipped)
        fs::create_dir_all(dir.path().join("packages/utils")).unwrap();
        let no_version_member = dir.path().join("packages/utils/package.json");
        fs::write(
            &no_version_member,
            r#"{
  "name": "@my/utils",
  "private": true
}"#,
        )
        .unwrap();

        let extra = bump_version_file(&root, "2.0.0").unwrap();

        // Root bumped
        let root_contents: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(&root).unwrap()).unwrap();
        assert_eq!(root_contents["version"], "2.0.0");

        // Member with version bumped
        let member_contents: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(&member).unwrap()).unwrap();
        assert_eq!(member_contents["version"], "2.0.0");

        // Member without version untouched
        let utils_contents: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(&no_version_member).unwrap()).unwrap();
        assert!(utils_contents.get("version").is_none());

        assert_eq!(extra.len(), 1);
        assert_eq!(extra[0], member);
    }

    #[test]
    fn bump_uv_workspace_discovers_members() {
        let dir = tempfile::tempdir().unwrap();

        // Create root pyproject.toml with uv workspace
        let root = dir.path().join("pyproject.toml");
        fs::write(
            &root,
            r#"[project]
name = "my-monorepo"
version = "1.0.0"

[tool.uv.workspace]
members = ["packages/*"]
"#,
        )
        .unwrap();

        // Create member
        fs::create_dir_all(dir.path().join("packages/core")).unwrap();
        let member = dir.path().join("packages/core/pyproject.toml");
        fs::write(
            &member,
            r#"[project]
name = "my-core"
version = "1.0.0"
"#,
        )
        .unwrap();

        let extra = bump_version_file(&root, "2.0.0").unwrap();

        // Root bumped
        let root_contents = fs::read_to_string(&root).unwrap();
        assert!(root_contents.contains("version = \"2.0.0\""));

        // Member bumped
        let member_contents = fs::read_to_string(&member).unwrap();
        assert!(member_contents.contains("version = \"2.0.0\""));

        assert_eq!(extra.len(), 1);
        assert_eq!(extra[0], member);
    }

    #[test]
    fn bump_non_workspace_returns_empty_extra() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("Cargo.toml");
        fs::write(
            &path,
            r#"[package]
name = "solo-crate"
version = "1.0.0"
"#,
        )
        .unwrap();

        let extra = bump_version_file(&path, "2.0.0").unwrap();
        assert!(extra.is_empty());
    }

    // --- auto-detection tests ---

    #[test]
    fn detect_cargo_toml() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(
            dir.path().join("Cargo.toml"),
            "[package]\nname = \"x\"\nversion = \"0.1.0\"\n",
        )
        .unwrap();

        let detected = detect_version_files(dir.path());
        assert_eq!(detected, vec!["Cargo.toml"]);
    }

    #[test]
    fn detect_package_json() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(
            dir.path().join("package.json"),
            r#"{"name": "x", "version": "1.0.0"}"#,
        )
        .unwrap();

        let detected = detect_version_files(dir.path());
        assert_eq!(detected, vec!["package.json"]);
    }

    #[test]
    fn detect_pyproject_toml() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(
            dir.path().join("pyproject.toml"),
            "[project]\nname = \"x\"\nversion = \"0.1.0\"\n",
        )
        .unwrap();

        let detected = detect_version_files(dir.path());
        assert_eq!(detected, vec!["pyproject.toml"]);
    }

    #[test]
    fn detect_multiple_ecosystems() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(
            dir.path().join("Cargo.toml"),
            "[package]\nname = \"x\"\nversion = \"0.1.0\"\n",
        )
        .unwrap();
        fs::write(
            dir.path().join("package.json"),
            r#"{"name": "x", "version": "1.0.0"}"#,
        )
        .unwrap();

        let detected = detect_version_files(dir.path());
        assert!(detected.contains(&"Cargo.toml".to_string()));
        assert!(detected.contains(&"package.json".to_string()));
    }

    #[test]
    fn detect_empty_directory() {
        let dir = tempfile::tempdir().unwrap();
        let detected = detect_version_files(dir.path());
        assert!(detected.is_empty());
    }

    #[test]
    fn detect_go_version_file() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(
            dir.path().join("version.go"),
            "package main\n\nvar Version = \"1.0.0\"\n",
        )
        .unwrap();

        let detected = detect_version_files(dir.path());
        assert_eq!(detected, vec!["version.go"]);
    }

    #[test]
    fn is_supported_recognizes_all_types() {
        assert!(is_supported_version_file("Cargo.toml"));
        assert!(is_supported_version_file("package.json"));
        assert!(is_supported_version_file("pyproject.toml"));
        assert!(is_supported_version_file("pom.xml"));
        assert!(is_supported_version_file("build.gradle"));
        assert!(is_supported_version_file("build.gradle.kts"));
        assert!(is_supported_version_file("version.go"));
        assert!(!is_supported_version_file("unknown.txt"));
    }
}