git-lfs 0.4.0

Large file storage for git, implemented in Rust
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
use std::io::{self, BufRead, BufWriter, Read, Write};
use std::process::ExitCode;

use clap::{CommandFactory, Parser};
use git_lfs_filter::{CleanExtension, SmudgeExtension, clean, filter_process, smudge_with_fetch};
use git_lfs_store::Store;

mod checkout;
mod clone;
mod env;
mod ext;
mod fetch;
mod fetcher;
mod fsck;
mod hooks;
mod http_client;
mod install;
mod lock;
mod lock_cache;
mod lockable;
mod locks_verify;
mod ls_files;
mod migrate;
mod pointer_cmd;
mod pre_push;
mod prune;
mod pull;
mod push;
mod status;
mod track;
mod track_cmd;
mod update;

use fetcher::LfsFetcher;

use git_lfs::args::{Cli, Command, MigrateCmd};

fn main() -> ExitCode {
    let cli = Cli::parse();
    if cli.version {
        println!("git-lfs/{} (rust)", env!("CARGO_PKG_VERSION"));
        return ExitCode::SUCCESS;
    }
    let Some(command) = cli.command else {
        // Mimic clap's default error path when no subcommand is given.
        Cli::command().print_help().ok();
        return ExitCode::FAILURE;
    };
    match dispatch(command) {
        Ok(code) => ExitCode::from(code),
        Err(e) => {
            eprintln!("git-lfs: {e}");
            ExitCode::FAILURE
        }
    }
}

/// Path-shaped git env vars that interpret relative values against
/// the caller's cwd. We canonicalize them once up front so subprocess
/// invocations using `git -C <dir>` don't re-resolve them.
const PATH_GIT_ENV_VARS: &[&str] = &[
    "GIT_DIR",
    "GIT_WORK_TREE",
    "GIT_COMMON_DIR",
    "GIT_INDEX_FILE",
    "GIT_OBJECT_DIRECTORY",
];

/// Snapshot of `PATH_GIT_ENV_VARS` taken before [`canonicalize_path_envs`]
/// rewrites them to absolute paths. `git lfs env` reports the original
/// (possibly relative) values to match upstream's output.
static ORIGINAL_PATH_ENVS: std::sync::OnceLock<Vec<(&'static str, std::ffi::OsString)>> =
    std::sync::OnceLock::new();

/// Look up the *original* value of a path-shaped git env var, before
/// canonicalization. Returns `None` if the variable wasn't set or
/// wasn't in the path-shaped allowlist.
pub fn original_path_env(name: &str) -> Option<std::ffi::OsString> {
    ORIGINAL_PATH_ENVS
        .get()?
        .iter()
        .find(|(k, _)| *k == name)
        .map(|(_, v)| v.clone())
}

/// Make any relative path-shaped git env var absolute against `base`,
/// so subsequent `git -C <some_dir>` calls don't re-resolve them
/// against the wrong directory. Operates in place via `set_var`. Saves
/// the originals via [`original_path_env`] so `git lfs env` can still
/// echo the user-visible value.
fn canonicalize_path_envs(base: &std::path::Path) {
    let mut snapshot = Vec::new();
    for name in PATH_GIT_ENV_VARS {
        let Some(raw) = std::env::var_os(name) else {
            continue;
        };
        snapshot.push((*name, raw.clone()));
        if raw.is_empty() {
            continue;
        }
        let p = std::path::Path::new(&raw);
        if p.is_absolute() {
            continue;
        }
        let absolute = base.join(p);
        // SAFETY: We're early in `dispatch` before any threads are
        // spawned. `set_var` is unsafe in 2024 edition because of
        // multi-threaded races; the single-threaded prelude here is
        // exactly the documented safe usage pattern.
        unsafe {
            std::env::set_var(name, absolute);
        }
    }
    let _ = ORIGINAL_PATH_ENVS.set(snapshot);
}

/// Reduce the per-flag scope toggles for `install` / `uninstall` to a
/// single [`install::InstallScope`]. Multiple scope flags is a usage
/// error matching upstream's exact wording.
fn resolve_install_scope(
    local: bool,
    system: bool,
    worktree: bool,
    file: Option<std::path::PathBuf>,
) -> Result<install::InstallScope, &'static str> {
    let count = [local, system, worktree, file.is_some()]
        .iter()
        .filter(|b| **b)
        .count();
    if count > 1 {
        return Err(
            "Only one of the --local, --system, --worktree, and --file options can be specified.",
        );
    }
    Ok(if let Some(p) = file {
        install::InstallScope::File(p)
    } else if local {
        install::InstallScope::Local
    } else if system {
        install::InstallScope::System
    } else if worktree {
        install::InstallScope::Worktree
    } else {
        install::InstallScope::Global
    })
}

/// If `e` is a `git config <scope> ...` failure, render it on stdout
/// in upstream's `error running 'git config ...': <stderr>` shape and
/// return exit code 2. Otherwise return `None` and let the caller
/// propagate the error normally. The `>out.log` redirection in
/// t-install test 9 and t-install-worktree test 4 means this has to
/// land on stdout, not stderr.
fn handle_install_config_failure(e: &install::InstallError) -> Option<u8> {
    if let install::InstallError::ConfigCommandFailed { .. } = e {
        println!("{e}");
        Some(2)
    } else {
        None
    }
}

/// Print upstream's `Not in a Git repository.` to stdout and return a
/// non-zero exit code if `cwd` isn't inside any git repo. Returns
/// `None` to keep going. Mirrors the error path test 7 of t-uninstall
/// (and the analogous t-install test) asserts on.
fn bail_if_outside_repo(cwd: &std::path::Path) -> Option<u8> {
    if git_lfs_git::git_dir(cwd).is_err() {
        println!("Not in a Git repository.");
        return Some(128);
    }
    None
}

/// `GIT_LFS_SKIP_SMUDGE=1` (any value other than empty/0/false) tells
/// the smudge filter to leave pointer text in place rather than fetch.
/// Used by clones that intentionally don't materialize content (e.g.
/// CI partial clones, t-pull's "skip" tests).
fn skip_smudge_env() -> bool {
    match std::env::var_os("GIT_LFS_SKIP_SMUDGE") {
        None => false,
        Some(v) => {
            let s = v.to_string_lossy();
            !matches!(s.as_ref(), "" | "0" | "false" | "False" | "FALSE")
        }
    }
}

/// Print a migrate error and choose an exit code. Usage-shaped errors
/// (`MigrateError::Usage`) print verbatim and exit with code 2 —
/// upstream's `if PIPESTATUS == 1 fatal` checks distinguish usage
/// errors from general failures, and exact-match tests like
/// `[$(cmd) = "Cannot use ..."]` don't care about the code anyway.
fn handle_migrate_error(e: migrate::MigrateError) -> u8 {
    match e {
        migrate::MigrateError::Usage(msg) => {
            eprintln!("{msg}");
            2
        }
        other => {
            eprintln!("git-lfs: {other}");
            1
        }
    }
}

/// Split each entry in `values` on commas and trim whitespace, dropping
/// empties. Mirrors upstream's `--include="*.md, *.txt"` parsing — clap
/// gives us one Vec entry per `--include` flag, and a comma-separated
/// list within the entry needs to expand. Repeated flags (e.g.
/// `--include foo --include bar`) are also flattened.
fn split_csv(values: &[String]) -> Vec<String> {
    values
        .iter()
        .flat_map(|s| s.split(','))
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .map(str::to_owned)
        .collect()
}

/// Read configured pointer extensions and convert to the filter crate's
/// runtime form. Skips entries whose `clean` is empty or whose priority
/// is outside the spec's 0-9 range — those wouldn't produce a valid
/// `ext-N-<name>` line anyway.
fn collect_clean_extensions(cwd: &std::path::Path) -> Vec<CleanExtension> {
    git_lfs_git::list_extensions(cwd)
        .into_iter()
        .filter_map(|ext| {
            if ext.clean.trim().is_empty() {
                return None;
            }
            let priority = u8::try_from(ext.priority).ok().filter(|&p| p <= 9)?;
            Some(CleanExtension {
                name: ext.name,
                priority,
                command: ext.clean,
            })
        })
        .collect()
}

/// Same shape as [`collect_clean_extensions`] but builds the `smudge`
/// side of the registered extensions. Used by the smudge filter,
/// filter-process, and the pull/checkout materialize loops to invert
/// what `clean` did during commit.
fn collect_smudge_extensions(cwd: &std::path::Path) -> Vec<SmudgeExtension> {
    git_lfs_git::list_extensions(cwd)
        .into_iter()
        .filter_map(|ext| {
            if ext.smudge.trim().is_empty() {
                return None;
            }
            let priority = u8::try_from(ext.priority).ok().filter(|&p| p <= 9)?;
            Some(SmudgeExtension {
                name: ext.name,
                priority,
                command: ext.smudge,
            })
        })
        .collect()
}

fn dispatch(cmd: Command) -> Result<u8, Box<dyn std::error::Error>> {
    let cwd = std::env::current_dir()?;
    // `GIT_DIR` / `GIT_WORK_TREE` (and the auxiliary `GIT_OBJECT_*`
    // variants) come in relative to the *caller's* cwd. Many of our
    // subprocess invocations later use `git -C <repo_root>`, which
    // would re-resolve those relative paths against the wrong base.
    // Canonicalize once up front so every downstream `git` call sees
    // absolute paths regardless of where it's chdir'd to.
    canonicalize_path_envs(&cwd);

    // Sweep stale temp-object files (`<oid>-<random>` under
    // `<lfs>/tmp/objects/`) whose object is already complete in the
    // store. Mirrors upstream's `lfs.cleanupTempFiles` startup task.
    // Skipped silently when we're not in a repo (e.g. `git lfs
    // version` outside any repo).
    if let Ok(lfs_root) = git_lfs_git::lfs_dir(&cwd) {
        Store::new(lfs_root).cleanup_tmp_objects();
    }

    match cmd {
        Command::Clean { path } => {
            let _ = install::try_install_hooks(&cwd);
            let store = Store::new(git_lfs_git::lfs_dir(&cwd)?);
            // No `with_references` here: clean writes new content
            // computed from working-tree input, so alternate stores
            // can't satisfy the lookup (and we don't want to reuse
            // their inode for a freshly-staged file).
            let stdin = io::stdin().lock();
            let mut input: Box<dyn Read> = Box::new(stdin);
            let mut output: Box<dyn Write> = Box::new(BufWriter::new(io::stdout().lock()));
            let extensions = collect_clean_extensions(&cwd);
            let path_str = path
                .as_deref()
                .map(|p| p.to_string_lossy().into_owned())
                .unwrap_or_default();
            clean(&store, &mut input, &mut output, &path_str, &extensions)?;
            output.flush()?;
        }
        Command::Smudge { path, skip } => {
            let _ = install::try_install_hooks(&cwd);
            let store = Store::new(git_lfs_git::lfs_dir(&cwd)?)
                .with_references(git_lfs_git::lfs_alternate_dirs(&cwd).unwrap_or_default());
            let stdin = io::stdin().lock();
            let mut input: Box<dyn Read> = Box::new(stdin);
            let mut output: Box<dyn Write> = Box::new(BufWriter::new(io::stdout().lock()));
            if skip || skip_smudge_env() {
                io::copy(&mut input, &mut output)?;
            } else {
                let fetcher = LfsFetcher::from_repo(&cwd, &store)?;
                let smudge_extensions = collect_smudge_extensions(&cwd);
                let path_str = path
                    .as_deref()
                    .map(|p| p.to_string_lossy().into_owned())
                    .unwrap_or_default();
                smudge_with_fetch(
                    &store,
                    &mut input,
                    &mut output,
                    &path_str,
                    &smudge_extensions,
                    |p| fetcher.fetch(p),
                )?;
                fetcher.persist_access_mode();
            }
            output.flush()?;
        }
        Command::Install {
            local,
            system,
            worktree,
            file,
            force,
            skip_repo,
            skip_smudge,
        } => {
            let scope = match resolve_install_scope(local, system, worktree, file) {
                Ok(s) => s,
                Err(msg) => {
                    eprintln!("{msg}");
                    return Ok(2);
                }
            };
            if scope.is_repo_scope()
                && let Some(code) = bail_if_outside_repo(&cwd)
            {
                return Ok(code);
            }
            let opts = install::InstallOptions {
                scope,
                force,
                skip_repo,
                skip_smudge,
            };
            // Compute up-front whether hooks would be installed so the
            // success path can print "Updated Git hooks." in the same
            // order upstream does. Mirrors the `install_hooks_too`
            // condition inside `install::install`.
            let hooks_active = !opts.skip_repo
                && (opts.scope.is_repo_scope() || git_lfs_git::git_dir(&cwd).is_ok());
            match install::install(&cwd, &opts) {
                Ok(()) => {
                    if hooks_active {
                        println!("Updated Git hooks.");
                    }
                    println!("Git LFS initialized.");
                }
                Err(e @ install::InstallError::FilterAttribute { .. }) => {
                    // Mirrors upstream's `commands/command_install.go`:
                    // print `warning: <err>` + the `--force` hint on
                    // stdout, exit 2. t-install test 2 captures via
                    // `tee install.log` (stdout only) and greps for
                    // `(clean|smudge)" attribute should be`.
                    println!("warning: {e}");
                    println!("Run `git lfs install --force` to reset Git configuration.");
                    return Ok(2);
                }
                Err(install::InstallError::HookConflict { hook, existing }) => {
                    install::print_hook_conflict(&hook, &existing);
                    return Ok(2);
                }
                Err(e) if let Some(code) = handle_install_config_failure(&e) => {
                    return Ok(code);
                }
                Err(e) => return Err(Box::new(e)),
            }
        }
        Command::Uninstall {
            mode,
            local,
            system,
            worktree,
            file,
            skip_repo,
        } => {
            let scope = match resolve_install_scope(local, system, worktree, file) {
                Ok(s) => s,
                Err(msg) => {
                    eprintln!("{msg}");
                    return Ok(2);
                }
            };
            let hooks_only = match mode.as_deref() {
                None => false,
                Some("hooks") => true,
                Some(other) => {
                    eprintln!("git-lfs: unknown mode {other:?}");
                    return Ok(2);
                }
            };
            if scope.is_repo_scope()
                && let Some(code) = bail_if_outside_repo(&cwd)
            {
                return Ok(code);
            }
            let opts = install::UninstallOptions {
                scope: scope.clone(),
                skip_repo,
                hooks_only,
            };
            if let Err(e) = install::uninstall(&cwd, &opts) {
                if matches!(e, install::InstallError::ConfigCommandFailed { .. }) {
                    // Uninstall is idempotent — a failing
                    // `git config <scope> --unset` (e.g. --worktree
                    // against a repo without the worktreeConfig
                    // extension) becomes a stdout warning and we keep
                    // going. Exit 0 matches upstream's t-uninstall-
                    // worktree test 4.
                    println!("{e}");
                    return Ok(0);
                }
                return Err(Box::new(e));
            }
            if hooks_only {
                // No "configuration removed" message: hooks-only mode
                // leaves the filter config exactly as-is.
            } else if scope.announces_global() {
                println!("Global Git LFS configuration has been removed.");
            } else {
                println!("Local Git LFS configuration has been removed.");
            }
        }
        Command::Clone { args } => {
            clone::run(&cwd, &args)?;
        }
        Command::FilterProcess { skip } => {
            let _ = install::try_install_hooks(&cwd);
            let store = Store::new(git_lfs_git::lfs_dir(&cwd)?)
                .with_references(git_lfs_git::lfs_alternate_dirs(&cwd).unwrap_or_default());
            let fetcher = LfsFetcher::from_repo(&cwd, &store)?;
            let stdin = io::stdin().lock();
            let stdout = io::stdout().lock();
            let clean_extensions = collect_clean_extensions(&cwd);
            let smudge_extensions = collect_smudge_extensions(&cwd);
            // Honor `lfs.fetchinclude`/`lfs.fetchexclude`: paths
            // outside the include set or inside the exclude set get
            // pointer-text passthrough at smudge time, matching
            // upstream's filter-process behavior (test 2 of
            // t-filter-process). Patterns are pulled via
            // `build_pattern_set`, the same helper fetch/pull use.
            let include_set = fetch::build_pattern_set(&cwd, &[], "lfs.fetchinclude")?;
            let exclude_set = fetch::build_pattern_set(&cwd, &[], "lfs.fetchexclude")?;
            let path_filter = move |path: &str| -> bool {
                let p = std::path::Path::new(path);
                fetch::path_passes_filter(Some(p), &include_set, &exclude_set)
            };
            filter_process(
                &store,
                stdin,
                stdout,
                |p| fetcher.fetch(p),
                skip || skip_smudge_env(),
                &clean_extensions,
                &smudge_extensions,
                &path_filter,
            )?;
            fetcher.persist_access_mode();
        }
        Command::Fetch {
            args,
            dry_run,
            json,
            all,
            refetch,
            stdin,
            prune,
            include,
            exclude,
        } => {
            let stdin_lines: Vec<String> = if stdin {
                io::stdin()
                    .lock()
                    .lines()
                    .map_while(Result::ok)
                    .map(|l| l.trim().to_owned())
                    .filter(|l| !l.is_empty())
                    .collect()
            } else {
                Vec::new()
            };
            let opts = fetch::FetchOptions {
                args: &args,
                stdin_lines: &stdin_lines,
                dry_run,
                json,
                all,
                refetch,
                stdin,
                prune,
                include: &include,
                exclude: &exclude,
            };
            match fetch::fetch(&cwd, &opts) {
                Ok(outcome) => {
                    if !outcome.report.failed.is_empty() {
                        return Err("one or more objects failed to download".into());
                    }
                }
                Err(fetch::FetchCommandError::Usage(msg)) if msg == "Not in a Git repository." => {
                    // Test `t-fetch.sh::fetch: outside git repository`
                    // greps for this on stdout (`2>&1 > fetch.log`
                    // captures stdout only). Match upstream and emit
                    // here, then exit 128.
                    println!("{msg}");
                    return Ok(128);
                }
                Err(e) => return Err(e.into()),
            }
        }
        Command::Pull {
            refs,
            include,
            exclude,
        } => {
            match pull::pull_with_filter(&cwd, &refs, &include, &exclude) {
                Ok(()) => {}
                Err(pull::PullCommandError::Fetch(fetch::FetchCommandError::Usage(msg)))
                    if msg == "Not in a Git repository." =>
                {
                    // Mirrors fetch's outside-repo handling for parity
                    // with `git lfs fetch` (and t-pull's `outside git
                    // repository` test, which expects exit 128).
                    println!("{msg}");
                    return Ok(128);
                }
                Err(e @ pull::PullCommandError::FetchFailures(_)) => {
                    // Per-object transfer failures (per-object-batch
                    // 404s, action-URL 4xx/5xx) — upstream exits 2
                    // here, and t-pull's `pull with invalid insteadof`
                    // greps for that exit code specifically.
                    eprintln!("git-lfs: {e}");
                    return Ok(2);
                }
                Err(e) => return Err(e.into()),
            }
        }
        Command::Push {
            remote,
            args,
            dry_run,
            all,
            stdin,
            object_id,
        } => {
            let stdin_lines: Vec<String> = if stdin {
                io::stdin()
                    .lock()
                    .lines()
                    .map_while(Result::ok)
                    .map(|l| l.trim().to_owned())
                    .filter(|l| !l.is_empty())
                    .collect()
            } else {
                Vec::new()
            };
            let opts = push::PushOptions {
                args: &args,
                stdin_lines: &stdin_lines,
                dry_run,
                all,
                stdin,
                object_id,
            };
            let outcome = push::push(&cwd, &remote, &opts)?;
            if outcome.aborted {
                return Ok(2);
            }
            if !outcome.report.failed.is_empty() {
                return Err("one or more objects failed to upload".into());
            }
        }
        Command::PostCheckout { args } => {
            hooks::post_checkout(&cwd, &args)?;
        }
        Command::PostCommit { args } => {
            hooks::post_commit(&cwd, &args)?;
        }
        Command::PostMerge { args } => {
            hooks::post_merge(&cwd, &args)?;
        }
        Command::PrePush {
            remote,
            url: _,
            dry_run,
        } => {
            let stdin = io::stdin().lock();
            let outcome = pre_push::pre_push(&cwd, &remote, stdin, dry_run)?;
            if outcome.aborted {
                return Ok(2);
            }
            if !outcome.report.failed.is_empty() {
                return Err("pre-push: one or more objects failed to upload".into());
            }
        }
        Command::Track {
            patterns,
            lockable,
            not_lockable,
            dry_run,
            verbose,
            json,
            no_excluded,
            filename,
            no_modify_attrs,
        } => {
            return track_cmd::run(track_cmd::Args {
                cwd: &cwd,
                patterns: &patterns,
                lockable,
                not_lockable,
                dry_run,
                verbose,
                json,
                no_excluded,
                filename,
                no_modify_attrs,
            });
        }
        Command::Version => {
            println!("git-lfs/{} (rust)", env!("CARGO_PKG_VERSION"));
        }
        Command::Pointer {
            file,
            pointer,
            stdin,
            check,
            strict,
            no_strict,
        } => {
            let opts = pointer_cmd::Options {
                file,
                pointer,
                stdin,
                check,
                strict,
                no_strict,
            };
            // Pointer's exit codes are semantic: 1 = mismatch / parse
            // failure, 2 = `--strict` non-canonical. Propagate verbatim.
            let code = pointer_cmd::run(&opts)?;
            return Ok(code as u8);
        }
        Command::Env => {
            env::run(&cwd)?;
        }
        Command::Ext => {
            ext::run(&cwd)?;
        }
        Command::Update { force, manual } => match update::run(&cwd, force, manual) {
            Ok(code) => return Ok(code),
            Err(update::UpdateError::NotInRepo) => {
                // Stdout, not stderr: upstream prints to stdout here
                // and `t-update` test 4 redirects only `>check.log`
                // (its `2>&1` is in the wrong order to capture stderr).
                println!("Not in a Git repository.");
                return Ok(128);
            }
            Err(e) => return Err(Box::new(e)),
        },
        Command::Migrate { cmd } => match cmd {
            MigrateCmd::Export {
                branches,
                everything,
                include,
                exclude,
                include_ref,
                exclude_ref,
                skip_fetch,
                object_map,
                verbose,
                remote,
                yes: _,
            } => {
                let opts = migrate::ExportOptions {
                    branches,
                    everything,
                    include: split_csv(&include),
                    exclude: split_csv(&exclude),
                    include_ref,
                    exclude_ref,
                    skip_fetch,
                    object_map,
                    verbose,
                    remote,
                };
                if let Err(e) = migrate::export(&cwd, &opts) {
                    return Ok(handle_migrate_error(e));
                }
            }
            MigrateCmd::Import {
                args,
                everything,
                include,
                exclude,
                include_ref,
                exclude_ref,
                above,
                no_rewrite,
                message,
                yes,
                fixup,
                skip_fetch,
                object_map,
                verbose,
                remote,
            } => {
                let above_bytes = migrate::parse_size(&above)?;
                let (branches, paths) = if no_rewrite {
                    (Vec::new(), args)
                } else {
                    (args, Vec::new())
                };
                let opts = migrate::ImportOptions {
                    branches,
                    everything,
                    include: split_csv(&include),
                    exclude: split_csv(&exclude),
                    include_ref,
                    exclude_ref,
                    above: above_bytes,
                    no_rewrite,
                    message,
                    paths,
                    fixup,
                    skip_fetch,
                    object_map,
                    verbose,
                    remote,
                    yes,
                };
                let _ = install::try_install_hooks(&cwd);
                if let Err(e) = migrate::import(&cwd, &opts) {
                    return Ok(handle_migrate_error(e));
                }
            }
            MigrateCmd::Info {
                branches,
                everything,
                include,
                exclude,
                include_ref,
                exclude_ref,
                above,
                top,
                pointers,
                unit,
                skip_fetch: _,
                remote: _,
                fixup,
            } => {
                let pointer_mode = match pointers.as_deref() {
                    Some("follow") => migrate::PointerMode::Follow,
                    Some("no-follow") => migrate::PointerMode::NoFollow,
                    Some("ignore") => migrate::PointerMode::Ignore,
                    Some(other) => {
                        return Ok(handle_migrate_error(migrate::MigrateError::Usage(format!(
                            "Unsupported --pointers option value: {other:?}"
                        ))));
                    }
                    // No `--pointers` flag: `--fixup` implies `ignore`
                    // (we want to see what *should* be LFS but isn't);
                    // otherwise default to `follow`.
                    None if fixup => migrate::PointerMode::Ignore,
                    None => migrate::PointerMode::Follow,
                };
                let above_bytes = migrate::parse_size(&above)?;
                let unit_bytes = match unit.as_deref() {
                    None | Some("") => None,
                    Some(s) => Some(migrate::parse_size(s)?),
                };
                let opts = migrate::InfoOptions {
                    branches,
                    everything,
                    include: split_csv(&include),
                    exclude: split_csv(&exclude),
                    include_ref,
                    exclude_ref,
                    above: above_bytes,
                    top,
                    pointers: pointer_mode,
                    unit: unit_bytes,
                    fixup,
                };
                if let Err(e) = migrate::info(&cwd, &opts) {
                    return Ok(handle_migrate_error(e));
                }
            }
        },
        Command::Checkout {
            paths,
            to,
            ours,
            theirs,
            base,
        } => {
            let opts = checkout::Options {
                paths,
                to,
                ours,
                theirs,
                base,
            };
            match checkout::run(&cwd, &opts) {
                Ok(()) => {}
                Err(checkout::CheckoutError::NotInWorkTree) => {
                    // Bare repo: matches t-status / t-checkout
                    // bare-repo expectation. Exit 0 with the
                    // upstream-compatible message.
                    println!("This operation must be run in a work tree.");
                }
                Err(checkout::CheckoutError::NotInRepo) => {
                    // Outside any repo. Exit 128 with the wording the
                    // t-checkout outside-repo test greps for.
                    println!("Not in a Git repository.");
                    return Ok(128);
                }
                Err(checkout::CheckoutError::Usage(msg)) => {
                    // Conflict-mode flag validation errors. Upstream
                    // exits via `Exit()` which writes to stderr and
                    // returns 2; mirror that.
                    eprintln!("{msg}");
                    return Ok(2);
                }
                Err(e) => return Err(e.into()),
            }
        }
        Command::Prune { dry_run, verbose } => {
            let opts = prune::Options { dry_run, verbose };
            prune::run(&cwd, &opts)?;
        }
        Command::Fsck {
            refspec,
            objects,
            pointers,
            dry_run,
        } => {
            let _ = install::try_install_hooks(&cwd);
            let mode = match (objects, pointers) {
                (true, false) => fsck::Mode::Objects,
                (false, true) => fsck::Mode::Pointers,
                _ => fsck::Mode::Both,
            };
            let opts = fsck::Options { mode, dry_run };
            let code = fsck::run(&cwd, refspec.as_deref(), &opts)?;
            return Ok(code as u8);
        }
        Command::Status { porcelain, json } => {
            let format = if json {
                status::Format::Json
            } else if porcelain {
                status::Format::Porcelain
            } else {
                status::Format::Default
            };
            match status::run(&cwd, format) {
                Ok(()) => {}
                Err(status::StatusError::NotInRepo) => {
                    // Match `git lfs fetch` / `pull`: emit the message
                    // on stdout and exit 128 so the t-status outside-
                    // repo test (and parity with upstream) holds.
                    println!("Not in a Git repository.");
                    return Ok(128);
                }
                Err(status::StatusError::NotInWorkTree) => {
                    // Bare repo: status has nothing to compare a work
                    // tree against. Upstream exits non-zero here.
                    println!("This operation must be run in a work tree.");
                    return Ok(1);
                }
                Err(e) => return Err(e.into()),
            }
        }
        Command::Lock {
            paths,
            remote,
            refspec,
            json,
        } => {
            let opts = lock::LockOptions {
                remote,
                refspec,
                json,
            };
            let ok = lock::lock(&cwd, &paths, &opts)?;
            if !ok {
                return Err("one or more locks failed".into());
            }
        }
        Command::Locks {
            remote,
            path,
            id,
            limit,
            refspec,
            verify,
            local,
            json,
        } => {
            let opts = lock::LocksOptions {
                remote,
                refspec,
                path,
                id,
                limit,
                verify,
                local,
                json,
            };
            lock::locks(&cwd, &opts)?;
        }
        Command::Unlock {
            paths,
            id,
            force,
            remote,
            refspec,
            json,
        } => {
            let opts = lock::UnlockOptions {
                remote,
                refspec,
                id,
                force,
                json,
            };
            let ok = lock::unlock(&cwd, &paths, &opts)?;
            if !ok {
                return Err("one or more unlocks failed".into());
            }
        }
        Command::LsFiles {
            refspec,
            long,
            size,
            name_only,
            all,
            debug,
            json,
        } => {
            let format = if json {
                ls_files::Format::Json
            } else if debug {
                ls_files::Format::Debug
            } else {
                ls_files::Format::Default
            };
            let opts = ls_files::Options {
                long,
                show_size: size,
                name_only,
                all,
                format,
            };
            ls_files::run(&cwd, refspec.as_deref(), &opts)?;
        }
        Command::Untrack { patterns } => {
            if patterns.is_empty() {
                return Err("git lfs untrack <pattern> [pattern...]".into());
            }
            // Resolve the work-tree root: a bare repo or being outside
            // any repo entirely is a "not in a git repository" error
            // matching git's exit code (128). When cwd is inside the
            // work tree we prefer it (so `cd a; git lfs untrack foo`
            // edits `a/.gitattributes`), falling back to the work-tree
            // root when GIT_WORK_TREE points outside cwd.
            let work_tree = match git_lfs_git::work_tree_root(&cwd) {
                Ok(p) => p,
                Err(_) => {
                    eprintln!("fatal: not in a git repository");
                    return Ok(128);
                }
            };
            let attrs_dir = if cwd.starts_with(&work_tree) {
                cwd.clone()
            } else {
                work_tree
            };
            let _ = install::try_install_hooks(&cwd);
            let outcome = track::untrack(&attrs_dir, &patterns)?;
            for p in &outcome.removed {
                println!("Untracking \"{p}\"");
            }
            for p in &outcome.missing {
                println!("\"{p}\" was not tracked");
            }
        }
    }
    Ok(0)
}