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
//! `git lfs lock`, `git lfs locks`, `git lfs unlock` — the file-lock
//! command surface. All three speak the locking API in `api/src/locks.rs`;
//! this module is mostly path-resolution + flag dispatch + display logic.
//!
//! `git lfs locks --local` reads from a side-effect cache populated by
//! `git lfs lock` and pruned by `git lfs unlock` (see [`crate::lock_cache`]).
//! `--cached` (which would persist the last remote query) is still
//! deferred — see NOTES.md.

use std::path::{Path, PathBuf};
use std::process::Command;

use git_lfs_api::{
    ApiError, Client as ApiClient, CreateLockError, CreateLockRequest, DeleteLockRequest,
    ListLocksFilter, Lock, LockList, Ref, VerifyLocksRequest, VerifyLocksResponse,
};
use serde::Serialize;
use tokio::runtime::Runtime;

use crate::fetcher::build_api_client;
use crate::lock_cache;
use crate::lockable;

#[derive(Debug, thiserror::Error)]
pub enum LockCommandError {
    #[error(transparent)]
    Io(#[from] std::io::Error),
    #[error("{0}")]
    Build(String),
    #[error("lock api: {0}")]
    Api(String),
    #[error("could not serialize JSON: {0}")]
    Json(#[from] serde_json::Error),
}

#[derive(Debug, Default, Clone)]
pub struct LockOptions {
    pub remote: Option<String>,
    /// Override the auto-detected refspec (`branch.<current>.merge` or
    /// the current branch). `None` means "auto".
    pub refspec: Option<String>,
    pub json: bool,
}

#[derive(Debug, Default, Clone)]
pub struct LocksOptions {
    pub remote: Option<String>,
    pub refspec: Option<String>,
    pub path: Option<String>,
    pub id: Option<String>,
    pub limit: Option<u32>,
    pub verify: bool,
    pub json: bool,
    /// `--local`: list from the on-disk cache without touching the
    /// server. Cache is populated as a side effect of `git lfs lock`
    /// and pruned by `git lfs unlock`. Combined with `--path`/`--id`/
    /// `--limit` the same way the remote query is.
    pub local: bool,
}

#[derive(Debug, Default, Clone)]
pub struct UnlockOptions {
    pub remote: Option<String>,
    pub refspec: Option<String>,
    pub id: Option<String>,
    pub force: bool,
    pub json: bool,
}

// --------------------------------------------------------------------------
// lock
// --------------------------------------------------------------------------

pub fn lock(cwd: &Path, paths: &[String], opts: &LockOptions) -> Result<bool, LockCommandError> {
    if paths.is_empty() {
        return Err(LockCommandError::Build(
            "git lfs lock requires at least one path".into(),
        ));
    }
    let api = build_api_client(cwd, opts.remote.as_deref()).map_err(LockCommandError::Build)?;
    let runtime = build_runtime()?;
    let root = repo_root(cwd).map_err(LockCommandError::Build)?;
    let refspec = resolve_refspec(&root, opts.refspec.as_deref());

    let mut success = true;
    let mut locks: Vec<Lock> = Vec::new();
    for raw in paths {
        let path = match resolve_lock_path(cwd, &root, raw) {
            Ok(p) => p,
            Err(e) => {
                eprintln!("git-lfs: {e}");
                success = false;
                continue;
            }
        };
        let mut req = CreateLockRequest::new(path.clone());
        if let Some(name) = &refspec {
            req = req.with_ref(Ref::new(name.clone()));
        }
        match runtime.block_on(api.create_lock(&req)) {
            Ok(lock) => {
                if !opts.json {
                    println!("Locked {path} ({})", lock.id);
                }
                // The user took the lock to edit the file; if the
                // file is currently read-only (because it matches a
                // lockable pattern and the previous post-* hook
                // chmod'd it), they need it writable. Best-effort —
                // a chmod failure shouldn't fail the lock op.
                let _ = lockable::force_writable(&root, &path);
                // Persist to the on-disk cache so a later
                // `git lfs locks --local` (or an unlock that needs
                // path→id lookup) can find it without a round-trip.
                lock_cache::add(cwd, &lock);
                locks.push(lock);
            }
            Err(CreateLockError::Conflict { existing, message }) => {
                // Match upstream's "Locking <path> failed: <reason>"
                // shape (see `t-lock.sh::locking a previously locked
                // file`). Owner goes on its own follow-up line.
                eprintln!("Locking {path} failed: {message}");
                if let Some(owner) = existing.as_ref().and_then(|l| l.owner.as_ref()) {
                    eprintln!("  Lock owner: {}", owner.name);
                }
                success = false;
            }
            Err(CreateLockError::Api(e)) => {
                eprintln!("Locking {path} failed: {}", api_error_reason(&e));
                success = false;
            }
        }
    }

    if opts.json {
        println!("{}", serde_json::to_string(&locks)?);
    }
    Ok(success)
}

// --------------------------------------------------------------------------
// locks (list)
// --------------------------------------------------------------------------

#[derive(Debug, Serialize)]
struct VerifyJsonOutput<'a> {
    ours: &'a [Lock],
    theirs: &'a [Lock],
}

pub fn locks(cwd: &Path, opts: &LocksOptions) -> Result<(), LockCommandError> {
    let root = repo_root(cwd).map_err(LockCommandError::Build)?;

    // `--local`: read from the on-disk cache without a server round-
    // trip (the test deliberately removes `origin` to prove we don't
    // talk to it). Path/id/limit filters apply, but `--verify` doesn't
    // make sense locally — upstream rejects that combination too.
    if opts.local {
        let path_filter = match opts.path.as_deref() {
            Some(raw) => Some(resolve_lock_path(cwd, &root, raw).map_err(LockCommandError::Build)?),
            None => None,
        };
        let cached = lock_cache::read(cwd);
        let mut filtered: Vec<Lock> = cached
            .into_iter()
            .filter(|l| match (&path_filter, &opts.id) {
                (Some(p), _) if &l.path != p => false,
                (_, Some(id)) if &l.id != id => false,
                _ => true,
            })
            .collect();
        if let Some(limit) = opts.limit {
            filtered.truncate(limit as usize);
        }
        if opts.json {
            println!("{}", serde_json::to_string(&filtered)?);
        } else {
            print_lock_table(&filtered, None);
        }
        return Ok(());
    }

    let api = build_api_client(cwd, opts.remote.as_deref()).map_err(LockCommandError::Build)?;
    let runtime = build_runtime()?;
    let refspec = resolve_refspec(&root, opts.refspec.as_deref());

    if opts.verify {
        let resp = runtime
            .block_on(verify_all(&api, opts.limit, refspec.clone()))
            .map_err(|e| format_api_error(&e))
            .map_err(LockCommandError::Api)?;
        if opts.json {
            println!(
                "{}",
                serde_json::to_string(&VerifyJsonOutput {
                    ours: &resp.ours,
                    theirs: &resp.theirs,
                })?
            );
        } else {
            print_verify_table(&resp);
        }
        return Ok(());
    }

    // Path filter must be relativized just like `lock` does — the server
    // stores repo-relative paths, so a user-supplied `./data/x.bin`
    // wouldn't match anything otherwise.
    let path_filter = match opts.path.as_deref() {
        Some(raw) => Some(resolve_lock_path(cwd, &root, raw).map_err(LockCommandError::Build)?),
        None => None,
    };

    let mut filter = ListLocksFilter {
        path: path_filter,
        id: opts.id.clone(),
        limit: opts.limit,
        refspec: refspec.clone(),
        ..Default::default()
    };
    let mut all_locks: Vec<Lock> = Vec::new();
    loop {
        let page: LockList = runtime
            .block_on(api.list_locks(&filter))
            .map_err(|e| LockCommandError::Api(format_api_error(&e)))?;
        all_locks.extend(page.locks);
        // Check the limit BEFORE the cursor — a server that ignores
        // `?limit=N` and returns more on the last page would otherwise
        // sneak past us (we'd see no next_cursor and exit before the
        // truncate would have fired).
        if let Some(limit) = opts.limit
            && all_locks.len() >= limit as usize
        {
            all_locks.truncate(limit as usize);
            break;
        }
        match page.next_cursor {
            Some(c) if !c.is_empty() => filter.cursor = Some(c),
            _ => break,
        }
    }

    if opts.json {
        println!("{}", serde_json::to_string(&all_locks)?);
    } else {
        print_lock_table(&all_locks, None);
    }
    Ok(())
}

/// Drain `verify_locks` across all pages, since the API paginates the same
/// way `list_locks` does.
async fn verify_all(
    api: &ApiClient,
    limit: Option<u32>,
    refspec: Option<String>,
) -> Result<VerifyLocksResponse, git_lfs_api::ApiError> {
    let mut req = VerifyLocksRequest {
        limit,
        r#ref: refspec.map(Ref::new),
        ..Default::default()
    };
    let mut combined = VerifyLocksResponse {
        ours: Vec::new(),
        theirs: Vec::new(),
        next_cursor: None,
    };
    loop {
        let page = api.verify_locks(&req).await?;
        combined.ours.extend(page.ours);
        combined.theirs.extend(page.theirs);
        match page.next_cursor {
            Some(c) if !c.is_empty() => req.cursor = Some(c),
            _ => break,
        }
    }
    Ok(combined)
}

// --------------------------------------------------------------------------
// unlock
// --------------------------------------------------------------------------

#[derive(Debug, Serialize)]
struct UnlockJsonEntry {
    #[serde(skip_serializing_if = "Option::is_none")]
    id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    path: Option<String>,
    unlocked: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    reason: Option<String>,
}

pub fn unlock(
    cwd: &Path,
    paths: &[String],
    opts: &UnlockOptions,
) -> Result<bool, LockCommandError> {
    let has_path = !paths.is_empty();
    let has_id = opts.id.is_some();
    if has_path == has_id {
        // Capital "E" matches the upstream test grep.
        return Err(LockCommandError::Build(
            "Exactly one of --id or a set of paths must be provided".into(),
        ));
    }

    let api = build_api_client(cwd, opts.remote.as_deref()).map_err(LockCommandError::Build)?;
    let runtime = build_runtime()?;
    let root = repo_root(cwd).map_err(LockCommandError::Build)?;
    let refspec = resolve_refspec(&root, opts.refspec.as_deref());
    let lockable_readonly = crate::lockable::lockable_readonly_enabled(&root);
    let mut success = true;
    let mut report: Vec<UnlockJsonEntry> = Vec::new();

    if has_id {
        let id = opts.id.clone().expect("checked above");
        let req = build_delete_request(opts.force, refspec.as_deref());
        let attrs = git_lfs_git::AttrSet::from_workdir(&root).ok();
        match runtime.block_on(api.delete_lock(&id, &req)) {
            Ok(lock) => {
                if !opts.json {
                    println!("Unlocked Lock {id}");
                } else {
                    report.push(UnlockJsonEntry {
                        id: Some(id.clone()),
                        path: None,
                        unlocked: true,
                        reason: None,
                    });
                }
                // The server hands back the unlocked lock's path in
                // the response; use it to restore the read-only
                // invariant for lockable patterns. Without this,
                // `unlock --id=<id>` doesn't chmod even though
                // path-based unlock does.
                if lockable_readonly && let Some(attrs) = attrs.as_ref() {
                    let _ = lockable::enforce_readonly_if_lockable(&root, attrs, &lock.path);
                }
                lock_cache::remove_by_id(cwd, &id);
            }
            Err(e) => {
                eprintln!("Unlocking {id} failed: {}", api_error_reason(&e));
                success = false;
                if opts.json {
                    report.push(UnlockJsonEntry {
                        id: Some(id),
                        path: None,
                        unlocked: false,
                        reason: Some(api_error_reason(&e)),
                    });
                }
            }
        }
    } else {
        // Built once so we can flip a successfully-released lockable
        // path back to read-only without re-parsing `.gitattributes`
        // for every path.
        let attrs = git_lfs_git::AttrSet::from_workdir(&root).ok();
        for raw in paths {
            let path = match resolve_lock_path(cwd, &root, raw) {
                Ok(p) => p,
                Err(e) if opts.force => {
                    // Match upstream: with --force, fall back to the
                    // raw path. The server may still reject it.
                    eprintln!("git-lfs: warning: {e} (continuing because --force)");
                    raw.replace('\\', "/").trim_start_matches("./").to_owned()
                }
                Err(e) => {
                    eprintln!("git-lfs: {e}");
                    success = false;
                    if opts.json {
                        report.push(UnlockJsonEntry {
                            id: None,
                            path: Some(raw.clone()),
                            unlocked: false,
                            reason: Some(e),
                        });
                    }
                    continue;
                }
            };

            // Refuse to unlock a path with uncommitted edits unless
            // `--force` is given (in which case we warn and continue,
            // matching upstream).
            if has_uncommitted_changes(&root, &path) {
                if opts.force {
                    eprintln!("warning: unlocking with uncommitted changes");
                } else {
                    let msg = "Cannot unlock file with uncommitted changes";
                    eprintln!("{msg}");
                    success = false;
                    if opts.json {
                        report.push(UnlockJsonEntry {
                            id: None,
                            path: Some(path.clone()),
                            unlocked: false,
                            reason: Some(msg.into()),
                        });
                    }
                    continue;
                }
            }

            // Look up the lock id by path. Use a bounded list — we want
            // exact-path matches, of which there's at most one.
            let lookup = ListLocksFilter {
                path: Some(path.clone()),
                refspec: refspec.clone(),
                ..Default::default()
            };
            let id = match runtime.block_on(api.list_locks(&lookup)) {
                Ok(list) => list
                    .locks
                    .iter()
                    .find(|l| l.path == path)
                    .map(|l| l.id.clone()),
                Err(e) => {
                    eprintln!(
                        "git-lfs: lookup failed for {path}: {}",
                        format_api_error(&e)
                    );
                    success = false;
                    if opts.json {
                        report.push(UnlockJsonEntry {
                            id: None,
                            path: Some(path.clone()),
                            unlocked: false,
                            reason: Some(format_api_error(&e)),
                        });
                    }
                    continue;
                }
            };
            let Some(id) = id else {
                eprintln!("git-lfs: {path} is not locked");
                success = false;
                if opts.json {
                    report.push(UnlockJsonEntry {
                        id: None,
                        path: Some(path.clone()),
                        unlocked: false,
                        reason: Some("not locked".into()),
                    });
                }
                continue;
            };
            let req = build_delete_request(opts.force, refspec.as_deref());
            match runtime.block_on(api.delete_lock(&id, &req)) {
                Ok(_) => {
                    if !opts.json {
                        println!("Unlocked {path}");
                    }
                    // Restore the read-only invariant for lockable
                    // paths now that we no longer hold the lock —
                    // unless `lfs.setlockablereadonly=false` opts out.
                    if lockable_readonly && let Some(attrs) = attrs.as_ref() {
                        let _ = lockable::enforce_readonly_if_lockable(&root, attrs, &path);
                    }
                    lock_cache::remove_by_id(cwd, &id);
                    lock_cache::remove_by_path(cwd, &path);
                    if opts.json {
                        // Path-based unlocks emit only `path` and
                        // `unlocked` per upstream's JSON schema; the
                        // id field is reserved for `--id`-keyed
                        // unlocks.
                        report.push(UnlockJsonEntry {
                            id: None,
                            path: Some(path),
                            unlocked: true,
                            reason: None,
                        });
                    }
                }
                Err(e) => {
                    eprintln!("Unlocking {path} failed: {}", api_error_reason(&e));
                    success = false;
                    if opts.json {
                        report.push(UnlockJsonEntry {
                            id: None,
                            path: Some(path),
                            unlocked: false,
                            reason: Some(api_error_reason(&e)),
                        });
                    }
                }
            }
        }
    }

    if opts.json {
        println!("{}", serde_json::to_string(&report)?);
    }
    Ok(success)
}

fn build_delete_request(force: bool, refspec: Option<&str>) -> DeleteLockRequest {
    DeleteLockRequest {
        force,
        r#ref: refspec.map(|n| Ref::new(n.to_string())),
    }
}

// --------------------------------------------------------------------------
// helpers
// --------------------------------------------------------------------------

fn build_runtime() -> std::io::Result<Runtime> {
    tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
}

/// Resolve the refspec to send with lock-API requests: caller-supplied
/// override wins, else `git_lfs_git::refs::current_refspec`. `None`
/// means "send no ref" (detached HEAD with no override).
fn resolve_refspec(repo_root: &Path, override_ref: Option<&str>) -> Option<String> {
    if let Some(s) = override_ref {
        return Some(s.to_owned());
    }
    git_lfs_git::refs::current_refspec(repo_root)
}

/// Pull just the human-readable reason out of an `ApiError`. For
/// `Status` with a server-supplied error body, use the body's
/// `message` directly so the user sees what the LFS server said
/// without our "server returned status N:" wrapper. The wrapper makes
/// the test grep brittle (e.g. `grep 'Locking a.dat failed: Expected
/// ref ...'`).
fn api_error_reason(e: &ApiError) -> String {
    match e {
        ApiError::Status { body: Some(b), .. } => b.message.clone(),
        _ => e.to_string(),
    }
}

/// Same idea as [`api_error_reason`], used at call sites where the
/// command is wrapping the error as a string for upper layers (e.g.
/// `lookup failed for {path}: {…}`).
fn format_api_error(e: &ApiError) -> String {
    api_error_reason(e)
}

/// True if `path` (relative to `root`) has staged or unstaged
/// modifications. `git status --porcelain -- <path>` prints a line
/// only for dirty paths; an empty result means clean. Errors fall
/// back to "clean" so a `git status` failure doesn't block unlock.
fn has_uncommitted_changes(root: &Path, path: &str) -> bool {
    let out = Command::new("git")
        .arg("-C")
        .arg(root)
        .args(["status", "--porcelain", "--", path])
        .output();
    match out {
        Ok(o) if o.status.success() => !o.stdout.is_empty(),
        _ => false,
    }
}

fn repo_root(cwd: &Path) -> Result<PathBuf, String> {
    let out = std::process::Command::new("git")
        .arg("-C")
        .arg(cwd)
        .args(["rev-parse", "--show-toplevel"])
        .output()
        .map_err(|e| format!("invoking git: {e}"))?;
    if !out.status.success() {
        return Err(format!(
            "git rev-parse failed: {}",
            String::from_utf8_lossy(&out.stderr).trim()
        ));
    }
    let s = String::from_utf8_lossy(&out.stdout).trim().to_owned();
    if s.is_empty() {
        return Err("not in a git repository".into());
    }
    Ok(PathBuf::from(s))
}

/// Resolve `file` to a repo-relative POSIX path suitable for the locking
/// API. Mirrors upstream's `lockPath` — it uses `filepath.Abs` which
/// also does not follow symlinks, just lexical normalization. That
/// matters when the user is locking a path that traverses a symlink:
/// `git lfs lock folder1/folder2/a.dat` (where `folder1/folder2` is a
/// symlink) should record the path as typed, not the resolved target
/// (`t-lock` test 14).
fn resolve_lock_path(cwd: &Path, repo_root: &Path, file: &str) -> Result<String, String> {
    let file_path = Path::new(file);
    let abs = if file_path.is_absolute() {
        file_path.to_path_buf()
    } else {
        cwd.join(file_path)
    };
    let cleaned = lexical_clean(&abs);
    let root_cleaned = lexical_clean(repo_root);

    let rel = cleaned
        .strip_prefix(&root_cleaned)
        .map_err(|_| format!("path is outside the repository: {file}"))?;
    let s = rel.to_string_lossy().replace('\\', "/");
    if s.is_empty() || s == "." {
        return Err(format!("cannot lock the repository root: {file}"));
    }

    // is_dir() follows symlinks for the metadata syscall but doesn't
    // change the path text — so we still emit the user-typed form on
    // success.
    if cleaned.is_dir() {
        // Test grep expects "cannot lock directory" verbatim
        // (`t-lock.sh::locking a directory`).
        return Err(format!("cannot lock directory: {file}"));
    }

    Ok(s)
}

/// Lexical path normalization: collapse `.` and `..` components without
/// touching the filesystem. Equivalent of Go's `path/filepath.Clean`.
fn lexical_clean(p: &Path) -> PathBuf {
    let mut out = PathBuf::new();
    for c in p.components() {
        match c {
            std::path::Component::CurDir => {}
            std::path::Component::ParentDir => {
                out.pop();
            }
            other => out.push(other.as_os_str()),
        }
    }
    out
}

fn print_lock_table(locks: &[Lock], owned: Option<&std::collections::HashSet<String>>) {
    let mut sorted: Vec<&Lock> = locks.iter().collect();
    sorted.sort_by(|a, b| a.path.cmp(&b.path));

    let max_path = sorted.iter().map(|l| l.path.len()).max().unwrap_or(0);
    let max_owner = sorted
        .iter()
        .map(|l| l.owner.as_ref().map(|o| o.name.len()).unwrap_or(0))
        .max()
        .unwrap_or(0);

    for lock in sorted {
        let owner_name = lock.owner.as_ref().map(|o| o.name.as_str()).unwrap_or("");
        let path_pad = " ".repeat(max_path.saturating_sub(lock.path.len()));
        let owner_pad = " ".repeat(max_owner.saturating_sub(owner_name.len()));
        let kind = match owned {
            Some(set) if set.contains(&lock.id) => "O ",
            Some(_) => "  ",
            None => "",
        };
        println!(
            "{kind}{}{path_pad}\t{}{owner_pad}\tID:{}",
            lock.path, owner_name, lock.id,
        );
    }
}

fn print_verify_table(resp: &VerifyLocksResponse) {
    let mut combined = Vec::with_capacity(resp.ours.len() + resp.theirs.len());
    combined.extend(resp.ours.iter().cloned());
    combined.extend(resp.theirs.iter().cloned());
    let owned: std::collections::HashSet<String> = resp.ours.iter().map(|l| l.id.clone()).collect();
    print_lock_table(&combined, Some(&owned));
}

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

    fn init_repo() -> TempDir {
        let tmp = TempDir::new().unwrap();
        let status = std::process::Command::new("git")
            .args(["init", "--quiet"])
            .arg(tmp.path())
            .status()
            .unwrap();
        assert!(status.success());
        tmp
    }

    #[test]
    fn resolve_lock_path_relative_under_root() {
        let tmp = init_repo();
        std::fs::write(tmp.path().join("a.bin"), b"x").unwrap();
        let path = resolve_lock_path(tmp.path(), tmp.path(), "a.bin").unwrap();
        assert_eq!(path, "a.bin");
    }

    #[test]
    fn resolve_lock_path_absolute() {
        let tmp = init_repo();
        std::fs::write(tmp.path().join("a.bin"), b"x").unwrap();
        let abs = tmp.path().join("a.bin");
        let path = resolve_lock_path(tmp.path(), tmp.path(), abs.to_str().unwrap()).unwrap();
        assert_eq!(path, "a.bin");
    }

    #[test]
    fn resolve_lock_path_subdir_uses_forward_slashes() {
        let tmp = init_repo();
        std::fs::create_dir(tmp.path().join("data")).unwrap();
        std::fs::write(tmp.path().join("data/blob.bin"), b"x").unwrap();
        let path = resolve_lock_path(tmp.path(), tmp.path(), "data/blob.bin").unwrap();
        assert_eq!(path, "data/blob.bin");
    }

    #[test]
    fn resolve_lock_path_rejects_directory() {
        let tmp = init_repo();
        std::fs::create_dir(tmp.path().join("data")).unwrap();
        let err = resolve_lock_path(tmp.path(), tmp.path(), "data").unwrap_err();
        assert!(err.contains("directory"), "{err}");
    }

    #[test]
    fn resolve_lock_path_rejects_outside_repo() {
        let tmp_repo = init_repo();
        let tmp_other = TempDir::new().unwrap();
        std::fs::write(tmp_other.path().join("x.bin"), b"x").unwrap();
        let outside = tmp_other.path().join("x.bin");
        let err = resolve_lock_path(tmp_repo.path(), tmp_repo.path(), outside.to_str().unwrap())
            .unwrap_err();
        assert!(err.contains("outside"), "{err}");
    }

    #[test]
    fn resolve_lock_path_allows_nonexistent_leaf() {
        // Locking a file that doesn't exist yet should be permitted —
        // the server stores the path string verbatim, and locking
        // ahead of file creation is a legitimate workflow.
        let tmp = init_repo();
        let path = resolve_lock_path(tmp.path(), tmp.path(), "nope.bin").unwrap();
        assert_eq!(path, "nope.bin");
    }
}