Add new `rustik-repo` crate

8d4e0e695fe8f04e6e7e6d152d8d09a13ad1b997
Alexis Sellier committed ago 1 parent c7734caf
Cargo.lock +4 -0
132 132
dependencies = [
133 133
 "microserde",
134 134
 "onig-regset",
135 135
]
136 136
137 +
[[package]]
138 +
name = "rustik-repo"
139 +
version = "0.1.0"
140 +
137 141
[[package]]
138 142
name = "rustik-signals"
139 143
version = "0.1.0"
140 144
dependencies = [
141 145
 "libc",
Cargo.toml +2 -0
1 1
[workspace]
2 2
members = [
3 3
  "crates/diff",
4 4
  "crates/highlight",
5 +
  "crates/repo",
5 6
  "crates/signals",
6 7
  "crates/tui",
7 8
  "crates/tui-core",
8 9
  "crates/tui-termion",
9 10
  "crates/tui-widgets"
44 45
onig = { package = "onig-regset", version = "6.7.0", default-features = false }
45 46
serde = { package = "microserde", version = "0.2.0" }
46 47
termion = { version = "4" }
47 48
rustik-highlight = { path = "crates/highlight", version = "0.1.0" }
48 49
rustik-diff = { path = "crates/diff", version = "0.1.0" }
50 +
rustik-repo = { path = "crates/repo", version = "0.1.0" }
49 51
rustik-signals = { path = "crates/signals", version = "0.1.0" }
50 52
rustik-tui = { path = "crates/tui", version = "0.1.0" }
51 53
rustik-tui-core = { path = "crates/tui-core", version = "0.1.0" }
52 54
rustik-tui-widgets = { path = "crates/tui-widgets", version = "0.1.0" }
53 55
rustik-tui-termion = { path = "crates/tui-termion", version = "0.1.0" }
crates/repo/Cargo.toml added +11 -0
1 +
[package]
2 +
name = "rustik-repo"
3 +
description = "Repository abstraction layer for Rustik tools."
4 +
documentation = "https://docs.rs/rustik-repo"
5 +
homepage = "https://crates.io/crates/rustik-repo"
6 +
version.workspace = true
7 +
edition.workspace = true
8 +
license.workspace = true
9 +
10 +
[lints]
11 +
workspace = true
crates/repo/src/lib.rs added +105 -0
1 +
//! Repository abstraction layer for Rustik tools.
2 +
//!
3 +
//! Expanding hunk context means rerunning a diff at a different unified-context
4 +
//! width. The [`Repo`] trait keeps that repository access behind a small
5 +
//! boundary so diff viewers stay I/O-free and testable; [`GitRepo`] is the
6 +
//! `git diff` implementation used by the `rustik-diff` pager. The trait yields
7 +
//! raw unified-diff bytes — parsing is left to the caller, so this crate
8 +
//! carries no diff-format dependency.
9 +
#![deny(unsafe_code)]
10 +
#![warn(missing_docs)]
11 +
#![warn(clippy::unwrap_used)]
12 +
13 +
use std::ffi::{OsStr, OsString};
14 +
use std::io;
15 +
use std::path::{Path, PathBuf};
16 +
use std::process::Command;
17 +
18 +
// Constants //
19 +
20 +
/// Environment variable that disables Git's colored output.
21 +
const NO_COLOR: &str = "NO_COLOR";
22 +
/// Pathspec separator that ends Git's option list.
23 +
const PATHSPEC_SEPARATOR: &str = "--";
24 +
25 +
// Repo //
26 +
27 +
/// A diff backend a viewer can re-query for wider hunk context.
28 +
pub trait Repo {
29 +
    /// Refetches `paths` with `context_lines` of unified context per hunk.
30 +
    ///
31 +
    /// Returns the raw unified-diff bytes; decoding them is the caller's job.
32 +
    fn diff(&self, context_lines: usize, paths: &[&Path]) -> Result<Vec<u8>, RepoError>;
33 +
}
34 +
35 +
/// A [`Repo`] backed by the `git diff` command.
36 +
pub struct GitRepo {
37 +
    /// Working directory for `git diff` invocations.
38 +
    cwd: PathBuf,
39 +
    /// CLI arguments forwarded to Git, as the pager was invoked.
40 +
    args: Vec<OsString>,
41 +
}
42 +
43 +
impl GitRepo {
44 +
    /// Creates a repo that runs `git diff` in `cwd` with forwarded `args`.
45 +
    pub fn new(cwd: impl Into<PathBuf>, args: impl Into<Vec<OsString>>) -> Self {
46 +
        Self {
47 +
            cwd: cwd.into(),
48 +
            args: args.into(),
49 +
        }
50 +
    }
51 +
}
52 +
53 +
impl Repo for GitRepo {
54 +
    fn diff(&self, context_lines: usize, paths: &[&Path]) -> Result<Vec<u8>, RepoError> {
55 +
        // Forwarded args up to any `--` pathspec separator select the diff; the
56 +
        // refetch supplies its own narrowed path list after a fresh separator.
57 +
        let forwarded = self
58 +
            .args
59 +
            .iter()
60 +
            .position(|arg| arg.as_os_str() == OsStr::new(PATHSPEC_SEPARATOR))
61 +
            .map_or(self.args.as_slice(), |separator| &self.args[..separator]);
62 +
        let context = OsString::from(format!("-U{context_lines}"));
63 +
        let output = Command::new("git")
64 +
            .arg("diff")
65 +
            .args(forwarded)
66 +
            .arg(context)
67 +
            .arg(PATHSPEC_SEPARATOR)
68 +
            .args(paths)
69 +
            .current_dir(&self.cwd)
70 +
            .env(NO_COLOR, "1")
71 +
            .output()?;
72 +
        if !output.status.success() {
73 +
            return Err(RepoError::Status(output.status.code().unwrap_or(1)));
74 +
        }
75 +
        Ok(output.stdout)
76 +
    }
77 +
}
78 +
79 +
// Error Handling //
80 +
81 +
/// A failure while refetching diff data from a [`Repo`].
82 +
#[derive(Debug)]
83 +
pub enum RepoError {
84 +
    /// Spawning or waiting on the backend failed.
85 +
    Io(io::Error),
86 +
    /// The backend exited with a failing status code.
87 +
    Status(i32),
88 +
}
89 +
90 +
impl From<io::Error> for RepoError {
91 +
    fn from(error: io::Error) -> Self {
92 +
        Self::Io(error)
93 +
    }
94 +
}
95 +
96 +
impl std::fmt::Display for RepoError {
97 +
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98 +
        match self {
99 +
            Self::Io(error) => write!(f, "{error}"),
100 +
            Self::Status(code) => write!(f, "git diff exited with status {code}"),
101 +
        }
102 +
    }
103 +
}
104 +
105 +
impl std::error::Error for RepoError {}