C3: chunk staging, unstaging and revert from the gutter and the diff viewer
- crates/vcs chunk.rs: chunks of a file (buffer text vs index, HEAD vs
index), a minimal patch applied with git apply --cached, revert as a
byte edit; token refusal when buffer, index or HEAD changed; CRLF
(autocrlf and stored), no final newline, BOM, staged renames, first
commit; binary and untracked refused. Real-git tests + property test.
- engine: git.chunks, git.stageChunk, git.unstageChunk, git.revertChunk
(revert edits the buffer under the lock, undoable in the editor);
cmd:
:start_then; git.lineChanges shares the vcs line diff.
- UI: chunk popup on a gutter marker click (Stage / Unstage / Revert /
Previous / Next), hollow staged markers, vcs.showChunk, diff viewer
hint, "partly staged" badge in the Changes window.
- Docs: G8 row, Git parity row evidence, ui-parity, architecture.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
d8e66a4652
commit
301443db7d
28 changed files with 3159 additions and 101 deletions
|
|
@ -23,7 +23,6 @@ lutra-vfs.workspace = true
|
|||
lutra-vcs.workspace = true
|
||||
serde = { version = "1.0.229", features = ["derive"] }
|
||||
serde_json = "1.0.154"
|
||||
similar = { version = "2.7.0", default-features = false }
|
||||
thiserror = "2.0.21"
|
||||
|
||||
[lints]
|
||||
|
|
|
|||
|
|
@ -187,6 +187,11 @@ struct Job {
|
|||
/// with `mutates`. Neither this file nor `repo.rs` needs another change.
|
||||
pub(super) type RepoFn = Box<dyn Fn(&Repo) -> Result<Value, VcsError> + Send>;
|
||||
|
||||
/// A step run under the lock after a [`start_then`] call succeeded: it
|
||||
/// takes the call's value and returns the command's (chunk revert edits
|
||||
/// the editor buffer here).
|
||||
pub(super) type ThenFn = Box<dyn FnOnce(&mut State, Value) -> Result<Value, EngineError> + Send>;
|
||||
|
||||
/// What one command does on its thread.
|
||||
enum Op {
|
||||
/// `git.status`.
|
||||
|
|
@ -277,7 +282,22 @@ pub(super) fn start_with(
|
|||
mutates: bool,
|
||||
run: RepoFn,
|
||||
) -> Result<Outcome, EngineError> {
|
||||
start(state, command, Op::Custom { mutates, run })
|
||||
start(state, command, Op::Custom { mutates, run }, None)
|
||||
}
|
||||
|
||||
/// As [`start_with`], then runs `then` under the lock with the call's value
|
||||
/// once it succeeded.
|
||||
///
|
||||
/// # Errors
|
||||
/// As [`start`]; the outcome fails with `then`'s error.
|
||||
pub(super) fn start_then(
|
||||
state: &mut State,
|
||||
command: &'static str,
|
||||
mutates: bool,
|
||||
run: RepoFn,
|
||||
then: ThenFn,
|
||||
) -> Result<Outcome, EngineError> {
|
||||
start(state, command, Op::Custom { mutates, run }, Some(then))
|
||||
}
|
||||
|
||||
/// Runs `op` on a new thread and returns the pending outcome.
|
||||
|
|
@ -285,7 +305,12 @@ pub(super) fn start_with(
|
|||
/// # Errors
|
||||
/// [`EngineError::Disabled`] without a project, [`EngineError::Failed`]
|
||||
/// when [`MAX_RUNNING`] calls are running already.
|
||||
fn start(state: &mut State, command: &'static str, op: Op) -> Result<Outcome, EngineError> {
|
||||
fn start(
|
||||
state: &mut State,
|
||||
command: &'static str,
|
||||
op: Op,
|
||||
then: Option<ThenFn>,
|
||||
) -> Result<Outcome, EngineError> {
|
||||
let project = state
|
||||
.project
|
||||
.as_ref()
|
||||
|
|
@ -349,7 +374,11 @@ fn start(state: &mut State, command: &'static str, op: Op) -> Result<Outcome, En
|
|||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.take()
|
||||
.ok_or_else(|| EngineError::Failed("git did not answer in time".into()))?;
|
||||
finish(state, &project, reply)
|
||||
let value = finish(state, &project, reply)?;
|
||||
match then {
|
||||
Some(then) => then(state, value),
|
||||
None => Ok(value),
|
||||
}
|
||||
})))
|
||||
}
|
||||
|
||||
|
|
@ -674,7 +703,7 @@ impl Command for StatusCommand {
|
|||
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
|
||||
let command = self.spec().id;
|
||||
let _: serde_json::Map<String, Value> = parse(command, params)?;
|
||||
start(state, command, Op::Status)
|
||||
start(state, command, Op::Status, None)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -699,7 +728,7 @@ impl Command for Stage {
|
|||
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
|
||||
let command = self.spec().id;
|
||||
let paths = paths(state, command, params)?;
|
||||
start(state, command, Op::Stage(paths))
|
||||
start(state, command, Op::Stage(paths), None)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -724,7 +753,7 @@ impl Command for Unstage {
|
|||
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
|
||||
let command = self.spec().id;
|
||||
let paths = paths(state, command, params)?;
|
||||
start(state, command, Op::Unstage(paths))
|
||||
start(state, command, Op::Unstage(paths), None)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -770,6 +799,7 @@ impl Command for Commit {
|
|||
message: p.message,
|
||||
amend: p.amend,
|
||||
},
|
||||
None,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
@ -795,7 +825,7 @@ impl Command for LastMessage {
|
|||
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
|
||||
let command = self.spec().id;
|
||||
let _: serde_json::Map<String, Value> = parse(command, params)?;
|
||||
start(state, command, Op::LastMessage)
|
||||
start(state, command, Op::LastMessage, None)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -847,7 +877,7 @@ impl Command for Show {
|
|||
RefParam::Head => Rev::Head,
|
||||
RefParam::Index => Rev::Index,
|
||||
};
|
||||
start(state, command, Op::Show(path, rev))
|
||||
start(state, command, Op::Show(path, rev), None)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -872,7 +902,7 @@ impl Command for BranchesCommand {
|
|||
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
|
||||
let command = self.spec().id;
|
||||
let _: serde_json::Map<String, Value> = parse(command, params)?;
|
||||
start(state, command, Op::Branches)
|
||||
start(state, command, Op::Branches, None)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -905,7 +935,7 @@ impl Command for Checkout {
|
|||
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
|
||||
let command = self.spec().id;
|
||||
let p: CheckoutParams = parse(command, params)?;
|
||||
start(state, command, Op::Checkout(p.branch))
|
||||
start(state, command, Op::Checkout(p.branch), None)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -951,6 +981,7 @@ impl Command for CreateBranch {
|
|||
from: p.from,
|
||||
checkout: p.checkout,
|
||||
},
|
||||
None,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
288
crates/engine/src/cmd/git_chunks.rs
Normal file
288
crates/engine/src/cmd/git_chunks.rs
Normal file
|
|
@ -0,0 +1,288 @@
|
|||
//! Chunk commands (C8 C3): `git.chunks`, `git.stageChunk`,
|
||||
//! `git.unstageChunk` and `git.revertChunk`, run like every `git.*`
|
||||
//! command (a pending outcome off the lock, git and the repository cached
|
||||
//! by [`super::git`]).
|
||||
//!
|
||||
//! - **Working text** is the open buffer's text (unsaved changes
|
||||
//! included), taken under the lock, so chunks match the gutter's
|
||||
//! `git.lineChanges` markers line for line.
|
||||
//! - **Token:** `git.chunks` returns a token of the texts it compared;
|
||||
//! every action passes it back with the chunk's position and is refused
|
||||
//! (`failed`, "changed since…") when the buffer, the index or HEAD
|
||||
//! changed meanwhile.
|
||||
//! - **Revert** edits the buffer through `buffer.edit` under the lock once
|
||||
//! git answered, only if the buffer is still at the version the chunk was
|
||||
//! computed for; the edit leaves the buffer dirty and is undoable in the
|
||||
//! editor (the UI marks it so). It sends no `gitChanged` (the index does
|
||||
//! not change); the gutter follows the buffer edit.
|
||||
//! - Stage and unstage change the index and send `gitChanged`.
|
||||
|
||||
use lutra_vcs::Chunk;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::git::{start_then, start_with};
|
||||
use super::params::parse;
|
||||
use crate::buffers::BufferId;
|
||||
use crate::workspace::path_string;
|
||||
use crate::{Command, CommandSpec, EngineError, Outcome, Registry, State};
|
||||
|
||||
/// Registers the chunk commands.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`EngineError::Internal`] if an id is taken.
|
||||
pub fn register(registry: &mut Registry) -> Result<(), EngineError> {
|
||||
registry.register(Box::new(Chunks))?;
|
||||
registry.register(Box::new(Action(Kind::Stage)))?;
|
||||
registry.register(Box::new(Action(Kind::Unstage)))?;
|
||||
registry.register(Box::new(Action(Kind::Revert)))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The buffer's path, text and version, taken under the lock.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`EngineError::Failed`] for an unknown buffer.
|
||||
fn buffer_of(
|
||||
state: &State,
|
||||
command: &str,
|
||||
id: BufferId,
|
||||
) -> Result<(String, String, u64), EngineError> {
|
||||
let open = state
|
||||
.buffers
|
||||
.get(id)
|
||||
.ok_or_else(|| EngineError::Failed(format!("{command}: no buffer {id}")))?;
|
||||
Ok((path_string(&open.path), open.buffer.text(), open.version))
|
||||
}
|
||||
|
||||
/// One chunk as the commands return it.
|
||||
fn chunk_json(chunk: &Chunk) -> Value {
|
||||
let kind = if chunk.old.is_empty() {
|
||||
"added"
|
||||
} else if chunk.new.is_empty() {
|
||||
"deleted"
|
||||
} else {
|
||||
"modified"
|
||||
};
|
||||
json!({
|
||||
"kind": kind,
|
||||
"startLine": chunk.lines.start,
|
||||
"endLine": chunk.lines.end,
|
||||
"oldStart": chunk.old.start,
|
||||
"oldEnd": chunk.old.end,
|
||||
"newStart": chunk.new.start,
|
||||
"newEnd": chunk.new.end,
|
||||
"removed": chunk.removed,
|
||||
"added": chunk.added,
|
||||
"truncated": chunk.truncated,
|
||||
})
|
||||
}
|
||||
|
||||
/// Params of `git.chunks`.
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct ChunksParams {
|
||||
/// Buffer id.
|
||||
id: BufferId,
|
||||
}
|
||||
|
||||
/// `git.chunks`.
|
||||
struct Chunks;
|
||||
|
||||
impl Command for Chunks {
|
||||
fn spec(&self) -> &CommandSpec {
|
||||
&CommandSpec {
|
||||
id: "git.chunks",
|
||||
label: "Git: Changed Chunks",
|
||||
menu_path: None,
|
||||
default_shortcut: None,
|
||||
params: "{ id: buffer id }; returns { version, token, headPath: string | null, unstaged: [chunk], staged: [chunk] } where chunk = { kind: \"added\"|\"modified\"|\"deleted\", startLine, endLine (buffer lines, 0-based, end exclusive; empty for a deletion point), oldStart, oldEnd, newStart, newEnd, removed: [line], added: [line], truncated }; unstaged compares the index with the buffer text, staged HEAD (the old path of a staged rename: headPath) with the index; staged chunks are placed on the buffer lines their index lines map to; failed for binary, too large, untracked or conflicted files",
|
||||
}
|
||||
}
|
||||
|
||||
fn enabled(&self, state: &State) -> bool {
|
||||
state.has_project()
|
||||
}
|
||||
|
||||
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
|
||||
let command = self.spec().id;
|
||||
let p: ChunksParams = parse(command, params)?;
|
||||
let (path, text, version) = buffer_of(state, command, p.id)?;
|
||||
start_with(
|
||||
state,
|
||||
command,
|
||||
false,
|
||||
Box::new(move |repo| {
|
||||
let chunks = repo.chunks(&path, &text)?;
|
||||
let unstaged: Vec<Value> = chunks.unstaged.iter().map(chunk_json).collect();
|
||||
let staged: Vec<Value> = chunks.staged.iter().map(chunk_json).collect();
|
||||
Ok(json!({
|
||||
"version": version,
|
||||
"token": chunks.token,
|
||||
"headPath": chunks.head_path,
|
||||
"unstaged": unstaged,
|
||||
"staged": staged,
|
||||
}))
|
||||
}),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Params of the chunk actions.
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct ActionParams {
|
||||
/// Buffer id.
|
||||
id: BufferId,
|
||||
/// The chunk's position in its list of `git.chunks`.
|
||||
index: usize,
|
||||
/// The token `git.chunks` returned.
|
||||
token: String,
|
||||
}
|
||||
|
||||
/// Which chunk action.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Kind {
|
||||
/// `git.stageChunk`.
|
||||
Stage,
|
||||
/// `git.unstageChunk`.
|
||||
Unstage,
|
||||
/// `git.revertChunk`.
|
||||
Revert,
|
||||
}
|
||||
|
||||
/// A chunk action.
|
||||
struct Action(Kind);
|
||||
|
||||
/// Longest token accepted.
|
||||
const MAX_TOKEN: usize = 64;
|
||||
|
||||
impl Command for Action {
|
||||
fn spec(&self) -> &CommandSpec {
|
||||
match self.0 {
|
||||
Kind::Stage => &CommandSpec {
|
||||
id: "git.stageChunk",
|
||||
label: "Git: Stage Chunk",
|
||||
menu_path: None,
|
||||
default_shortcut: None,
|
||||
params: "{ id: buffer id, index: position in git.chunks' unstaged list, token: git.chunks' token }; stages that chunk of the buffer text (unsaved changes included) with git apply --cached; returns {}; failed when the buffer, the index or HEAD changed since git.chunks (look again), or git refuses the patch",
|
||||
},
|
||||
Kind::Unstage => &CommandSpec {
|
||||
id: "git.unstageChunk",
|
||||
label: "Git: Unstage Chunk",
|
||||
menu_path: None,
|
||||
default_shortcut: None,
|
||||
params: "{ id: buffer id, index: position in git.chunks' staged list, token }; puts HEAD's lines of that chunk back into the index (the old path of a staged rename); the working copy is not touched; returns {}; failed as git.stageChunk",
|
||||
},
|
||||
Kind::Revert => &CommandSpec {
|
||||
id: "git.revertChunk",
|
||||
label: "Git: Revert Chunk",
|
||||
menu_path: None,
|
||||
default_shortcut: None,
|
||||
params: "{ id: buffer id, index: position in git.chunks' unstaged list, token }; replaces the chunk's buffer lines with the index's (an ordinary, unsaved buffer edit); returns { id, version, dirty }; failed when the buffer, the index or HEAD changed since git.chunks",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn enabled(&self, state: &State) -> bool {
|
||||
state.has_project()
|
||||
}
|
||||
|
||||
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
|
||||
let command = self.spec().id;
|
||||
let p: ActionParams = parse(command, params)?;
|
||||
if p.token.len() > MAX_TOKEN {
|
||||
return Err(EngineError::invalid_params(command, "token is too long"));
|
||||
}
|
||||
let (path, text, version) = buffer_of(state, command, p.id)?;
|
||||
let (index, token) = (p.index, p.token);
|
||||
match self.0 {
|
||||
Kind::Stage => start_with(
|
||||
state,
|
||||
command,
|
||||
true,
|
||||
Box::new(move |repo| {
|
||||
repo.stage_chunk(&path, &text, index, &token)
|
||||
.map(|()| json!({}))
|
||||
}),
|
||||
),
|
||||
Kind::Unstage => start_with(
|
||||
state,
|
||||
command,
|
||||
true,
|
||||
Box::new(move |repo| {
|
||||
repo.unstage_chunk(&path, &text, index, &token)
|
||||
.map(|()| json!({}))
|
||||
}),
|
||||
),
|
||||
Kind::Revert => {
|
||||
let id = p.id;
|
||||
start_then(
|
||||
state,
|
||||
command,
|
||||
false,
|
||||
Box::new(move |repo| {
|
||||
let edit = repo.revert_chunk(&path, &text, index, &token)?;
|
||||
Ok(json!({
|
||||
"from": edit.range.start,
|
||||
"to": edit.range.end,
|
||||
"insert": edit.insert,
|
||||
}))
|
||||
}),
|
||||
Box::new(move |state, value| apply_revert(state, command, id, version, &value)),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies a revert edit (byte offsets of the buffer at `version`) through
|
||||
/// `buffer.edit`.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`EngineError::Failed`] when the buffer is gone or changed since, or
|
||||
/// the edit does not fit it.
|
||||
fn apply_revert(
|
||||
state: &mut State,
|
||||
command: &str,
|
||||
id: BufferId,
|
||||
version: u64,
|
||||
value: &Value,
|
||||
) -> Result<Value, EngineError> {
|
||||
let stale = || {
|
||||
EngineError::Failed(
|
||||
"the file or the index changed since the chunk was shown; look at it again".into(),
|
||||
)
|
||||
};
|
||||
let open = state.buffers.get(id).ok_or_else(stale)?;
|
||||
if open.version != version {
|
||||
return Err(stale());
|
||||
}
|
||||
let offset = |key: &str| -> Result<usize, EngineError> {
|
||||
let bytes = value
|
||||
.get(key)
|
||||
.and_then(Value::as_u64)
|
||||
.and_then(|v| usize::try_from(v).ok())
|
||||
.ok_or_else(|| EngineError::Internal(format!("{command}: no {key} offset")))?;
|
||||
open.buffer
|
||||
.offset_to_utf16(bytes)
|
||||
.map_err(|e| EngineError::Failed(format!("{command}: {e}")))
|
||||
};
|
||||
let (from, to) = (offset("from")?, offset("to")?);
|
||||
let insert = value.get("insert").and_then(Value::as_str).unwrap_or("");
|
||||
let out = super::buffer::Edit.run(
|
||||
state,
|
||||
json!({"id": id, "baseVersion": version, "edits": [{"from": from, "to": to, "insert": insert}]}),
|
||||
)?;
|
||||
Ok(out.value)
|
||||
}
|
||||
|
||||
/// The ids of the commands this module registers, checked against the
|
||||
/// registry by the engine's listing test. Add a new command's id here.
|
||||
#[cfg(test)]
|
||||
pub(crate) const COMMAND_IDS: &[&str] = &[
|
||||
"git.chunks",
|
||||
"git.revertChunk",
|
||||
"git.stageChunk",
|
||||
"git.unstageChunk",
|
||||
];
|
||||
|
|
@ -34,8 +34,6 @@ use lutra_text::Buffer;
|
|||
use lutra_vcs::{Git, Repo, Rev};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use similar::DiffOp;
|
||||
use similar::algorithms::{Capture, Replace, myers};
|
||||
|
||||
use super::params::parse;
|
||||
use crate::buffers::BufferId;
|
||||
|
|
@ -185,6 +183,7 @@ pub struct LineRange {
|
|||
|
||||
/// Splits `text` into lines at `\n`, `\r\n` and a lone `\r`, without an
|
||||
/// empty line after a final break.
|
||||
#[cfg(test)]
|
||||
fn split_lines(text: &str) -> Vec<&str> {
|
||||
let mut lines = Vec::new();
|
||||
let mut rest = text;
|
||||
|
|
@ -211,40 +210,21 @@ fn split_lines(text: &str) -> Vec<&str> {
|
|||
/// The changed ranges of `new` against `old`, at most [`MAX_RANGES`];
|
||||
/// the diff gives up refining after `deadline`.
|
||||
///
|
||||
/// Myers' diff with adjacent deletes and inserts merged into replacements.
|
||||
/// `similar`'s `Compact` step is left out on purpose: in 2.7.0 it can move
|
||||
/// a delete to a wrong position in the new text (found by the property
|
||||
/// test below).
|
||||
/// The hunks come from [`lutra_vcs::chunk::line_hunks`], the diff the
|
||||
/// chunk commands use too, so markers and chunks line up.
|
||||
pub fn line_changes(old: &str, new: &str, deadline: Option<Instant>) -> Vec<LineRange> {
|
||||
let old = split_lines(old);
|
||||
let new = split_lines(new);
|
||||
let mut hook = Replace::new(Capture::new());
|
||||
if myers::diff_deadline(&mut hook, &old, 0..old.len(), &new, 0..new.len(), deadline).is_err() {
|
||||
return Vec::new();
|
||||
}
|
||||
let ops = hook.into_inner().into_ops();
|
||||
ops.iter()
|
||||
.filter_map(|op| match *op {
|
||||
DiffOp::Equal { .. } => None,
|
||||
DiffOp::Insert {
|
||||
new_index, new_len, ..
|
||||
} => Some(LineRange {
|
||||
kind: ChangeKind::Added,
|
||||
start_line: new_index,
|
||||
end_line: new_index + new_len,
|
||||
}),
|
||||
DiffOp::Delete { new_index, .. } => Some(LineRange {
|
||||
kind: ChangeKind::Deleted,
|
||||
start_line: new_index,
|
||||
end_line: new_index,
|
||||
}),
|
||||
DiffOp::Replace {
|
||||
new_index, new_len, ..
|
||||
} => Some(LineRange {
|
||||
kind: ChangeKind::Modified,
|
||||
start_line: new_index,
|
||||
end_line: new_index + new_len,
|
||||
}),
|
||||
lutra_vcs::chunk::line_hunks(old, new, deadline)
|
||||
.into_iter()
|
||||
.map(|hunk| LineRange {
|
||||
kind: if hunk.old.is_empty() {
|
||||
ChangeKind::Added
|
||||
} else if hunk.new.is_empty() {
|
||||
ChangeKind::Deleted
|
||||
} else {
|
||||
ChangeKind::Modified
|
||||
},
|
||||
start_line: hunk.new.start,
|
||||
end_line: hunk.new.end,
|
||||
})
|
||||
.take(MAX_RANGES)
|
||||
.collect()
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ mod buffer;
|
|||
mod file;
|
||||
pub mod git;
|
||||
pub mod git_blame;
|
||||
pub mod git_chunks;
|
||||
pub mod git_ignore;
|
||||
pub mod git_lines;
|
||||
pub mod git_log;
|
||||
|
|
@ -79,6 +80,7 @@ pub fn register_builtins(registry: &mut Registry) -> Result<(), EngineError> {
|
|||
git_remote::register(registry)?;
|
||||
git_merge::register(registry)?;
|
||||
git_stash::register(registry)?;
|
||||
git_chunks::register(registry)?;
|
||||
git_ignore::register(registry)?;
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -93,6 +95,7 @@ pub(crate) const BUILTIN_COMMAND_IDS: &[&[&str]] = &[
|
|||
file::COMMAND_IDS,
|
||||
git::COMMAND_IDS,
|
||||
git_blame::COMMAND_IDS,
|
||||
git_chunks::COMMAND_IDS,
|
||||
git_ignore::COMMAND_IDS,
|
||||
git_lines::COMMAND_IDS,
|
||||
git_log::COMMAND_IDS,
|
||||
|
|
|
|||
228
crates/engine/tests/git_chunks.rs
Normal file
228
crates/engine/tests/git_chunks.rs
Normal file
|
|
@ -0,0 +1,228 @@
|
|||
//! Chunk commands (C8 C3) through the engine against real temp
|
||||
//! repositories: `git.chunks` of an edited, unsaved buffer, staging and
|
||||
//! unstaging one chunk (with `gitChanged`), reverting one as an unsaved
|
||||
//! buffer edit, and the refusal of a stale token. Skips with a message
|
||||
//! when git is not installed.
|
||||
|
||||
#![allow(
|
||||
clippy::unwrap_used,
|
||||
clippy::expect_used,
|
||||
clippy::panic,
|
||||
clippy::indexing_slicing
|
||||
)]
|
||||
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use lutra_engine::{Engine, EngineError, Event, run_waiting};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// Whether git is installed; prints why a test is skipped.
|
||||
fn have_git() -> bool {
|
||||
let ok = Command::new("git")
|
||||
.arg("--version")
|
||||
.output()
|
||||
.is_ok_and(|o| o.status.success());
|
||||
if !ok {
|
||||
eprintln!("skipped: git is not installed");
|
||||
}
|
||||
ok
|
||||
}
|
||||
|
||||
/// Runs git for test setup and returns its output.
|
||||
fn git(dir: &Path, args: &[&str]) -> String {
|
||||
let out = Command::new("git")
|
||||
.args(args)
|
||||
.current_dir(dir)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
out.status.success(),
|
||||
"git {args:?}: {}",
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
String::from_utf8(out.stdout).unwrap()
|
||||
}
|
||||
|
||||
/// A repository with `a.php` committed as `text`.
|
||||
fn repo(dir: &Path, text: &str) {
|
||||
git(dir, &["init", "-q", "-b", "main"]);
|
||||
for (key, value) in [
|
||||
("user.name", "Lutra Test"),
|
||||
("user.email", "test@lutra.invalid"),
|
||||
("commit.gpgsign", "false"),
|
||||
("core.autocrlf", "false"),
|
||||
("core.hooksPath", ".git/hooks"),
|
||||
] {
|
||||
git(dir, &["config", key, value]);
|
||||
}
|
||||
std::fs::write(dir.join("a.php"), text).unwrap();
|
||||
git(dir, &["add", "-A"]);
|
||||
git(dir, &["commit", "-q", "-m", "base"]);
|
||||
}
|
||||
|
||||
/// An engine behind a lock, like a host, recording every event.
|
||||
struct Host {
|
||||
/// The engine.
|
||||
engine: Mutex<Engine>,
|
||||
/// Events published so far.
|
||||
events: Mutex<Vec<Event>>,
|
||||
}
|
||||
|
||||
impl Host {
|
||||
/// An engine with `root` open as the project.
|
||||
fn open(root: &Path) -> Self {
|
||||
let host = Self {
|
||||
engine: Mutex::new(Engine::new().unwrap()),
|
||||
events: Mutex::new(Vec::new()),
|
||||
};
|
||||
host.run("project.open", json!({"path": root})).unwrap();
|
||||
host
|
||||
}
|
||||
|
||||
/// Runs a command the way hosts do, waiting without the lock.
|
||||
fn run(&self, command: &str, params: Value) -> Result<Value, EngineError> {
|
||||
run_waiting(
|
||||
|| self.engine.lock().unwrap(),
|
||||
command,
|
||||
params,
|
||||
|events| self.events.lock().unwrap().extend_from_slice(events),
|
||||
)
|
||||
.map(|o| o.value)
|
||||
}
|
||||
|
||||
/// Takes the number of `gitChanged` events seen so far.
|
||||
fn git_changes(&self) -> usize {
|
||||
let mut events = self.events.lock().unwrap();
|
||||
let count = events
|
||||
.iter()
|
||||
.filter(|e| matches!(e, Event::GitChanged(_)))
|
||||
.count();
|
||||
events.clear();
|
||||
count
|
||||
}
|
||||
|
||||
/// Replaces the whole text of buffer `id`.
|
||||
fn set_text(&self, id: u64, text: &str) {
|
||||
let current = self.run("buffer.get", json!({"id": id})).unwrap();
|
||||
let len = current["text"].as_str().unwrap().encode_utf16().count();
|
||||
self.run(
|
||||
"buffer.edit",
|
||||
json!({
|
||||
"id": id,
|
||||
"baseVersion": current["version"],
|
||||
"edits": [{"from": 0, "to": len, "insert": text}],
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// The text of buffer `id`.
|
||||
fn text(&self, id: u64) -> String {
|
||||
self.run("buffer.get", json!({"id": id})).unwrap()["text"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// Ten numbered lines.
|
||||
const TEN: &str = "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n";
|
||||
|
||||
#[test]
|
||||
fn stages_unstages_and_reverts_chunks_of_an_unsaved_buffer() {
|
||||
if !have_git() {
|
||||
return;
|
||||
}
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
repo(dir.path(), TEN);
|
||||
let host = Host::open(dir.path());
|
||||
let id = host.run("file.open", json!({"path": "a.php"})).unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
host.set_text(id, "1\ntwo\n3\n4\n5\n6\n7\n8\nnine\n10\n");
|
||||
|
||||
let chunks = host.run("git.chunks", json!({"id": id})).unwrap();
|
||||
assert_eq!(chunks["unstaged"].as_array().unwrap().len(), 2);
|
||||
assert_eq!(
|
||||
chunks["unstaged"][1],
|
||||
json!({
|
||||
"kind": "modified", "startLine": 8, "endLine": 9,
|
||||
"oldStart": 8, "oldEnd": 9, "newStart": 8, "newEnd": 9,
|
||||
"removed": ["9"], "added": ["nine"], "truncated": false,
|
||||
})
|
||||
);
|
||||
let token = chunks["token"].clone();
|
||||
|
||||
host.git_changes();
|
||||
host.run(
|
||||
"git.stageChunk",
|
||||
json!({"id": id, "index": 1, "token": token}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(host.git_changes(), 1);
|
||||
assert_eq!(
|
||||
git(dir.path(), &["show", ":0:a.php"]),
|
||||
"1\n2\n3\n4\n5\n6\n7\n8\nnine\n10\n"
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(dir.path().join("a.php")).unwrap(),
|
||||
TEN
|
||||
);
|
||||
|
||||
let stale = host.run(
|
||||
"git.stageChunk",
|
||||
json!({"id": id, "index": 0, "token": token}),
|
||||
);
|
||||
assert!(
|
||||
matches!(&stale, Err(EngineError::Failed(m)) if m.contains("changed since")),
|
||||
"{stale:?}"
|
||||
);
|
||||
|
||||
let chunks = host.run("git.chunks", json!({"id": id})).unwrap();
|
||||
assert_eq!(chunks["staged"][0]["startLine"], 8);
|
||||
let token = chunks["token"].clone();
|
||||
let reverted = host
|
||||
.run(
|
||||
"git.revertChunk",
|
||||
json!({"id": id, "index": 0, "token": token}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(reverted["dirty"], true);
|
||||
assert_eq!(host.text(id), "1\n2\n3\n4\n5\n6\n7\n8\nnine\n10\n");
|
||||
|
||||
let chunks = host.run("git.chunks", json!({"id": id})).unwrap();
|
||||
assert!(chunks["unstaged"].as_array().unwrap().is_empty());
|
||||
host.run(
|
||||
"git.unstageChunk",
|
||||
json!({"id": id, "index": 0, "token": chunks["token"]}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(git(dir.path(), &["show", ":0:a.php"]), TEN);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_unknown_buffers_and_bad_params() {
|
||||
if !have_git() {
|
||||
return;
|
||||
}
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
repo(dir.path(), TEN);
|
||||
let host = Host::open(dir.path());
|
||||
assert!(matches!(
|
||||
host.run("git.chunks", json!({"id": 999})),
|
||||
Err(EngineError::Failed(_))
|
||||
));
|
||||
assert!(matches!(
|
||||
host.run("git.stageChunk", json!({"id": 1})),
|
||||
Err(EngineError::InvalidParams { .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
host.run(
|
||||
"git.stageChunk",
|
||||
json!({"id": 1, "index": 0, "token": "x".repeat(65)})
|
||||
),
|
||||
Err(EngineError::InvalidParams { .. })
|
||||
));
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue