chronogit 0.9.0

A terminal UI for Git history, diffs, and source code
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
//! Domain-level repository operations built on the typed Git runner boundary.

use std::ffi::{OsStr, OsString};
use std::fs::File;
use std::io::Read;
use std::num::NonZeroUsize;
use std::os::fd::OwnedFd;
use std::path::Path;
use std::sync::atomic::{AtomicBool, Ordering};

#[cfg(unix)]
use std::os::unix::ffi::{OsStrExt, OsStringExt};

use bstr::ByteSlice;
use rustix::fs::{FileType, Mode, OFlags};
use rustix::io::Errno;

use crate::domain::{
    ChangedFile, CommitBaseline, CommitMessage, CommitPage, CommitSummary, DiffDocument,
    DiffTarget, FileDocument, FileRevision, LocalBranch, ObjectId, RepoPath, RepositoryRoot,
    SearchHit, TextFileDocument, TreeEntry, WorktreeChange, WorktreeDiffKind,
};
use crate::git::parse::{
    parse_changed_files, parse_commits, parse_file_paths, parse_grep_matches, parse_patch,
    parse_status, parse_tree_entries,
};
use crate::git::{CommandOutput, GitCommand, GitError, GitRunner, OutputCompleteness};

const MAX_FILE_BYTES: usize = 8 * 1024 * 1024;
const FILE_READ_WITH_TRUNCATION_SENTINEL: u64 = MAX_FILE_BYTES as u64 + 1;
const REVISION_NOT_FOUND_EXIT_CODE: i32 = 1;
const GREP_NO_MATCH_EXIT_CODE: i32 = 1;
const OBJECT_NOT_FOUND_EXIT_CODE: i32 = 128;
const DIFF_DIFFERENCES_EXIT_CODE: i32 = 1;

#[derive(Clone, Copy)]
enum SourceRetention {
    DisplayOnly,
    RetainExact,
}

impl SourceRetention {
    const fn retains_exact_source(self) -> bool {
        matches!(self, Self::RetainExact)
    }
}

/// A discovered, non-bare repository accessed through a [`GitRunner`].
///
/// The service owns the absolute worktree root and is the only component that
/// combines typed commands, bounded output, parsers, and domain comparison
/// policy. Explicit local-branch switching is its only repository mutation.
#[derive(Debug)]
pub struct GitService<R> {
    runner: R,
    root: RepositoryRoot,
    worktree: OwnedFd,
    retain_exact_source: AtomicBool,
}

impl<R: GitRunner> GitService<R> {
    /// Resolves `start` to a non-bare worktree and constructs its service.
    ///
    /// `start` may be the worktree root or any directory beneath it.
    ///
    /// # Errors
    ///
    /// Returns an error when the path cannot be canonicalized, is not a
    /// directory, is outside a Git worktree, is bare, or when Git returns
    /// malformed, truncated, or unsuccessful discovery output.
    pub fn discover(runner: R, start: &Path) -> Result<Self, GitError> {
        let start = start.canonicalize().map_err(|source| GitError::Io {
            operation: "resolve repository path",
            source,
        })?;
        if !start.is_dir() {
            return Err(GitError::Unsupported(format!(
                "repository path is not a directory: {}",
                start.display()
            )));
        }
        let output = runner.run(None, &GitCommand::Discover { start })?;
        ensure_complete(&output, "discover repository")?;
        ensure_success(&output, "discover repository")?;
        // rev-parse appends one LF; any preceding CR/LF bytes belong to the
        // Unix path and must survive repository-root validation unchanged.
        let raw = output
            .stdout()
            .strip_suffix(b"\n")
            .unwrap_or(output.stdout());
        if raw.is_empty() {
            return Err(GitError::parse(
                "repository root",
                "Git returned an empty path",
            ));
        }
        #[cfg(unix)]
        let path = std::path::PathBuf::from(OsString::from_vec(raw.to_vec()));
        let root = RepositoryRoot::new(path)
            .map_err(|detail| GitError::parse("repository root", detail.to_string()))?;
        let bare = runner.run(Some(&root), &GitCommand::IsBare)?;
        ensure_complete(&bare, "check bare repository")?;
        ensure_success(&bare, "check bare repository")?;
        if trim_newline(bare.stdout()) == b"true" {
            return Err(GitError::Unsupported(format!(
                "bare repositories are not supported by ChronoGit v{}",
                env!("CARGO_PKG_VERSION")
            )));
        }
        let worktree = rustix::fs::open(
            root.as_path(),
            OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
            Mode::empty(),
        )
        .map_err(|source| filesystem_error("open repository root", source))?;
        Ok(Self {
            runner,
            root,
            worktree,
            retain_exact_source: AtomicBool::new(false),
        })
    }

    pub(crate) fn enable_exact_source(&self) {
        self.retain_exact_source.store(true, Ordering::Relaxed);
    }

    /// Returns the absolute root of the discovered working tree.
    #[must_use]
    pub fn root(&self) -> &RepositoryRoot {
        &self.root
    }

    /// Lists existing local branches in name order, marking the current branch.
    ///
    /// Detached HEAD has no current marker; an empty repository has no branches.
    ///
    /// # Errors
    /// Returns an error for unsuccessful, truncated, or malformed Git output.
    pub fn local_branches(&self) -> Result<Vec<LocalBranch>, GitError> {
        let output = self
            .runner
            .run(Some(&self.root), &GitCommand::LocalBranches)?;
        ensure_complete(&output, "list local branches")?;
        ensure_success(&output, "list local branches")?;
        if output.stdout().is_empty() {
            return Ok(Vec::new());
        }
        let records = output
            .stdout()
            .strip_suffix(b"\n")
            .ok_or_else(|| GitError::parse("local branches", "missing record terminator"))?;
        records
            .split(|byte| *byte == b'\n')
            .map(|record| {
                let (marker, reference) = record
                    .split_once_str(b"\0")
                    .ok_or_else(|| GitError::parse("local branches", "missing branch name"))?;
                if !matches!(marker, b"*" | b" ") {
                    return Err(GitError::parse("local branches", "invalid current marker"));
                }
                LocalBranch::from_ref(reference, marker == b"*")
                    .ok_or_else(|| GitError::parse("local branches", "invalid local reference"))
            })
            .collect()
    }

    /// Switches HEAD, index, and worktree to a listed local branch.
    ///
    /// Git preserves compatible local changes and refuses conflicts. This never
    /// forces a checkout, creates a branch, runs hooks, or recurses into submodules.
    ///
    /// # Errors
    /// Returns Git's error for conflicting changes, missing branches, branches
    /// checked out elsewhere, or process failure. Reload repository state after
    /// a timeout because the process may have changed files before it stopped.
    pub fn switch_branch(&self, branch: &LocalBranch) -> Result<(), GitError> {
        let output = self.runner.run(
            Some(&self.root),
            &GitCommand::SwitchBranch {
                branch: branch.clone(),
            },
        )?;
        ensure_success(&output, "switch branch")?;
        ensure_complete(&output, "switch branch")
    }

    /// Reads unstaged tracked and untracked worktree changes.
    ///
    /// Inclusion follows the worktree side of porcelain-v2 XY status, so a
    /// staged-only path is intentionally omitted.
    ///
    /// # Errors
    ///
    /// Returns an error when Git cannot read status, bounded output is
    /// incomplete, or a porcelain record is malformed.
    pub fn changes(&self) -> Result<Vec<WorktreeChange>, GitError> {
        let output = self.runner.run(Some(&self.root), &GitCommand::Status)?;
        ensure_complete(&output, "read worktree status")?;
        ensure_success(&output, "read worktree status")?;
        parse_status(output.stdout())
    }

    /// Reads one validated, non-empty page of commit summaries.
    ///
    /// An unborn `HEAD` is a valid empty history. Parent order and complete
    /// object IDs are retained for graph rendering and baseline selection.
    ///
    /// # Errors
    ///
    /// Returns an error when Git execution fails, bounded output is incomplete,
    /// or a commit record is malformed.
    pub fn commits(&self, page: CommitPage) -> Result<Vec<CommitSummary>, GitError> {
        let head = self.runner.run(Some(&self.root), &GitCommand::HasHead)?;
        ensure_complete(&head, "check HEAD")?;
        if !head.success() && head.code() == Some(REVISION_NOT_FOUND_EXIT_CODE) {
            return Ok(Vec::new());
        }
        ensure_success(&head, "check HEAD")?;
        let output = self
            .runner
            .run(Some(&self.root), &GitCommand::Commits { page })?;
        ensure_complete(&output, "read commit history")?;
        ensure_success(&output, "read commit history")?;
        parse_commits(output.stdout())
    }

    /// Searches tracked and untracked path names using smart-case substring matching.
    ///
    /// Queries containing an uppercase character are case-sensitive; all other
    /// queries use Unicode lowercase matching. An empty query returns every path.
    ///
    /// # Errors
    ///
    /// Returns an error when Git cannot enumerate files, output crosses its
    /// limit, or the NUL-delimited path list is malformed.
    pub fn search_files(&self, query: &str) -> Result<Vec<SearchHit>, GitError> {
        let mut files = self
            .repository_files()?
            .into_iter()
            .map(SearchHit::file)
            .collect::<Vec<_>>();
        let case_sensitive = query.chars().any(char::is_uppercase);
        let folded_query = (!case_sensitive).then(|| query.to_lowercase());
        files.retain(|hit| {
            let path = hit.path().display();
            if case_sensitive {
                path.contains(query)
            } else {
                path.to_lowercase()
                    .contains(folded_query.as_deref().unwrap_or_default())
            }
        });
        Ok(files)
    }

    /// Lists tracked and untracked working-tree file paths.
    ///
    /// Ignored files are omitted according to Git's standard exclude rules.
    /// The result retains repository-relative path bytes on Unix and is used by
    /// both file search and the code-viewer tree.
    ///
    /// # Errors
    ///
    /// Returns an error when Git cannot enumerate files, output crosses its
    /// limit, or the NUL-delimited path list is malformed.
    pub fn repository_files(&self) -> Result<Vec<RepoPath>, GitError> {
        let output = self
            .runner
            .run(Some(&self.root), &GitCommand::RepositoryFiles)?;
        ensure_complete(&output, "list repository files")?;
        ensure_success(&output, "list repository files")?;
        parse_file_paths(output.stdout()).map(|hits| {
            hits.into_iter()
                .map(|hit| hit.path().clone())
                .collect::<Vec<_>>()
        })
    }

    /// Searches non-binary working-tree contents for literal `query` text.
    ///
    /// An empty query or Git's no-match status returns an empty result rather
    /// than an error. Matches include repository path, one-based line, and a
    /// bounded preview supplied by Git.
    ///
    /// # Errors
    ///
    /// Returns an error for Git execution failures other than no-match,
    /// truncated output, or malformed match records.
    pub fn search_content(&self, query: &str) -> Result<Vec<SearchHit>, GitError> {
        if query.is_empty() {
            return Ok(Vec::new());
        }
        let output = self.runner.run(
            Some(&self.root),
            &GitCommand::Grep {
                query: query.to_owned(),
            },
        )?;
        ensure_complete(&output, "search repository content")?;
        if !output.success()
            && output.code() == Some(GREP_NO_MATCH_EXIT_CODE)
            && output.stderr().is_empty()
        {
            return Ok(Vec::new());
        }
        ensure_success(&output, "search repository content")?;
        parse_grep_matches(output.stdout())
    }

    /// Reads at most `limit` commits that touched `path`.
    ///
    /// # Errors
    ///
    /// Returns an error when Git execution fails, output is incomplete, or a
    /// commit record is malformed.
    pub fn file_history(
        &self,
        path: &RepoPath,
        limit: NonZeroUsize,
    ) -> Result<Vec<CommitSummary>, GitError> {
        let output = self.runner.run(
            Some(&self.root),
            &GitCommand::FileHistory {
                path: path.clone(),
                limit,
            },
        )?;
        ensure_complete(&output, "read file history")?;
        ensure_success(&output, "read file history")?;
        parse_commits(output.stdout())
    }

    /// Reads current working-tree content without following symbolic links in
    /// any path component.
    ///
    /// Regular-file reads are capped at 8 MiB. A NUL byte classifies the result
    /// as binary, missing or special files become an unavailable document, and
    /// a symbolic link returns its target instead of opening the target.
    ///
    /// # Errors
    ///
    /// Returns an error when metadata, link-target, open, or read operations fail
    /// for reasons other than a missing path or a rejected intermediate link.
    pub fn file_content(&self, path: &RepoPath) -> Result<FileDocument, GitError> {
        let (mut file, size) = match open_current_file(&self.worktree, path)? {
            CurrentFile::Regular { file, size } => (file, size),
            CurrentFile::Symlink { target } => return Ok(FileDocument::Symlink { target }),
            CurrentFile::Unavailable { summary } => {
                return Ok(FileDocument::Unavailable { summary });
            }
        };
        let mut bytes = Vec::with_capacity(size.min(MAX_FILE_BYTES));
        file.by_ref()
            .take(FILE_READ_WITH_TRUNCATION_SENTINEL)
            .read_to_end(&mut bytes)
            .map_err(|source| GitError::Io {
                operation: "read working tree file",
                source,
            })?;
        let truncated = bytes.len() > MAX_FILE_BYTES;
        bytes.truncate(MAX_FILE_BYTES);
        let completeness = OutputCompleteness::from_truncated(truncated);
        let retention = if self.retain_exact_source.load(Ordering::Relaxed) {
            SourceRetention::RetainExact
        } else {
            SourceRetention::DisplayOnly
        };
        Ok(decode_file_document(&bytes, completeness, path, retention))
    }

    /// Reads a complete source file from the working tree or an immutable commit.
    ///
    /// Revision reads use a validated object ID and repository path through the
    /// closed Git command boundary. Like working-tree reads, retained output is
    /// capped at 8 MiB and exact UTF-8 source is kept only when LSP support is enabled.
    ///
    /// # Errors
    ///
    /// Returns an error when Git cannot read a requested commit path or when its
    /// diagnostic stream is incomplete.
    pub fn source_file(
        &self,
        revision: &FileRevision,
        path: &RepoPath,
    ) -> Result<FileDocument, GitError> {
        let revision = match revision {
            FileRevision::WorkingTree => return self.file_content(path),
            FileRevision::Commit(revision) => revision,
        };
        let command = GitCommand::RevisionFile {
            revision: revision.clone(),
            path: path.clone(),
        };
        let output = self.runner.run(Some(&self.root), &command)?;
        if output.stderr_truncated() {
            return Err(GitError::OutputLimit {
                operation: command.kind(),
            });
        }
        if !output.success()
            && !output.stdout_truncated()
            && output.code() == Some(OBJECT_NOT_FOUND_EXIT_CODE)
            && output.stdout().is_empty()
        {
            return Ok(FileDocument::Unavailable {
                summary: format!(
                    "File does not exist in {}: {}",
                    FileRevision::Commit(revision.clone()).display(),
                    path.display()
                ),
            });
        }
        if !output.success() && !output.stdout_truncated() {
            ensure_success(&output, command.kind())?;
        }
        let completeness = OutputCompleteness::from_truncated(output.stdout_truncated());
        let retention = if self.retain_exact_source.load(Ordering::Relaxed) {
            SourceRetention::RetainExact
        } else {
            SourceRetention::DisplayOnly
        };
        Ok(decode_file_document(
            output.stdout(),
            completeness,
            path,
            retention,
        ))
    }

    /// Reads the complete subject and body of `commit`.
    ///
    /// Invalid UTF-8 is replaced only at this presentation-oriented text
    /// boundary; object identifiers remain validated full hexadecimal values.
    ///
    /// # Errors
    ///
    /// Returns an error when Git execution fails or either output stream is
    /// incomplete.
    pub fn commit_message(&self, commit: &ObjectId) -> Result<CommitMessage, GitError> {
        let output = self.runner.run(
            Some(&self.root),
            &GitCommand::CommitMessage {
                commit: commit.clone(),
            },
        )?;
        ensure_complete(&output, "read commit message")?;
        ensure_success(&output, "read commit message")?;
        Ok(CommitMessage::new(
            output.stdout().to_str_lossy().into_owned(),
        ))
    }

    /// Lists paths changed by `commit` relative to `baseline`.
    ///
    /// # Errors
    ///
    /// Returns an error when Git execution fails, output is incomplete, or a
    /// NUL-delimited name-status record is malformed.
    pub fn changed_files(
        &self,
        commit: &ObjectId,
        baseline: &CommitBaseline,
    ) -> Result<Vec<ChangedFile>, GitError> {
        let output = self.runner.run(
            Some(&self.root),
            &GitCommand::ChangedFiles {
                commit: commit.clone(),
                baseline: baseline.clone(),
            },
        )?;
        ensure_complete(&output, "read changed files")?;
        ensure_success(&output, "read changed files")?;
        parse_changed_files(output.stdout())
    }

    /// Reads and parses a bounded patch for a worktree or commit target.
    ///
    /// Text standard output that crosses 8 MiB becomes
    /// [`DiffDocument::Truncated`] so a useful prefix remains visible. Truncated
    /// standard error and unsuccessful commands remain failures.
    ///
    /// # Errors
    ///
    /// Returns an error when the runner or Git fails, or when diagnostic output
    /// is incomplete. Exit status 1 is accepted only for the expected
    /// `--no-index` difference produced for an untracked path.
    pub fn diff(&self, target: &DiffTarget) -> Result<DiffDocument, GitError> {
        let command = match target {
            DiffTarget::Worktree {
                path,
                kind: WorktreeDiffKind::Untracked,
            } => GitCommand::UntrackedDiff { path: path.clone() },
            DiffTarget::Worktree { path, .. } => GitCommand::WorktreeDiff { path: path.clone() },
            DiffTarget::Commit {
                commit,
                baseline,
                path,
            } => GitCommand::CommitDiff {
                commit: commit.clone(),
                baseline: baseline.clone(),
                path: path.clone(),
            },
        };
        let output = self.runner.run(Some(&self.root), &command)?;
        if output.stderr_truncated() {
            return Err(GitError::OutputLimit {
                operation: command.kind(),
            });
        }
        let allowed_no_index_difference = matches!(command, GitCommand::UntrackedDiff { .. })
            && output.code() == Some(DIFF_DIFFERENCES_EXIT_CODE)
            && output.stderr().is_empty();
        if !output.success() && !allowed_no_index_difference && !output.stdout_truncated() {
            return Err(command_failed(&output, command.kind()));
        }
        Ok(parse_patch(
            output.stdout(),
            OutputCompleteness::from_truncated(output.stdout_truncated()),
        ))
    }

    /// Reads the direct children of one commit or tree object.
    ///
    /// Recursion is deliberately left to the application so directories can be
    /// expanded lazily.
    ///
    /// # Errors
    ///
    /// Returns an error when Git execution fails, output is incomplete, or an
    /// `ls-tree` record is malformed.
    pub fn tree_entries(&self, treeish: &ObjectId) -> Result<Vec<TreeEntry>, GitError> {
        let output = self.runner.run(
            Some(&self.root),
            &GitCommand::TreeEntries {
                treeish: treeish.clone(),
            },
        )?;
        ensure_complete(&output, "read tree entries")?;
        ensure_success(&output, "read tree entries")?;
        parse_tree_entries(output.stdout())
    }
}

fn decode_file_document(
    bytes: &[u8],
    completeness: OutputCompleteness,
    path: &RepoPath,
    retention: SourceRetention,
) -> FileDocument {
    if bytes.contains(&0) {
        return FileDocument::Binary {
            summary: format!("Binary file: {}", path.display()),
        };
    }
    let text = bytes.to_str_lossy();
    let lines = text.lines().map(ToOwned::to_owned).collect();
    let text = if completeness.is_truncated() {
        TextFileDocument::truncated(lines)
    } else if retention.retains_exact_source() && matches!(&text, std::borrow::Cow::Borrowed(_)) {
        TextFileDocument::exact(text.into_owned())
    } else {
        TextFileDocument::display_only(lines)
    };
    FileDocument::Text(text)
}

enum CurrentFile {
    Regular { file: File, size: usize },
    Symlink { target: String },
    Unavailable { summary: String },
}

fn open_current_file(worktree: &OwnedFd, path: &RepoPath) -> Result<CurrentFile, GitError> {
    let directory_flags = OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC;
    let mut directory = rustix::io::dup(worktree)
        .map_err(|source| filesystem_error("duplicate repository root", source))?;

    let mut components = path.as_bytes().split(|byte| *byte == b'/');
    let final_component = components
        .next_back()
        .ok_or_else(|| GitError::parse("working tree path", "path is empty"))?;
    for component in components {
        let name = OsStr::from_bytes(component);
        directory = match rustix::fs::openat(&directory, name, directory_flags, Mode::empty()) {
            Ok(descriptor) => descriptor,
            Err(Errno::NOENT) => {
                return Ok(CurrentFile::Unavailable {
                    summary: format!(
                        "File does not exist in the current working tree: {}",
                        path.display()
                    ),
                });
            }
            Err(Errno::LOOP | Errno::NOTDIR) => {
                return Ok(CurrentFile::Unavailable {
                    summary: format!(
                        "Path contains a symbolic link or non-directory component: {}",
                        path.display()
                    ),
                });
            }
            Err(source) => {
                return Err(filesystem_error(
                    "open working tree directory component",
                    source,
                ));
            }
        };
    }

    let final_name = OsStr::from_bytes(final_component);
    let descriptor = match rustix::fs::openat(
        &directory,
        final_name,
        OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC,
        Mode::empty(),
    ) {
        Ok(descriptor) => descriptor,
        Err(Errno::LOOP) => {
            let target = rustix::fs::readlinkat(&directory, final_name, Vec::new())
                .map_err(|source| filesystem_error("read working tree symlink", source))?;
            let target = OsString::from_vec(target.as_bytes().to_vec());
            return Ok(CurrentFile::Symlink {
                target: format!("symlink → {}", target.to_string_lossy()),
            });
        }
        Err(Errno::NOENT) => {
            return Ok(CurrentFile::Unavailable {
                summary: format!(
                    "File does not exist in the current working tree: {}",
                    path.display()
                ),
            });
        }
        Err(Errno::NOTDIR) => {
            return Ok(CurrentFile::Unavailable {
                summary: format!("Not a regular working-tree file: {}", path.display()),
            });
        }
        Err(source) => return Err(filesystem_error("open working tree file", source)),
    };

    let metadata = rustix::fs::fstat(&descriptor)
        .map_err(|source| filesystem_error("read working tree file metadata", source))?;
    if !FileType::from_raw_mode(metadata.st_mode).is_file() {
        return Ok(CurrentFile::Unavailable {
            summary: format!("Not a regular working-tree file: {}", path.display()),
        });
    }
    Ok(CurrentFile::Regular {
        file: File::from(descriptor),
        size: usize::try_from(metadata.st_size).unwrap_or(usize::MAX),
    })
}

fn filesystem_error(operation: &'static str, source: Errno) -> GitError {
    GitError::Io {
        operation,
        source: source.into(),
    }
}

fn ensure_success(output: &CommandOutput, operation: &'static str) -> Result<(), GitError> {
    if output.success() {
        Ok(())
    } else {
        Err(command_failed(output, operation))
    }
}

fn ensure_complete(output: &CommandOutput, operation: &'static str) -> Result<(), GitError> {
    if output.stdout_truncated() || output.stderr_truncated() {
        Err(GitError::OutputLimit { operation })
    } else {
        Ok(())
    }
}

fn command_failed(output: &CommandOutput, operation: &'static str) -> GitError {
    GitError::CommandFailed {
        operation,
        code: output.code(),
        stderr: output.stderr().to_str_lossy().into_owned(),
    }
}

fn trim_newline(mut value: &[u8]) -> &[u8] {
    while value
        .last()
        .is_some_and(|byte| matches!(byte, b'\n' | b'\r'))
    {
        value = &value[..value.len() - 1];
    }
    value
}