wsb 0.222.4636

Workspace - A tool suite for file operations, version management, and development workflow automation
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
use crate::fleet::config::gitmodules::validate_gitmodules_structure;
use crate::prelude::*;
use anyhow::{bail, Context, Result};
use gix::bstr::BString;
use gix::remote;
use gix::status;
use gix::status::index_worktree;
use gix::status::index_worktree::iter::Summary as IndexWorktreeSummary;
use gix::status::plumbing::index_as_worktree::{Change as WorktreeChange, EntryStatus};
use ignore::WalkBuilder;
use std::collections::BTreeSet;
use std::fs;

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BranchKind {
    Local,
    Remote,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum FileStatusKind {
    Staged,
    Modified,
    Untracked,
    Ignored,
    Deleted,
    Renamed,
    Conflict,
}

#[derive(Debug, Clone)]
pub struct StatusEntry {
    pub path: String,
    pub status: FileStatusKind,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PushOutcome {
    Updated,
    UpToDate,
}

pub fn discover_repo(path: &Path) -> Result<gix::Repository> {
    gix::discover(path)
        .with_context(|| format!("Failed to discover git repository from {}", path.display()))
}

pub fn is_git_repository(path: &Path) -> bool {
    gix::discover(path).is_ok()
}

pub fn repo_root(path: &Path) -> Result<PathBuf> {
    let repo = discover_repo(path)?;
    repo.workdir()
        .map(Path::to_path_buf)
        .or_else(|| repo.git_dir().parent().map(Path::to_path_buf))
        .context("Discovered repository does not expose a usable root path")
}

pub fn init_repository(path: &Path) -> Result<gix::Repository> {
    let output = std::process::Command::new("git")
        .args(["init"])
        .current_dir(path)
        .output()
        .context("Failed to execute git init")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("git init failed: {}", stderr.trim());
    }

    open_repo(path)
}

pub fn configure_local_user(repo: &gix::Repository, name: &str, email: &str) -> Result<()> {
    let config_path = repo.git_dir().join("config");
    let existing = fs::read_to_string(&config_path).with_context(|| {
        format!(
            "Failed to read repository config at {}",
            config_path.display()
        )
    })?;
    let user_block = format!("[user]\n\tname = {name}\n\temail = {email}\n");
    let updated = replace_or_append_config_section(&existing, "user", &user_block);
    fs::write(&config_path, updated).with_context(|| {
        format!(
            "Failed to write repository config at {}",
            config_path.display()
        )
    })
}

pub fn open_repo(path: &Path) -> Result<gix::Repository> {
    gix::open(path).with_context(|| format!("Failed to open git repository at {}", path.display()))
}

pub fn current_branch(repo: &gix::Repository) -> Result<String> {
    let head = repo.head().context("Failed to read HEAD")?;
    if head.is_detached() {
        bail!("Detached HEAD");
    }

    let name = head
        .referent_name()
        .context("HEAD is not attached to a branch")?
        .shorten()
        .to_string();
    Ok(name)
}

pub fn is_detached_head(repo: &gix::Repository) -> Result<bool> {
    Ok(repo.head().context("Failed to read HEAD")?.is_detached())
}

pub fn remote_url(repo: &gix::Repository, remote_name: &str) -> Result<String> {
    let remote = repo
        .find_remote(remote_name)
        .with_context(|| format!("Remote '{remote_name}' not found"))?;
    let url = remote
        .url(remote::Direction::Fetch)
        .context("Remote does not have a fetch URL configured")?;
    Ok(url.to_bstring().to_string())
}

pub fn branch_exists(repo: &gix::Repository, branch_name: &str, kind: BranchKind) -> Result<bool> {
    let full_name = match kind {
        BranchKind::Local => format!("refs/heads/{branch_name}"),
        BranchKind::Remote => format!("refs/remotes/{branch_name}"),
    };
    Ok(repo
        .try_find_reference(full_name.as_str())
        .context("Failed to query branch reference")?
        .is_some())
}

pub fn local_branches(repo: &gix::Repository) -> Result<Vec<String>> {
    let mut branches: Vec<String> = repo
        .references()
        .context("Failed to list references")?
        .local_branches()
        .context("Failed to list local branches")?
        .flatten()
        .map(|branch| branch.name().shorten().to_string())
        .collect();
    branches.sort();
    Ok(branches)
}

pub fn remote_branches(repo: &gix::Repository) -> Result<Vec<String>> {
    let mut branches: Vec<String> = repo
        .references()
        .context("Failed to list references")?
        .remote_branches()
        .context("Failed to list remote branches")?
        .flatten()
        .map(|branch| branch.name().shorten().to_string())
        .collect();
    branches.sort();
    Ok(branches)
}

pub fn remotes(repo: &gix::Repository) -> Result<Vec<String>> {
    let workdir = repo
        .workdir()
        .context("Bare repositories are not supported for remote listing")?;

    let output = std::process::Command::new("git")
        .args(["remote"])
        .current_dir(workdir)
        .output()
        .context("Failed to execute git remote")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("git remote failed: {}", stderr.trim());
    }

    let remotes: Vec<String> = String::from_utf8(output.stdout)
        .context("git remote output is not valid UTF-8")?
        .lines()
        .map(str::trim)
        .filter(|line| !line.is_empty())
        .map(ToOwned::to_owned)
        .collect();

    if remotes.is_empty() {
        bail!("No remotes configured");
    }

    Ok(remotes)
}

pub fn is_clean(repo: &gix::Repository) -> Result<bool> {
    let entries = status_entries(repo)?;
    Ok(entries
        .iter()
        .all(|entry| entry.status == FileStatusKind::Ignored))
}

pub fn has_uncommitted_changes(entries: &[StatusEntry]) -> bool {
    entries
        .iter()
        .any(|entry| entry.status != FileStatusKind::Ignored)
}

/// Returns the unified diff of `rel_path` against HEAD (worktree vs last commit).
/// For staged files, includes both staged and unstaged changes relative to HEAD.
/// Returns an empty string if the path has no changes relative to HEAD.
pub fn diff_file(repo: &gix::Repository, rel_path: &str) -> Result<String> {
    let workdir = repo
        .workdir()
        .context("bare repositories are not supported for diff")?;

    // `git diff HEAD -- <path>` covers unstaged changes against HEAD.
    // `git diff --cached HEAD -- <path>` covers staged changes against HEAD.
    // Running both and concatenating gives the full picture from HEAD.
    let unstaged = std::process::Command::new("git")
        .args(["diff", "HEAD", "--", rel_path])
        .current_dir(workdir)
        .output()
        .context("failed to execute git diff")?;

    if !unstaged.status.success() {
        let stderr = String::from_utf8_lossy(&unstaged.stderr);
        bail!("git diff failed: {}", stderr.trim());
    }

    let unstaged_text =
        String::from_utf8(unstaged.stdout).context("git diff output is not valid UTF-8")?;

    // If unstaged already has output we are done — it covers the worktree vs HEAD.
    // If empty, the file may be fully staged; check the index vs HEAD.
    if !unstaged_text.is_empty() {
        return Ok(unstaged_text);
    }

    let staged = std::process::Command::new("git")
        .args(["diff", "--cached", "HEAD", "--", rel_path])
        .current_dir(workdir)
        .output()
        .context("failed to execute git diff --cached")?;

    if !staged.status.success() {
        let stderr = String::from_utf8_lossy(&staged.stderr);
        bail!("git diff --cached failed: {}", stderr.trim());
    }

    String::from_utf8(staged.stdout).context("git diff --cached output is not valid UTF-8")
}

/// Returns `true` if `dir` (an absolute path) contains at least one file that
/// is **not** gitignored.  Uses the `ignore` crate which honours nested
/// `.gitignore` files.  An empty directory (or one with only empty subdirs)
/// returns `false`.
fn dir_has_non_ignored_files(dir: &Path) -> bool {
    if !dir.is_dir() {
        return true; // not a directory → treat as real content
    }
    let walker = WalkBuilder::new(dir)
        .hidden(false) // don't skip dotfiles — git doesn't
        .git_ignore(true) // respect .gitignore
        .git_global(true) // respect global gitignore
        .git_exclude(true) // respect .git/info/exclude
        .build();
    for entry in walker {
        let Ok(entry) = entry else { continue };
        if entry.file_type().is_some_and(|kind| kind.is_file()) {
            return true;
        }
    }
    false
}

/// Whether an untracked dirwalk entry is something git would actually report.
///
/// gix emits a directory as untracked even when it holds nothing git could ever
/// track — it is empty, contains only empty subdirectories, or everything in it
/// is ignored. Git has no concept of an empty directory and reports none of
/// these, so neither do we.
///
/// `workdir` is the working directory `entry.rela_path` is relative to.
fn untracked_entry_is_reportable(workdir: &Path, entry: &gix::dir::Entry) -> bool {
    if entry.disk_kind.is_some_and(|kind| kind.is_dir()) {
        dir_has_non_ignored_files(&workdir.join(entry.rela_path.to_string()))
    } else {
        true
    }
}

/// Whether a submodule gix reported as modified has actually changed.
///
/// gix marks a submodule modified when anything at all turns up in its worktree
/// walk, including an untracked directory that git would never report. Without
/// this check a repository calls its own submodule dirty while reporting that
/// same submodule as clean when asked about it directly — and `pull` then skips
/// a tree that has nothing to lose.
///
/// `workdir` is the submodule's own working directory.
fn submodule_modification_is_reportable(workdir: &Path, status: &gix::submodule::Status) -> bool {
    // The gitlink pointing somewhere other than the checked-out HEAD is a real
    // change no matter what the worktree looks like.
    if status.index_id != status.checked_out_head_id {
        return true;
    }
    match &status.changes {
        // The walk was skipped: no clone, or no worktree. Not a local change.
        None => false,
        Some(changes) => changes
            .iter()
            .any(|item| status_item_is_reportable(workdir, item)),
    }
}

/// Whether one status item is a change git would report.
///
/// Submodule changes nest — a submodule's own changes are themselves status
/// items — so this recurses, and the same rules decide at every depth.
fn status_item_is_reportable(workdir: &Path, item: &status::Item) -> bool {
    match item {
        // A difference between HEAD and the index is always a staged change.
        status::Item::TreeIndex(_) => true,
        status::Item::IndexWorktree(item) => match item {
            index_worktree::Item::Modification {
                rela_path, status, ..
            } => match status {
                EntryStatus::Change(WorktreeChange::SubmoduleModification(submodule)) => {
                    submodule_modification_is_reportable(
                        &workdir.join(rela_path.to_string()),
                        submodule,
                    )
                }
                _ => true,
            },
            index_worktree::Item::DirectoryContents { entry, .. } => match entry.status {
                gix::dir::entry::Status::Untracked => untracked_entry_is_reportable(workdir, entry),
                // Ignored content is not a change, and tracked or pruned entries
                // are not reported as one.
                gix::dir::entry::Status::Ignored(_)
                | gix::dir::entry::Status::Tracked
                | gix::dir::entry::Status::Pruned => false,
            },
            index_worktree::Item::Rewrite { .. } => true,
        },
    }
}

pub fn status_entries(repo: &gix::Repository) -> Result<Vec<StatusEntry>> {
    // gix status reads .gitmodules internally. Validate it first so we can
    // surface a clear, actionable error instead of a cryptic parse failure.
    if let Some(workdir) = repo.workdir() {
        let gitmodules = workdir.join(".gitmodules");
        if gitmodules.exists() {
            let bytes = std::fs::read(&gitmodules)
                .with_context(|| format!("failed to read {}", gitmodules.display()))?;
            validate_gitmodules_structure(&bytes, &gitmodules)?;
        }
    }

    // Track staged paths (TreeIndex) and worktree paths separately so we can
    // classify correctly.  A path in TreeIndex only → Staged.  A path in
    // IndexWorktree only → Modified/Untracked/etc.  A path in both → Modified
    // (has both staged and unstaged changes — the unstaged state dominates for
    // display purposes, matching VS Code behaviour).
    let workdir = repo
        .workdir()
        .context("bare repository has no working directory")?
        .to_path_buf();

    let mut staged: BTreeSet<String> = BTreeSet::new();
    let mut worktree: std::collections::BTreeMap<String, FileStatusKind> =
        std::collections::BTreeMap::new();

    let mut platform = repo
        .status(gix::progress::Discard)
        .context("Failed to initialise status")?;
    platform.dirwalk_options_mut(|opts| {
        // Collapse ignored entries to directory level (e.g. "target/" instead of
        // individual files inside it).
        opts.set_emit_ignored(Some(gix::dir::walk::EmissionMode::CollapseDirectory));
        // Collapse untracked entries to directory level.  This prevents reporting
        // directories as "untracked" when they only contain ignored files or empty
        // subdirectories — matching what `git status` actually reports.
        opts.set_emit_untracked(gix::dir::walk::EmissionMode::CollapseDirectory);
    });

    let iter = platform
        .into_iter(Vec::<BString>::new())
        .context("Failed to compute repository status")?;
    for item in iter {
        match item.context("Failed to inspect status entry")? {
            status::Item::TreeIndex(change) => match change {
                gix::diff::index::Change::Addition { location, .. }
                | gix::diff::index::Change::Modification { location, .. } => {
                    staged.insert(location.to_string());
                }
                gix::diff::index::Change::Deletion { location, .. } => {
                    worktree.insert(location.to_string(), FileStatusKind::Deleted);
                }
                gix::diff::index::Change::Rewrite {
                    source_location,
                    location,
                    ..
                } => {
                    worktree.insert(source_location.to_string(), FileStatusKind::Deleted);
                    worktree.insert(location.to_string(), FileStatusKind::Renamed);
                }
            },
            status::Item::IndexWorktree(entry) => match entry {
                index_worktree::Item::Modification {
                    ref rela_path,
                    status: ref entry_status,
                    ..
                } => {
                    // A submodule gix calls modified may hold nothing git would
                    // report. Decided by the same rules used for this repository's
                    // own entries, so a submodule is never dirty here and clean
                    // when inspected directly.
                    if let EntryStatus::Change(WorktreeChange::SubmoduleModification(submodule)) =
                        entry_status
                    {
                        if !submodule_modification_is_reportable(
                            &workdir.join(rela_path.to_string()),
                            submodule,
                        ) {
                            continue;
                        }
                    }

                    match entry.summary() {
                        Some(IndexWorktreeSummary::Conflict) => {
                            worktree.insert(rela_path.to_string(), FileStatusKind::Conflict);
                        }
                        Some(IndexWorktreeSummary::Removed) => {
                            worktree.insert(rela_path.to_string(), FileStatusKind::Deleted);
                        }
                        Some(IndexWorktreeSummary::TypeChange)
                        | Some(IndexWorktreeSummary::Modified)
                        | Some(IndexWorktreeSummary::Copied) => {
                            worktree.insert(rela_path.to_string(), FileStatusKind::Modified);
                        }
                        Some(IndexWorktreeSummary::IntentToAdd) => {
                            staged.insert(rela_path.to_string());
                        }
                        Some(IndexWorktreeSummary::Added) => {
                            worktree.insert(rela_path.to_string(), FileStatusKind::Untracked);
                        }
                        Some(IndexWorktreeSummary::Renamed) => {
                            worktree.insert(rela_path.to_string(), FileStatusKind::Renamed);
                        }
                        None => {}
                    }
                }
                index_worktree::Item::DirectoryContents {
                    entry,
                    collapsed_directory_status: _,
                } => {
                    let status = match entry.status {
                        gix::dir::entry::Status::Untracked => {
                            if untracked_entry_is_reportable(&workdir, &entry) {
                                Some(FileStatusKind::Untracked)
                            } else {
                                None
                            }
                        }
                        gix::dir::entry::Status::Ignored(_) => Some(FileStatusKind::Ignored),
                        gix::dir::entry::Status::Tracked | gix::dir::entry::Status::Pruned => None,
                    };

                    if let Some(status) = status {
                        worktree.insert(entry.rela_path.to_string(), status);
                    }
                }
                index_worktree::Item::Rewrite {
                    dirwalk_entry,
                    source,
                    ..
                } => {
                    worktree.insert(dirwalk_entry.rela_path.to_string(), FileStatusKind::Renamed);
                    worktree.insert(source.rela_path().to_string(), FileStatusKind::Deleted);
                }
            },
        }
    }

    // Merge: worktree status wins if a path is in both sets.
    let mut result: std::collections::BTreeMap<String, FileStatusKind> =
        std::collections::BTreeMap::new();

    for path in &staged {
        if let Some(wt_status) = worktree.get(path) {
            // Path has both staged and worktree changes — show worktree kind
            result.insert(path.clone(), *wt_status);
        } else {
            result.insert(path.clone(), FileStatusKind::Staged);
        }
    }
    for (path, kind) in &worktree {
        result.entry(path.clone()).or_insert(*kind);
    }

    Ok(result
        .into_iter()
        .map(|(path, status)| StatusEntry { path, status })
        .collect())
}

pub fn get_default_branch(repo: &gix::Repository) -> Result<String> {
    for branch in ["main", "master"] {
        if branch_exists(repo, branch, BranchKind::Local)? {
            return Ok(branch.to_string());
        }
    }
    local_branches(repo)?
        .into_iter()
        .next()
        .context("No branches found")
}

pub fn fetch(repo: &gix::Repository, remote_name: Option<&str>) -> Result<()> {
    let workdir = repo
        .workdir()
        .context("Bare repositories are not supported for fetch")?;

    let remote = remote_name.unwrap_or("origin");
    let output = std::process::Command::new("git")
        .args(["fetch", remote])
        .current_dir(workdir)
        .output()
        .context("Failed to execute git fetch")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("git fetch failed: {}", stderr.trim());
    }

    Ok(())
}

pub fn fetch_remote_branch(
    repo: &gix::Repository,
    remote_name: &str,
    branch_name: &str,
) -> Result<()> {
    let workdir = repo
        .workdir()
        .context("Bare repositories are not supported for fetch")?;
    let refspec = format!("{branch_name}:refs/remotes/{remote_name}/{branch_name}");

    let output = std::process::Command::new("git")
        .args(["fetch", remote_name, &refspec])
        .current_dir(workdir)
        .output()
        .with_context(|| format!("Failed to execute git fetch for {remote_name}/{branch_name}"))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!(
            "git fetch failed for {remote_name}/{branch_name}: {}",
            stderr.trim()
        );
    }

    Ok(())
}

pub fn fetch_all(repo: &gix::Repository) -> Result<()> {
    let workdir = repo
        .workdir()
        .context("Bare repositories are not supported for fetch")?;

    let output = std::process::Command::new("git")
        .args(["fetch", "--all"])
        .current_dir(workdir)
        .output()
        .context("Failed to execute git fetch --all")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("git fetch --all failed: {}", stderr.trim());
    }

    Ok(())
}

pub fn remote_branch_head(
    repo: &gix::Repository,
    remote_name: &str,
    branch_name: &str,
) -> Result<Option<gix::ObjectId>> {
    let workdir = repo
        .workdir()
        .context("Bare repositories are not supported for remote inspection")?;
    let ref_name = format!("refs/heads/{branch_name}");

    let output = std::process::Command::new("git")
        .args(["ls-remote", "--heads", remote_name, &ref_name])
        .current_dir(workdir)
        .output()
        .with_context(|| {
            format!("Failed to execute git ls-remote for {remote_name}/{branch_name}")
        })?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!(
            "git ls-remote failed for {remote_name}/{branch_name}: {}",
            stderr.trim()
        );
    }

    let stdout =
        String::from_utf8(output.stdout).context("git ls-remote output is not valid UTF-8")?;
    let line = stdout.trim();
    if line.is_empty() {
        return Ok(None);
    }

    let oid_text = line
        .split_whitespace()
        .next()
        .context("git ls-remote output did not contain an object id")?;
    let oid = gix::ObjectId::from_hex(oid_text.as_bytes())
        .with_context(|| format!("Remote object id '{oid_text}' is invalid"))?;
    Ok(Some(oid))
}

pub fn remote_refs(
    repo: &gix::Repository,
    remote_name: &str,
) -> Result<Vec<(String, gix::ObjectId)>> {
    let workdir = repo
        .workdir()
        .context("Bare repositories are not supported for remote inspection")?;

    let output = std::process::Command::new("git")
        .args(["ls-remote", "--heads", "--tags", remote_name])
        .current_dir(workdir)
        .output()
        .with_context(|| format!("Failed to execute git ls-remote for {remote_name}"))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("git ls-remote failed for {remote_name}: {}", stderr.trim());
    }

    let stdout =
        String::from_utf8(output.stdout).context("git ls-remote output is not valid UTF-8")?;
    let mut refs = Vec::new();
    for line in stdout.lines().filter(|line| !line.trim().is_empty()) {
        let mut fields = line.split_whitespace();
        let oid_text = fields
            .next()
            .context("git ls-remote output did not contain an object id")?;
        let ref_name = fields
            .next()
            .context("git ls-remote output did not contain a ref name")?;
        if ref_name.ends_with("^{}") {
            continue;
        }
        let oid = gix::ObjectId::from_hex(oid_text.as_bytes())
            .with_context(|| format!("Remote object id '{oid_text}' is invalid"))?;
        refs.push((ref_name.to_string(), oid));
    }
    Ok(refs)
}

pub fn local_remote_tracking_head(
    repo: &gix::Repository,
    remote_name: &str,
    branch_name: &str,
) -> Result<Option<gix::ObjectId>> {
    let ref_name = format!("refs/remotes/{remote_name}/{branch_name}");
    match repo.try_find_reference(ref_name.as_str()) {
        Ok(Some(mut reference)) => Ok(Some(
            reference
                .peel_to_id()
                .context("Failed to peel local remote-tracking reference")?
                .detach(),
        )),
        Ok(None) => Ok(None),
        Err(err) => {
            Err(anyhow::Error::from(err)
                .context("Failed to inspect local remote-tracking reference"))
        }
    }
}

pub fn current_branch_remote(repo: &gix::Repository, default_remote: &str) -> Result<String> {
    let head = repo.head().context("Failed to read HEAD")?;
    let branch = head
        .referent_name()
        .context("Detached HEAD is not supported")?;
    if let Some(remote) = repo
        .branch_remote(branch.shorten(), gix::remote::Direction::Fetch)
        .transpose()
        .context("Failed to determine branch remote")?
    {
        return remote
            .name()
            .and_then(|name| name.as_symbol())
            .map(ToOwned::to_owned)
            .context("Remote name must be symbolic");
    }
    repo.find_remote(default_remote)
        .with_context(|| format!("Remote '{default_remote}' not found"))?;
    Ok(default_remote.to_string())
}

pub fn has_outgoing_commits(repo: &gix::Repository, remote_name: Option<&str>) -> Result<bool> {
    let branch = current_branch(repo)?;
    let remote = current_branch_remote(repo, remote_name.unwrap_or("origin"))?;
    let head_id = repo.head_id().context("Failed to resolve HEAD")?.detach();

    let Some(remote_id) = remote_branch_head(repo, &remote, &branch)? else {
        return Ok(true);
    };

    if head_id == remote_id {
        return Ok(false);
    }

    let merge_base = repo
        .merge_base(head_id, remote_id)
        .context("Failed to compute merge base against remote branch")?;
    Ok(merge_base == remote_id)
}

pub fn has_incoming_commits(repo: &gix::Repository, remote_name: Option<&str>) -> Result<bool> {
    let branch = current_branch(repo)?;
    let remote = current_branch_remote(repo, remote_name.unwrap_or("origin"))?;
    let head_id = repo.head_id().context("Failed to resolve HEAD")?.detach();

    let remote_id = remote_branch_head(repo, &remote, &branch)?
        .with_context(|| format!("Remote branch '{remote}/{branch}' does not exist"))?;

    if head_id == remote_id {
        return Ok(false);
    }

    match repo.merge_base(head_id, remote_id) {
        Ok(merge_base) => Ok(merge_base == head_id),
        Err(err) => {
            let local_tracking_id = local_remote_tracking_head(repo, &remote, &branch)?
                .with_context(|| {
                    format!("Local remote-tracking branch '{remote}/{branch}' does not exist")
                })?;
            if local_tracking_id == head_id {
                Ok(true)
            } else {
                Err(anyhow::Error::from(err).context(format!(
                    "Cannot prove remote branch '{remote}/{branch}' is ahead of local HEAD"
                )))
            }
        }
    }
}

pub fn has_fetchable_updates(repo: &gix::Repository, all_remotes: bool) -> Result<bool> {
    let remote_names = if all_remotes {
        remotes(repo)?
    } else {
        vec!["origin".to_string()]
    };

    for remote in remote_names {
        repo.find_remote(remote.as_str())
            .with_context(|| format!("Remote '{remote}' not found"))?;
        for (remote_ref, remote_id) in remote_refs(repo, &remote)? {
            let Some(branch_name) = remote_ref.strip_prefix("refs/heads/") else {
                return Ok(true);
            };
            match local_remote_tracking_head(repo, &remote, branch_name)? {
                Some(local_id) if local_id == remote_id => {}
                _ => return Ok(true),
            }
        }
    }

    Ok(false)
}

pub fn pull(repo: &gix::Repository, rebase: bool) -> Result<()> {
    if rebase {
        bail!("Rebase pulls are not supported");
    }

    let head = repo.head().context("Failed to read HEAD")?;
    let branch = head
        .referent_name()
        .context("Detached HEAD is not supported for pull")?;

    let remote_name = match repo
        .branch_remote(branch.shorten(), gix::remote::Direction::Fetch)
        .transpose()
        .context("Failed to determine branch remote")?
    {
        Some(remote) => remote
            .name()
            .cloned()
            .context("Remote name must be available")?,
        None => repo
            .find_default_remote(gix::remote::Direction::Fetch)
            .context("No fetch remote configured for current branch")??
            .name()
            .cloned()
            .context("Remote name must be available")?,
    };

    let remote_name_str = remote_name
        .as_symbol()
        .context("Remote name must be symbolic")?
        .to_string();
    fetch(repo, Some(&remote_name_str))?;

    let tracking = repo
        .branch_remote_tracking_ref_name(branch, gix::remote::Direction::Fetch)
        .transpose()
        .context("Failed to resolve tracking branch")?
        .context("No tracking branch configured for current branch")?;
    merge_ff(repo, &tracking.to_string())
}

pub fn nearest_tag(repo: &gix::Repository, revspec: Option<&str>) -> Result<Option<String>> {
    let mut repo = repo.clone();
    repo.object_cache_size_if_unset(4 * 1024 * 1024);
    let commit = match revspec {
        Some(spec) => repo
            .rev_parse_single(spec)
            .with_context(|| format!("Failed to resolve revision '{spec}'"))?
            .object()
            .context("Failed to open revision object")?
            .try_into_commit()
            .context("Revision does not resolve to a commit")?,
        None => match repo.head_commit() {
            Ok(commit) => commit,
            Err(_) => return Ok(None),
        },
    };
    let resolution = match commit.describe().try_resolve() {
        Ok(Some(resolution)) => resolution,
        Ok(None) => return Ok(None),
        Err(_) => return Ok(None),
    };
    let describe = resolution.format()?.to_string();
    Ok(Some(
        describe
            .split_once('-')
            .map(|(tag, _)| tag.to_string())
            .unwrap_or(describe),
    ))
}

pub fn list_tags(repo: &gix::Repository) -> Result<Vec<String>> {
    let mut tags: Vec<String> = repo
        .references()
        .context("Failed to list references")?
        .tags()
        .context("Failed to list tags")?
        .flatten()
        .map(|tag| tag.name().shorten().to_string())
        .collect();
    sort_tags_newest_first(&mut tags);
    Ok(tags)
}

/// Order tags newest-first by numeric version precedence, breaking ties by
/// reverse lexicographic order.
///
/// Tags carrying no digits sort last, so `tags[0]` is the highest version
/// whenever any version-like tag exists.
pub fn sort_tags_newest_first(tags: &mut [String]) {
    tags.sort_by(|a, b| {
        version_sort_key(b)
            .cmp(&version_sort_key(a))
            .then_with(|| b.cmp(a))
    });
}

/// List the tags that actually exist on `remote_name`, newest first.
///
/// This contacts the remote over the network. Unlike [`list_tags`] the result is
/// unaffected by which tags happen to have been fetched into this clone, which
/// is what makes it usable for stamping a dependency pin that an outside
/// consumer has to be able to resolve.
pub fn remote_tags(repo: &gix::Repository, remote_name: &str) -> Result<Vec<String>> {
    let mut tags: Vec<String> = remote_refs(repo, remote_name)?
        .into_iter()
        .filter_map(|(name, _)| name.strip_prefix("refs/tags/").map(str::to_string))
        .collect();
    sort_tags_newest_first(&mut tags);
    Ok(tags)
}

pub fn total_commit_count(repo: &gix::Repository, revspec: Option<&str>) -> Result<u32> {
    let commit = match revspec {
        Some(spec) => resolve_commit_id(repo, spec)?,
        None => match repo.head_id() {
            Ok(id) => id.detach(),
            Err(_) => return Ok(0),
        },
    };
    let commit = repo.find_commit(commit).context("Failed to open commit")?;
    let mut count = 0u32;
    for ancestor in commit
        .ancestors()
        .all()
        .context("Failed to walk commit history")?
    {
        let _ = ancestor.context("Failed to inspect ancestor commit")?;
        count = count.saturating_add(1);
    }
    Ok(count)
}

pub fn commit_count_since(repo: &gix::Repository, revspec: &str) -> Result<u32> {
    if revspec == "v0" {
        return total_commit_count(repo, None);
    }
    let stop = resolve_commit_id(repo, revspec)?;
    let head = match repo.head_id() {
        Ok(id) => id.detach(),
        Err(_) => return Ok(0),
    };
    count_commits_until(repo, head, Some(stop))
}

pub fn change_count_since(repo: &gix::Repository, revspec: Option<&str>) -> Result<u32> {
    let stop = match revspec {
        Some(spec) => Some(resolve_commit_id(repo, spec)?),
        None => None,
    };
    let head = match repo.head_id() {
        Ok(id) => id.detach(),
        Err(_) => return Ok(0),
    };
    count_tree_changes_until(repo, head, stop)
}

pub fn count_commits_since_midnight(repo: &gix::Repository) -> Result<usize> {
    let now = chrono::Local::now();
    let midnight = now
        .date_naive()
        .and_hms_opt(0, 0, 0)
        .context("Failed to compute local midnight")?
        .and_local_timezone(*now.offset())
        .single()
        .context("Failed to resolve local midnight timezone")?
        .timestamp();
    let head = match repo.head_id() {
        Ok(id) => id.detach(),
        Err(_) => return Ok(0),
    };
    let commit = repo
        .find_commit(head)
        .context("Failed to open HEAD commit")?;
    let mut count = 0usize;
    for ancestor in commit
        .ancestors()
        .all()
        .context("Failed to walk commit history")?
    {
        let ancestor = ancestor.context("Failed to inspect ancestor commit")?;
        if ancestor.commit_time.unwrap_or(i64::MIN) < midnight {
            break;
        }
        count += 1;
    }
    Ok(count)
}

pub fn has_changes(repo: &gix::Repository) -> Result<bool> {
    Ok(!status_entries(repo)?.is_empty())
}

pub fn stage_paths(repo: &gix::Repository, paths: &[String]) -> Result<Vec<String>> {
    if paths.is_empty() {
        return Ok(Vec::new());
    }

    let workdir = repo
        .workdir()
        .context("Bare repositories are not supported")?;

    // `--` keeps a path that begins with a dash from being parsed as an option.
    let mut args = vec!["add".to_string(), "--".to_string()];
    for path in paths {
        args.push(path.clone());
    }

    let output = std::process::Command::new("git")
        .args(&args)
        .current_dir(workdir)
        .output()
        .context("Failed to execute git add")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("git add failed: {}", stderr.trim());
    }

    Ok(paths.to_vec())
}

pub fn checkout_branch(repo: &gix::Repository, branch_name: &str) -> Result<()> {
    let workdir = repo
        .workdir()
        .context("Bare repositories are not supported")?;

    let output = std::process::Command::new("git")
        .args(["checkout", branch_name])
        .current_dir(workdir)
        .output()
        .context("Failed to execute git checkout")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("git checkout failed: {}", stderr.trim());
    }

    Ok(())
}

pub fn create_branch(
    repo: &gix::Repository,
    branch_name: &str,
    from_ref: Option<&str>,
) -> Result<()> {
    let workdir = repo
        .workdir()
        .context("Bare repositories are not supported")?;

    let mut args = vec![
        "checkout".to_string(),
        "-b".to_string(),
        branch_name.to_string(),
    ];
    if let Some(from) = from_ref {
        args.push(from.to_string());
    }

    let output = std::process::Command::new("git")
        .args(&args)
        .current_dir(workdir)
        .output()
        .context("Failed to execute git checkout -b")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("git checkout -b failed: {}", stderr.trim());
    }

    Ok(())
}

pub fn delete_local_branch(repo: &gix::Repository, branch_name: &str, force: bool) -> Result<()> {
    let current = current_branch(repo).ok();
    if current.as_deref() == Some(branch_name) {
        bail!("Cannot delete the currently checked out branch '{branch_name}'");
    }

    let workdir = repo
        .workdir()
        .context("Bare repositories are not supported for branch deletion")?;

    let delete_flag = if force { "-D" } else { "-d" };
    let output = std::process::Command::new("git")
        .args(["branch", delete_flag, branch_name])
        .current_dir(workdir)
        .output()
        .context("Failed to execute git branch deletion")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("git branch {delete_flag} failed: {}", stderr.trim());
    }

    Ok(())
}

pub fn stage_all(repo: &gix::Repository) -> Result<()> {
    let workdir = repo
        .workdir()
        .context("Bare repositories are not supported")?;

    let output = std::process::Command::new("git")
        .args(["add", "-A"])
        .current_dir(workdir)
        .output()
        .context("Failed to execute git add -A")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("git add -A failed: {}", stderr.trim());
    }

    Ok(())
}

pub fn commit_all(repo: &gix::Repository, message: &str) -> Result<Option<String>> {
    let workdir = repo
        .workdir()
        .context("Bare repositories are not supported")?;

    let output = std::process::Command::new("git")
        .args(["commit", "-m", message])
        .current_dir(workdir)
        .output()
        .context("Failed to execute git commit")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        let stdout = String::from_utf8_lossy(&output.stdout);
        let combined = format!("{} {}", stderr.trim(), stdout.trim());
        if combined.contains("nothing to commit") || combined.contains("nothing added to commit") {
            return Ok(None);
        }
        let msg = if stderr.trim().is_empty() {
            stdout.trim().to_string()
        } else {
            stderr.trim().to_string()
        };
        bail!("git commit failed: {}", msg);
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    let commit_hash = stdout
        .lines()
        .find(|line| line.starts_with('['))
        .and_then(|line| line.split_whitespace().nth(1))
        .map(|s| s.to_string());

    Ok(commit_hash)
}

pub fn create_tag(repo: &gix::Repository, name: &str, message: &str) -> Result<()> {
    let workdir = repo
        .workdir()
        .context("Bare repositories are not supported")?;

    let output = std::process::Command::new("git")
        .args(["tag", "-a", name, "-m", message])
        .current_dir(workdir)
        .output()
        .context("Failed to execute git tag")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("git tag failed: {}", stderr.trim());
    }

    Ok(())
}

pub fn merge_ff(repo: &gix::Repository, branch: &str) -> Result<()> {
    let workdir = repo
        .workdir()
        .context("Bare repositories are not supported")?;

    let current_commit = repo
        .head_id()
        .context("Failed to resolve current HEAD")?
        .detach();
    let target_commit = resolve_commit_id(repo, branch)?;
    let merge_base = repo
        .merge_base(current_commit, target_commit)
        .context("Failed to compute merge base")?;
    if merge_base != current_commit {
        bail!("Fast-forward merge is not possible");
    }

    let output = std::process::Command::new("git")
        .args(["merge", "--ff-only", branch])
        .current_dir(workdir)
        .output()
        .context("Failed to execute git merge --ff-only")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("git merge --ff-only failed: {}", stderr.trim());
    }

    Ok(())
}

pub fn checkout_commit(repo: &gix::Repository, commit: gix::ObjectId) -> Result<()> {
    let workdir = repo
        .workdir()
        .context("Bare repositories are not supported")?;

    let output = std::process::Command::new("git")
        .args(["checkout", &commit.to_string()])
        .current_dir(workdir)
        .output()
        .context("Failed to execute git checkout")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("git checkout failed: {}", stderr.trim());
    }

    Ok(())
}

pub fn clone_repository(url: &str, destination: &Path) -> Result<gix::Repository> {
    clone_repository_impl(url, destination, None)
}

/// Clone with the git process rooted at `working_dir`.
///
/// Submodule URLs are interpreted relative to the repository that declares them,
/// so cloning a submodule must not inherit the caller's arbitrary current directory.
pub fn clone_repository_in(
    url: &str,
    destination: &Path,
    working_dir: &Path,
) -> Result<gix::Repository> {
    clone_repository_impl(url, destination, Some(working_dir))
}

fn clone_repository_impl(
    url: &str,
    destination: &Path,
    working_dir: Option<&Path>,
) -> Result<gix::Repository> {
    let destination = if destination.is_absolute() {
        destination.to_path_buf()
    } else {
        match working_dir {
            Some(dir) => dir.join(destination),
            None => destination.to_path_buf(),
        }
    };

    let mut command = std::process::Command::new("git");
    command.args(["clone", "--", url, destination.to_str().unwrap_or_default()]);
    if let Some(dir) = working_dir {
        command.current_dir(dir);
    }

    let output = command.output().context("Failed to execute git clone")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("git clone failed: {}", stderr.trim());
    }

    open_repo(&destination)
}

pub fn push_current_branch(
    repo: &gix::Repository,
    remote_name: Option<&str>,
    set_upstream: bool,
    force_with_lease: bool,
) -> Result<PushOutcome> {
    let workdir = repo
        .workdir()
        .context("Bare repositories are not supported for push")?;

    let remote = remote_name.unwrap_or("origin");

    let mut args: Vec<String> = vec!["push".to_string()];
    if set_upstream {
        args.push("--set-upstream".to_string());
    }
    if force_with_lease {
        args.push("--force-with-lease".to_string());
    }
    args.push(remote.to_string());

    // `--set-upstream` can only establish tracking if it is told which ref to
    // push. Without an explicit refspec git has no name to record and fails on
    // exactly the branches that need it — the ones with no upstream yet.
    if set_upstream {
        let branch = current_branch(repo)
            .context("Cannot set an upstream while HEAD is detached; check out a branch first")?;
        args.push(branch);
    }

    let output = std::process::Command::new("git")
        .args(&args)
        .current_dir(workdir)
        .output()
        .context("Failed to execute git push — is git installed?")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        // git push exits 0 when already up to date, so any failure is real
        bail!("git push failed: {}", stderr.trim());
    }

    let stderr = String::from_utf8_lossy(&output.stderr);
    if stderr.contains("Everything up-to-date") {
        Ok(PushOutcome::UpToDate)
    } else {
        Ok(PushOutcome::Updated)
    }
}

pub fn delete_remote_branch(
    repo: &gix::Repository,
    remote_name: Option<&str>,
    branch_name: &str,
) -> Result<()> {
    let workdir = repo
        .workdir()
        .context("Bare repositories are not supported for remote branch deletion")?;

    let remote = remote_name.unwrap_or("origin");
    let refspec = format!(":{branch_name}");

    let output = std::process::Command::new("git")
        .args(["push", remote, &refspec])
        .current_dir(workdir)
        .output()
        .context("Failed to execute git push — is git installed?")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("git push --delete failed: {}", stderr.trim());
    }

    Ok(())
}

fn resolve_commit_id(repo: &gix::Repository, spec: &str) -> Result<gix::ObjectId> {
    repo.rev_parse_single(spec)
        .with_context(|| format!("Failed to resolve revision '{spec}'"))?
        .object()
        .context("Failed to open resolved revision")?
        .peel_to_commit()
        .context("Revision does not resolve to a commit")
        .map(|commit| commit.id)
}

fn count_commits_until(
    repo: &gix::Repository,
    from: gix::ObjectId,
    stop: Option<gix::ObjectId>,
) -> Result<u32> {
    let commit = repo.find_commit(from).context("Failed to open commit")?;
    let mut count = 0u32;
    for ancestor in commit
        .ancestors()
        .all()
        .context("Failed to walk commit history")?
    {
        let ancestor = ancestor.context("Failed to inspect ancestor commit")?;
        if stop.is_some_and(|stop_id| ancestor.id == stop_id) {
            break;
        }
        count = count.saturating_add(1);
    }
    Ok(count)
}

fn count_tree_changes_until(
    repo: &gix::Repository,
    from: gix::ObjectId,
    stop: Option<gix::ObjectId>,
) -> Result<u32> {
    let commit = repo.find_commit(from).context("Failed to open commit")?;
    let mut total = 0u32;
    let mut current = Some(commit);
    while let Some(commit) = current {
        if stop.is_some_and(|stop_id| commit.id == stop_id) {
            break;
        }
        let tree_id = commit.tree_id().context("Failed to read commit tree id")?;
        let tree = repo.find_object(tree_id)?.peel_to_tree()?;
        let parent_tree = if let Some(parent_id) = commit.parent_ids().next() {
            let parent = repo
                .find_commit(parent_id)
                .context("Failed to open parent commit")?;
            Some(repo.find_object(parent.tree_id()?)?.peel_to_tree()?)
        } else {
            None
        };
        let changes = repo
            .diff_tree_to_tree(parent_tree.as_ref(), &tree, None)
            .context("Failed to diff commit trees")?;
        total = total.saturating_add(changes.len() as u32);

        let next_parent = commit.parent_ids().next();
        current = next_parent
            .map(|parent_id| {
                repo.find_commit(parent_id)
                    .context("Failed to open parent commit")
            })
            .transpose()?;
    }
    Ok(total)
}

fn version_sort_key(tag: &str) -> Vec<u64> {
    tag.trim_start_matches('v')
        .split(|ch: char| !ch.is_ascii_digit())
        .filter(|part| !part.is_empty())
        .map(|part| part.parse::<u64>().unwrap_or(0))
        .collect()
}

fn replace_or_append_config_section(config: &str, section: &str, replacement: &str) -> String {
    let mut output = String::new();
    let mut lines = config.lines().peekable();
    let header = format!("[{section}]");
    let mut replaced = false;

    while let Some(line) = lines.next() {
        let trimmed = line.trim();
        if trimmed == header {
            replaced = true;
            output.push_str(replacement);
            if !replacement.ends_with('\n') {
                output.push('\n');
            }
            while let Some(next) = lines.peek() {
                let next_trimmed = next.trim();
                if next_trimmed.starts_with('[') && next_trimmed.ends_with(']') {
                    break;
                }
                lines.next();
            }
            continue;
        }
        output.push_str(line);
        output.push('\n');
    }

    if !replaced {
        if !output.is_empty() && !output.ends_with("\n\n") {
            output.push('\n');
        }
        output.push_str(replacement);
        if !replacement.ends_with('\n') {
            output.push('\n');
        }
    }

    output
}