repo: Centralized repository plumbing

cafbb5adbd00477c310965cd5649abd29ed2b69c
Alexis Sellier committed ago 1 parent 443d96b5
STYLE +4 -1
14 14
* Avoid using third-party macros.
15 15
16 16
CALLSITES
17 17
18 18
* Avoid boolean parameters when the meaning is not obvious at the callsite.
19 -
* Avoid `Option` parameters for the same reason.
19 +
* Avoid `Option` parameters in functions.
20 20
* Use option structs when a function takes multiple configuration values, when that helps with clarity.
21 21
* Keep callsites readable without needing to inspect the callee signature.
22 22
23 23
TRAITS
24 24
48 48
49 49
HELPERS
50 50
51 51
* Do not create small helper functions when they are only used in one place.
52 52
* Generally avoid one-line helpers, unless it's a complicated line.
53 +
* Avoid free helper functions if they return a type defined in the same crate.
54 +
  Use a constructor function on that type instead, defined in the same file as
55 +
  the type.
53 56
54 57
DOCUMENTATION
55 58
56 59
* Start modules with `//!` documentation that states the module's role.
57 60
* Document all top-level types, functions, constants, and struct/enum fields with `///`.
crates/diff/benches/highlight.rs +0 -0
{path}\n")); +0 -0
crates/diff/benches/render.rs +0 -0
src/file_{file:04}.rs\n" +0 -0
crates/diff/src/bin/rustik-diff.rs +24 -29
6 6
mod session;
7 7
8 8
use std::ffi::OsString;
9 9
use std::io::{self, IsTerminal as _, Read as _, Write as _};
10 10
use std::path::Path;
11 -
use std::process::{Command, ExitCode, Output};
11 +
use std::process::ExitCode;
12 12
use std::{env, str};
13 13
14 14
use rustik_diff::{Builtins, Decode, DiffDocument, DiffOptions, DiffViewer, FileTreeMode};
15 -
use rustik_repo::GitRepo;
15 +
use rustik_repo::git;
16 16
use rustik_tui as tui;
17 17
use rustik_tui::Terminal;
18 18
use rustik_tui_termion as tui_termion;
19 19
20 20
use error::Error;
22 22
/// Default static render width for non-terminal output.
23 23
const STATIC_COLS: usize = 100;
24 24
/// Maximum static render rows for non-terminal output.
25 25
const STATIC_MAX_ROWS: usize = 10_000;
26 26
27 +
/// Repository context available while rendering.
28 +
enum RenderRepo {
29 +
    /// Input came from a Git command and can be refetched.
30 +
    Git(git::Repository),
31 +
    /// Input came from stdin and has no backing repository context.
32 +
    Stdin,
33 +
}
34 +
27 35
/// Program entry point.
28 36
fn main() -> ExitCode {
29 37
    match run(env::args_os().skip(1).collect()) {
30 38
        Ok(()) => ExitCode::SUCCESS,
31 39
        Err(error) => {
49 57
        git_args.push(arg);
50 58
    }
51 59
52 60
    let cwd = env::current_dir()?;
53 61
    let input_from_git = io::stdin().is_terminal();
54 -
    let input = if input_from_git {
55 -
        let output = git_diff(&git_args, &cwd)?;
62 +
    let repo = if input_from_git {
63 +
        let repository = git::Repository::new(&cwd, git_args.clone())?;
64 +
        RenderRepo::Git(repository)
65 +
    } else {
66 +
        RenderRepo::Stdin
67 +
    };
68 +
    let input = if let RenderRepo::Git(repository) = &repo {
69 +
        let output = repository.diff_output(&git_args)?;
56 70
        if !output.status.success() {
57 71
            io::stderr().write_all(&output.stderr)?;
58 72
            return Err(Error::Git(output.status.code().unwrap_or(1)));
59 73
        }
60 74
        output.stdout
61 75
    } else {
62 76
        let mut buf = Vec::new();
63 77
        io::stdin().read_to_end(&mut buf)?;
64 78
        buf
65 79
    };
66 -
67 -
    run_or_forward(
68 -
        &input,
69 -
        &cwd,
70 -
        input_from_git.then_some(git_args.as_slice()),
71 -
        debug,
72 -
    )
80 +
    run_or_forward(&input, &cwd, repo, debug)
73 81
}
74 82
75 83
/// Renders diff input or passes non-diff data through unchanged.
76 -
fn run_or_forward(
77 -
    input: &[u8],
78 -
    cwd: &Path,
79 -
    args: Option<&[OsString]>,
80 -
    debug: bool,
81 -
) -> Result<(), Error> {
84 +
fn run_or_forward(input: &[u8], cwd: &Path, repo: RenderRepo, debug: bool) -> Result<(), Error> {
82 85
    let document = match DiffDocument::decode_bytes(input) {
83 86
        Ok(document) if !document.is_empty() => document,
84 87
        Ok(_) => {
85 88
            io::stdout().write_all(input)?;
86 89
            return Ok(());
115 118
    let mut viewer = DiffViewer::new(document, options);
116 119
117 120
    terminal.clear()?;
118 121
    terminal.set_cursor_visible(false)?;
119 122
120 -
    let repo = args.map(|args| GitRepo::new(cwd, args));
123 +
    let repo = match repo {
124 +
        RenderRepo::Git(repository) => Some(repository),
125 +
        RenderRepo::Stdin => None,
126 +
    };
121 127
    let result = session::run(&mut terminal, &mut viewer, repo, debug);
122 128
    let cursor = terminal.set_cursor_visible(true);
123 129
124 130
    result?;
125 131
    cursor.map_err(Error::Io)
126 132
}
127 -
128 -
/// Runs `git diff` in `cwd`.
129 -
fn git_diff(args: &[OsString], cwd: &Path) -> io::Result<Output> {
130 -
    let mut command = Command::new("git");
131 -
    command
132 -
        .arg("diff")
133 -
        .args(args)
134 -
        .current_dir(cwd)
135 -
        .env("NO_COLOR", "1");
136 -
    command.output()
137 -
}
crates/diff/src/bin/rustik-diff/error.rs +10 -0
2 2
3 3
use std::io;
4 4
5 5
use rustik_diff::DecodeError;
6 6
use rustik_highlight as syntax;
7 +
use rustik_repo::RepoError;
7 8
8 9
/// Binary error type.
9 10
#[derive(Debug)]
10 11
pub(super) enum Error {
11 12
    /// I/O failed.
12 13
    Io(io::Error),
13 14
    /// Git returned a failing exit status.
14 15
    Git(i32),
16 +
    /// Repository discovery or Git plumbing failed.
17 +
    Repo(RepoError),
15 18
    /// Diff parsing failed.
16 19
    Parse(DecodeError),
17 20
    /// Syntax highlighting setup failed.
18 21
    Highlight(syntax::Error),
19 22
}
34 37
    fn from(error: syntax::Error) -> Self {
35 38
        Self::Highlight(error)
36 39
    }
37 40
}
38 41
42 +
impl From<RepoError> for Error {
43 +
    fn from(error: RepoError) -> Self {
44 +
        Self::Repo(error)
45 +
    }
46 +
}
47 +
39 48
impl std::fmt::Display for Error {
40 49
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41 50
        match self {
42 51
            Self::Io(error) => write!(f, "{error}"),
43 52
            Self::Git(code) => write!(f, "git diff exited with status {code}"),
53 +
            Self::Repo(error) => write!(f, "{error}"),
44 54
            Self::Parse(error) => write!(f, "{error}"),
45 55
            Self::Highlight(error) => write!(f, "{error}"),
46 56
        }
47 57
    }
48 58
}
crates/diff/src/bin/rustik-diff/session.rs +2 -2
6 6
use std::time::{Duration, Instant};
7 7
8 8
use rustik_diff::{
9 9
    ContextChange, DiffViewer, HighlightOutput, HighlightRequest, Highlighter, spawn_highlighter,
10 10
};
11 -
use rustik_repo::GitRepo;
11 +
use rustik_repo::git;
12 12
use rustik_tui as tui;
13 13
use rustik_tui::{
14 14
    Color, Control, Event, Key, Label, Line, Mouse, MouseButton, Rect, Style, Terminal,
15 15
};
16 16
use rustik_tui_termion as tui_termion;
30 30
31 31
/// Runs the terminal event loop.
32 32
pub(super) fn run(
33 33
    terminal: &mut DiffTerminal,
34 34
    viewer: &mut DiffViewer,
35 -
    repo: Option<GitRepo>,
35 +
    repo: Option<git::Repository>,
36 36
    debug: bool,
37 37
) -> Result<(), Error> {
38 38
    let (events_tx, events_rx) = mpsc::channel();
39 39
    TerminalEvent::spawn_input_worker(events_tx.clone());
40 40
crates/diff/src/builtins.rs +0 -0
script\n\ +0 -0
{path}\n\ +0 -0
crates/diff/src/commit.rs +12 -8
135 135
#[cfg(test)]
136 136
#[allow(clippy::unwrap_used)]
137 137
mod tests {
138 138
    use super::*;
139 139
140 +
    const SHA1: &str = "1234567890abcdef1234567890abcdef12345678";
141 +
140 142
    #[test]
141 143
    fn parses_headers_only() {
142 -
        let commit = Commit::from_str("commit abc\nAuthor: A\n\n").unwrap();
144 +
        let input = format!("commit {SHA1}\nAuthor: A\n\n");
145 +
        let commit = Commit::from_str(&input).unwrap();
143 146
144 -
        assert_eq!(commit.hash.as_str(), "abc");
147 +
        assert_eq!(commit.hash.to_string(), SHA1);
145 148
        assert_eq!(commit.decoration, None);
146 149
        assert_eq!(commit.header("author"), Some("A"));
147 150
        assert!(commit.message.is_empty());
148 151
    }
149 152
151 154
    fn parses_sha256_hash() {
152 155
        let oid = "0".repeat(64);
153 156
        let input = format!("commit {oid}\n\n");
154 157
        let commit = Commit::from_str(&input).unwrap();
155 158
156 -
        assert_eq!(commit.hash.as_str(), oid);
159 +
        assert_eq!(commit.hash.to_string(), oid);
157 160
    }
158 161
159 162
    #[test]
160 163
    fn parses_decoration_after_hash() {
161 -
        let commit = Commit::from_str("commit abc (HEAD -> main)\n\n").unwrap();
164 +
        let input = format!("commit {SHA1} (HEAD -> main)\n\n");
165 +
        let commit = Commit::from_str(&input).unwrap();
162 166
163 -
        assert_eq!(commit.hash.as_str(), "abc");
167 +
        assert_eq!(commit.hash.to_string(), SHA1);
164 168
        assert_eq!(commit.decoration.as_deref(), Some("(HEAD -> main)"));
165 169
    }
166 170
167 171
    #[test]
168 172
    fn parses_message_with_indent_preserved() {
169 -
        let input = "commit abc\nAuthor: A\n\n    Subject\n\n    Body\n";
170 -
        let commit = Commit::from_str(input).unwrap();
173 +
        let input = format!("commit {SHA1}\nAuthor: A\n\n    Subject\n\n    Body\n");
174 +
        let commit = Commit::from_str(&input).unwrap();
171 175
172 176
        assert_eq!(commit.message, "    Subject\n\n    Body\n");
173 177
    }
174 178
175 179
    #[test]
190 194
    }
191 195
192 196
    #[test]
193 197
    fn display_matches_decoder_line_encoding() {
194 198
        let lines = [
195 -
            "commit abc",
199 +
            "commit 1234567890abcdef1234567890abcdef12345678",
196 200
            "Author: A",
197 201
            "",
198 202
            "    Subject",
199 203
            "",
200 204
            "    Body",
crates/diff/src/context.rs +0 -0
a.txt +0 -0
a.txt +0 -0
crates/diff/src/decode.rs +0 -0
{ +0 -0
+0 -0
=> break, +0 -0
a.rs +0 -0
new.rs +0 -0
old.rs +0 -0
to.rs +0 -0
copy2.rs +0 -0
mode.sh +0 -0
image.png +0 -0
a +0 -0
a +0 -0
a +0 -0
a.rs +0 -0
b.rs +0 -0
a.rs\x1b[m +0 -0
crates/diff/src/document.rs +2 -44
2 2
//!
3 3
//! Defines the data tree (`DiffDocument` โ†’ `FileDiff` โ†’ `Hunk` โ†’ `DiffLine`)
4 4
//! that callers consume. The decoder that produces these values lives in
5 5
//! [`crate::decode`]; `document` is intentionally model-only.
6 6
7 +
pub use rustik_repo::{Oid, OidError};
8 +
7 9
use std::fmt;
8 10
use std::io;
9 11
use std::num::ParseIntError;
10 12
use std::path::PathBuf;
11 -
use std::str::FromStr;
12 13
13 14
/// Stable identifier for a file section in one diff document.
14 15
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
15 16
pub struct FileId(usize);
16 17
20 21
21 22
/// Stable identifier for a rendered hunk row in one diff document.
22 23
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
23 24
pub struct RowId(usize);
24 25
25 -
/// Object identifier as it appears in a Git diff header.
26 -
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
27 -
pub struct Oid(String);
28 -
29 26
impl FileId {
30 27
    /// Wraps a raw index as a [`FileId`].
31 28
    pub const fn new(index: usize) -> Self {
32 29
        Self(index)
33 30
    }
45 42
    pub const fn new(index: usize) -> Self {
46 43
        Self(index)
47 44
    }
48 45
}
49 46
50 -
impl Oid {
51 -
    /// Returns the object identifier text.
52 -
    pub fn as_str(&self) -> &str {
53 -
        &self.0
54 -
    }
55 -
}
56 -
57 -
impl FromStr for Oid {
58 -
    type Err = OidError;
59 -
60 -
    fn from_str(input: &str) -> Result<Self, Self::Err> {
61 -
        if input.is_empty() {
62 -
            return Err(OidError);
63 -
        }
64 -
        if !input.bytes().all(|byte| byte.is_ascii_hexdigit()) {
65 -
            return Err(OidError);
66 -
        }
67 -
        Ok(Self(input.to_owned()))
68 -
    }
69 -
}
70 -
71 -
impl fmt::Display for Oid {
72 -
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73 -
        f.write_str(&self.0)
74 -
    }
75 -
}
76 -
77 -
/// Error returned when a diff object identifier is malformed.
78 -
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
79 -
pub struct OidError;
80 -
81 -
impl fmt::Display for OidError {
82 -
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83 -
        f.write_str("object id must be non-empty hexadecimal text")
84 -
    }
85 -
}
86 -
87 -
impl std::error::Error for OidError {}
88 -
89 47
impl std::ops::Deref for FileId {
90 48
    type Target = usize;
91 49
92 50
    fn deref(&self) -> &usize {
93 51
        &self.0
a.txt +0 -0
a +0 -0
crates/diff/src/encode.rs +0 -0
a.txt +0 -0
b.txt +0 -0
crates/diff/src/highlight.rs +0 -0
a.css +0 -0
a.rs\n", +0 -0
crates/diff/src/highlighter.rs +7 -7
11 11
use std::collections::{BTreeMap, BTreeSet};
12 12
use std::path::PathBuf;
13 13
use std::sync::mpsc::{self, SyncSender, TrySendError};
14 14
use std::thread;
15 15
16 -
use rustik_repo::{GitRepo, Repo};
16 +
use rustik_repo::{DiffRepository, git};
17 17
18 18
use crate::builtins::Builtins;
19 19
use crate::{
20 20
    BuiltinHighlighter, ContextRequest, ContextUpdate, Decode, DiffDocument, DiffHighlighter,
21 21
    DiffSide, FileId, HighlightRequest, HighlightResult, HighlightSource, Oid,
86 86
/// `output` is invoked on the worker thread for each produced
87 87
/// [`HighlightOutput`]; forward it to the UI thread (for example over a
88 88
/// channel) and apply it to the viewer.
89 89
pub fn spawn_highlighter(
90 90
    document: &DiffDocument,
91 -
    repo: Option<GitRepo>,
91 +
    repo: Option<git::Repository>,
92 92
    output: impl Fn(HighlightOutput) + Send + 'static,
93 93
) -> Highlighter {
94 94
    let (commands, requests) = mpsc::sync_channel::<Command>(COMMAND_QUEUE);
95 95
    let seed = Seed::new(document);
96 96
130 130
impl Seed {
131 131
    /// Extracts the worker's seed from `document`.
132 132
    fn new(document: &DiffDocument) -> Self {
133 133
        let mut head_oids = BTreeMap::new();
134 134
        for file in &document.files {
135 -
            if let Some(oid) = file.header.old_oid.clone() {
135 +
            if let Some(oid) = file.header.old_oid {
136 136
                head_oids.insert((file.id, DiffSide::Old), oid);
137 137
            }
138 -
            if let Some(oid) = file.header.new_oid.clone() {
138 +
            if let Some(oid) = file.header.new_oid {
139 139
                head_oids.insert((file.id, DiffSide::New), oid);
140 140
            }
141 141
        }
142 142
        Self {
143 143
            paths: Builtins::document_paths(document),
149 149
/// Background worker for blocking repo and syntax-highlighting work.
150 150
struct HighlightWorker {
151 151
    /// Built-in syntax highlighter.
152 152
    highlighter: BuiltinHighlighter,
153 153
    /// Git-backed repo used for direct Git invocations.
154 -
    repo: Option<GitRepo>,
154 +
    repo: Option<git::Repository>,
155 155
    /// Highlight source context cache keyed by diff file and side.
156 156
    context_sources: BTreeMap<(FileId, DiffSide), Vec<HighlightSource>>,
157 157
    /// Source object ids keyed by diff file and side.
158 158
    head_oids: BTreeMap<(FileId, DiffSide), Oid>,
159 159
    /// File-side heads already checked for first-line grammar metadata.
160 160
    loaded_heads: BTreeSet<(FileId, DiffSide)>,
161 161
}
162 162
163 163
impl HighlightWorker {
164 164
    /// Creates a background worker.
165 -
    fn new(seed: Seed, repo: Option<GitRepo>) -> Self {
165 +
    fn new(seed: Seed, repo: Option<git::Repository>) -> Self {
166 166
        Self {
167 167
            highlighter: Builtins::highlighter_for_paths(&seed.paths)
168 168
                .unwrap_or_else(|_| BuiltinHighlighter::new(Default::default(), "")),
169 169
            repo,
170 170
            context_sources: BTreeMap::new(),
207 207
            return;
208 208
        }
209 209
        let Some(oid) = self.head_oids.get(&key) else {
210 210
            return;
211 211
        };
212 -
        let head = repo.head_line(oid.as_str());
212 +
        let head = repo.head_line(*oid);
213 213
        if let Ok(Some(head)) = head {
214 214
            let _ = Builtins::load_head_grammars(&mut self.highlighter, &head);
215 215
        }
216 216
    }
217 217
crates/diff/src/lib.rs +1 -1
1 1
//! Unified diff parsing and terminal-buffer viewing.
2 2
//!
3 3
//! The viewer is intentionally I/O-free: it parses or accepts patch data,
4 4
//! owns read-only viewer state, and writes frames into a
5 5
//! [`rustik_tui::Buffer`]. Backend access is abstracted behind the
6 -
//! [`rustik_repo::Repo`] trait so the viewer stays testable. The `rustik-diff`
6 +
//! [`rustik_repo::DiffRepository`] trait so the viewer stays testable. The `rustik-diff`
7 7
//! binary owns stdin/stdout, terminals, and events.
8 8
//!
9 9
//! The optional `builtins` feature (on by default) bundles default highlighting
10 10
//! assets ([`Builtins`]) and a background worker ([`spawn_highlighter`]) so
11 11
//! hosts get a batteries-included viewer; disable it to bring your own.
crates/diff/src/viewer.rs +4 -4
1331 1331
                    .collect()
1332 1332
            } else {
1333 1333
                Vec::new()
1334 1334
            }
1335 1335
        };
1336 -
        let hash_width = commit.hash.as_str().width()
1337 -
            + commit.decoration.as_deref().map_or(0, |d| 1 + d.width());
1336 +
        let hash = commit.hash.to_string();
1337 +
        let hash_width = hash.width() + commit.decoration.as_deref().map_or(0, |d| 1 + d.width());
1338 1338
        let value_width = std::iter::once(hash_width)
1339 1339
            .chain(commit.headers.iter().map(|h| h.value.as_str().width()))
1340 1340
            .max()
1341 1341
            .unwrap_or_default();
1342 1342
        // Hash row is a two-part component (hash plus optional signature marker).
1343 -
        let hash_line = Line::new(Label::new(commit.hash.as_str()).fg(colors::rgb::ORANGE));
1343 +
        let hash_line = Line::new(Label::new(hash.as_str()).fg(colors::rgb::ORANGE));
1344 1344
        let hash_value = if let Some(decoration) = commit.decoration.as_deref() {
1345 1345
            HStack::default()
1346 1346
                .child(hash_line)
1347 1347
                .spacer()
1348 1348
                .child(Line::new(Label::new(decoration).fg(colors::rgb::DIM)))
2016 2016
2017 2017
    use super::*;
2018 2018
2019 2019
    use crate::Decode;
2020 2020
    use crate::DiffDocument;
2021 -
    use rustik_repo::{Repo, RepoError};
2021 +
    use rustik_repo::{DiffRepository, RepoError};
2022 2022
    use rustik_tui::{Modifiers, Point};
2023 2023
2024 2024
    /// Returns a left-click event for tests.
2025 2025
    fn left_click(x: usize, y: usize, modifiers: Modifiers) -> Event<()> {
2026 2026
        Event::Mouse(Mouse::Press {
a.rs +0 -0
a.rs +0 -0
b.rs +0 -0
a.rs +0 -0
a.rs +0 -0
a.rs +0 -0
b.rs +0 -0
crates/diff/tests/golden/sticky_header_before_next_file_64x5.txt +0 -0
src/a.rs +0 -0
src/b.rs +0 -0
README.md +0 -0
src/app/a.rs +0 -0
src/lib/b.rs +0 -0
README.md +0 -0
a.rs +0 -0
b.rs +0 -0
assets/css/style.css +0 -0
assets/css/style.css +0 -0
a.rs +0 -0
a.rs +0 -0
a.rs +0 -0
b.rs +0 -0
crates/diff/src/viewer/tree.rs +0 -0
a.rs +0 -0
b.rs +0 -0
crates/diff/tests/golden.rs +0 -0
a.rs +0 -0
crates/diff/tests/golden/file_kinds.diff +0 -0
new.rs +0 -0
old.rs +0 -0
to.rs +0 -0
copy2.rs +0 -0
mode.sh +0 -0
image.png +0 -0
crates/diff/tests/golden/preamble_no_newline.diff +0 -0
a.rs +0 -0
crates/diff/tests/golden/sample.diff +0 -0
a.rs +0 -0
crates/diff/tests/golden/two_files.diff +0 -0
a.rs +0 -0
b.rs +0 -0
crates/diff/tests/golden/two_hunks.diff +0 -0
a.rs +0 -0
crates/repo/src/git.rs +593 -1
1 -
//! Git data types and operations.
1 +
//! Git plumbing for reading and writing repository state.
2 +
3 +
use std::collections::BTreeMap;
4 +
use std::ffi::OsString;
5 +
use std::fs;
6 +
use std::io::{self, Read as _, Write as _};
7 +
use std::path::{Path, PathBuf};
8 +
use std::process::{Command, Output, Stdio};
9 +
use std::time::{SystemTime, UNIX_EPOCH};
10 +
11 +
use self::refs::{Qualified, RefStr};
12 +
use crate::{DiffRepository, DiffStat, Oid, PatchId, ReadRepository, RepoError, WriteRepository};
2 13
3 14
/// Git reference names and refspecs.
4 15
pub mod refs;
16 +
17 +
/// Environment variable that disables Git's colored output.
18 +
const NO_COLOR: &str = "NO_COLOR";
19 +
/// Environment variable selecting the locale for Git's output.
20 +
///
21 +
/// Forced to `C` so translatable output that gets parsed here, such as
22 +
/// `--shortstat` summaries, stays in English regardless of the user's locale.
23 +
const LC_ALL: &str = "LC_ALL";
24 +
/// Maximum bytes read from a file head for shebang-style inference.
25 +
const HEAD_BYTES: usize = 64;
26 +
/// Pathspec separator that ends Git's option list.
27 +
const PATHSPEC_SEPARATOR: &str = "--";
28 +
29 +
/// Git repository command context.
30 +
#[derive(Clone, Debug)]
31 +
pub struct Repository {
32 +
    /// Working directory for worktree-aware invocations.
33 +
    cwd: PathBuf,
34 +
    /// Git repository directory used for plumbing invocations.
35 +
    git_dir: PathBuf,
36 +
    /// Revision and option arguments forwarded during context refetches.
37 +
    selector_args: Vec<OsString>,
38 +
}
39 +
40 +
impl Repository {
41 +
    /// Creates a repository context for `cwd` with selectors from raw diff args.
42 +
    pub fn new(
43 +
        cwd: impl Into<PathBuf>,
44 +
        diff_args: impl Into<Vec<OsString>>,
45 +
    ) -> Result<Self, RepoError> {
46 +
        let repository = Self::discover(cwd.into())?;
47 +
        let selector_args = repository.diff_selector_args(diff_args.into())?;
48 +
        Ok(repository.with_selector_args(selector_args))
49 +
    }
50 +
51 +
    /// Creates a repository command context with an explicit repository directory.
52 +
    pub fn from_git_dir(cwd: PathBuf, git_dir: PathBuf) -> Self {
53 +
        Self {
54 +
            cwd,
55 +
            git_dir,
56 +
            selector_args: Vec::new(),
57 +
        }
58 +
    }
59 +
60 +
    /// Creates a repository command context by resolving the repository for `cwd`.
61 +
    pub fn discover(cwd: PathBuf) -> Result<Self, RepoError> {
62 +
        let output = Command::new("git")
63 +
            .arg("rev-parse")
64 +
            .args(["--absolute-git-dir"])
65 +
            .current_dir(&cwd)
66 +
            .env(NO_COLOR, "1")
67 +
            .env(LC_ALL, "C")
68 +
            .output()?;
69 +
        if !output.status.success() {
70 +
            return Err(RepoError::git(&output));
71 +
        }
72 +
        let text = utf8(output.stdout)?;
73 +
        let git_dir = PathBuf::from(text.trim());
74 +
        if git_dir.as_os_str().is_empty() {
75 +
            return Err(RepoError::Git(
76 +
                "git rev-parse --absolute-git-dir returned an empty path".to_owned(),
77 +
            ));
78 +
        }
79 +
        Ok(Self {
80 +
            cwd,
81 +
            git_dir,
82 +
            selector_args: Vec::new(),
83 +
        })
84 +
    }
85 +
86 +
    /// Returns a copy with `selector_args` used for diff context refetches.
87 +
    pub fn with_selector_args(&self, selector_args: impl Into<Vec<OsString>>) -> Self {
88 +
        Self {
89 +
            cwd: self.cwd.clone(),
90 +
            git_dir: self.git_dir.clone(),
91 +
            selector_args: selector_args.into(),
92 +
        }
93 +
    }
94 +
95 +
    /// Runs `git diff` with raw command-line arguments.
96 +
    pub fn diff_output(&self, args: &[OsString]) -> Result<Output, RepoError> {
97 +
        self.command("diff")
98 +
            .args(args)
99 +
            .output()
100 +
            .map_err(RepoError::Io)
101 +
    }
102 +
103 +
    /// Reads the first bytes of a Git blob object.
104 +
    pub fn head_line(&self, oid: Oid) -> Result<Option<String>, RepoError> {
105 +
        let mut child = self
106 +
            .command("show")
107 +
            .arg(oid.to_string())
108 +
            .stdout(Stdio::piped())
109 +
            .stderr(Stdio::null())
110 +
            .spawn()?;
111 +
        let Some(mut stdout) = child.stdout.take() else {
112 +
            return Ok(None);
113 +
        };
114 +
        let head = read_head(&mut stdout)?;
115 +
        let _ = child.kill();
116 +
        let _ = child.wait();
117 +
118 +
        Ok(head)
119 +
    }
120 +
121 +
    /// Returns a Git command configured for this repository.
122 +
    fn command(&self, subcommand: &str) -> Command {
123 +
        let mut command = Command::new("git");
124 +
        command
125 +
            .arg(subcommand)
126 +
            .current_dir(&self.cwd)
127 +
            .env("GIT_DIR", &self.git_dir)
128 +
            .env(NO_COLOR, "1")
129 +
            .env(LC_ALL, "C");
130 +
        command
131 +
    }
132 +
133 +
    /// Returns diff selectors without pathspec arguments.
134 +
    fn diff_selector_args(&self, args: Vec<OsString>) -> Result<Vec<OsString>, RepoError> {
135 +
        if let Some(separator) = args
136 +
            .iter()
137 +
            .position(|arg| arg.as_os_str() == PATHSPEC_SEPARATOR)
138 +
        {
139 +
            return Ok(args[..separator].to_vec());
140 +
        }
141 +
        let mut selectors = self.rev_parse(&["--flags", "--no-revs"], &args)?;
142 +
        let revisions = self.rev_parse(&["--revs-only", "--symbolic"], &args)?;
143 +
        selectors.extend(revisions);
144 +
145 +
        Ok(selectors)
146 +
    }
147 +
148 +
    /// Runs `git rev-parse` to classify diff arguments.
149 +
    fn rev_parse(&self, modes: &[&str], args: &[OsString]) -> Result<Vec<OsString>, RepoError> {
150 +
        let output = self.command("rev-parse").args(modes).args(args).output()?;
151 +
        if !output.status.success() {
152 +
            return Err(RepoError::git(&output));
153 +
        }
154 +
        Ok(String::from_utf8_lossy(&output.stdout)
155 +
            .lines()
156 +
            .filter(|line| !line.is_empty())
157 +
            .map(OsString::from)
158 +
            .collect())
159 +
    }
160 +
161 +
    /// Runs a Git subcommand with default options and returns stdout bytes on success.
162 +
    fn git(&self, subcommand: &str, args: &[&str]) -> Result<Vec<u8>, RepoError> {
163 +
        let output = self.run(subcommand, args, Opts::default())?;
164 +
        if output.status.success() {
165 +
            Ok(output.stdout)
166 +
        } else {
167 +
            Err(RepoError::git(&output))
168 +
        }
169 +
    }
170 +
171 +
    /// Runs a Git subcommand with optional stdin, index, and environment overrides.
172 +
    fn run(&self, subcommand: &str, args: &[&str], opts: Opts<'_>) -> Result<Output, RepoError> {
173 +
        let mut command = self.command(subcommand);
174 +
        command.args(args);
175 +
176 +
        for (key, value) in opts.env {
177 +
            command.env(key, value);
178 +
        }
179 +
        if let Some(index) = opts.index {
180 +
            command.env("GIT_INDEX_FILE", index);
181 +
        }
182 +
        if let Some(stdin) = opts.stdin {
183 +
            command
184 +
                .stdin(Stdio::piped())
185 +
                .stdout(Stdio::piped())
186 +
                .stderr(Stdio::piped());
187 +
            let mut child = command.spawn()?;
188 +
189 +
            if let Some(child_stdin) = child.stdin.as_mut() {
190 +
                child_stdin.write_all(stdin)?;
191 +
            }
192 +
            child.wait_with_output().map_err(RepoError::Io)
193 +
        } else {
194 +
            command.output().map_err(RepoError::Io)
195 +
        }
196 +
    }
197 +
}
198 +
199 +
impl ReadRepository for Repository {
200 +
    /// Resolves a revision reference to a commit id.
201 +
    fn commit_id(&self, rev: &RefStr) -> Result<Oid, RepoError> {
202 +
        let revision = format!("{rev}^{{commit}}");
203 +
        let bytes = self.git("rev-parse", &[&revision])?;
204 +
        Oid::try_from(bytes.as_slice())
205 +
            .map_err(|_| RepoError::Git(format!("invalid oid from rev-parse {rev}")))
206 +
    }
207 +
208 +
    /// Returns the tree id for any commit or tree object.
209 +
    fn tree_id(&self, object: Oid) -> Result<Oid, RepoError> {
210 +
        let object = format!("{object}^{{tree}}");
211 +
        let bytes = self.git("rev-parse", &[&object])?;
212 +
        Oid::try_from(bytes.as_slice())
213 +
            .map_err(|_| RepoError::Git(format!("invalid oid from rev-parse {object}")))
214 +
    }
215 +
216 +
    /// Returns the current commit stored in `reference`, if the ref exists.
217 +
    fn optional_ref(&self, reference: &Qualified<'_>) -> Result<Option<Oid>, RepoError> {
218 +
        let output = self.run(
219 +
            "rev-parse",
220 +
            &["--verify", "--quiet", reference.as_str()],
221 +
            Opts::default(),
222 +
        )?;
223 +
        if !output.status.success() {
224 +
            return Ok(None);
225 +
        }
226 +
        let oid = Oid::try_from(output.stdout.as_slice())
227 +
            .map_err(|_| RepoError::Git(format!("invalid oid from {reference}")))?;
228 +
229 +
        Ok(Some(oid))
230 +
    }
231 +
232 +
    /// Returns the single parent of `commit`, or an error if it has more or fewer.
233 +
    fn parent(&self, commit: Oid) -> Result<Oid, RepoError> {
234 +
        let commit = commit.to_string();
235 +
        let bytes = self.git("show", &["-s", "--format=%P", &commit])?;
236 +
        let text = utf8(bytes)?;
237 +
        let parents = text.split_whitespace().collect::<Vec<_>>();
238 +
239 +
        match parents.as_slice() {
240 +
            [parent] => parent
241 +
                .parse()
242 +
                .map_err(|_| RepoError::Git(format!("{commit} parent is not a valid hash"))),
243 +
            _ => Err(RepoError::Git(format!(
244 +
                "{commit} does not have exactly one parent"
245 +
            ))),
246 +
        }
247 +
    }
248 +
249 +
    /// Returns the full commit message for `commit`.
250 +
    fn commit_message(&self, commit: Oid) -> Result<String, RepoError> {
251 +
        let commit = commit.to_string();
252 +
        self.git("show", &["-s", "--format=%B", &commit])
253 +
            .and_then(utf8)
254 +
    }
255 +
256 +
    /// Returns each commit's aggregated diff size, in the given order.
257 +
    ///
258 +
    /// All stats come from one `git log --shortstat` invocation so callers can
259 +
    /// size a whole review range without a subprocess per commit. Commits with
260 +
    /// no shortstat output (empty diffs, unwalked merges) report zero stats.
261 +
    fn commit_stats(&self, commits: &[Oid]) -> Result<Vec<DiffStat>, RepoError> {
262 +
        if commits.is_empty() {
263 +
            return Ok(Vec::new());
264 +
        }
265 +
        let mut args = vec![
266 +
            "--no-walk=unsorted".to_owned(),
267 +
            "--format=%H".to_owned(),
268 +
            "--shortstat".to_owned(),
269 +
        ];
270 +
        args.extend(commits.iter().map(Oid::to_string));
271 +
        let args = args.iter().map(String::as_str).collect::<Vec<_>>();
272 +
        let text = self.git("log", &args).and_then(utf8)?;
273 +
274 +
        let mut stats = BTreeMap::new();
275 +
        let mut current = None;
276 +
        for line in text.lines() {
277 +
            if let Ok(oid) = line.trim().parse::<Oid>() {
278 +
                current = Some(oid);
279 +
            } else if let Some(oid) = current
280 +
                && line.contains("changed")
281 +
            {
282 +
                stats.insert(oid, DiffStat::from_shortstat(line));
283 +
            }
284 +
        }
285 +
        Ok(commits
286 +
            .iter()
287 +
            .map(|commit| stats.get(commit).copied().unwrap_or_default())
288 +
            .collect())
289 +
    }
290 +
291 +
    /// Reads a blob object's bytes.
292 +
    fn cat_blob(&self, blob: Oid) -> Result<Vec<u8>, RepoError> {
293 +
        let blob = blob.to_string();
294 +
        self.git("cat-file", &["blob", &blob])
295 +
    }
296 +
297 +
    /// Produces a unified diff between two objects as text.
298 +
    fn diff(&self, from: Oid, to: Oid) -> Result<String, RepoError> {
299 +
        let from = from.to_string();
300 +
        let to = to.to_string();
301 +
        let bytes = self.git(
302 +
            "diff",
303 +
            &["--no-ext-diff", "--no-color", "--full-index", &from, &to],
304 +
        )?;
305 +
        utf8(bytes)
306 +
    }
307 +
308 +
    /// Computes a stable Git patch id for `patch` text.
309 +
    fn patch_id(&self, patch: &str) -> Result<PatchId, RepoError> {
310 +
        if patch.trim().is_empty() {
311 +
            return Ok(PatchId::default());
312 +
        }
313 +
        let output = self.run(
314 +
            "patch-id",
315 +
            &["--stable"],
316 +
            Opts {
317 +
                stdin: Some(patch.as_bytes()),
318 +
                ..Opts::default()
319 +
            },
320 +
        )?;
321 +
        if !output.status.success() {
322 +
            return Err(RepoError::git(&output));
323 +
        }
324 +
        let stdout = utf8(output.stdout)?;
325 +
        let id = stdout.split_once(' ').map_or(stdout.trim(), |(id, _)| id);
326 +
327 +
        Ok(PatchId(id.to_owned()))
328 +
    }
329 +
330 +
    /// Computes a three-way merge tree and returns the resulting tree id.
331 +
    fn merge_tree(&self, merge_base: Oid, ours: Oid, theirs: Oid) -> Result<Oid, RepoError> {
332 +
        let merge_base = merge_base.to_string();
333 +
        let ours = ours.to_string();
334 +
        let theirs = theirs.to_string();
335 +
        let output = self.run(
336 +
            "merge-tree",
337 +
            &["--write-tree", "--merge-base", &merge_base, &ours, &theirs],
338 +
            Opts::default(),
339 +
        )?;
340 +
        if output.status.success() {
341 +
            let stdout = String::from_utf8_lossy(&output.stdout);
342 +
            // On success `--write-tree` prints the created tree id as the first
343 +
            // line. Conflict details only appear on failing output.
344 +
            return stdout
345 +
                .lines()
346 +
                .next()
347 +
                .map(str::trim)
348 +
                .filter(|line| !line.is_empty())
349 +
                .and_then(|line| line.parse().ok())
350 +
                .ok_or_else(|| RepoError::Git("git merge-tree did not return a tree".to_owned()));
351 +
        }
352 +
        let message = RepoError::git(&output).to_string();
353 +
        if output.status.code() == Some(1) {
354 +
            Err(RepoError::MergeConflict(message))
355 +
        } else {
356 +
            Err(RepoError::Git(message))
357 +
        }
358 +
    }
359 +
360 +
    /// Returns commits in `base..target`, oldest first, as `(id, summary)` pairs.
361 +
    fn commits(&self, base: &RefStr, target: &RefStr) -> Result<Vec<(Oid, String)>, RepoError> {
362 +
        let range = format!("{base}..{target}");
363 +
        let bytes = self.git("log", &["--reverse", "--format=%H%x00%s", &range])?;
364 +
        let text = utf8(bytes)?;
365 +
        let mut commits = Vec::new();
366 +
367 +
        for line in text.lines() {
368 +
            let Some((id, summary)) = line.split_once('\0') else {
369 +
                return Err(RepoError::Git(
370 +
                    "malformed commit line from git log".to_owned(),
371 +
                ));
372 +
            };
373 +
            let id = id
374 +
                .trim()
375 +
                .parse()
376 +
                .map_err(|_| RepoError::Git("invalid oid from git log".to_owned()))?;
377 +
            commits.push((id, summary.to_owned()));
378 +
        }
379 +
        Ok(commits)
380 +
    }
381 +
382 +
    /// Returns the unified diff for `commit` against its parent.
383 +
    fn commit_diff(&self, commit: Oid) -> Result<Vec<u8>, RepoError> {
384 +
        let commit = commit.to_string();
385 +
        let parent = format!("{commit}^");
386 +
        self.git("diff", &["--full-index", &parent, &commit])
387 +
    }
388 +
}
389 +
390 +
impl WriteRepository for Repository {
391 +
    /// Writes `bytes` as a blob object and returns its id.
392 +
    fn write_blob(&self, bytes: &[u8]) -> Result<Oid, RepoError> {
393 +
        let output = self.run(
394 +
            "hash-object",
395 +
            &["-w", "--stdin"],
396 +
            Opts {
397 +
                stdin: Some(bytes),
398 +
                ..Opts::default()
399 +
            },
400 +
        )?;
401 +
        if !output.status.success() {
402 +
            return Err(RepoError::git(&output));
403 +
        }
404 +
        Oid::try_from(output.stdout.as_slice())
405 +
            .map_err(|_| RepoError::Git("invalid oid from hash-object".to_owned()))
406 +
    }
407 +
408 +
    /// Applies a Git-format patch to a temporary index and returns its tree id.
409 +
    ///
410 +
    /// The temporary index is seeded from `base`, patched with
411 +
    /// `git apply --cached`, then written with `git write-tree`. This keeps
412 +
    /// acceptance updates isolated from the user's working tree and real index.
413 +
    fn apply_patch_to_tree(&self, base: Oid, patch: &str) -> Result<Oid, RepoError> {
414 +
        if patch.trim().is_empty() {
415 +
            return self.tree_id(base);
416 +
        }
417 +
        let index = TempIndex::new()?;
418 +
        let index_path = index.path();
419 +
        let base = base.to_string();
420 +
421 +
        // `read-tree` initializes the temporary index to the exact tree being
422 +
        // updated; subsequent Git commands use only `GIT_INDEX_FILE`.
423 +
        let output = self.run(
424 +
            "read-tree",
425 +
            &[&base],
426 +
            Opts {
427 +
                index: Some(index_path),
428 +
                ..Opts::default()
429 +
            },
430 +
        )?;
431 +
        if !output.status.success() {
432 +
            return Err(RepoError::git(&output));
433 +
        }
434 +
        // `--recount` lets single-hunk patches keep working after context
435 +
        // filtering changes hunk line counts.
436 +
        let output = self.run(
437 +
            "apply",
438 +
            &["--cached", "--recount", "--whitespace=nowarn", "--binary"],
439 +
            Opts {
440 +
                index: Some(index_path),
441 +
                stdin: Some(patch.as_bytes()),
442 +
                ..Opts::default()
443 +
            },
444 +
        )?;
445 +
        if !output.status.success() {
446 +
            return Err(RepoError::git(&output));
447 +
        }
448 +
        let output = self.run(
449 +
            "write-tree",
450 +
            &[],
451 +
            Opts {
452 +
                index: Some(index_path),
453 +
                ..Opts::default()
454 +
            },
455 +
        )?;
456 +
        if !output.status.success() {
457 +
            return Err(RepoError::git(&output));
458 +
        }
459 +
        Oid::try_from(output.stdout.as_slice())
460 +
            .map_err(|_| RepoError::Git("invalid oid from write-tree".to_owned()))
461 +
    }
462 +
463 +
    /// Creates a commit with `tree` and `parent`.
464 +
    fn commit(
465 +
        &self,
466 +
        tree: Oid,
467 +
        parent: Oid,
468 +
        author: &str,
469 +
        email: &str,
470 +
        message: &str,
471 +
    ) -> Result<Oid, RepoError> {
472 +
        let tree = tree.to_string();
473 +
        let parent = parent.to_string();
474 +
        let output = self.run(
475 +
            "commit-tree",
476 +
            &[&tree, "-p", &parent, "-m", message],
477 +
            Opts {
478 +
                env: &[
479 +
                    ("GIT_AUTHOR_NAME", author),
480 +
                    ("GIT_AUTHOR_EMAIL", email),
481 +
                    ("GIT_COMMITTER_NAME", author),
482 +
                    ("GIT_COMMITTER_EMAIL", email),
483 +
                ],
484 +
                ..Opts::default()
485 +
            },
486 +
        )?;
487 +
        if !output.status.success() {
488 +
            return Err(RepoError::git(&output));
489 +
        }
490 +
        Oid::try_from(output.stdout.as_slice())
491 +
            .map_err(|_| RepoError::Git("invalid oid from commit-tree".to_owned()))
492 +
    }
493 +
494 +
    /// Moves `reference` to point at `commit`.
495 +
    fn update_ref(&self, reference: &Qualified<'_>, commit: Oid) -> Result<(), RepoError> {
496 +
        let commit = commit.to_string();
497 +
        let output = self.run(
498 +
            "update-ref",
499 +
            &[reference.as_str(), &commit],
500 +
            Opts::default(),
501 +
        )?;
502 +
        if !output.status.success() {
503 +
            return Err(RepoError::git(&output));
504 +
        }
505 +
        Ok(())
506 +
    }
507 +
}
508 +
509 +
impl DiffRepository for Repository {
510 +
    fn diff(&self, context_lines: usize, paths: &[&Path]) -> Result<Vec<u8>, RepoError> {
511 +
        let context = OsString::from(format!("-U{context_lines}"));
512 +
        let output = self
513 +
            .command("diff")
514 +
            .args(&self.selector_args)
515 +
            .arg("--full-index")
516 +
            .arg(context)
517 +
            .arg("--")
518 +
            .args(paths)
519 +
            .output()?;
520 +
        if !output.status.success() {
521 +
            return Err(RepoError::Status(output.status.code().unwrap_or(1)));
522 +
        }
523 +
        Ok(output.stdout)
524 +
    }
525 +
}
526 +
527 +
/// Optional execution context for a single Git invocation.
528 +
#[derive(Clone, Copy, Debug, Default)]
529 +
struct Opts<'a> {
530 +
    /// Extra environment variables.
531 +
    env: &'a [(&'a str, &'a str)],
532 +
    /// Temporary index file written via `GIT_INDEX_FILE`.
533 +
    index: Option<&'a Path>,
534 +
    /// Stdin payload, if any.
535 +
    stdin: Option<&'a [u8]>,
536 +
}
537 +
538 +
/// Temporary index file path removed when dropped.
539 +
#[derive(Debug)]
540 +
struct TempIndex {
541 +
    /// Directory holding the temporary index file.
542 +
    dir: PathBuf,
543 +
    /// Path passed through `GIT_INDEX_FILE`.
544 +
    path: PathBuf,
545 +
}
546 +
547 +
impl TempIndex {
548 +
    /// Creates an empty temporary index path.
549 +
    fn new() -> io::Result<Self> {
550 +
        let suffix = SystemTime::now()
551 +
            .duration_since(UNIX_EPOCH)
552 +
            .unwrap_or_default()
553 +
            .as_nanos();
554 +
        let dir = std::env::temp_dir().join(format!(
555 +
            "rustik-brain-index-{}-{suffix}",
556 +
            std::process::id()
557 +
        ));
558 +
        fs::create_dir(&dir)?;
559 +
        let path = dir.join("index");
560 +
561 +
        Ok(Self { dir, path })
562 +
    }
563 +
564 +
    /// Returns the temporary index path.
565 +
    fn path(&self) -> &Path {
566 +
        &self.path
567 +
    }
568 +
}
569 +
570 +
impl Drop for TempIndex {
571 +
    fn drop(&mut self) {
572 +
        let _ = fs::remove_dir_all(&self.dir);
573 +
    }
574 +
}
575 +
576 +
/// Converts bytes to a UTF-8 string.
577 +
fn utf8(bytes: Vec<u8>) -> Result<String, RepoError> {
578 +
    String::from_utf8(bytes).map_err(|e| RepoError::Git(e.to_string()))
579 +
}
580 +
581 +
/// Reads a bounded file prefix and returns its first line.
582 +
fn read_head(reader: &mut impl io::Read) -> Result<Option<String>, RepoError> {
583 +
    let mut bytes = Vec::with_capacity(HEAD_BYTES);
584 +
    let read = reader.take(HEAD_BYTES as u64).read_to_end(&mut bytes)?;
585 +
586 +
    if read == 0 {
587 +
        return Ok(None);
588 +
    }
589 +
    if let Some(end) = bytes.iter().position(|byte| *byte == b'\n') {
590 +
        bytes.truncate(end);
591 +
    }
592 +
    if bytes.last() == Some(&b'\r') {
593 +
        bytes.pop();
594 +
    }
595 +
    Ok(Some(String::from_utf8_lossy(&bytes).into_owned()))
596 +
}
crates/repo/src/jj.rs added +101 -0
1 +
//! Jujutsu plumbing handle for reading workspace state.
2 +
3 +
use std::path::PathBuf;
4 +
use std::process::Command;
5 +
6 +
use crate::git::refs::RefStr;
7 +
use crate::{Oid, RepoError, git};
8 +
9 +
/// Jujutsu repository command context.
10 +
#[derive(Clone, Debug)]
11 +
pub struct Repository {
12 +
    /// Workspace directory used for `jj` invocations.
13 +
    cwd: PathBuf,
14 +
}
15 +
16 +
impl Repository {
17 +
    /// Creates a new Jujutsu repository context rooted at `cwd`.
18 +
    pub fn new(cwd: impl Into<PathBuf>) -> Self {
19 +
        Self { cwd: cwd.into() }
20 +
    }
21 +
22 +
    /// Returns commits in `base..target`, oldest first, as `(id, summary)` pairs.
23 +
    pub fn commits(&self, base: &RefStr, target: &RefStr) -> Result<Vec<(Oid, String)>, RepoError> {
24 +
        let revset = format!("{base}..{target}");
25 +
        let stdout = self.jj_bytes(&[
26 +
            "log",
27 +
            "--no-graph",
28 +
            "--reverse",
29 +
            "-r",
30 +
            &revset,
31 +
            "-T",
32 +
            "commit_id ++ \" \" ++ description.first_line() ++ \"\\n\"",
33 +
        ])?;
34 +
        let text = String::from_utf8(stdout).map_err(|e| RepoError::Git(e.to_string()))?;
35 +
        let mut commits = Vec::new();
36 +
        for line in text.lines() {
37 +
            let Some((id, summary)) = line.split_once(' ') else {
38 +
                return Err(RepoError::Git(
39 +
                    "malformed commit line from jj log".to_owned(),
40 +
                ));
41 +
            };
42 +
            let id = id
43 +
                .parse()
44 +
                .map_err(|_| RepoError::Git("invalid oid from jj log".to_owned()))?;
45 +
            commits.push((id, summary.trim_start().to_owned()));
46 +
        }
47 +
        Ok(commits)
48 +
    }
49 +
50 +
    /// Returns `commit`'s diff in unified Git format.
51 +
    pub fn commit_diff(&self, commit: Oid) -> Result<Vec<u8>, RepoError> {
52 +
        let commit = commit.to_string();
53 +
        self.jj_bytes(&["diff", "--git", "-r", &commit])
54 +
    }
55 +
56 +
    /// Returns a [`git::Repository`] for the embedded Git repository in this workspace.
57 +
    pub fn git_repository(&self) -> Result<git::Repository, RepoError> {
58 +
        let root = self.git_root()?;
59 +
        Ok(git::Repository::from_git_dir(self.cwd.clone(), root))
60 +
    }
61 +
62 +
    /// Resolves `revision` to a full commit hash.
63 +
    pub fn resolve(&self, revision: &RefStr) -> Result<Oid, RepoError> {
64 +
        let text = self.jj_text(&[
65 +
            "log",
66 +
            "--no-graph",
67 +
            "-r",
68 +
            revision.as_str(),
69 +
            "-T",
70 +
            "commit_id",
71 +
        ])?;
72 +
        text.trim()
73 +
            .parse()
74 +
            .map_err(|_| RepoError::Git("invalid commit id from jj".to_owned()))
75 +
    }
76 +
77 +
    /// Returns the path of the embedded Git repository.
78 +
    fn git_root(&self) -> Result<PathBuf, RepoError> {
79 +
        let text = self.jj_text(&["git", "root"])?;
80 +
        Ok(PathBuf::from(text.trim()))
81 +
    }
82 +
83 +
    /// Runs `jj` and returns its stdout bytes on success.
84 +
    fn jj_bytes(&self, args: &[&str]) -> Result<Vec<u8>, RepoError> {
85 +
        let output = Command::new("jj")
86 +
            .args(args)
87 +
            .current_dir(&self.cwd)
88 +
            .output()?;
89 +
        if output.status.success() {
90 +
            Ok(output.stdout)
91 +
        } else {
92 +
            Err(RepoError::Status(output.status.code().unwrap_or(1)))
93 +
        }
94 +
    }
95 +
96 +
    /// Runs `jj` and returns its stdout as UTF-8 text on success.
97 +
    fn jj_text(&self, args: &[&str]) -> Result<String, RepoError> {
98 +
        let bytes = self.jj_bytes(args)?;
99 +
        String::from_utf8(bytes).map_err(|e| RepoError::Git(e.to_string()))
100 +
    }
101 +
}
crates/repo/src/lib.rs +154 -146
1 1
//! Repository abstraction layer for Rustik tools.
2 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.
3 +
//! Provides object identifiers ([`Oid`]) and backend modules for Git and
4 +
//! Jujutsu repositories.
5 +
6 +
#![deny(unsafe_code)]
9 7
#![warn(missing_docs)]
10 8
#![warn(clippy::unwrap_used)]
11 9
12 10
pub mod git;
11 +
pub mod jj;
12 +
pub mod oid;
13 13
14 -
use std::ffi::{OsStr, OsString};
15 -
use std::io::{self, Read as _};
16 -
use std::path::{Path, PathBuf};
17 -
use std::process::{Command, Stdio};
14 +
pub use oid::{Oid, OidError};
18 15
19 -
// Constants //
16 +
use std::fmt;
17 +
use std::io;
18 +
use std::path::Path;
19 +
use std::process::Output;
20 20
21 -
/// Environment variable that disables Git's colored output.
22 -
const NO_COLOR: &str = "NO_COLOR";
23 -
/// Pathspec separator that ends Git's option list.
24 -
const PATHSPEC_SEPARATOR: &str = "--";
25 -
/// Maximum bytes read from a file head for shebang-style inference.
26 -
const HEAD_BYTES: usize = 64;
21 +
use git::refs::{Qualified, RefStr};
27 22
28 -
// Repo //
23 +
/// Stable patch identifier returned by `git patch-id`.
24 +
#[derive(Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
25 +
pub struct PatchId(String);
29 26
30 -
/// A diff backend a viewer can re-query for wider hunk context.
31 -
pub trait Repo {
32 -
    /// Refetches `paths` with `context_lines` of unified context per hunk.
33 -
    ///
34 -
    /// Returns the raw unified-diff bytes; decoding them is the caller's job.
35 -
    fn diff(&self, context_lines: usize, paths: &[&Path]) -> Result<Vec<u8>, RepoError>;
36 -
}
37 -
38 -
/// A [`Repo`] backed by the `git diff` command.
39 -
pub struct GitRepo {
40 -
    /// Working directory for `git diff` invocations.
41 -
    cwd: PathBuf,
42 -
    /// CLI arguments forwarded to Git, as the pager was invoked.
43 -
    args: Vec<OsString>,
44 -
}
45 -
46 -
impl GitRepo {
47 -
    /// Creates a repo that runs `git diff` in `cwd` with forwarded `args`.
48 -
    pub fn new(cwd: impl Into<PathBuf>, args: impl Into<Vec<OsString>>) -> Self {
49 -
        Self {
50 -
            cwd: cwd.into(),
51 -
            args: args.into(),
52 -
        }
27 +
impl PatchId {
28 +
    /// Returns the patch identifier text.
29 +
    pub fn as_str(&self) -> &str {
30 +
        &self.0
53 31
    }
32 +
}
54 33
55 -
    /// Returns original diff selector args without pathspecs being refetched.
56 -
    fn forwarded_args<'a>(&'a self, paths: &[&Path]) -> Vec<&'a OsStr> {
57 -
        let args = 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 -
63 -
        args.iter()
64 -
            .map(OsString::as_os_str)
65 -
            .filter(|arg| !is_refetched_path(arg, paths))
66 -
            .collect()
34 +
impl fmt::Display for PatchId {
35 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36 +
        f.write_str(&self.0)
67 37
    }
38 +
}
68 39
69 -
    /// Reads the first bytes of a Git blob object.
70 -
    pub fn head_line(&self, oid: &str) -> Result<Option<String>, RepoError> {
71 -
        let mut child = Command::new("git")
72 -
            .arg("show")
73 -
            .arg(oid)
74 -
            .current_dir(&self.cwd)
75 -
            .stdout(Stdio::piped())
76 -
            .stderr(Stdio::null())
77 -
            .spawn()?;
78 -
        let Some(mut stdout) = child.stdout.take() else {
79 -
            return Ok(None);
80 -
        };
81 -
        let head = read_head(&mut stdout)?;
82 -
        let _ = child.kill();
83 -
        let _ = child.wait();
84 -
85 -
        Ok(head)
86 -
    }
40 +
/// Aggregated diff size of one commit, as reported by `git log --shortstat`.
41 +
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
42 +
pub struct DiffStat {
43 +
    /// Number of files the commit touches.
44 +
    pub files_changed: usize,
45 +
    /// Number of inserted lines.
46 +
    pub insertions: usize,
47 +
    /// Number of deleted lines.
48 +
    pub deletions: usize,
87 49
}
88 50
89 -
impl Repo for GitRepo {
90 -
    fn diff(&self, context_lines: usize, paths: &[&Path]) -> Result<Vec<u8>, RepoError> {
91 -
        // Forwarded args up to any `--` pathspec separator select the diff; the
92 -
        // refetch supplies its own narrowed path list after a fresh separator.
93 -
        let forwarded = self.forwarded_args(paths);
94 -
        let context = OsString::from(format!("-U{context_lines}"));
95 -
        let output = Command::new("git")
96 -
            .arg("diff")
97 -
            .args(forwarded)
98 -
            .arg(context)
99 -
            .arg(PATHSPEC_SEPARATOR)
100 -
            .args(paths)
101 -
            .current_dir(&self.cwd)
102 -
            .env(NO_COLOR, "1")
103 -
            .output()?;
104 -
        if !output.status.success() {
105 -
            return Err(RepoError::Status(output.status.code().unwrap_or(1)));
51 +
impl DiffStat {
52 +
    /// Parses one `--shortstat` summary line.
53 +
    ///
54 +
    /// Segments that Git omits (for example deletions in an insert-only
55 +
    /// commit) stay zero, so an unrecognized line parses as an empty stat.
56 +
    pub fn from_shortstat(line: &str) -> Self {
57 +
        let mut stat = Self::default();
58 +
        for segment in line.split(',') {
59 +
            let segment = segment.trim();
60 +
            let Some((count, label)) = segment.split_once(' ') else {
61 +
                continue;
62 +
            };
63 +
            let Ok(count) = count.parse() else {
64 +
                continue;
65 +
            };
66 +
            if label.starts_with("file") {
67 +
                stat.files_changed = count;
68 +
            } else if label.starts_with("insertion") {
69 +
                stat.insertions = count;
70 +
            } else if label.starts_with("deletion") {
71 +
                stat.deletions = count;
72 +
            }
106 73
        }
107 -
        Ok(output.stdout)
74 +
        stat
108 75
    }
109 76
}
110 77
111 -
/// Returns whether an original argument is one of the pathspecs being refetched.
112 -
fn is_refetched_path(arg: &OsStr, paths: &[&Path]) -> bool {
113 -
    let arg = Path::new(arg);
114 -
    let normalized = arg.strip_prefix(".").unwrap_or(arg);
78 +
/// Repository operations that read commits, objects, refs, and derived data.
79 +
pub trait ReadRepository {
80 +
    /// Resolves a revision reference to a commit id.
81 +
    fn commit_id(&self, rev: &RefStr) -> Result<Oid, RepoError>;
82 +
83 +
    /// Returns the tree id for any commit or tree object.
84 +
    fn tree_id(&self, object: Oid) -> Result<Oid, RepoError>;
85 +
86 +
    /// Returns the current commit stored in `reference`, if the ref exists.
87 +
    fn optional_ref(&self, reference: &Qualified<'_>) -> Result<Option<Oid>, RepoError>;
88 +
89 +
    /// Returns the single parent of `commit`, or an error if it has more or fewer.
90 +
    fn parent(&self, commit: Oid) -> Result<Oid, RepoError>;
91 +
92 +
    /// Returns the full commit message for `commit`.
93 +
    fn commit_message(&self, commit: Oid) -> Result<String, RepoError>;
94 +
95 +
    /// Returns each commit's aggregated diff size, in the given order.
96 +
    fn commit_stats(&self, commits: &[Oid]) -> Result<Vec<DiffStat>, RepoError>;
97 +
98 +
    /// Reads a blob object's bytes.
99 +
    fn cat_blob(&self, blob: Oid) -> Result<Vec<u8>, RepoError>;
100 +
101 +
    /// Produces a unified diff between two objects as text.
102 +
    fn diff(&self, from: Oid, to: Oid) -> Result<String, RepoError>;
115 103
116 -
    paths.iter().any(|path| {
117 -
        let normalized_path = path.strip_prefix(".").unwrap_or(path);
118 -
        normalized == normalized_path
119 -
    })
104 +
    /// Computes a stable Git patch id for `patch` text.
105 +
    fn patch_id(&self, patch: &str) -> Result<PatchId, RepoError>;
106 +
107 +
    /// Computes a three-way merge tree and returns the resulting tree id.
108 +
    fn merge_tree(&self, merge_base: Oid, ours: Oid, theirs: Oid) -> Result<Oid, RepoError>;
109 +
110 +
    /// Returns commits in `base..target`, oldest first, as `(id, summary)` pairs.
111 +
    fn commits(&self, base: &RefStr, target: &RefStr) -> Result<Vec<(Oid, String)>, RepoError>;
112 +
113 +
    /// Returns the unified diff for `commit` against its parent.
114 +
    fn commit_diff(&self, commit: Oid) -> Result<Vec<u8>, RepoError>;
120 115
}
121 116
122 -
/// Reads a bounded file prefix and returns its first line.
123 -
fn read_head(reader: &mut impl io::Read) -> Result<Option<String>, RepoError> {
124 -
    let mut bytes = Vec::with_capacity(HEAD_BYTES);
125 -
    let read = reader.take(HEAD_BYTES as u64).read_to_end(&mut bytes)?;
126 -
    if read == 0 {
127 -
        return Ok(None);
128 -
    }
129 -
    if let Some(end) = bytes.iter().position(|byte| *byte == b'\n') {
130 -
        bytes.truncate(end);
131 -
    }
132 -
    if bytes.last() == Some(&b'\r') {
133 -
        bytes.pop();
134 -
    }
135 -
    Ok(Some(String::from_utf8_lossy(&bytes).into_owned()))
117 +
/// Repository operations that write objects and refs.
118 +
pub trait WriteRepository {
119 +
    /// Writes `bytes` as a blob object and returns its id.
120 +
    fn write_blob(&self, bytes: &[u8]) -> Result<Oid, RepoError>;
121 +
122 +
    /// Applies a Git-format patch to a temporary index and returns its tree id.
123 +
    fn apply_patch_to_tree(&self, base: Oid, patch: &str) -> Result<Oid, RepoError>;
124 +
125 +
    /// Creates a commit with `tree` and `parent`.
126 +
    fn commit(
127 +
        &self,
128 +
        tree: Oid,
129 +
        parent: Oid,
130 +
        author: &str,
131 +
        email: &str,
132 +
        message: &str,
133 +
    ) -> Result<Oid, RepoError>;
134 +
135 +
    /// Moves `reference` to point at `commit`.
136 +
    fn update_ref(&self, reference: &Qualified<'_>, commit: Oid) -> Result<(), RepoError>;
136 137
}
137 138
138 -
// Error Handling //
139 +
/// A diff backend a viewer can re-query for wider hunk context.
140 +
pub trait DiffRepository {
141 +
    /// Refetches `paths` with `context_lines` of unified context per hunk.
142 +
    ///
143 +
    /// Returns the raw unified-diff bytes; decoding them is the caller's job.
144 +
    fn diff(&self, context_lines: usize, paths: &[&Path]) -> Result<Vec<u8>, RepoError>;
145 +
}
139 146
140 -
/// A failure while refetching diff data from a [`Repo`].
147 +
/// A failure from a Git-backed repository operation.
141 148
#[derive(Debug)]
142 149
pub enum RepoError {
143 -
    /// Spawning or waiting on the backend failed.
150 +
    /// Spawning or waiting on a process failed.
144 151
    Io(io::Error),
145 -
    /// The backend exited with a failing status code.
152 +
    /// A backend command exited with a failing status code.
146 153
    Status(i32),
154 +
    /// A Git plumbing command failed, carrying its diagnostic.
155 +
    Git(String),
156 +
    /// A three-way merge produced conflicts.
157 +
    MergeConflict(String),
158 +
}
159 +
160 +
impl RepoError {
161 +
    /// Builds a Git error from a failed command's output.
162 +
    pub(crate) fn git(output: &Output) -> Self {
163 +
        let stdout = String::from_utf8_lossy(&output.stdout);
164 +
        let stderr = String::from_utf8_lossy(&output.stderr);
165 +
        Self::Git(format!("{stdout}{stderr}").trim().to_owned())
166 +
    }
147 167
}
148 168
149 169
impl From<io::Error> for RepoError {
150 170
    fn from(error: io::Error) -> Self {
151 171
        Self::Io(error)
154 174
155 175
impl std::fmt::Display for RepoError {
156 176
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
157 177
        match self {
158 178
            Self::Io(error) => write!(f, "{error}"),
159 -
            Self::Status(code) => write!(f, "git diff exited with status {code}"),
179 +
            Self::Status(code) => write!(f, "command exited with status {code}"),
180 +
            Self::Git(message) => write!(f, "{message}"),
181 +
            Self::MergeConflict(message) => write!(f, "merge conflict: {message}"),
160 182
        }
161 183
    }
162 184
}
163 185
164 186
impl std::error::Error for RepoError {}
167 189
#[allow(clippy::unwrap_used)]
168 190
mod tests {
169 191
    use super::*;
170 192
171 193
    #[test]
172 -
    fn forwarded_args_strip_refetched_pathspecs_without_separator() {
173 -
        let repo = GitRepo::new(
174 -
            ".",
175 -
            vec![
176 -
                OsString::from("HEAD~14"),
177 -
                OsString::from("HEAD"),
178 -
                OsString::from("assets/css/style.css"),
179 -
            ],
194 +
    fn shortstat_lines_parse_with_partial_segments() {
195 +
        assert_eq!(
196 +
            DiffStat::from_shortstat(" 3 files changed, 10 insertions(+), 2 deletions(-)"),
197 +
            DiffStat {
198 +
                files_changed: 3,
199 +
                insertions: 10,
200 +
                deletions: 2
201 +
            }
180 202
        );
181 -
        let path = Path::new("assets/css/style.css");
182 -
183 -
        let args = repo.forwarded_args(&[path]);
184 -
185 -
        assert_eq!(args, vec![OsStr::new("HEAD~14"), OsStr::new("HEAD")]);
186 -
    }
187 -
188 -
    #[test]
189 -
    fn forwarded_args_ignore_pathspecs_after_separator() {
190 -
        let repo = GitRepo::new(
191 -
            ".",
192 -
            vec![
193 -
                OsString::from("HEAD~14"),
194 -
                OsString::from("HEAD"),
195 -
                OsString::from("--"),
196 -
                OsString::from("assets/css/style.css"),
197 -
            ],
203 +
        assert_eq!(
204 +
            DiffStat::from_shortstat(" 1 file changed, 5 insertions(+)"),
205 +
            DiffStat {
206 +
                files_changed: 1,
207 +
                insertions: 5,
208 +
                deletions: 0
209 +
            }
198 210
        );
199 -
        let path = Path::new("assets/css/style.css");
200 -
201 -
        let args = repo.forwarded_args(&[path]);
202 -
203 -
        assert_eq!(args, vec![OsStr::new("HEAD~14"), OsStr::new("HEAD")]);
211 +
        assert_eq!(DiffStat::from_shortstat("nonsense"), DiffStat::default());
204 212
    }
205 213
}
crates/repo/src/oid.rs added +101 -0
1 +
//! Object identifier parsing and formatting.
2 +
3 +
use std::str::FromStr;
4 +
use std::{fmt, str};
5 +
6 +
/// Number of bytes in a SHA-1 object digest.
7 +
const SHA1_LEN: usize = 20;
8 +
/// Number of bytes in a SHA-256 object digest.
9 +
const SHA256_LEN: usize = 32;
10 +
/// Number of leading hash characters shown as an abbreviated object id.
11 +
const SHORT_LEN: usize = 9;
12 +
13 +
/// Object identifier as it appears in a Git diff header or rev-parse output.
14 +
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
15 +
pub enum Oid {
16 +
    /// A SHA-1 hash digest.
17 +
    Sha1([u8; SHA1_LEN]),
18 +
    /// A SHA-256 hash digest.
19 +
    Sha256([u8; SHA256_LEN]),
20 +
}
21 +
22 +
impl Oid {
23 +
    /// Returns the abbreviated object id used in compact displays.
24 +
    pub fn short(&self) -> String {
25 +
        self.to_string()[..SHORT_LEN].to_owned()
26 +
    }
27 +
}
28 +
29 +
impl FromStr for Oid {
30 +
    type Err = OidError;
31 +
32 +
    fn from_str(input: &str) -> Result<Self, Self::Err> {
33 +
        match input.len() {
34 +
            40 => {
35 +
                let mut bytes = [0; SHA1_LEN];
36 +
                parse_hex(input, &mut bytes)?;
37 +
                Ok(Self::Sha1(bytes))
38 +
            }
39 +
            64 => {
40 +
                let mut bytes = [0; SHA256_LEN];
41 +
                parse_hex(input, &mut bytes)?;
42 +
                Ok(Self::Sha256(bytes))
43 +
            }
44 +
            _ => Err(OidError),
45 +
        }
46 +
    }
47 +
}
48 +
49 +
impl TryFrom<&[u8]> for Oid {
50 +
    type Error = OidError;
51 +
52 +
    fn try_from(input: &[u8]) -> Result<Self, Self::Error> {
53 +
        let input = str::from_utf8(input).map_err(|_| OidError)?;
54 +
        input.trim().parse()
55 +
    }
56 +
}
57 +
58 +
impl fmt::Display for Oid {
59 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60 +
        let bytes: &[u8] = match self {
61 +
            Self::Sha1(bytes) => bytes,
62 +
            Self::Sha256(bytes) => bytes,
63 +
        };
64 +
        for byte in bytes {
65 +
            write!(f, "{byte:02x}")?;
66 +
        }
67 +
        Ok(())
68 +
    }
69 +
}
70 +
71 +
/// Error returned when an object identifier is malformed.
72 +
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
73 +
pub struct OidError;
74 +
75 +
impl fmt::Display for OidError {
76 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77 +
        f.write_str("object id must be non-empty hexadecimal text")
78 +
    }
79 +
}
80 +
81 +
impl std::error::Error for OidError {}
82 +
83 +
/// Parses a hexadecimal digest string into `out`.
84 +
fn parse_hex(input: &str, out: &mut [u8]) -> Result<(), OidError> {
85 +
    for (index, chunk) in input.as_bytes().chunks_exact(2).enumerate() {
86 +
        let high = hex_val(chunk[0])?;
87 +
        let low = hex_val(chunk[1])?;
88 +
        out[index] = (high << 4) | low;
89 +
    }
90 +
    Ok(())
91 +
}
92 +
93 +
/// Returns the numeric value of one ASCII hex digit.
94 +
fn hex_val(byte: u8) -> Result<u8, OidError> {
95 +
    match byte {
96 +
        b'0'..=b'9' => Ok(byte - b'0'),
97 +
        b'a'..=b'f' => Ok(byte - b'a' + 10),
98 +
        b'A'..=b'F' => Ok(byte - b'A' + 10),
99 +
        _ => Err(OidError),
100 +
    }
101 +
}
crates/tui-termion/src/event.rs +2 -1
130 130
    if !raw.starts_with(b"\x1B[") || raw.last() != Some(&b'u') {
131 131
        return None;
132 132
    }
133 133
    let body = &raw[2..raw.len() - 1];
134 134
    let mut fields = body.split(|&byte| byte == b';');
135 -
    let code = csi_u_number(fields.next()?)?;
135 +
    let field = fields.next()?;
136 +
    let code = csi_u_number(field)?;
136 137
    // Modifiers are encoded as a one-based bitmask; absent means no modifiers.
137 138
    let mask = fields
138 139
        .next()
139 140
        .and_then(csi_u_number)
140 141
        .unwrap_or(1)
crates/tui-termion/src/term.rs +6 -3
41 41
/// Raw alternate terminal-device screen with the enhanced keyboard protocol.
42 42
pub type TerminalScreen = KeyboardProtocol<AlternateScreen<MouseTerminal<RawTerminal<File>>>>;
43 43
44 44
/// Creates a raw alternate-screen backend on the terminal device.
45 45
pub fn screen() -> io::Result<TermionBackend<TerminalScreen>> {
46 -
    let screen =
47 -
        MouseTerminal::from(terminal_screen()?.into_raw_mode()?).into_alternate_screen()?;
48 -
    Ok(TermionBackend::new(KeyboardProtocol::new(screen)?))
46 +
    let terminal = terminal_screen()?;
47 +
    let raw = terminal.into_raw_mode()?;
48 +
    let mouse = MouseTerminal::from(raw);
49 +
    let screen = mouse.into_alternate_screen()?;
50 +
    let keyboard = KeyboardProtocol::new(screen)?;
51 +
    Ok(TermionBackend::new(keyboard))
49 52
}
50 53
51 54
/// Output wrapper that enables the enhanced keyboard protocol for its lifetime.
52 55
///
53 56
/// The protocol lets the terminal report modified keys unambiguously; terminals that do not
crates/tui-widgets/src/input.rs +20 -4
57 57
    /// Returns the caret screen position recorded by the last render.
58 58
    pub fn caret(&self) -> Point {
59 59
        self.caret
60 60
    }
61 61
62 -
    /// Applies the edit or navigation bound to `key`, returning whether the
63 -
    /// input changed. `Enter`, `Tab`, and other keys are left to the caller so
64 -
    /// it can decide submit and newline semantics.
62 +
    /// Applies the edit or navigation bound to `key`.
63 +
    ///
64 +
    /// Returns whether the buffer or caret changed. `Enter`, `Tab`, and other
65 +
    /// keys are left to the caller so it can decide submit, focus, and newline
66 +
    /// semantics for its own mode.
65 67
    pub fn input(&mut self, key: Key) -> bool {
66 68
        match key {
67 69
            Key::Char(ch) => self.insert(ch),
68 70
            Key::Backspace => self.backspace(),
69 71
            Key::Delete => self.delete(),
76 78
            _ => false,
77 79
        }
78 80
    }
79 81
80 82
    /// Inserts `ch` at the caret.
83 +
    ///
84 +
    /// The caret is stored as a byte offset, so movement after insertion uses
85 +
    /// the UTF-8 width of the inserted character.
81 86
    pub fn insert(&mut self, ch: char) -> bool {
82 87
        self.value.insert(self.cursor, ch);
83 88
        self.cursor += ch.len_utf8();
84 89
        true
85 90
    }
149 154
        self.cursor = end;
150 155
        true
151 156
    }
152 157
153 158
    /// Moves the caret up one line, keeping the column where possible.
159 +
    ///
160 +
    /// Columns are counted in `char`s and then translated back to a byte offset
161 +
    /// on the target line. Moving to a shorter line clamps at that line's end.
154 162
    pub fn move_up(&mut self) -> bool {
155 163
        let (row, col) = self.row_col();
156 164
        if row == 0 {
157 165
            return false;
158 166
        }
159 167
        self.cursor = self.offset_at(row - 1, col);
160 168
        true
161 169
    }
162 170
163 171
    /// Moves the caret down one line, keeping the column where possible.
172 +
    ///
173 +
    /// Columns are counted in `char`s and then translated back to a byte offset
174 +
    /// on the target line. Moving to a shorter line clamps at that line's end.
164 175
    pub fn move_down(&mut self) -> bool {
165 176
        let (row, col) = self.row_col();
166 177
        if row + 1 >= self.lines().count() {
167 178
            return false;
168 179
        }
199 210
            .map_or(0, |line| line.chars().count());
200 211
        (row, col)
201 212
    }
202 213
203 214
    /// Returns the byte offset of `column` on `row`, clamped to the line end.
215 +
    ///
216 +
    /// `column` is a character column, not a byte index. This keeps the stored
217 +
    /// cursor on a UTF-8 boundary even when the edited text contains non-ASCII
218 +
    /// characters.
204 219
    fn offset_at(&self, row: usize, column: usize) -> usize {
205 220
        let ranges = self.line_ranges();
206 221
        let Some(&(start, end)) = ranges.get(row) else {
207 222
            return self.value.len();
208 223
        };
282 297
            state.hscroll = 0;
283 298
            state.caret = Point::new(area.x, area.y);
284 299
            return;
285 300
        }
286 301
        let (row, col) = state.row_col();
287 -
288 302
        if row < state.scroll {
289 303
            state.scroll = row;
290 304
        } else if row >= state.scroll + area.rows {
291 305
            state.scroll = row + 1 - area.rows;
292 306
        }
299 313
300 314
        for screen_row in 0..area.rows {
301 315
            let Some(&(start, end)) = ranges.get(state.scroll + screen_row) else {
302 316
                break;
303 317
            };
318 +
            // Horizontal scrolling is also character-based to match caret
319 +
            // movement. Wide glyphs are documented as an approximation.
304 320
            let text: String = state.value[start..end]
305 321
                .chars()
306 322
                .skip(state.hscroll)
307 323
                .take(area.cols)
308 324
                .collect();