puregit 0.0.1

A pure-Rust implementation of git, in the spirit of libgit2, built on purecrypto. Object model, packfiles, refs, and the smart transport over HTTP and SSH — client and server.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
//! `git` — a thin command-line front end over the puregit library.
//!
//! This is intentionally minimal while the library grows: it wires a handful of
//! plumbing/porcelain commands to the crate's public API so the engine can be
//! exercised end to end. Commands are added as the corresponding library
//! capability lands; unimplemented ones print a clear message rather than
//! pretending to succeed.

use std::path::PathBuf;
use std::process::ExitCode;

use puregit::Repository;
use puregit::object::ObjectType;
use puregit::oid::{HashAlgo, ObjectId};

fn main() -> ExitCode {
    let args: Vec<String> = std::env::args().skip(1).collect();
    let Some(command) = args.first() else {
        eprintln!("{USAGE}");
        // No command is a usage error; git exits 129 for these.
        return ExitCode::from(129);
    };

    // Meta commands short-circuit with their own exit codes.
    match command.as_str() {
        "--version" | "version" => {
            println!("puregit {}", env!("CARGO_PKG_VERSION"));
            return ExitCode::SUCCESS;
        }
        "--help" => {
            println!("{USAGE}");
            return ExitCode::SUCCESS;
        }
        "help" => return cmd_help(&args[1..]),
        _ => {}
    }

    let result = match command.as_str() {
        "init" => cmd_init(&args[1..]),
        "hash-object" => cmd_hash_object(&args[1..]),
        "cat-file" => cmd_cat_file(&args[1..]),
        "rev-parse" => cmd_rev_parse(&args[1..]),
        "add" => cmd_add(&args[1..]),
        "rm" => cmd_rm(&args[1..]),
        "mv" => cmd_mv(&args[1..]),
        "write-tree" => cmd_write_tree(&args[1..]),
        "read-tree" => cmd_read_tree(&args[1..]),
        "mktree" => cmd_mktree(&args[1..]),
        "commit-tree" => cmd_commit_tree(&args[1..]),
        "commit" => cmd_commit(&args[1..]),
        "log" => cmd_log(&args[1..]),
        "reflog" => cmd_reflog(&args[1..]),
        "show" => cmd_show(&args[1..]),
        "status" => cmd_status(&args[1..]),
        "branch" => cmd_branch(&args[1..]),
        "checkout" => cmd_checkout(&args[1..]),
        "reset" => cmd_reset(&args[1..]),
        "gc" | "repack" => cmd_gc(&args[1..]),
        "fsck" => cmd_fsck(&args[1..]),
        "prune" => cmd_prune(&args[1..]),
        "commit-graph" => cmd_commit_graph(&args[1..]),
        "multi-pack-index" => cmd_multi_pack_index(&args[1..]),
        "worktree" => cmd_worktree(&args[1..]),
        "merge-base" => cmd_merge_base(&args[1..]),
        "merge" => cmd_merge(&args[1..]),
        "lfs" => cmd_lfs(&args[1..]),
        "tag" => cmd_tag(&args[1..]),
        "ls-tree" => cmd_ls_tree(&args[1..]),
        "diff-tree" => cmd_diff_tree(&args[1..]),
        "diff" => cmd_diff(&args[1..]),
        "unpack-objects" => cmd_unpack_objects(&args[1..]),
        "verify-pack" => cmd_verify_pack(&args[1..]),
        "clone" => cmd_clone(&args[1..]),
        "completion" => cmd_completion(&args[1..]),
        other => {
            eprintln!("git: '{other}' is not a git command. See 'git help'.");
            // git returns 1 for an unknown command (distinct from a usage error).
            return ExitCode::from(1);
        }
    };

    match result {
        Ok(()) => ExitCode::SUCCESS,
        Err(msg) => {
            eprintln!("error: {msg}");
            // Parity with git: a usage error exits 129, any other fatal error 128.
            if msg.contains("usage:") {
                ExitCode::from(129)
            } else {
                ExitCode::from(128)
            }
        }
    }
}

const USAGE: &str = "\
usage: git <command> [<args>]

commands:
    init [<dir>]                 create an empty repository
    hash-object [-w] <file>      compute an object id (and optionally store it)
    cat-file -t|-p|-s <oid>      show an object's type, contents, or size
    cat-file --batch            print type/size/contents for oids read on stdin
    rev-parse <ref>             resolve a ref to an object id
    add <file>...               stage working-tree files (or deletions)
    rm <file>...                remove files from the index and work tree
    mv <source> <dest>          move/rename a tracked file
    write-tree                  write the index out as a tree, print its id
    read-tree <tree-ish>        load a tree into the index (replacing it)
    mktree                      read `ls-tree` lines from stdin, write a tree
    commit-tree <tree> [-p <parent>]... [-m <msg>]
                                create a commit object, print its id
    commit -m <msg>             commit the staged index
    log                         show commit history from HEAD
    reflog [<ref>]              show the update log of a ref (default HEAD)
    show [<object>]             show a commit (with patch), tag, tree, or blob
    status                      show working-tree status
    branch <name>               create a branch at HEAD
    checkout <branch>           switch to a branch (updates the work tree)
    reset [--soft|--mixed|--hard] [<commit>]
                                move HEAD (and index/work tree) to a commit
    gc                          pack loose objects and prune them
    fsck                        verify object connectivity and integrity
    prune                       delete unreachable loose objects
    commit-graph write|verify   write or verify the commit-graph cache
    multi-pack-index write|verify  write or verify the multi-pack-index
    worktree add <path> [<commit>] | list   manage linked worktrees
    merge-base <a> <b>          print the best common ancestor of two commits
    merge <branch>              merge a branch into the current branch
    lfs track <pattern>         track a path pattern with Git LFS
    lfs ls-files                list LFS-pointer files in the index
    lfs pull                    download LFS objects for the current checkout
    tag <name> [<commit>]       create a lightweight tag (or list tags)
    ls-tree <tree-ish>          list the entries of a tree
    diff-tree <a> <b>           name-status diff between two commits/trees
    diff                        unified diff of the work tree vs the index
    unpack-objects <pack>       explode a packfile into loose objects
    verify-pack <pack>          check a packfile against its .idx
    clone <url> [<dir>]         clone a remote repository (http/https)
    completion [bash]           print a shell completion script
    version                     print the puregit version";

/// Handles `git help [--man] [<command>]`.
///
/// `--man` writes a roff-formatted `git.1` man page to stdout (pipe it to a file
/// under a `man1/` directory to install it); `git help <command>` prints that
/// command's usage line from [`USAGE`]; bare `git help` prints the full usage.
fn cmd_help(args: &[String]) -> ExitCode {
    match args.first().map(|s| s.as_str()) {
        Some("--man") => {
            print!("{}", manpage());
            ExitCode::SUCCESS
        }
        Some(topic) => {
            // Print the usage line(s) whose command column names this topic.
            let mut printed = false;
            for line in USAGE.lines() {
                // `split_whitespace` already skips the leading indentation.
                if line.split_whitespace().next().is_some_and(|w| w == topic) {
                    println!("{}", line.trim_start());
                    printed = true;
                }
            }
            if !printed {
                eprintln!("git help: no such command '{topic}'");
                return ExitCode::from(129);
            }
            ExitCode::SUCCESS
        }
        None => {
            println!("{USAGE}");
            ExitCode::SUCCESS
        }
    }
}

/// Renders the `git.1` man page as roff.
///
/// Pure-Rust and dependency-free: the command table is derived from [`USAGE`], so
/// the page stays in sync with the implemented subcommands, and the EXIT STATUS
/// section documents the git-compatible codes `main` returns.
fn manpage() -> String {
    let version = env!("CARGO_PKG_VERSION");
    let mut out = String::new();
    // Header: title, manual section 1, and the source/version footer.
    out.push_str(&format!(
        ".TH PUREGIT 1 \"\" \"puregit {version}\" \"puregit Manual\"\n"
    ));
    out.push_str(".SH NAME\n");
    out.push_str("puregit \\- pure-Rust git command-line front end\n");
    out.push_str(".SH SYNOPSIS\n");
    out.push_str(".B puregit\n");
    out.push_str(".I command\n");
    out.push_str("[\\fIargs\\fR]\n");
    out.push_str(".SH DESCRIPTION\n");
    out.push_str(
        "A minimal git command-line interface over the pure-Rust puregit library. \
It maintains repositories and clones, fetches, and pushes over HTTP and SSH \
without any C toolchain.\n",
    );
    out.push_str(".SH COMMANDS\n");
    // Each usage line becomes a tagged paragraph: the command column is the tag,
    // the rest is the description.
    for line in USAGE.lines() {
        let trimmed = line.trim_start();
        // Skip the header, the "commands:" label, and blank lines.
        if trimmed.is_empty() || trimmed.starts_with("usage:") || trimmed == "commands:" {
            continue;
        }
        // A continuation line (a wrapped synopsis) has no command column.
        if !line.starts_with("    ") {
            continue;
        }
        // Split the synopsis (the command column) from its description at the
        // first run of two or more spaces, so only the synopsis is bold.
        let (synopsis, description) = match trimmed.find("  ") {
            Some(i) => (trimmed[..i].trim_end(), trimmed[i..].trim_start()),
            None => (trimmed, ""),
        };
        out.push_str(".TP\n.B ");
        out.push_str(&roff_escape(synopsis));
        out.push('\n');
        if !description.is_empty() {
            out.push_str(&roff_escape(description));
            out.push('\n');
        }
    }
    out.push_str(".SH EXIT STATUS\n");
    out.push_str(".TP\n.B 0\nSuccess.\n");
    out.push_str(
        ".TP\n.B 1\nA controlled negative result \\(em \
\\fBdiff \\-\\-exit\\-code\\fR found changes, or \
\\fBmerge\\-base \\-\\-is\\-ancestor\\fR was false \\(em or an unknown command.\n",
    );
    out.push_str(".TP\n.B 128\nA fatal error (the operation could not be performed).\n");
    out.push_str(".TP\n.B 129\nA usage error (invalid arguments).\n");
    out.push_str(".SH SEE ALSO\n");
    out.push_str(".BR git (1)\n");
    out
}

/// Escapes a string for a roff line: backslashes (roff's escape introducer) are
/// doubled and a leading control character (`.`/`'`) is neutralised so the text
/// is never taken for a request.
fn roff_escape(s: &str) -> String {
    let mut out = s.replace('\\', "\\\\");
    if out.starts_with('.') || out.starts_with('\'') {
        out.insert_str(0, "\\&");
    }
    out
}

/// The subcommands offered for shell completion (kept in sync with `main`'s
/// dispatch and `USAGE`).
const SUBCOMMANDS: &[&str] = &[
    "init",
    "hash-object",
    "cat-file",
    "rev-parse",
    "add",
    "rm",
    "mv",
    "write-tree",
    "read-tree",
    "mktree",
    "commit-tree",
    "commit",
    "log",
    "reflog",
    "show",
    "status",
    "branch",
    "checkout",
    "reset",
    "gc",
    "repack",
    "fsck",
    "prune",
    "merge-base",
    "merge",
    "lfs",
    "tag",
    "ls-tree",
    "diff-tree",
    "diff",
    "unpack-objects",
    "verify-pack",
    "clone",
    "completion",
    "version",
];

/// `completion [bash]` — print a shell completion script for this `git` binary.
/// Only bash is supported today; source the output (e.g. from `~/.bashrc`).
fn cmd_completion(args: &[String]) -> Result<(), String> {
    let shell = args.first().map(String::as_str).unwrap_or("bash");
    if shell != "bash" {
        return Err(format!(
            "completion: unsupported shell '{shell}' (try 'bash')"
        ));
    }
    let words = SUBCOMMANDS.join(" ");
    // A minimal completion: complete the first argument against the subcommand
    // list; leave later words to the filesystem default.
    println!(
        "_puregit_git() {{\n  \
           local cur=\"${{COMP_WORDS[COMP_CWORD]}}\"\n  \
           if [ \"$COMP_CWORD\" -eq 1 ]; then\n    \
             COMPREPLY=( $(compgen -W \"{words}\" -- \"$cur\") )\n  \
           fi\n\
         }}\n\
         complete -o default -F _puregit_git git"
    );
    Ok(())
}

fn cmd_init(args: &[String]) -> Result<(), String> {
    let dir = args
        .first()
        .map(PathBuf::from)
        .unwrap_or_else(|| PathBuf::from("."));
    let repo = Repository::init(&dir).map_err(|e| e.to_string())?;
    println!(
        "Initialized empty Git repository in {}",
        repo.git_dir().display()
    );
    Ok(())
}

fn cmd_hash_object(args: &[String]) -> Result<(), String> {
    let mut write = false;
    let mut file = None;
    for arg in args {
        match arg.as_str() {
            "-w" => write = true,
            other => file = Some(other.to_string()),
        }
    }
    let file = file.ok_or("hash-object: missing <file>")?;
    let content = std::fs::read(&file).map_err(|e| format!("reading {file}: {e}"))?;

    if write {
        let repo = open_here()?;
        let id = repo
            .write_object(ObjectType::Blob, &content)
            .map_err(|e| e.to_string())?;
        println!("{id}");
    } else {
        let id = puregit::hash::hash_object(HashAlgo::Sha1, ObjectType::Blob, &content);
        println!("{id}");
    }
    Ok(())
}

fn cmd_cat_file(args: &[String]) -> Result<(), String> {
    if args.first().map(String::as_str) == Some("--batch") {
        return cmd_cat_file_batch();
    }
    if args.len() < 2 {
        return Err("cat-file: usage: cat-file -t|-p|-s <oid> | --batch".into());
    }
    let flag = &args[0];
    let repo = open_here()?;
    let id = ObjectId::from_hex(repo.algo(), &args[1]).map_err(|e| e.to_string())?;
    let (ty, payload) = repo.objects_read(&id).map_err(|e| e.to_string())?;

    match flag.as_str() {
        "-t" => println!("{ty}"),
        "-s" => println!("{}", payload.len()),
        "-p" => {
            use std::io::Write;
            std::io::stdout()
                .write_all(&payload)
                .map_err(|e| e.to_string())?;
        }
        other => return Err(format!("cat-file: unknown flag '{other}'")),
    }
    Ok(())
}

/// `cat-file --batch` — read object names on stdin (one per line) and, for each,
/// print `<oid> SP <type> SP <size> LF` followed by the raw contents and a LF.
/// An unresolvable name prints `<name> missing`, matching git.
fn cmd_cat_file_batch() -> Result<(), String> {
    use std::io::{BufRead, Write};

    let repo = open_here()?;
    let stdin = std::io::stdin();
    let mut out = std::io::stdout();
    for line in stdin.lock().lines() {
        let line = line.map_err(|e| e.to_string())?;
        let rev = line.trim();
        if rev.is_empty() {
            continue;
        }
        let resolved = repo
            .refs()
            .resolve(rev)
            .or_else(|_| ObjectId::from_hex(repo.algo(), rev).map_err(|e| e.to_string()))
            .ok()
            .and_then(|id| repo.objects_read(&id).ok().map(|(ty, p)| (id, ty, p)));
        match resolved {
            Some((id, ty, payload)) => {
                writeln!(out, "{id} {ty} {}", payload.len()).map_err(|e| e.to_string())?;
                out.write_all(&payload).map_err(|e| e.to_string())?;
                out.write_all(b"\n").map_err(|e| e.to_string())?;
            }
            None => {
                writeln!(out, "{rev} missing").map_err(|e| e.to_string())?;
            }
        }
    }
    Ok(())
}

fn cmd_rev_parse(args: &[String]) -> Result<(), String> {
    let name = args.first().ok_or("rev-parse: missing <ref>")?;
    let repo = open_here()?;
    let id = repo.refs().resolve(name).map_err(|e| e.to_string())?;
    println!("{id}");
    Ok(())
}

fn cmd_add(args: &[String]) -> Result<(), String> {
    if args.is_empty() {
        return Err("add: nothing specified".into());
    }
    let repo = open_here()?;
    for path in args {
        repo.add_path(path).map_err(|e| e.to_string())?;
    }
    Ok(())
}

fn cmd_rm(args: &[String]) -> Result<(), String> {
    if args.is_empty() {
        return Err("rm: nothing specified".into());
    }
    let repo = open_here()?;
    for path in args {
        repo.remove_path(path).map_err(|e| e.to_string())?;
        println!("rm '{path}'");
    }
    Ok(())
}

fn cmd_mv(args: &[String]) -> Result<(), String> {
    if args.len() < 2 {
        return Err("mv: usage: mv <source> <dest>".into());
    }
    let repo = open_here()?;
    repo.mv(&args[0], &args[1]).map_err(|e| e.to_string())
}

fn cmd_write_tree(_args: &[String]) -> Result<(), String> {
    use puregit::tree_builder::write_tree_from_index;
    let repo = open_here()?;
    let index = repo.index().map_err(|e| e.to_string())?;
    let id = write_tree_from_index(repo.objects(), &index).map_err(|e| e.to_string())?;
    println!("{id}");
    Ok(())
}

/// `read-tree <tree-ish>` — resolve a tree/commit and load its tree into the
/// index, replacing the current staged contents.
fn cmd_read_tree(args: &[String]) -> Result<(), String> {
    use puregit::object::Object;
    let rev = args.first().ok_or("read-tree: missing <tree-ish>")?;
    let repo = open_here()?;
    let id = repo
        .refs()
        .resolve(rev)
        .or_else(|_| ObjectId::from_hex(repo.algo(), rev).map_err(|e| e.to_string()))?;
    let tree = match repo.read_object(&id).map_err(|e| e.to_string())? {
        Object::Commit(c) => c.tree,
        Object::Tree(_) => id,
        other => {
            return Err(format!(
                "read-tree: {} is not a tree or commit",
                other.object_type()
            ));
        }
    };
    repo.read_tree(&tree).map_err(|e| e.to_string())
}

/// `mktree` — read `ls-tree`-style lines from stdin and write a single tree
/// object, printing its id. Each line is `<mode> SP <type> SP <sha> TAB <name>`
/// (the `<type>` column is accepted but ignored; the mode determines the entry
/// kind). Entries are canonically sorted by `Tree::serialize`, so the input
/// order does not matter.
fn cmd_mktree(_args: &[String]) -> Result<(), String> {
    use puregit::object::tree::FileMode;
    use puregit::object::{Tree, TreeEntry};
    use std::io::Read;

    let repo = open_here()?;
    let mut input = String::new();
    std::io::stdin()
        .read_to_string(&mut input)
        .map_err(|e| format!("mktree: reading stdin: {e}"))?;

    let mut entries = Vec::new();
    for line in input.lines() {
        if line.trim().is_empty() {
            continue;
        }
        // Split "<mode> <type> <sha>\t<name>": the name is after the TAB, the
        // three space-separated fields are before it.
        let (meta, name) = line
            .split_once('\t')
            .ok_or_else(|| format!("mktree: no TAB before name in: {line}"))?;
        let mut fields = meta.split_whitespace();
        let mode = fields
            .next()
            .ok_or_else(|| format!("mktree: missing mode in: {line}"))?;
        let _kind = fields.next(); // "blob"/"tree"/"commit" — informational.
        let sha = fields
            .next()
            .ok_or_else(|| format!("mktree: missing sha in: {line}"))?;

        entries.push(TreeEntry {
            mode: FileMode::from_octal(mode.as_bytes()).map_err(|e| e.to_string())?,
            name: name.as_bytes().to_vec(),
            id: ObjectId::from_hex(repo.algo(), sha).map_err(|e| e.to_string())?,
        });
    }

    let id = repo
        .write_object(ObjectType::Tree, &Tree { entries }.serialize())
        .map_err(|e| e.to_string())?;
    println!("{id}");
    Ok(())
}

/// `commit-tree <tree> [-p <parent>]... [-m <msg>]` — create a commit object for
/// an existing tree and print its id, without touching `HEAD` or the index.
/// The message comes from `-m` (repeatable, joined by blank lines) or, if none
/// is given, from stdin.
fn cmd_commit_tree(args: &[String]) -> Result<(), String> {
    use puregit::object::{Commit, Object};
    use std::io::Read;

    let mut tree_arg = None;
    let mut parents_hex = Vec::new();
    let mut messages = Vec::new();
    let mut i = 0;
    while i < args.len() {
        match args[i].as_str() {
            "-p" => {
                let p = args.get(i + 1).ok_or("commit-tree: -p needs a <parent>")?;
                parents_hex.push(p.clone());
                i += 2;
            }
            "-m" => {
                let m = args.get(i + 1).ok_or("commit-tree: -m needs a <message>")?;
                messages.push(m.clone());
                i += 2;
            }
            other => {
                if tree_arg.is_some() {
                    return Err(format!("commit-tree: unexpected argument '{other}'"));
                }
                tree_arg = Some(other.to_string());
                i += 1;
            }
        }
    }
    let tree_arg = tree_arg.ok_or("commit-tree: missing <tree>")?;

    let repo = open_here()?;
    let tree = ObjectId::from_hex(repo.algo(), &tree_arg).map_err(|e| e.to_string())?;
    // Validate the id names a tree so a typo fails loudly rather than producing
    // a dangling commit.
    match repo.read_object(&tree).map_err(|e| e.to_string())? {
        Object::Tree(_) => {}
        other => {
            return Err(format!(
                "commit-tree: {tree} is a {}, not a tree",
                other.object_type()
            ));
        }
    }

    let mut parents = Vec::new();
    for p in &parents_hex {
        parents.push(ObjectId::from_hex(repo.algo(), p).map_err(|e| e.to_string())?);
    }

    let mut message = if messages.is_empty() {
        let mut buf = String::new();
        std::io::stdin()
            .read_to_string(&mut buf)
            .map_err(|e| format!("commit-tree: reading stdin: {e}"))?;
        buf
    } else {
        messages.join("\n\n")
    };
    if !message.ends_with('\n') {
        message.push('\n');
    }

    let who = signature_now(&repo)?;
    let commit = Commit {
        tree,
        parents,
        author: who.clone(),
        committer: who,
        extra_headers: Vec::new(),
        message: message.into_bytes(),
    };
    let id = repo
        .write_object(ObjectType::Commit, &commit.serialize())
        .map_err(|e| e.to_string())?;
    println!("{id}");
    Ok(())
}

fn cmd_commit(args: &[String]) -> Result<(), String> {
    // Minimal flag parsing: `-m <message>`.
    let mut message = None;
    let mut i = 0;
    while i < args.len() {
        if args[i] == "-m" {
            message = args.get(i + 1).cloned();
            i += 2;
        } else {
            i += 1;
        }
    }
    let message = message.ok_or("commit: -m <message> is required")?;

    let repo = open_here()?;
    let who = signature_now(&repo)?;
    let mut body = message.into_bytes();
    body.push(b'\n');
    let id = repo
        .commit(&body, who.clone(), who)
        .map_err(|e| e.to_string())?;
    println!("committed {id}");
    Ok(())
}

fn cmd_log(_args: &[String]) -> Result<(), String> {
    use puregit::walk::RevWalk;
    let repo = open_here()?;
    let head = match repo.head_id() {
        Ok(h) => h,
        Err(_) => return Err("log: HEAD does not point at any commit yet".into()),
    };
    for item in RevWalk::new(repo.objects(), &[head]) {
        let (id, commit) = item.map_err(|e| e.to_string())?;
        let summary = String::from_utf8_lossy(commit.summary());
        let author = String::from_utf8_lossy(&commit.author.name);
        println!("commit {id}");
        println!("Author: {author}");
        println!("\n    {summary}\n");
    }
    Ok(())
}

/// `show [<object>]` (default `HEAD`) — display an object. A commit prints its
/// header and message followed by a unified patch against its first parent; a
/// tag prints its header and then shows the object it points at; a tree lists
/// its entries; a blob prints its raw contents.
fn cmd_show(args: &[String]) -> Result<(), String> {
    let rev = args.first().map(String::as_str).unwrap_or("HEAD");
    let repo = open_here()?;
    let id = repo
        .refs()
        .resolve(rev)
        .or_else(|_| ObjectId::from_hex(repo.algo(), rev).map_err(|e| e.to_string()))?;
    show_object(&repo, &id)
}

/// Renders one object for `show`, recursing through a tag to its target.
fn show_object(repo: &Repository, id: &ObjectId) -> Result<(), String> {
    use puregit::object::Object;
    use std::io::Write;

    match repo.read_object(id).map_err(|e| e.to_string())? {
        Object::Commit(c) => {
            println!("commit {id}");
            println!(
                "Author: {} <{}>",
                String::from_utf8_lossy(&c.author.name),
                String::from_utf8_lossy(&c.author.email)
            );
            println!();
            for line in String::from_utf8_lossy(&c.message).lines() {
                println!("    {line}");
            }
            println!();

            // Unified patch against the first parent (an empty tree for a root
            // commit), built from flattened path → blob maps of both trees.
            let new_map =
                puregit::walk::flatten_tree(repo.objects(), &c.tree).map_err(|e| e.to_string())?;
            let mut old_map = std::collections::BTreeMap::new();
            if let Some(parent) = c.parents.first()
                && let Object::Commit(pc) = repo.read_object(parent).map_err(|e| e.to_string())?
            {
                old_map = puregit::walk::flatten_tree(repo.objects(), &pc.tree)
                    .map_err(|e| e.to_string())?;
            }
            print_patch(repo, &old_map, &new_map)
        }
        Object::Tag(t) => {
            println!("tag {}", String::from_utf8_lossy(&t.name));
            if let Some(tagger) = &t.tagger {
                println!(
                    "Tagger: {} <{}>",
                    String::from_utf8_lossy(&tagger.name),
                    String::from_utf8_lossy(&tagger.email)
                );
            }
            println!();
            for line in String::from_utf8_lossy(&t.message).lines() {
                println!("{line}");
            }
            println!();
            // Show the object the tag points at (a commit, usually).
            show_object(repo, &t.object)
        }
        Object::Tree(t) => {
            for entry in &t.entries {
                let kind = if entry.mode.is_tree() { "tree" } else { "blob" };
                println!(
                    "{:0>6} {} {}\t{}",
                    entry.mode.as_octal(),
                    kind,
                    entry.id,
                    String::from_utf8_lossy(&entry.name)
                );
            }
            Ok(())
        }
        Object::Blob(bytes) => std::io::stdout()
            .write_all(&bytes)
            .map_err(|e| e.to_string()),
    }
}

/// Prints a `git show`-style unified patch between two flattened trees.
fn print_patch(
    repo: &Repository,
    old: &std::collections::BTreeMap<Vec<u8>, (puregit::object::FileMode, ObjectId)>,
    new: &std::collections::BTreeMap<Vec<u8>, (puregit::object::FileMode, ObjectId)>,
) -> Result<(), String> {
    use puregit::object::FileMode;

    // The union of paths, in sorted order (both maps are already ordered).
    let mut paths: Vec<&Vec<u8>> = old.keys().chain(new.keys()).collect();
    paths.sort();
    paths.dedup();

    for path in paths {
        let o = old.get(path);
        let n = new.get(path);
        if o.map(|(_, i)| i) == n.map(|(_, i)| i) {
            continue; // unchanged (same blob id)
        }
        let name = String::from_utf8_lossy(path);
        // Submodule (gitlink) entries have no local blob to diff; note the id
        // change and move on.
        let is_gitlink =
            |e: Option<&(FileMode, ObjectId)>| matches!(e, Some((FileMode::Gitlink, _)));
        if is_gitlink(o) || is_gitlink(n) {
            println!("Submodule {name} changed");
            continue;
        }
        let read = |e: Option<&(FileMode, ObjectId)>| -> Result<Vec<u8>, String> {
            match e {
                Some((_, id)) => repo
                    .objects_read(id)
                    .map(|(_, p)| p)
                    .map_err(|err| err.to_string()),
                None => Ok(Vec::new()),
            }
        };
        let old_bytes = read(o)?;
        let new_bytes = read(n)?;
        println!("diff --git a/{name} b/{name}");
        let patch = puregit::diff::unified(
            &old_bytes,
            &new_bytes,
            &format!("a/{name}"),
            &format!("b/{name}"),
            3,
        );
        print!("{patch}");
    }
    Ok(())
}

/// `reflog [<ref>]` — print a ref's update log; `reflog expire [--expire=<secs>]
/// [<ref>]` — drop entries older than `<secs>` ago (default 90 days).
fn cmd_reflog(args: &[String]) -> Result<(), String> {
    if args.first().map(String::as_str) == Some("expire") {
        return cmd_reflog_expire(&args[1..]);
    }
    let refname = args.first().map(String::as_str).unwrap_or("HEAD");
    let repo = open_here()?;
    let path = repo.git_dir().join("logs").join(refname);
    let content = std::fs::read_to_string(&path).unwrap_or_default();

    // Entries are appended oldest-first; git numbers them newest-first as @{0}.
    let lines: Vec<&str> = content.lines().collect();
    for (i, line) in lines.iter().rev().enumerate() {
        let Some((meta, message)) = line.split_once('\t') else {
            continue;
        };
        // meta = "<old> <new> <name> <email> <time> <tz>"; we want <new>.
        let new = meta.split_whitespace().nth(1).unwrap_or("");
        let short = &new[..new.len().min(8)];
        println!("{short} {refname}@{{{i}}}: {message}");
    }
    Ok(())
}

/// `reflog expire [--expire=<seconds>] [<ref>]` — drop entries in `logs/<ref>`
/// older than `<seconds>` ago (default 90 days), matching `git reflog expire`.
fn cmd_reflog_expire(args: &[String]) -> Result<(), String> {
    use std::time::{SystemTime, UNIX_EPOCH};
    let mut seconds: i64 = 90 * 24 * 60 * 60; // 90 days
    let mut refname = "HEAD".to_string();
    for arg in args {
        if let Some(v) = arg.strip_prefix("--expire=") {
            seconds = v
                .parse()
                .map_err(|_| format!("reflog expire: bad --expire value {v:?}"))?;
        } else {
            refname = arg.clone();
        }
    }
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .unwrap_or(0);
    let repo = open_here()?;
    let removed = repo
        .reflog_expire(&refname, now - seconds)
        .map_err(|e| e.to_string())?;
    eprintln!(
        "reflog expire: dropped {removed} entr{}",
        if removed == 1 { "y" } else { "ies" }
    );
    Ok(())
}

/// Builds an author/committer signature from `user.name`/`user.email` in config
/// (falling back to the `GIT_AUTHOR_*` env vars, then placeholders) stamped with
/// the current wall-clock time in UTC.
fn signature_now(repo: &Repository) -> Result<puregit::object::Signature, String> {
    use std::time::{SystemTime, UNIX_EPOCH};
    let cfg = repo.config().map_err(|e| e.to_string())?;
    let name = cfg
        .get("user", None, "name")
        .map(String::from)
        .or_else(|| std::env::var("GIT_AUTHOR_NAME").ok())
        .unwrap_or_else(|| "puregit".into());
    let email = cfg
        .get("user", None, "email")
        .map(String::from)
        .or_else(|| std::env::var("GIT_AUTHOR_EMAIL").ok())
        .unwrap_or_else(|| "puregit@localhost".into());
    let time = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .unwrap_or(0);
    Ok(puregit::object::Signature {
        name: name.into_bytes(),
        email: email.into_bytes(),
        time,
        tz: b"+0000".to_vec(),
    })
}

fn cmd_clone(args: &[String]) -> Result<(), String> {
    let url = args.first().ok_or("clone: missing <url>")?;
    let dir = match args.get(1) {
        Some(d) => d.clone(),
        None => dir_from_url(url),
    };

    if url.starts_with("http://") || url.starts_with("https://") {
        return clone_http(url, &dir);
    }
    if url.starts_with("ssh://") || is_scp_like(url) {
        return clone_ssh(url, &dir);
    }
    Err(format!("clone: unsupported URL scheme in '{url}'"))
}

/// Whether `url` looks like an scp-style SSH target (`user@host:path`) rather
/// than a local path — i.e. it has a `:` before any `/`.
fn is_scp_like(url: &str) -> bool {
    match (url.find(':'), url.find('/')) {
        (Some(colon), Some(slash)) => colon < slash,
        (Some(_), None) => true,
        _ => false,
    }
}

#[cfg(feature = "ssh")]
fn clone_ssh(url: &str, dir: &str) -> Result<(), String> {
    use puregit::oid::HashAlgo;
    use puregit::transport::ssh::SshTransport;
    let mut transport = SshTransport::from_url(url, HashAlgo::Sha1).map_err(|e| e.to_string())?;
    if let Ok(pw) = std::env::var("GIT_SSH_PASSWORD") {
        transport = transport.with_password(pw);
    } else if let Ok(key) = std::env::var("GIT_SSH_KEY") {
        transport = transport.with_key(key, std::env::var("GIT_SSH_KEY_PASSPHRASE").ok());
    }
    let repo = puregit::client::clone(dir, &mut transport).map_err(|e| e.to_string())?;
    println!(
        "Cloned into '{}' (HEAD {})",
        dir,
        repo.head_id()
            .map(|h| h.to_hex_short(8))
            .unwrap_or_else(|_| "unborn".into())
    );
    write_origin_config(&repo, url)?;
    Ok(())
}

/// Records `[remote "origin"]` (URL + default fetch refspec) in a freshly cloned
/// repository's config, so later fetches and `git lfs pull` know the origin.
#[cfg(any(feature = "http", feature = "ssh"))]
fn write_origin_config(repo: &Repository, url: &str) -> Result<(), String> {
    use puregit::refs::Reference;

    let mut cfg = repo.config().map_err(|e| e.to_string())?;
    cfg.set("remote", Some("origin"), "url", url);
    cfg.set(
        "remote",
        Some("origin"),
        "fetch",
        &puregit::remote::Remote::default_fetch("origin").to_string_form(),
    );
    // Set the checked-out branch to track origin's matching branch.
    if let Ok(Reference::Symbolic(head_ref)) = repo.head()
        && let Some(branch) = head_ref.strip_prefix("refs/heads/")
    {
        cfg.set("branch", Some(branch), "remote", "origin");
        cfg.set("branch", Some(branch), "merge", &head_ref);
    }
    repo.write_config(&cfg).map_err(|e| e.to_string())
}

#[cfg(not(feature = "ssh"))]
fn clone_ssh(_url: &str, _dir: &str) -> Result<(), String> {
    Err("clone: this build lacks the `ssh` feature".into())
}

#[cfg(feature = "http")]
fn clone_http(url: &str, dir: &str) -> Result<(), String> {
    use puregit::oid::HashAlgo;
    use puregit::transport::http::HttpTransport;
    let mut transport = HttpTransport::new(url.to_string(), HashAlgo::Sha1);
    let repo = puregit::client::clone(dir, &mut transport).map_err(|e| e.to_string())?;
    println!(
        "Cloned into '{}' (HEAD {})",
        dir,
        repo.head_id()
            .map(|h| h.to_hex_short(8))
            .unwrap_or_else(|_| "unborn".into())
    );

    // Record the origin URL + default fetch refspec so `git lfs pull` and
    // future fetches know the origin.
    write_origin_config(&repo, url)?;

    // Best-effort: fetch any LFS objects the checkout left as pointers.
    match cmd_lfs_pull(&repo) {
        Ok(()) => {}
        Err(e) => eprintln!("warning: lfs pull skipped: {e}"),
    }
    Ok(())
}

#[cfg(not(feature = "http"))]
fn clone_http(_url: &str, _dir: &str) -> Result<(), String> {
    Err("clone: this build lacks the `http` feature".into())
}

/// Derives a directory name from a clone URL (last path segment, sans `.git`).
fn dir_from_url(url: &str) -> String {
    let trimmed = url.trim_end_matches('/');
    let last = trimmed.rsplit('/').next().unwrap_or("repo");
    last.strip_suffix(".git").unwrap_or(last).to_string()
}

fn cmd_status(args: &[String]) -> Result<(), String> {
    use puregit::status::{Change, status};
    let repo = open_here()?;
    let st = status(&repo).map_err(|e| e.to_string())?;

    if args
        .iter()
        .any(|a| a == "--porcelain" || a == "-s" || a == "--short")
    {
        return status_porcelain(&st);
    }

    if st.is_clean() {
        println!("nothing to commit, working tree clean");
        return Ok(());
    }
    let show = |label: &str, items: &[(Vec<u8>, Change)]| {
        if !items.is_empty() {
            println!("{label}:");
            for (path, change) in items {
                let tag = match change {
                    Change::Added => "new file",
                    Change::Modified => "modified",
                    Change::Deleted => "deleted",
                };
                println!("\t{tag}:   {}", String::from_utf8_lossy(path));
            }
        }
    };
    show("Changes to be committed", &st.staged);
    show("Changes not staged for commit", &st.unstaged);
    if !st.untracked.is_empty() {
        println!("Untracked files:");
        for path in &st.untracked {
            println!("\t{}", String::from_utf8_lossy(path));
        }
    }
    Ok(())
}

/// `status --porcelain` (v1) — one `XY SP <path>` line per changed path, sorted
/// by path. `X` is the index-vs-`HEAD` (staged) state and `Y` the worktree-vs-
/// index (unstaged) state; each is `A`/`M`/`D` or a space when unchanged on that
/// side. Untracked paths are `??`. This is the stable, script-friendly format.
fn status_porcelain(st: &puregit::status::Status) -> Result<(), String> {
    use puregit::status::Change;
    use std::collections::BTreeMap;

    let code = |c: &Change| match c {
        Change::Added => 'A',
        Change::Modified => 'M',
        Change::Deleted => 'D',
    };
    // path -> (staged col, unstaged col), both defaulting to space (unchanged).
    let mut rows: BTreeMap<&[u8], (char, char)> = BTreeMap::new();
    for (path, change) in &st.staged {
        rows.entry(path).or_insert((' ', ' ')).0 = code(change);
    }
    for (path, change) in &st.unstaged {
        rows.entry(path).or_insert((' ', ' ')).1 = code(change);
    }
    for path in &st.untracked {
        rows.insert(path, ('?', '?'));
    }
    for (path, (x, y)) in &rows {
        println!("{x}{y} {}", String::from_utf8_lossy(path));
    }
    Ok(())
}

fn cmd_branch(args: &[String]) -> Result<(), String> {
    let repo = open_here()?;
    match args.first() {
        None => {
            // List branches, marking the current one.
            let current = repo.head().ok();
            for (name, _) in repo.refs().list().map_err(|e| e.to_string())? {
                if let Some(short) = name.strip_prefix("refs/heads/") {
                    let marker = matches!(&current, Some(puregit::refs::Reference::Symbolic(t)) if t == &name);
                    println!("{} {short}", if marker { "*" } else { " " });
                }
            }
            Ok(())
        }
        Some(name) => repo.create_branch(name, None).map_err(|e| e.to_string()),
    }
}

fn cmd_checkout(args: &[String]) -> Result<(), String> {
    let name = args.first().ok_or("checkout: missing <branch>")?;
    let repo = open_here()?;
    repo.checkout(name).map_err(|e| e.to_string())?;
    println!("Switched to branch '{name}'");
    Ok(())
}

/// `reset [--soft|--mixed|--hard] [<commit>]` — move the current branch to
/// `<commit>` (default `HEAD`); `--mixed` (default) also resets the index,
/// `--hard` also overwrites the working tree, `--soft` moves the ref only.
fn cmd_reset(args: &[String]) -> Result<(), String> {
    use puregit::repository::ResetMode;

    let mut mode = ResetMode::Mixed;
    let mut target = None;
    for arg in args {
        match arg.as_str() {
            "--soft" => mode = ResetMode::Soft,
            "--mixed" => mode = ResetMode::Mixed,
            "--hard" => mode = ResetMode::Hard,
            other if other.starts_with('-') => {
                return Err(format!("reset: unknown option '{other}'"));
            }
            other => target = Some(other.to_string()),
        }
    }
    let target = target.unwrap_or_else(|| "HEAD".to_string());

    let repo = open_here()?;
    let commit = repo
        .refs()
        .resolve(&target)
        .or_else(|_| ObjectId::from_hex(repo.algo(), &target).map_err(|e| e.to_string()))?;
    repo.reset(mode, &commit).map_err(|e| e.to_string())?;
    let label = match mode {
        ResetMode::Soft => "soft",
        ResetMode::Mixed => "mixed",
        ResetMode::Hard => "hard",
    };
    println!("HEAD is now at {} ({label} reset)", commit.to_hex_short(8));
    Ok(())
}

fn cmd_tag(args: &[String]) -> Result<(), String> {
    let repo = open_here()?;
    match args.first() {
        None => {
            // List tags.
            for (name, _) in repo.refs().list().map_err(|e| e.to_string())? {
                if let Some(short) = name.strip_prefix("refs/tags/") {
                    println!("{short}");
                }
            }
            Ok(())
        }
        Some(name) => {
            let target = match args.get(1) {
                Some(rev) => repo
                    .refs()
                    .resolve(rev)
                    .or_else(|_| ObjectId::from_hex(repo.algo(), rev).map_err(|e| e.to_string()))?,
                None => repo.head_id().map_err(|e| e.to_string())?,
            };
            let full = format!("refs/tags/{name}");
            if repo.refs().lookup(&full).is_ok() {
                return Err(format!("tag '{name}' already exists"));
            }
            repo.refs()
                .update(&full, &puregit::refs::Reference::Direct(target))
                .map_err(|e| e.to_string())
        }
    }
}

fn cmd_ls_tree(args: &[String]) -> Result<(), String> {
    use puregit::object::Object;
    let rev = args.first().ok_or("ls-tree: missing <tree-ish>")?;
    let repo = open_here()?;
    let id = repo
        .refs()
        .resolve(rev)
        .or_else(|_| ObjectId::from_hex(repo.algo(), rev).map_err(|e| e.to_string()))?;

    // Resolve a commit to its tree; accept a tree id directly.
    let tree = match repo.read_object(&id).map_err(|e| e.to_string())? {
        Object::Commit(c) => match repo.read_object(&c.tree).map_err(|e| e.to_string())? {
            Object::Tree(t) => t,
            _ => return Err("ls-tree: commit tree is not a tree".into()),
        },
        Object::Tree(t) => t,
        other => {
            return Err(format!(
                "ls-tree: {} is not a tree or commit",
                other.object_type()
            ));
        }
    };

    for entry in &tree.entries {
        let kind = if entry.mode == puregit::object::tree::FileMode::Tree {
            "tree"
        } else {
            "blob"
        };
        // git pads the mode to six octal digits (e.g. 040000 for a subtree).
        println!(
            "{:0>6} {} {}\t{}",
            entry.mode.as_octal(),
            kind,
            entry.id,
            String::from_utf8_lossy(&entry.name)
        );
    }
    Ok(())
}

fn cmd_diff(args: &[String]) -> Result<(), String> {
    use puregit::object::Object;
    // `--quiet` implies `--exit-code` and suppresses output; `--exit-code` shows
    // the diff but still exits 1 when there are differences (git parity).
    let quiet = args.iter().any(|a| a == "--quiet");
    let exit_code = quiet || args.iter().any(|a| a == "--exit-code");

    let repo = open_here()?;
    let work = repo
        .work_tree()
        .ok_or("diff: bare repository has no work tree")?
        .to_path_buf();
    let index = repo.index().map_err(|e| e.to_string())?;

    let mut differed = false;
    for entry in &index.entries {
        if entry.stage != 0 {
            continue;
        }
        let path = String::from_utf8_lossy(&entry.path).into_owned();
        // An empty buffer represents a file deleted from the work tree.
        let wt = std::fs::read(work.join(&path)).unwrap_or_default();
        // The staged blob content.
        let staged = match repo.read_object(&entry.id).map_err(|e| e.to_string())? {
            Object::Blob(b) => b,
            _ => continue,
        };
        if wt == staged {
            continue;
        }
        differed = true;
        if quiet {
            break; // one difference is enough to decide the exit status
        }
        let d = puregit::diff::unified(&staged, &wt, &format!("a/{path}"), &format!("b/{path}"), 3);
        print!("{d}");
    }

    if exit_code && differed {
        // Flush the printed diff before exiting with the "changes found" status.
        use std::io::Write;
        let _ = std::io::stdout().flush();
        std::process::exit(1);
    }
    Ok(())
}

fn cmd_diff_tree(args: &[String]) -> Result<(), String> {
    use puregit::object::Object;
    use puregit::walk::{TreeChange, diff_trees};
    if args.len() < 2 {
        return Err("diff-tree: usage: diff-tree <a> <b>".into());
    }
    let repo = open_here()?;

    // Resolve a commit/tree-ish argument to a tree id.
    let to_tree = |rev: &str| -> Result<ObjectId, String> {
        let id = repo
            .refs()
            .resolve(rev)
            .or_else(|_| ObjectId::from_hex(repo.algo(), rev).map_err(|e| e.to_string()))?;
        match repo.read_object(&id).map_err(|e| e.to_string())? {
            Object::Commit(c) => Ok(c.tree),
            Object::Tree(_) => Ok(id),
            other => Err(format!(
                "diff-tree: {} is not a tree or commit",
                other.object_type()
            )),
        }
    };
    let a = to_tree(&args[0])?;
    let b = to_tree(&args[1])?;

    for entry in diff_trees(repo.objects(), Some(&a), Some(&b)).map_err(|e| e.to_string())? {
        let tag = match entry.change {
            TreeChange::Added => 'A',
            TreeChange::Modified => 'M',
            TreeChange::Deleted => 'D',
        };
        println!("{tag}\t{}", String::from_utf8_lossy(&entry.path));
    }
    Ok(())
}

fn cmd_lfs(args: &[String]) -> Result<(), String> {
    use puregit::lfs::Pointer;
    let sub = args.first().map(String::as_str).unwrap_or("");
    let repo = open_here()?;
    match sub {
        "track" => {
            let pattern = args.get(1).ok_or("lfs track: missing <pattern>")?;
            repo.lfs_track(pattern).map_err(|e| e.to_string())?;
            println!("Tracking \"{pattern}\"");
            Ok(())
        }
        "ls-files" => {
            use puregit::odb::ObjectDatabase;
            let index = repo.index().map_err(|e| e.to_string())?;
            for entry in &index.entries {
                if entry.stage != 0 {
                    continue;
                }
                if let Ok((_, blob)) = repo.objects().read(&entry.id)
                    && let Ok(ptr) = Pointer::parse(&blob)
                {
                    println!(
                        "{} * {}",
                        &ptr.oid[..10],
                        String::from_utf8_lossy(&entry.path)
                    );
                }
            }
            Ok(())
        }
        "pull" => cmd_lfs_pull(&repo),
        other => Err(format!(
            "lfs: unknown subcommand '{other}' (try track|ls-files|pull)"
        )),
    }
}

#[cfg(feature = "http")]
fn cmd_lfs_pull(repo: &Repository) -> Result<(), String> {
    use puregit::lfs::batch::Operation;
    use puregit::lfs::transfer::LfsClient;

    let url = repo
        .config()
        .map_err(|e| e.to_string())?
        .get("remote", Some("origin"), "url")
        .map(String::from)
        .ok_or("lfs pull: no remote.origin.url configured")?;
    let client = LfsClient::new(LfsClient::endpoint_from_remote(&url));

    let n = repo
        .lfs_smudge_worktree(|p| {
            let results = client.batch(Operation::Download, std::slice::from_ref(p))?;
            let action = results
                .first()
                .and_then(|r| r.download.as_ref())
                .ok_or_else(|| puregit::Error::Protocol("lfs pull: no download action".into()))?;
            client.download(p, action)
        })
        .map_err(|e| e.to_string())?;
    println!("Downloaded {n} LFS object(s).");
    Ok(())
}

#[cfg(not(feature = "http"))]
fn cmd_lfs_pull(_repo: &Repository) -> Result<(), String> {
    Err("lfs pull: this build lacks the `http` feature".into())
}

fn cmd_merge(args: &[String]) -> Result<(), String> {
    use puregit::merge::MergeOutcome;
    let branch = args.first().ok_or("merge: missing <branch>")?;
    let repo = open_here()?;
    let their = repo
        .refs()
        .resolve(&format!("refs/heads/{branch}"))
        .or_else(|_| repo.refs().resolve(branch))
        .or_else(|_| ObjectId::from_hex(repo.algo(), branch).map_err(|e| e.to_string()))?;

    let who = signature_now(&repo)?;
    let msg = format!("Merge branch '{branch}'\n");
    match repo
        .merge(&their, who.clone(), who, msg.as_bytes())
        .map_err(|e| e.to_string())?
    {
        MergeOutcome::AlreadyUpToDate => println!("Already up to date."),
        MergeOutcome::FastForward(id) => println!("Fast-forward to {}", id.to_hex_short(8)),
        MergeOutcome::Merged(id) => println!(
            "Merge made by the 'three-way' strategy: {}",
            id.to_hex_short(8)
        ),
        MergeOutcome::Conflicts(paths) => {
            println!("Automatic merge failed; fix conflicts and then commit the result:");
            for p in paths {
                println!("\tboth modified: {}", String::from_utf8_lossy(&p));
            }
            return Err("merge conflicts".into());
        }
    }
    Ok(())
}

fn cmd_merge_base(args: &[String]) -> Result<(), String> {
    let is_ancestor = args.iter().any(|a| a == "--is-ancestor");
    let positional: Vec<&String> = args.iter().filter(|a| !a.starts_with('-')).collect();
    if positional.len() < 2 {
        return Err("merge-base: usage: merge-base [--is-ancestor] <commit> <commit>".into());
    }
    let repo = open_here()?;
    let resolve = |spec: &String| -> Result<ObjectId, String> {
        repo.refs()
            .resolve(spec)
            .or_else(|_| ObjectId::from_hex(repo.algo(), spec).map_err(|e| e.to_string()))
    };
    let a = resolve(positional[0])?;
    let b = resolve(positional[1])?;

    if is_ancestor {
        // `--is-ancestor <a> <b>`: exit 0 if a is an ancestor of b, else 1 —
        // no output, matching git.
        let anc = puregit::walk::is_ancestor(repo.objects(), &a, &b).map_err(|e| e.to_string())?;
        std::process::exit(if anc { 0 } else { 1 });
    }

    match puregit::walk::merge_base(repo.objects(), &a, &b).map_err(|e| e.to_string())? {
        Some(base) => {
            println!("{base}");
            Ok(())
        }
        // git prints nothing and exits 1 when there is no common ancestor.
        None => std::process::exit(1),
    }
}

fn cmd_gc(_args: &[String]) -> Result<(), String> {
    let mut repo = open_here()?;
    let n = repo.repack().map_err(|e| e.to_string())?;
    println!("Packed {n} loose object(s).");
    Ok(())
}

/// `fsck` — verify object connectivity and integrity. Prints each missing or
/// malformed object and each dangling loose object, and exits non-zero if any
/// integrity problem (not merely dangling) was found.
fn cmd_fsck(_args: &[String]) -> Result<(), String> {
    let repo = open_here()?;
    let report = puregit::fsck::fsck(&repo).map_err(|e| e.to_string())?;

    for p in &report.problems {
        match &p.referenced_by {
            Some(parent) => println!("{} ({}, referenced by {parent})", p.message, p.id),
            None => println!("{} ({})", p.message, p.id),
        }
    }
    for id in &report.dangling {
        println!("dangling object {id}");
    }
    if report.is_ok() {
        eprintln!(
            "fsck: {} object(s) checked, no problems found",
            report.checked
        );
        Ok(())
    } else {
        Err(format!(
            "{} integrity problem(s) found",
            report.problems.len()
        ))
    }
}

/// `commit-graph write|verify` — write the `objects/info/commit-graph` cache
/// (covering all commits reachable from refs/HEAD) or parse-and-verify it.
fn cmd_commit_graph(args: &[String]) -> Result<(), String> {
    let sub = args.first().map(String::as_str).unwrap_or("write");
    let repo = open_here()?;
    match sub {
        "write" => {
            let n = repo.write_commit_graph().map_err(|e| e.to_string())?;
            eprintln!("commit-graph: wrote {n} commit(s)");
            Ok(())
        }
        "verify" => {
            let path = repo.git_dir().join("objects/info/commit-graph");
            let data = std::fs::read(&path).map_err(|e| format!("reading commit-graph: {e}"))?;
            let g = puregit::commit_graph::CommitGraph::parse(repo.algo(), &data)
                .map_err(|e| e.to_string())?;
            eprintln!("commit-graph: OK, {} commit(s)", g.len());
            Ok(())
        }
        other => Err(format!("commit-graph: unknown subcommand '{other}'")),
    }
}

/// `multi-pack-index write|verify` — write `objects/pack/multi-pack-index`
/// covering every `.idx`, or parse-and-verify it.
fn cmd_multi_pack_index(args: &[String]) -> Result<(), String> {
    let sub = args.first().map(String::as_str).unwrap_or("write");
    let repo = open_here()?;
    match sub {
        "write" => {
            let n = repo.write_multi_pack_index().map_err(|e| e.to_string())?;
            eprintln!("multi-pack-index: wrote an index over {n} pack(s)");
            Ok(())
        }
        "verify" => {
            let path = repo.git_dir().join("objects/pack/multi-pack-index");
            let data =
                std::fs::read(&path).map_err(|e| format!("reading multi-pack-index: {e}"))?;
            let m = puregit::multi_pack_index::MultiPackIndex::parse(repo.algo(), &data)
                .map_err(|e| e.to_string())?;
            eprintln!(
                "multi-pack-index: OK, {} object(s) over {} pack(s)",
                m.len(),
                m.pack_names().len()
            );
            Ok(())
        }
        other => Err(format!("multi-pack-index: unknown subcommand '{other}'")),
    }
}

/// `worktree add <path> [<commit>]` — create a linked worktree checked out at
/// `<commit>` (default `HEAD`); `worktree list` — list linked worktrees.
fn cmd_worktree(args: &[String]) -> Result<(), String> {
    let repo = open_here()?;
    match args.first().map(String::as_str) {
        Some("add") => {
            let path = args.get(1).ok_or("worktree add: missing <path>")?;
            let commit = match args.get(2) {
                Some(rev) => repo
                    .refs()
                    .resolve(rev)
                    .or_else(|_| ObjectId::from_hex(repo.algo(), rev).map_err(|e| e.to_string()))?,
                None => repo.head_id().map_err(|e| e.to_string())?,
            };
            repo.add_worktree(std::path::Path::new(path), &commit)
                .map_err(|e| e.to_string())?;
            println!("Prepared worktree at {path} ({})", commit.to_hex_short(8));
            Ok(())
        }
        Some("list") | None => {
            // The main working tree first, then the linked ones.
            if let (Some(work), Ok(head)) = (repo.work_tree(), repo.head_id()) {
                println!("{}  {}", work.display(), head.to_hex_short(8));
            }
            for (name, id) in repo.worktrees().map_err(|e| e.to_string())? {
                println!("worktrees/{name}  {}", id.to_hex_short(8));
            }
            Ok(())
        }
        Some(other) => Err(format!("worktree: unknown subcommand '{other}'")),
    }
}

fn cmd_prune(_args: &[String]) -> Result<(), String> {
    let mut repo = open_here()?;
    let n = repo.prune().map_err(|e| e.to_string())?;
    println!("Pruned {n} unreachable loose object(s).");
    Ok(())
}

/// `verify-pack <packfile>` — validate a pack against its `.idx`. The index path
/// is derived by swapping the `.pack` suffix for `.idx`. Runs in a repository so
/// bases of a thin pack can be resolved from the object store.
fn cmd_verify_pack(args: &[String]) -> Result<(), String> {
    let pack_path = args.first().ok_or("verify-pack: missing <packfile>")?;
    let idx_path = match pack_path.strip_suffix(".pack") {
        Some(stem) => format!("{stem}.idx"),
        None => format!("{pack_path}.idx"),
    };
    let pack = std::fs::read(pack_path).map_err(|e| format!("reading {pack_path}: {e}"))?;
    let idx = std::fs::read(&idx_path).map_err(|e| format!("reading {idx_path}: {e}"))?;

    use puregit::odb::ObjectDatabase;
    let repo = open_here()?;
    let resolver = |id: &ObjectId| repo.objects().read(id);
    let v = puregit::pack::verify_pack(&pack, &idx, repo.algo(), &resolver)
        .map_err(|e| e.to_string())?;

    for p in &v.problems {
        println!("{p}");
    }
    if v.is_ok() {
        eprintln!("verify-pack: {} object(s) ok", v.objects);
        Ok(())
    } else {
        Err(format!("{} problem(s) found", v.problems.len()))
    }
}

fn cmd_unpack_objects(args: &[String]) -> Result<(), String> {
    let path = args.first().ok_or("unpack-objects: missing <packfile>")?;
    let pack = std::fs::read(path).map_err(|e| format!("reading {path}: {e}"))?;
    let repo = open_here()?;
    let ids = repo.ingest_pack(&pack).map_err(|e| e.to_string())?;
    eprintln!("Unpacked {} objects.", ids.len());
    Ok(())
}

fn open_here() -> Result<Repository, String> {
    Repository::open(".").map_err(|e| e.to_string())
}

// Small extension trait shim so `cat-file` can read the raw (type, payload)
// without importing the ObjectDatabase trait at the call site.
trait ObjectsReadExt {
    fn objects_read(&self, id: &ObjectId) -> puregit::Result<(ObjectType, Vec<u8>)>;
}
impl ObjectsReadExt for Repository {
    fn objects_read(&self, id: &ObjectId) -> puregit::Result<(ObjectType, Vec<u8>)> {
        use puregit::odb::ObjectDatabase;
        self.objects().read(id)
    }
}

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

    #[test]
    fn roff_escapes_backslashes_and_leading_control() {
        assert_eq!(roff_escape("a\\b"), "a\\\\b");
        // A line starting with a roff control char is neutralised with \&.
        assert_eq!(roff_escape(".hidden"), "\\&.hidden");
        assert_eq!(roff_escape("'quote"), "\\&'quote");
        assert_eq!(roff_escape("plain"), "plain");
    }

    #[test]
    fn manpage_has_required_roff_sections() {
        let man = manpage();
        assert!(man.starts_with(".TH PUREGIT 1 "));
        for section in [
            ".SH NAME",
            ".SH SYNOPSIS",
            ".SH DESCRIPTION",
            ".SH COMMANDS",
            ".SH EXIT STATUS",
        ] {
            assert!(man.contains(section), "man page missing {section}");
        }
        // The command table is derived from USAGE, so a known command appears.
        assert!(man.contains(".B init"));
        // Exit-status parity is documented.
        assert!(man.contains(".B 128"));
        assert!(man.contains(".B 129"));
    }
}