- 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>
288 lines
10 KiB
Rust
288 lines
10 KiB
Rust
//! 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",
|
|
];
|