PM: merge C3 chunk staging, unstaging and revert
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
30de747ad6
28 changed files with 3159 additions and 101 deletions
2
Cargo.lock
generated
2
Cargo.lock
generated
|
|
@ -2643,7 +2643,6 @@ dependencies = [
|
|||
"proptest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"similar",
|
||||
"tempfile",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
|
@ -2756,6 +2755,7 @@ version = "0.1.0-alpha"
|
|||
dependencies = [
|
||||
"lutra-proc",
|
||||
"proptest",
|
||||
"similar",
|
||||
"tempfile",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
|
|
|||
|
|
@ -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 { .. })
|
||||
));
|
||||
}
|
||||
|
|
@ -13,6 +13,7 @@ layer = 3
|
|||
|
||||
[dependencies]
|
||||
lutra-proc.workspace = true
|
||||
similar = { version = "2.7.0", default-features = false }
|
||||
thiserror = "2.0.21"
|
||||
|
||||
[lints]
|
||||
|
|
|
|||
906
crates/vcs/src/chunk.rs
Normal file
906
crates/vcs/src/chunk.rs
Normal file
|
|
@ -0,0 +1,906 @@
|
|||
//! Chunk staging (C8 C3): the changed chunks of one file, and staging,
|
||||
//! unstaging or reverting a single one.
|
||||
//!
|
||||
//! **Three texts.** A file has a working text (the caller passes it: the
|
||||
//! editor buffer, which may hold unsaved changes), its version in the
|
||||
//! index (`:0:<path>`) and its version at HEAD (under the old name when
|
||||
//! the index holds a staged rename). *Unstaged* chunks compare the index
|
||||
//! with the working text, *staged* chunks HEAD with the index.
|
||||
//!
|
||||
//! **Lines.** Texts split at `\n`, `\r\n` and a lone `\r`, and lines
|
||||
//! compare without their break, so a CRLF working copy against an LF index
|
||||
//! (`core.autocrlf`) shows no change, and neither does a missing final
|
||||
//! break alone. A UTF-8 byte order mark of a stored blob does not count
|
||||
//! either. The diff is Myers' (`similar`) with adjacent deletes and inserts
|
||||
//! merged, exactly as the gutter's `git.lineChanges`, so chunks and
|
||||
//! markers line up.
|
||||
//!
|
||||
//! **Staging and unstaging** build a minimal patch against the index blob
|
||||
//! as stored (its own line breaks, BOM and final break) that replaces the
|
||||
//! chunk's lines, with up to [`CONTEXT`] lines of context, and run
|
||||
//! `git apply --cached` with it. Unstaging builds the patch that puts
|
||||
//! HEAD's lines back into the index (the same as `git apply --cached
|
||||
//! --reverse` of the staged chunk). New lines take the line break the
|
||||
//! target already uses; the final break follows the source when the chunk
|
||||
//! reaches the end of both texts. git checks the context and refuses a
|
||||
//! patch that no longer fits.
|
||||
//!
|
||||
//! **Reverting** returns the byte edit that puts the index's lines back
|
||||
//! into the working text; the engine applies it to the editor buffer, so
|
||||
//! it is undoable there.
|
||||
//!
|
||||
//! **Stale chunks.** [`FileChunks::token`] hashes the working text, the
|
||||
//! index blob, the HEAD blob and HEAD's path. Every action takes the token
|
||||
//! the chunks were shown with and refuses with [`VcsError::Stale`] when
|
||||
//! the texts changed since.
|
||||
//!
|
||||
//! **Refused:** binary and too large files, files without an index entry
|
||||
//! (untracked, conflicted), and patches over lines broken by a lone `\r`.
|
||||
|
||||
use std::ops::Range;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use similar::DiffOp;
|
||||
use similar::algorithms::{Capture, Replace, myers};
|
||||
|
||||
use crate::repo::{BINARY_PROBE, Object, SMALL_CAP};
|
||||
use crate::runner::Call;
|
||||
use crate::{Repo, VcsError};
|
||||
|
||||
/// Lines of context around a chunk in the patches.
|
||||
pub const CONTEXT: usize = 3;
|
||||
|
||||
/// Most chunks listed per side.
|
||||
pub const MAX_CHUNKS: usize = 10_000;
|
||||
|
||||
/// Most removed and added lines each chunk carries for display.
|
||||
pub const MAX_SHOWN_LINES: usize = 500;
|
||||
|
||||
/// Longest the line diff may take before it settles for a coarser result.
|
||||
const DIFF_DEADLINE: Duration = Duration::from_secs(1);
|
||||
|
||||
/// The byte order mark git keeps in a stored blob.
|
||||
const BOM: &str = "\u{feff}";
|
||||
|
||||
/// A changed range: lines `old` of one text are replaced by lines `new` of
|
||||
/// the other (0-based, the end exclusive; an empty range is an insertion
|
||||
/// or deletion point).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Hunk {
|
||||
/// Lines of the older text.
|
||||
pub old: Range<usize>,
|
||||
/// Lines of the newer text.
|
||||
pub new: Range<usize>,
|
||||
}
|
||||
|
||||
/// One chunk as the actions and the UI see it.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Chunk {
|
||||
/// Lines of the older side (the index for unstaged chunks, HEAD for
|
||||
/// staged ones).
|
||||
pub old: Range<usize>,
|
||||
/// Lines of the newer side (the working text, or the index).
|
||||
pub new: Range<usize>,
|
||||
/// Lines of the working text the chunk covers: `new` for unstaged
|
||||
/// chunks; for staged ones the index lines mapped through the unstaged
|
||||
/// changes (empty where the lines were removed or rewritten since).
|
||||
pub lines: Range<usize>,
|
||||
/// The removed lines without breaks, at most [`MAX_SHOWN_LINES`].
|
||||
pub removed: Vec<String>,
|
||||
/// The added lines without breaks, at most [`MAX_SHOWN_LINES`].
|
||||
pub added: Vec<String>,
|
||||
/// Whether `removed` or `added` was cut.
|
||||
pub truncated: bool,
|
||||
}
|
||||
|
||||
/// The chunks of one file.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct FileChunks {
|
||||
/// Identifies the texts the chunks were computed from; actions refuse
|
||||
/// a different one.
|
||||
pub token: String,
|
||||
/// Index → working text, in line order.
|
||||
pub unstaged: Vec<Chunk>,
|
||||
/// HEAD → index, in line order.
|
||||
pub staged: Vec<Chunk>,
|
||||
/// The file's path at HEAD (project-relative) when the index holds it
|
||||
/// as a rename; `None` otherwise.
|
||||
pub head_path: Option<String>,
|
||||
}
|
||||
|
||||
/// A text edit: replace bytes `range` of the working text with `insert`.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct TextEdit {
|
||||
/// Byte range in the working text, on UTF-8 boundaries.
|
||||
pub range: Range<usize>,
|
||||
/// The replacement.
|
||||
pub insert: String,
|
||||
}
|
||||
|
||||
/// Splits `text` into lines that keep their break (`\n`, `\r\n` or a lone
|
||||
/// `\r`); no empty line after a final break.
|
||||
pub fn split_lines(text: &str) -> Vec<&str> {
|
||||
let mut lines = Vec::new();
|
||||
let mut rest = text;
|
||||
while !rest.is_empty() {
|
||||
let end = match rest.find(['\n', '\r']) {
|
||||
Some(at) if rest.get(at..at + 2) == Some("\r\n") => at + 2,
|
||||
Some(at) => at + 1,
|
||||
None => rest.len(),
|
||||
};
|
||||
lines.push(rest.get(..end).unwrap_or(rest));
|
||||
rest = rest.get(end..).unwrap_or_default();
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
/// A line without its break.
|
||||
pub fn content(line: &str) -> &str {
|
||||
line.strip_suffix("\r\n")
|
||||
.or_else(|| line.strip_suffix('\n'))
|
||||
.or_else(|| line.strip_suffix('\r'))
|
||||
.unwrap_or(line)
|
||||
}
|
||||
|
||||
/// Whether a line ends with a break.
|
||||
fn terminated(line: &str) -> bool {
|
||||
line.ends_with(['\n', '\r'])
|
||||
}
|
||||
|
||||
/// The changed ranges between two texts, comparing lines without their
|
||||
/// breaks; the diff gives up refining after `deadline` (an empty list
|
||||
/// when it cannot finish at all).
|
||||
///
|
||||
/// `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.
|
||||
pub fn line_hunks(old: &str, new: &str, deadline: Option<Instant>) -> Vec<Hunk> {
|
||||
let old: Vec<&str> = split_lines(old).into_iter().map(content).collect();
|
||||
let new: Vec<&str> = split_lines(new).into_iter().map(content).collect();
|
||||
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();
|
||||
}
|
||||
hook.into_inner()
|
||||
.into_ops()
|
||||
.iter()
|
||||
.filter_map(|op| match *op {
|
||||
DiffOp::Equal { .. } => None,
|
||||
DiffOp::Insert {
|
||||
old_index,
|
||||
new_index,
|
||||
new_len,
|
||||
} => Some(Hunk {
|
||||
old: old_index..old_index,
|
||||
new: new_index..new_index + new_len,
|
||||
}),
|
||||
DiffOp::Delete {
|
||||
old_index,
|
||||
old_len,
|
||||
new_index,
|
||||
} => Some(Hunk {
|
||||
old: old_index..old_index + old_len,
|
||||
new: new_index..new_index,
|
||||
}),
|
||||
DiffOp::Replace {
|
||||
old_index,
|
||||
old_len,
|
||||
new_index,
|
||||
new_len,
|
||||
} => Some(Hunk {
|
||||
old: old_index..old_index + old_len,
|
||||
new: new_index..new_index + new_len,
|
||||
}),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Maps a line boundary of the older text of `hunks` into the newer one.
|
||||
///
|
||||
/// # Parameters
|
||||
/// - `hunks`: the changes, in order.
|
||||
/// - `line`: the boundary (a line number, or the line count).
|
||||
/// - `end`: inside a changed range, map to its end rather than its start.
|
||||
fn map_line(hunks: &[Hunk], line: usize, end: bool) -> usize {
|
||||
let mut at = line;
|
||||
for hunk in hunks {
|
||||
if line <= hunk.old.start {
|
||||
break;
|
||||
}
|
||||
if line < hunk.old.end {
|
||||
return if end { hunk.new.end } else { hunk.new.start };
|
||||
}
|
||||
at = at
|
||||
.saturating_sub(hunk.old.len())
|
||||
.saturating_add(hunk.new.len());
|
||||
}
|
||||
at
|
||||
}
|
||||
|
||||
/// The first line break of `text`, if any.
|
||||
fn eol_of(text: &str) -> Option<&'static str> {
|
||||
let at = text.find(['\n', '\r'])?;
|
||||
Some(match text.get(at..at + 2) {
|
||||
Some("\r\n") => "\r\n",
|
||||
_ if text.get(at..=at) == Some("\r") => "\r",
|
||||
_ => "\n",
|
||||
})
|
||||
}
|
||||
|
||||
/// FNV-1a over the parts, each followed by a separator byte.
|
||||
fn token(parts: &[&[u8]]) -> String {
|
||||
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
|
||||
for part in parts {
|
||||
for byte in part.iter().chain(std::iter::once(&0xff)) {
|
||||
hash ^= u64::from(*byte);
|
||||
hash = hash.wrapping_mul(0x0100_0000_01b3);
|
||||
}
|
||||
}
|
||||
format!("{hash:016x}")
|
||||
}
|
||||
|
||||
/// Shown lines of `lines` in `range`, capped; the flag says whether they
|
||||
/// were cut.
|
||||
fn shown(lines: &[&str], range: &Range<usize>) -> (Vec<String>, bool) {
|
||||
let all = lines.get(range.clone()).unwrap_or_default();
|
||||
let out = all
|
||||
.iter()
|
||||
.take(MAX_SHOWN_LINES)
|
||||
.map(|l| content(l).to_string())
|
||||
.collect();
|
||||
(out, all.len() > MAX_SHOWN_LINES)
|
||||
}
|
||||
|
||||
/// The lines that replace a target range: the source's lines in `range`
|
||||
/// with the target's line break `eol`; the source's last line keeps having
|
||||
/// no break when the target range reaches the end of the target.
|
||||
fn replacement(source: &[&str], range: &Range<usize>, at_end: bool, eol: &str) -> Vec<String> {
|
||||
let last = source.len().checked_sub(1);
|
||||
source
|
||||
.get(range.clone())
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, line)| {
|
||||
if at_end && Some(range.start + i) == last && !terminated(line) {
|
||||
line.to_string()
|
||||
} else {
|
||||
format!("{}{eol}", content(line))
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Widens a change so its patch stays valid:
|
||||
/// - an insertion after a last target line without a break takes that
|
||||
/// line along (it gains the break);
|
||||
/// - a deletion of the first lines of a target with a BOM takes the next
|
||||
/// line along (it carries the BOM on).
|
||||
///
|
||||
/// # Parameters
|
||||
/// - `target`, `source`: the lines of the text that changes and of the
|
||||
/// text whose lines it takes.
|
||||
/// - `hunk`: `old` lines of the target, `new` lines of the source.
|
||||
/// - `bom`: whether the target's first line starts with a BOM.
|
||||
fn widen(target: &[&str], source: &[&str], mut hunk: Hunk, bom: bool) -> Hunk {
|
||||
let last_open = target.last().is_some_and(|l| !terminated(l));
|
||||
if hunk.old.start == target.len() && last_open && hunk.old.start > 0 && hunk.new.start > 0 {
|
||||
hunk.old.start -= 1;
|
||||
hunk.new.start -= 1;
|
||||
}
|
||||
if bom
|
||||
&& hunk.old.start == 0
|
||||
&& hunk.new.is_empty()
|
||||
&& hunk.old.end < target.len()
|
||||
&& hunk.new.end < source.len()
|
||||
{
|
||||
hunk.old.end += 1;
|
||||
hunk.new.end += 1;
|
||||
}
|
||||
hunk
|
||||
}
|
||||
|
||||
/// The replacement for `hunk.old` of `target` from `hunk.new` of `source`,
|
||||
/// with the target's break (else the source's, else `\n`) and the BOM kept
|
||||
/// on the first line.
|
||||
fn replacement_for(target: &[&str], source: &[&str], hunk: &Hunk, bom: bool) -> Vec<String> {
|
||||
let target_text: String = target.concat();
|
||||
let source_text: String = source.concat();
|
||||
let eol = eol_of(&target_text)
|
||||
.or_else(|| eol_of(&source_text))
|
||||
.unwrap_or("\n");
|
||||
let at_end = hunk.old.end == target.len();
|
||||
let mut lines = replacement(source, &hunk.new, at_end, eol);
|
||||
if bom
|
||||
&& hunk.old.start == 0
|
||||
&& let Some(first) = lines.first_mut()
|
||||
{
|
||||
first.insert_str(0, BOM);
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
/// Whether a path needs git's C-style quoting in a patch header.
|
||||
fn needs_quotes(path: &str) -> bool {
|
||||
path.chars()
|
||||
.any(|c| c.is_control() || c == '"' || c == '\\')
|
||||
}
|
||||
|
||||
/// A patch header name: `a/<path>` or `b/<path>`, quoted like git does
|
||||
/// when it holds control characters, quotes or backslashes.
|
||||
fn header_name(prefix: &str, path: &str) -> String {
|
||||
let name = format!("{prefix}{path}");
|
||||
if !needs_quotes(&name) {
|
||||
return name;
|
||||
}
|
||||
let mut out = String::from("\"");
|
||||
for c in name.chars() {
|
||||
match c {
|
||||
'"' => out.push_str("\\\""),
|
||||
'\\' => out.push_str("\\\\"),
|
||||
'\t' => out.push_str("\\t"),
|
||||
'\n' => out.push_str("\\n"),
|
||||
'\r' => out.push_str("\\r"),
|
||||
c if c.is_control() => {
|
||||
let mut buf = [0u8; 4];
|
||||
for byte in c.encode_utf8(&mut buf).bytes() {
|
||||
out.push_str(&format!("\\{byte:03o}"));
|
||||
}
|
||||
}
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out.push('"');
|
||||
out
|
||||
}
|
||||
|
||||
/// Appends one patch line; a line without a break gets git's marker.
|
||||
fn push_line(out: &mut String, sign: char, line: &str) {
|
||||
out.push(sign);
|
||||
out.push_str(line);
|
||||
if !line.ends_with('\n') {
|
||||
out.push_str("\n\\ No newline at end of file\n");
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds a patch that replaces lines `range` of `target` (a blob as
|
||||
/// stored) with `replacement` (lines with their breaks), with up to
|
||||
/// [`CONTEXT`] lines of context.
|
||||
///
|
||||
/// # Parameters
|
||||
/// - `path`: the root-relative path.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`VcsError::ChunkRefused`] when a line involved ends with a lone `\r`
|
||||
/// (git's patches cannot carry it), or the range is outside the target.
|
||||
pub fn build_patch(
|
||||
path: &str,
|
||||
target: &str,
|
||||
range: Range<usize>,
|
||||
replacement: &[String],
|
||||
) -> Result<String, VcsError> {
|
||||
let lines = split_lines(target);
|
||||
if range.start > range.end || range.end > lines.len() {
|
||||
return Err(VcsError::Stale);
|
||||
}
|
||||
let lone_cr = |l: &str| l.ends_with('\r');
|
||||
if lines.iter().any(|l| lone_cr(l)) || replacement.iter().any(|l| lone_cr(l)) {
|
||||
return Err(VcsError::ChunkRefused(
|
||||
"lines broken by a lone carriage return cannot be staged by chunk".into(),
|
||||
));
|
||||
}
|
||||
let before = range.start.saturating_sub(CONTEXT);
|
||||
let after = range.end.saturating_add(CONTEXT).min(lines.len());
|
||||
let pre = lines.get(before..range.start).unwrap_or_default();
|
||||
let removed = lines.get(range.clone()).unwrap_or_default();
|
||||
let post = lines.get(range.end..after).unwrap_or_default();
|
||||
let old_count = pre.len() + removed.len() + post.len();
|
||||
let new_count = pre.len() + replacement.len() + post.len();
|
||||
let start = |count: usize| if count == 0 { before } else { before + 1 };
|
||||
let mut out = format!(
|
||||
"diff --git {a} {b}\n--- {a}\n+++ {b}\n@@ -{},{old_count} +{},{new_count} @@\n",
|
||||
start(old_count),
|
||||
start(new_count),
|
||||
a = header_name("a/", path),
|
||||
b = header_name("b/", path),
|
||||
);
|
||||
for line in pre {
|
||||
push_line(&mut out, ' ', line);
|
||||
}
|
||||
for line in removed {
|
||||
push_line(&mut out, '-', line);
|
||||
}
|
||||
for line in replacement {
|
||||
push_line(&mut out, '+', line);
|
||||
}
|
||||
for line in post {
|
||||
push_line(&mut out, ' ', line);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The texts of one file and their chunks, read for an action.
|
||||
struct Loaded {
|
||||
/// Root-relative path.
|
||||
path: String,
|
||||
/// The index blob as stored (BOM kept).
|
||||
index: String,
|
||||
/// The index blob without BOM, compared with the other texts.
|
||||
index_view: String,
|
||||
/// The HEAD blob without BOM; empty when missing at HEAD.
|
||||
head_view: String,
|
||||
/// The working text.
|
||||
worktree: String,
|
||||
/// The chunks.
|
||||
chunks: FileChunks,
|
||||
}
|
||||
|
||||
impl Loaded {
|
||||
/// Whether the index blob starts with a BOM.
|
||||
fn bom(&self) -> bool {
|
||||
self.index.starts_with(BOM)
|
||||
}
|
||||
}
|
||||
|
||||
/// Decodes a blob for chunks: UTF-8 with the BOM kept.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`VcsError::ChunkRefused`] for binary or too large blobs.
|
||||
fn blob_text(object: Object, what: &str) -> Result<Option<String>, VcsError> {
|
||||
let binary = || VcsError::ChunkRefused(format!("{what} is binary; stage the whole file"));
|
||||
match object {
|
||||
Object::Missing => Ok(None),
|
||||
Object::NotBlob => Err(binary()),
|
||||
Object::TooLarge => Err(VcsError::ChunkRefused(format!(
|
||||
"{what} is too large for chunks; stage the whole file"
|
||||
))),
|
||||
Object::Blob(bytes) => {
|
||||
let probe = bytes
|
||||
.get(..BINARY_PROBE.min(bytes.len()))
|
||||
.unwrap_or_default();
|
||||
if probe.contains(&0) {
|
||||
return Err(binary());
|
||||
}
|
||||
String::from_utf8(bytes).map(Some).map_err(|_| binary())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Computes the chunks of the three texts.
|
||||
///
|
||||
/// # Parameters
|
||||
/// - `index`, `head`, `worktree`: the texts without BOM.
|
||||
/// - `token`: the token of the texts.
|
||||
/// - `head_path`: the project-relative HEAD path of a rename.
|
||||
pub fn compute(
|
||||
index: &str,
|
||||
head: &str,
|
||||
worktree: &str,
|
||||
token: String,
|
||||
head_path: Option<String>,
|
||||
) -> FileChunks {
|
||||
let deadline = Instant::now().checked_add(DIFF_DEADLINE);
|
||||
let index_lines = split_lines(index);
|
||||
let head_lines = split_lines(head);
|
||||
let work_lines = split_lines(worktree);
|
||||
let unstaged_hunks = line_hunks(index, worktree, deadline);
|
||||
let staged_hunks = line_hunks(head, index, deadline);
|
||||
let chunk = |old: &[&str], new: &[&str], hunk: &Hunk, lines: Range<usize>| {
|
||||
let (removed, cut_removed) = shown(old, &hunk.old);
|
||||
let (added, cut_added) = shown(new, &hunk.new);
|
||||
Chunk {
|
||||
old: hunk.old.clone(),
|
||||
new: hunk.new.clone(),
|
||||
lines,
|
||||
removed,
|
||||
added,
|
||||
truncated: cut_removed || cut_added,
|
||||
}
|
||||
};
|
||||
let unstaged = unstaged_hunks
|
||||
.iter()
|
||||
.take(MAX_CHUNKS)
|
||||
.map(|h| chunk(&index_lines, &work_lines, h, h.new.clone()))
|
||||
.collect();
|
||||
let staged = staged_hunks
|
||||
.iter()
|
||||
.take(MAX_CHUNKS)
|
||||
.map(|h| {
|
||||
let start = map_line(&unstaged_hunks, h.new.start, false);
|
||||
let end = map_line(&unstaged_hunks, h.new.end, true).max(start);
|
||||
chunk(&head_lines, &index_lines, h, start..end)
|
||||
})
|
||||
.collect();
|
||||
FileChunks {
|
||||
token,
|
||||
unstaged,
|
||||
staged,
|
||||
head_path,
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses `git diff --cached --name-status -z -M` and returns the old path
|
||||
/// of the entry renamed to `path`.
|
||||
pub fn rename_source(output: &[u8], path: &str) -> Option<String> {
|
||||
let mut fields = output
|
||||
.split(|b| *b == 0)
|
||||
.map(|f| String::from_utf8_lossy(f).into_owned());
|
||||
while let Some(status) = fields.next() {
|
||||
if status.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if status.starts_with('R') || status.starts_with('C') {
|
||||
let old = fields.next()?;
|
||||
let new = fields.next()?;
|
||||
if status.starts_with('R') && new == path {
|
||||
return Some(old);
|
||||
}
|
||||
} else {
|
||||
fields.next()?;
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
impl Repo {
|
||||
/// The root-relative HEAD path of `path` (the source of a staged
|
||||
/// rename, else `path` itself); `None` before the first commit.
|
||||
fn head_path_of(&self, path: &str) -> Result<Option<String>, VcsError> {
|
||||
if !self.has_head()? {
|
||||
return Ok(None);
|
||||
}
|
||||
let output = self
|
||||
.run(Call::read(
|
||||
self.root(),
|
||||
&[
|
||||
"diff",
|
||||
"--cached",
|
||||
"--name-status",
|
||||
"-z",
|
||||
"-M",
|
||||
"--no-ext-diff",
|
||||
"HEAD",
|
||||
"--",
|
||||
],
|
||||
SMALL_CAP,
|
||||
))?
|
||||
.checked()?;
|
||||
Ok(Some(
|
||||
rename_source(&output.stdout, path).unwrap_or_else(|| path.to_string()),
|
||||
))
|
||||
}
|
||||
|
||||
/// Reads the texts of `path` and computes its chunks.
|
||||
fn load(&self, path: &str, worktree: &str) -> Result<Loaded, VcsError> {
|
||||
let repo_path = self.to_repo_path(path)?;
|
||||
let index = blob_text(
|
||||
self.read_object(&format!(":0:{repo_path}"))?,
|
||||
"the staged version",
|
||||
)?
|
||||
.ok_or_else(|| {
|
||||
VcsError::ChunkRefused(format!(
|
||||
"{path} has no staged version (untracked or conflicted); stage the whole file"
|
||||
))
|
||||
})?;
|
||||
let head_path = self.head_path_of(&repo_path)?;
|
||||
let head = match &head_path {
|
||||
Some(p) => blob_text(self.read_object(&format!("HEAD:{p}"))?, "the HEAD version")?
|
||||
.unwrap_or_default(),
|
||||
None => String::new(),
|
||||
};
|
||||
let renamed = head_path
|
||||
.as_deref()
|
||||
.filter(|p| *p != repo_path)
|
||||
.and_then(|p| self.from_repo_path(p).or_else(|| Some(p.to_string())));
|
||||
let token = token(&[
|
||||
repo_path.as_bytes(),
|
||||
worktree.as_bytes(),
|
||||
index.as_bytes(),
|
||||
head_path.as_deref().unwrap_or_default().as_bytes(),
|
||||
head.as_bytes(),
|
||||
]);
|
||||
let index_view = index.strip_prefix(BOM).unwrap_or(&index).to_string();
|
||||
let head_view = head.strip_prefix(BOM).unwrap_or(&head).to_string();
|
||||
let worktree_view = worktree.strip_prefix(BOM).unwrap_or(worktree);
|
||||
let chunks = compute(&index_view, &head_view, worktree_view, token, renamed);
|
||||
Ok(Loaded {
|
||||
path: repo_path,
|
||||
index,
|
||||
index_view,
|
||||
head_view,
|
||||
worktree: worktree_view.to_string(),
|
||||
chunks,
|
||||
})
|
||||
}
|
||||
|
||||
/// The chunks of `path` against the working text `worktree`.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`VcsError::InvalidPath`], [`VcsError::ChunkRefused`] for binary,
|
||||
/// too large or untracked files, or the runner's errors.
|
||||
pub fn chunks(&self, path: &str, worktree: &str) -> Result<FileChunks, VcsError> {
|
||||
Ok(self.load(path, worktree)?.chunks)
|
||||
}
|
||||
|
||||
/// Loads `path` and checks the token.
|
||||
fn load_checked(&self, path: &str, worktree: &str, token: &str) -> Result<Loaded, VcsError> {
|
||||
let loaded = self.load(path, worktree)?;
|
||||
if loaded.chunks.token != token {
|
||||
return Err(VcsError::Stale);
|
||||
}
|
||||
Ok(loaded)
|
||||
}
|
||||
|
||||
/// Runs `git apply --cached` with `patch`.
|
||||
fn apply_cached(&self, patch: String) -> Result<(), VcsError> {
|
||||
self.run(
|
||||
Call::write(
|
||||
self.root(),
|
||||
&["apply", "--cached", "--whitespace=nowarn", "-"],
|
||||
)
|
||||
.stdin(patch.into_bytes()),
|
||||
)?
|
||||
.checked()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stages unstaged chunk `n` of `path`: the index takes the working
|
||||
/// text's lines of that chunk.
|
||||
///
|
||||
/// # Parameters
|
||||
/// - `worktree`: the working text the chunks were computed from.
|
||||
/// - `n`: the chunk's position in [`FileChunks::unstaged`].
|
||||
/// - `token`: [`FileChunks::token`] as shown.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`VcsError::Stale`] when the texts changed since or there is no such
|
||||
/// chunk; as [`Repo::chunks`]; git's refusal of the patch.
|
||||
pub fn stage_chunk(
|
||||
&self,
|
||||
path: &str,
|
||||
worktree: &str,
|
||||
n: usize,
|
||||
token: &str,
|
||||
) -> Result<(), VcsError> {
|
||||
let _guard = self.lock();
|
||||
let loaded = self.load_checked(path, worktree, token)?;
|
||||
let chunk = loaded.chunks.unstaged.get(n).ok_or(VcsError::Stale)?;
|
||||
let target = split_lines(&loaded.index);
|
||||
let source = split_lines(&loaded.worktree);
|
||||
let hunk = widen(
|
||||
&target,
|
||||
&source,
|
||||
Hunk {
|
||||
old: chunk.old.clone(),
|
||||
new: chunk.new.clone(),
|
||||
},
|
||||
loaded.bom(),
|
||||
);
|
||||
let lines = replacement_for(&target, &source, &hunk, loaded.bom());
|
||||
let patch = build_patch(&loaded.path, &loaded.index, hunk.old, &lines)?;
|
||||
self.apply_cached(patch)
|
||||
}
|
||||
|
||||
/// Unstages staged chunk `n` of `path`: the index takes HEAD's lines of
|
||||
/// that chunk back (for a staged rename, from the old path).
|
||||
///
|
||||
/// # Parameters
|
||||
/// As [`Repo::stage_chunk`], with `n` a position in
|
||||
/// [`FileChunks::staged`].
|
||||
///
|
||||
/// # Errors
|
||||
/// As [`Repo::stage_chunk`].
|
||||
pub fn unstage_chunk(
|
||||
&self,
|
||||
path: &str,
|
||||
worktree: &str,
|
||||
n: usize,
|
||||
token: &str,
|
||||
) -> Result<(), VcsError> {
|
||||
let _guard = self.lock();
|
||||
let loaded = self.load_checked(path, worktree, token)?;
|
||||
let chunk = loaded.chunks.staged.get(n).ok_or(VcsError::Stale)?;
|
||||
let target = split_lines(&loaded.index);
|
||||
let source = split_lines(&loaded.head_view);
|
||||
let hunk = widen(
|
||||
&target,
|
||||
&source,
|
||||
Hunk {
|
||||
old: chunk.new.clone(),
|
||||
new: chunk.old.clone(),
|
||||
},
|
||||
loaded.bom(),
|
||||
);
|
||||
let lines = replacement_for(&target, &source, &hunk, loaded.bom());
|
||||
let patch = build_patch(&loaded.path, &loaded.index, hunk.old, &lines)?;
|
||||
self.apply_cached(patch)
|
||||
}
|
||||
|
||||
/// The edit that reverts unstaged chunk `n` of `path` in the working
|
||||
/// text: its lines become the index's again. Nothing is written; the
|
||||
/// caller applies the edit (the engine, to the editor buffer).
|
||||
///
|
||||
/// # Parameters
|
||||
/// As [`Repo::stage_chunk`].
|
||||
///
|
||||
/// # Returns
|
||||
/// The edit, in bytes of `worktree`.
|
||||
///
|
||||
/// # Errors
|
||||
/// As [`Repo::stage_chunk`], without git's refusal.
|
||||
pub fn revert_chunk(
|
||||
&self,
|
||||
path: &str,
|
||||
worktree: &str,
|
||||
n: usize,
|
||||
token: &str,
|
||||
) -> Result<TextEdit, VcsError> {
|
||||
let loaded = self.load_checked(path, worktree, token)?;
|
||||
let chunk = loaded.chunks.unstaged.get(n).ok_or(VcsError::Stale)?;
|
||||
let offset = worktree.len() - loaded.worktree.len();
|
||||
let target = split_lines(&loaded.worktree);
|
||||
let source = split_lines(&loaded.index_view);
|
||||
let hunk = widen(
|
||||
&target,
|
||||
&source,
|
||||
Hunk {
|
||||
old: chunk.new.clone(),
|
||||
new: chunk.old.clone(),
|
||||
},
|
||||
false,
|
||||
);
|
||||
let lines = replacement_for(&target, &source, &hunk, false);
|
||||
let start: usize = target
|
||||
.get(..hunk.old.start)
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.map(|l| l.len())
|
||||
.sum();
|
||||
let len: usize = target
|
||||
.get(hunk.old.clone())
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.map(|l| l.len())
|
||||
.sum();
|
||||
Ok(TextEdit {
|
||||
range: offset + start..offset + start + len,
|
||||
insert: lines.concat(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn hunk(old: Range<usize>, new: Range<usize>) -> Hunk {
|
||||
Hunk { old, new }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn splits_lines_keeping_their_breaks() {
|
||||
assert_eq!(split_lines(""), Vec::<&str>::new());
|
||||
assert_eq!(split_lines("a"), vec!["a"]);
|
||||
assert_eq!(
|
||||
split_lines("a\r\nb\rc\n\n"),
|
||||
vec!["a\r\n", "b\r", "c\n", "\n"]
|
||||
);
|
||||
assert_eq!(content("a\r\n"), "a");
|
||||
assert_eq!(content("a\r"), "a");
|
||||
assert_eq!(content("a"), "a");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hunks_ignore_line_breaks() {
|
||||
assert_eq!(line_hunks("a\nb\n", "a\r\nb", None), vec![]);
|
||||
assert_eq!(
|
||||
line_hunks("a\nb\nc\n", "a\nB\nc\nd\n", None),
|
||||
vec![hunk(1..2, 1..2), hunk(3..3, 3..4)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_index_lines_through_unstaged_changes() {
|
||||
let hunks = vec![hunk(1..2, 1..4), hunk(5..7, 7..7)];
|
||||
assert_eq!(map_line(&hunks, 0, false), 0);
|
||||
assert_eq!(map_line(&hunks, 1, false), 1);
|
||||
assert_eq!(map_line(&hunks, 2, false), 4);
|
||||
assert_eq!(map_line(&hunks, 3, true), 5);
|
||||
assert_eq!(map_line(&hunks, 6, false), 7);
|
||||
assert_eq!(map_line(&hunks, 6, true), 7);
|
||||
assert_eq!(map_line(&hunks, 9, false), 9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn patches_carry_context_and_missing_final_breaks() {
|
||||
let target = "1\n2\n3\n4\n5\n6\n7\n8";
|
||||
let patch = build_patch("src/a b.php", target, 3..4, &["four\n".into()]).unwrap();
|
||||
assert_eq!(
|
||||
patch,
|
||||
"diff --git a/src/a b.php b/src/a b.php\n--- a/src/a b.php\n+++ b/src/a b.php\n\
|
||||
@@ -1,7 +1,7 @@\n 1\n 2\n 3\n-4\n+four\n 5\n 6\n 7\n"
|
||||
);
|
||||
let patch = build_patch("a", target, 7..8, &["8\n".into(), "9".into()]).unwrap();
|
||||
assert!(
|
||||
patch.ends_with(
|
||||
"@@ -5,4 +5,5 @@\n 5\n 6\n 7\n-8\n\\ No newline at end of file\n+8\n+9\n\\ No newline at end of file\n"
|
||||
),
|
||||
"{patch}"
|
||||
);
|
||||
let patch = build_patch("a", "", 0..0, &["x\n".into()]).unwrap();
|
||||
assert!(patch.ends_with("@@ -0,0 +1,1 @@\n+x\n"), "{patch}");
|
||||
assert!(build_patch("a", "x\r", 0..1, &[]).is_err());
|
||||
assert!(build_patch("a", "x\n", 0..2, &[]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quotes_special_paths_like_git() {
|
||||
assert_eq!(header_name("a/", "plain.php"), "a/plain.php");
|
||||
assert_eq!(header_name("a/", "q\"t\\.php"), "\"a/q\\\"t\\\\.php\"");
|
||||
assert_eq!(header_name("b/", "tab\there"), "\"b/tab\\there\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replacements_take_the_target_break_and_keep_a_missing_final_one() {
|
||||
let target = split_lines("a\r\nb\r\n");
|
||||
let source = split_lines("a\nB\nC");
|
||||
let h = hunk(1..2, 1..3);
|
||||
assert_eq!(
|
||||
replacement_for(&target, &source, &h, false),
|
||||
vec!["B\r\n".to_string(), "C".to_string()]
|
||||
);
|
||||
let target = split_lines("a\nb\nc\n");
|
||||
let h = hunk(1..2, 1..2);
|
||||
assert_eq!(
|
||||
replacement_for(&target, &split_lines("a\nX\nc"), &h, false),
|
||||
vec!["X\n".to_string()]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn widens_appends_after_an_open_last_line_and_bom_deletions() {
|
||||
let target = split_lines("a\nb");
|
||||
let source = split_lines("a\nb\nc\n");
|
||||
assert_eq!(
|
||||
widen(&target, &source, hunk(2..2, 2..3), false),
|
||||
hunk(1..2, 1..3)
|
||||
);
|
||||
let target = split_lines("\u{feff}a\nb\nc\n");
|
||||
let source = split_lines("b\nc\n");
|
||||
assert_eq!(
|
||||
widen(&target, &source, hunk(0..1, 0..0), true),
|
||||
hunk(0..2, 0..1)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_the_source_of_a_staged_rename() {
|
||||
let out = b"M\0x.php\0R087\0old.php\0new.php\0A\0y.php\0";
|
||||
assert_eq!(rename_source(out, "new.php"), Some("old.php".into()));
|
||||
assert_eq!(rename_source(out, "x.php"), None);
|
||||
assert_eq!(rename_source(b"R1\0a", "a"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tokens_differ_with_any_text() {
|
||||
let a = token(&[b"p", b"x", b"y"]);
|
||||
assert_eq!(a, token(&[b"p", b"x", b"y"]));
|
||||
assert_ne!(a, token(&[b"p", b"xy", b""]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn staged_chunks_map_to_working_lines() {
|
||||
let chunks = compute(
|
||||
"a\nB\nc\nd\n",
|
||||
"a\nb\nc\nd\n",
|
||||
"new\na\nB\nc\nd\n",
|
||||
"t".into(),
|
||||
None,
|
||||
);
|
||||
assert_eq!(chunks.unstaged.len(), 1);
|
||||
assert_eq!(chunks.unstaged[0].lines, 0..1);
|
||||
assert_eq!(chunks.staged.len(), 1);
|
||||
assert_eq!(chunks.staged[0].lines, 2..3);
|
||||
assert_eq!(chunks.staged[0].removed, vec!["b".to_string()]);
|
||||
assert_eq!(chunks.staged[0].added, vec!["B".to_string()]);
|
||||
}
|
||||
}
|
||||
|
|
@ -52,6 +52,14 @@ pub enum VcsError {
|
|||
/// A remote URL or clone target from the caller is not valid.
|
||||
#[error("{0}")]
|
||||
InvalidInput(String),
|
||||
/// The file, the index or HEAD changed since the chunk was computed,
|
||||
/// or the chunk no longer exists.
|
||||
#[error("the file or the index changed since the chunk was shown; look at it again")]
|
||||
Stale,
|
||||
/// A chunk action is not possible for this file (binary, too large,
|
||||
/// untracked); the message says why.
|
||||
#[error("{0}")]
|
||||
ChunkRefused(String),
|
||||
}
|
||||
|
||||
impl VcsError {
|
||||
|
|
|
|||
|
|
@ -14,6 +14,8 @@
|
|||
//! editor buffer (`blame.rs`).
|
||||
//! - Ignoring files (C7 A3): literal patterns appended to `.gitignore`
|
||||
//! (`ignore.rs`).
|
||||
//! - Chunks (C8 C3): the changed chunks of a file against the index and
|
||||
//! HEAD; staging, unstaging and reverting one (`chunk.rs`).
|
||||
//! - [`RepoWatch`] notices changes inside `.git` (HEAD, index, refs).
|
||||
//!
|
||||
//! Every call goes through [`runner::run`]: arguments as an array, never a
|
||||
|
|
@ -26,6 +28,7 @@
|
|||
//! own threads, off its lock.
|
||||
|
||||
pub mod blame;
|
||||
pub mod chunk;
|
||||
mod error;
|
||||
mod ignore;
|
||||
pub mod log;
|
||||
|
|
@ -37,6 +40,7 @@ pub mod stash;
|
|||
mod watch;
|
||||
|
||||
pub use blame::{BlameLine, UNCOMMITTED_AUTHOR, is_uncommitted};
|
||||
pub use chunk::{Chunk, FileChunks, TextEdit};
|
||||
pub use error::VcsError;
|
||||
pub use ignore::ignore_pattern;
|
||||
pub use log::{CommitDetails, CommitFile, LOG_LIMIT, LogCommit, LogQuery};
|
||||
|
|
|
|||
|
|
@ -27,7 +27,7 @@ pub const FILE_CAP: usize = 32 * 1024 * 1024;
|
|||
pub(crate) const SMALL_CAP: usize = 16 * 1024 * 1024;
|
||||
|
||||
/// How many leading bytes [`Repo::show`] checks for NUL, as git does.
|
||||
const BINARY_PROBE: usize = 8000;
|
||||
pub(crate) const BINARY_PROBE: usize = 8000;
|
||||
|
||||
/// The installed git, checked to be recent enough.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
|
|
@ -167,6 +167,19 @@ pub struct Contents {
|
|||
pub too_large: bool,
|
||||
}
|
||||
|
||||
/// An object read by [`Repo::read_object`].
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) enum Object {
|
||||
/// It does not exist (or is a tree).
|
||||
Missing,
|
||||
/// It is not a blob (a submodule).
|
||||
NotBlob,
|
||||
/// It is larger than [`FILE_CAP`].
|
||||
TooLarge,
|
||||
/// The blob's bytes as stored.
|
||||
Blob(Vec<u8>),
|
||||
}
|
||||
|
||||
/// A branch.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Branch {
|
||||
|
|
@ -366,7 +379,7 @@ impl Repo {
|
|||
}
|
||||
|
||||
/// Whether HEAD points to a commit (false before the first commit).
|
||||
fn has_head(&self) -> Result<bool, VcsError> {
|
||||
pub(crate) fn has_head(&self) -> Result<bool, VcsError> {
|
||||
let output = self.run(Call::read(
|
||||
&self.root,
|
||||
&["rev-parse", "--verify", "--quiet", "HEAD^{commit}"],
|
||||
|
|
@ -483,42 +496,61 @@ impl Repo {
|
|||
pub fn show(&self, path: &str, rev: Rev) -> Result<Contents, VcsError> {
|
||||
let path = self.to_repo_path(path)?;
|
||||
let object = match rev {
|
||||
Rev::Head => format!("HEAD:{path}\n"),
|
||||
Rev::Index => format!(":0:{path}\n"),
|
||||
Rev::Head => format!("HEAD:{path}"),
|
||||
Rev::Index => format!(":0:{path}"),
|
||||
};
|
||||
Ok(match self.read_object(&object)? {
|
||||
Object::Missing => Contents::default(),
|
||||
Object::NotBlob => Contents {
|
||||
binary: true,
|
||||
..Contents::default()
|
||||
},
|
||||
Object::TooLarge => Contents {
|
||||
too_large: true,
|
||||
..Contents::default()
|
||||
},
|
||||
Object::Blob(bytes) => decode(bytes),
|
||||
})
|
||||
}
|
||||
|
||||
/// Reads an object such as `HEAD:<path>` or `:0:<path>` (a root-relative
|
||||
/// path) as stored.
|
||||
///
|
||||
/// # Errors
|
||||
/// The runner's errors or [`VcsError::BadOutput`].
|
||||
pub(crate) fn read_object(&self, object: &str) -> Result<Object, VcsError> {
|
||||
let output = self
|
||||
.run(
|
||||
Call::read(&self.root, &["cat-file", "--batch-check"], SMALL_CAP)
|
||||
.stdin(object.into_bytes()),
|
||||
Call::read(&self.root, &["cat-file", "--batch-check"], SMALL_CAP).stdin(
|
||||
format!(
|
||||
"{object}
|
||||
"
|
||||
)
|
||||
.into_bytes(),
|
||||
),
|
||||
)?
|
||||
.checked()?;
|
||||
let line = String::from_utf8_lossy(&output.stdout);
|
||||
let fields: Vec<&str> = line.trim_end().rsplitn(3, ' ').collect();
|
||||
let [size, kind, oid] = fields.as_slice() else {
|
||||
return Ok(Contents::default());
|
||||
return Ok(Object::Missing);
|
||||
};
|
||||
if *size == "missing" || *kind == "missing" || *kind == "tree" {
|
||||
return Ok(Contents::default());
|
||||
return Ok(Object::Missing);
|
||||
}
|
||||
if *kind != "blob" {
|
||||
return Ok(Contents {
|
||||
binary: true,
|
||||
..Contents::default()
|
||||
});
|
||||
return Ok(Object::NotBlob);
|
||||
}
|
||||
let size: usize = size
|
||||
.parse()
|
||||
.map_err(|_| VcsError::BadOutput(line.to_string()))?;
|
||||
if size > FILE_CAP {
|
||||
return Ok(Contents {
|
||||
too_large: true,
|
||||
..Contents::default()
|
||||
});
|
||||
return Ok(Object::TooLarge);
|
||||
}
|
||||
let output = self
|
||||
.run(Call::read(&self.root, &["cat-file", "blob", oid], FILE_CAP))?
|
||||
.checked()?;
|
||||
Ok(decode(output.stdout))
|
||||
Ok(Object::Blob(output.stdout))
|
||||
}
|
||||
|
||||
/// Local and remote-tracking branches.
|
||||
|
|
|
|||
402
crates/vcs/tests/chunk.rs
Normal file
402
crates/vcs/tests/chunk.rs
Normal file
|
|
@ -0,0 +1,402 @@
|
|||
//! Chunk staging (C8 C3) against real repositories in temp folders:
|
||||
//! staging, unstaging and reverting single chunks; CRLF files (stored as
|
||||
//! LF through `core.autocrlf`, and stored as CRLF), files without a final
|
||||
//! line break, a byte order mark, a staged rename, the first commit, and
|
||||
//! every refusal (binary, untracked, stale token). Every test 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 lutra_vcs::{FileChunks, Git, Repo, VcsError};
|
||||
|
||||
/// The installed git, or `None` (with a message) when there is none.
|
||||
fn installed() -> Option<Git> {
|
||||
match Git::detect("") {
|
||||
Ok(git) => Some(git),
|
||||
Err(e) => {
|
||||
eprintln!("skipped: no usable git installed ({e})");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs git in `dir` for test setup, asserts it succeeded and returns its
|
||||
/// raw output.
|
||||
fn git_raw(dir: &Path, args: &[&str]) -> String {
|
||||
let out = Command::new("git")
|
||||
.args(args)
|
||||
.current_dir(dir)
|
||||
.env_remove("GIT_DIR")
|
||||
.env_remove("GIT_WORK_TREE")
|
||||
.env_remove("GIT_INDEX_FILE")
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
out.status.success(),
|
||||
"git {args:?}: {}",
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
String::from_utf8(out.stdout).unwrap()
|
||||
}
|
||||
|
||||
/// Runs git for setup.
|
||||
fn git(dir: &Path, args: &[&str]) {
|
||||
git_raw(dir, args);
|
||||
}
|
||||
|
||||
/// A new repository on `main` with a local identity and `autocrlf`.
|
||||
fn init(dir: &Path, autocrlf: &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", autocrlf),
|
||||
("core.safecrlf", "false"),
|
||||
("core.hooksPath", ".git/hooks"),
|
||||
] {
|
||||
git(dir, &["config", key, value]);
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes a file.
|
||||
fn write(dir: &Path, path: &str, text: &[u8]) {
|
||||
std::fs::write(dir.join(path), text).unwrap();
|
||||
}
|
||||
|
||||
/// The index blob of `path`, as stored.
|
||||
fn index(dir: &Path, path: &str) -> String {
|
||||
git_raw(dir, &["cat-file", "blob", &format!(":0:{path}")])
|
||||
}
|
||||
|
||||
/// A repository with `path` committed as `text`, opened.
|
||||
fn committed(g: &Git, dir: &Path, autocrlf: &str, path: &str, text: &str) -> Repo {
|
||||
init(dir, autocrlf);
|
||||
write(dir, path, text.as_bytes());
|
||||
git(dir, &["add", "-A"]);
|
||||
git(dir, &["commit", "-q", "-m", "init"]);
|
||||
g.open(dir).unwrap().expect("a repository")
|
||||
}
|
||||
|
||||
/// Ten numbered lines.
|
||||
const TEN: &str = "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n";
|
||||
|
||||
/// The chunks of `path` for `text`.
|
||||
fn chunks(repo: &Repo, path: &str, text: &str) -> FileChunks {
|
||||
repo.chunks(path, text).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stages_and_unstages_one_of_two_chunks() {
|
||||
let Some(g) = installed() else { return };
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path();
|
||||
let repo = committed(&g, dir, "false", "a.php", TEN);
|
||||
let work = "1\ntwo\n3\n4\n5\n6\n7\n8\nnine\n10\n";
|
||||
write(dir, "a.php", work.as_bytes());
|
||||
|
||||
let before = chunks(&repo, "a.php", work);
|
||||
assert_eq!(before.unstaged.len(), 2);
|
||||
assert!(before.staged.is_empty());
|
||||
assert_eq!(before.unstaged[1].lines, 8..9);
|
||||
assert_eq!(before.unstaged[1].removed, vec!["9".to_string()]);
|
||||
assert_eq!(before.unstaged[1].added, vec!["nine".to_string()]);
|
||||
|
||||
repo.stage_chunk("a.php", work, 1, &before.token).unwrap();
|
||||
assert_eq!(index(dir, "a.php"), "1\n2\n3\n4\n5\n6\n7\n8\nnine\n10\n");
|
||||
let after = chunks(&repo, "a.php", work);
|
||||
assert_eq!(after.unstaged.len(), 1);
|
||||
assert_eq!(after.unstaged[0].lines, 1..2);
|
||||
assert_eq!(after.staged.len(), 1);
|
||||
assert_eq!(after.staged[0].lines, 8..9);
|
||||
|
||||
repo.unstage_chunk("a.php", work, 0, &after.token).unwrap();
|
||||
assert_eq!(index(dir, "a.php"), TEN);
|
||||
assert_eq!(chunks(&repo, "a.php", work).unstaged.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stale_token_or_text_is_refused() {
|
||||
let Some(g) = installed() else { return };
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path();
|
||||
let repo = committed(&g, dir, "false", "a.php", TEN);
|
||||
let work = "1\ntwo\n3\n4\n5\n6\n7\n8\n9\n10\n";
|
||||
let shown = chunks(&repo, "a.php", work);
|
||||
|
||||
let edited = "1\ntwo\n3\n4\n5\n6\n7\n8\n9\nten\n";
|
||||
assert_eq!(
|
||||
repo.stage_chunk("a.php", edited, 0, &shown.token),
|
||||
Err(VcsError::Stale)
|
||||
);
|
||||
assert_eq!(
|
||||
repo.stage_chunk("a.php", work, 5, &shown.token),
|
||||
Err(VcsError::Stale)
|
||||
);
|
||||
|
||||
write(dir, "a.php", b"1\n2\n3\n4\n5\n6\n7\n8\n9\nX\n");
|
||||
git(dir, &["add", "a.php"]);
|
||||
assert_eq!(
|
||||
repo.stage_chunk("a.php", work, 0, &shown.token),
|
||||
Err(VcsError::Stale)
|
||||
);
|
||||
assert_eq!(
|
||||
repo.revert_chunk("a.php", work, 0, &shown.token),
|
||||
Err(VcsError::Stale)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crlf_working_copy_with_an_lf_index_stays_lf() {
|
||||
let Some(g) = installed() else { return };
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path();
|
||||
let repo = committed(&g, dir, "true", "a.php", "a\r\nb\r\nc\r\n");
|
||||
assert_eq!(index(dir, "a.php"), "a\nb\nc\n");
|
||||
let work = "a\r\nB\r\nc\r\nd\r\n";
|
||||
let shown = chunks(&repo, "a.php", work);
|
||||
assert_eq!(shown.unstaged.len(), 2);
|
||||
|
||||
repo.stage_chunk("a.php", work, 0, &shown.token).unwrap();
|
||||
assert_eq!(index(dir, "a.php"), "a\nB\nc\n");
|
||||
let next = chunks(&repo, "a.php", work);
|
||||
repo.stage_chunk("a.php", work, 0, &next.token).unwrap();
|
||||
assert_eq!(index(dir, "a.php"), "a\nB\nc\nd\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crlf_stored_in_the_index_keeps_crlf() {
|
||||
let Some(g) = installed() else { return };
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path();
|
||||
let repo = committed(&g, dir, "false", "a.php", "a\r\nb\r\nc\r\n");
|
||||
let work = "a\nB\nc\n";
|
||||
let shown = chunks(&repo, "a.php", work);
|
||||
assert_eq!(shown.unstaged.len(), 1);
|
||||
repo.stage_chunk("a.php", work, 0, &shown.token).unwrap();
|
||||
assert_eq!(index(dir, "a.php"), "a\r\nB\r\nc\r\n");
|
||||
|
||||
let crlf = "a\r\nB\r\nc\r\n";
|
||||
let after = chunks(&repo, "a.php", crlf);
|
||||
assert!(after.unstaged.is_empty());
|
||||
assert_eq!(after.staged.len(), 1);
|
||||
repo.unstage_chunk("a.php", crlf, 0, &after.token).unwrap();
|
||||
assert_eq!(index(dir, "a.php"), "a\r\nb\r\nc\r\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_without_a_final_line_break() {
|
||||
let Some(g) = installed() else { return };
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path();
|
||||
let repo = committed(&g, dir, "false", "a.php", "a\nb");
|
||||
|
||||
let work = "a\nb\nc\n";
|
||||
let shown = chunks(&repo, "a.php", work);
|
||||
assert_eq!(shown.unstaged.len(), 1);
|
||||
repo.stage_chunk("a.php", work, 0, &shown.token).unwrap();
|
||||
assert_eq!(index(dir, "a.php"), "a\nb\nc\n");
|
||||
|
||||
let work = "a\nX";
|
||||
let shown = chunks(&repo, "a.php", work);
|
||||
assert_eq!(shown.unstaged.len(), 1);
|
||||
repo.stage_chunk("a.php", work, 0, &shown.token).unwrap();
|
||||
assert_eq!(index(dir, "a.php"), "a\nX");
|
||||
|
||||
let after = chunks(&repo, "a.php", work);
|
||||
let edit = repo.revert_chunk("a.php", "a\nY", 0, &chunks(&repo, "a.php", "a\nY").token);
|
||||
assert_eq!(edit.unwrap().insert, "X");
|
||||
repo.unstage_chunk("a.php", work, 0, &after.token).unwrap();
|
||||
assert_eq!(index(dir, "a.php"), "a\nb");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_byte_order_mark_survives_staging() {
|
||||
let Some(g) = installed() else { return };
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path();
|
||||
let repo = committed(&g, dir, "false", "a.php", "\u{feff}a\nb\nc\n");
|
||||
let work = "b\nc\nd\n";
|
||||
let shown = chunks(&repo, "a.php", work);
|
||||
assert_eq!(shown.unstaged.len(), 2);
|
||||
repo.stage_chunk("a.php", work, 0, &shown.token).unwrap();
|
||||
assert_eq!(index(dir, "a.php"), "\u{feff}b\nc\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reverting_returns_the_index_lines_for_the_buffer() {
|
||||
let Some(g) = installed() else { return };
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path();
|
||||
let repo = committed(&g, dir, "true", "a.php", "a\r\nb\r\nc\r\nd\r\n");
|
||||
let work = "a\r\nB\r\nB2\r\nc\r\n";
|
||||
let shown = chunks(&repo, "a.php", work);
|
||||
assert_eq!(shown.unstaged.len(), 2);
|
||||
|
||||
let edit = repo.revert_chunk("a.php", work, 0, &shown.token).unwrap();
|
||||
let mut text = work.to_string();
|
||||
text.replace_range(edit.range.clone(), &edit.insert);
|
||||
assert_eq!(text, "a\r\nb\r\nc\r\n");
|
||||
|
||||
let edit = repo.revert_chunk("a.php", work, 1, &shown.token).unwrap();
|
||||
let mut text = work.to_string();
|
||||
text.replace_range(edit.range, &edit.insert);
|
||||
assert_eq!(text, "a\r\nB\r\nB2\r\nc\r\nd\r\n");
|
||||
assert_eq!(index(dir, "a.php"), "a\nb\nc\nd\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reverting_lines_deleted_after_an_open_last_line() {
|
||||
let Some(g) = installed() else { return };
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path();
|
||||
let repo = committed(&g, dir, "false", "a.php", "a\nb\nc\n");
|
||||
let work = "a\nb";
|
||||
let shown = chunks(&repo, "a.php", work);
|
||||
assert_eq!(shown.unstaged.len(), 1);
|
||||
let edit = repo.revert_chunk("a.php", work, 0, &shown.token).unwrap();
|
||||
let mut text = work.to_string();
|
||||
text.replace_range(edit.range, &edit.insert);
|
||||
assert_eq!(text, "a\nb\nc\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_staged_rename_unstages_against_the_old_path() {
|
||||
let Some(g) = installed() else { return };
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path();
|
||||
let repo = committed(&g, dir, "false", "old.php", TEN);
|
||||
git(dir, &["mv", "old.php", "new.php"]);
|
||||
let work = "1\n2\n3\n4\n5\n6\n7\n8\n9\nten\n";
|
||||
write(dir, "new.php", work.as_bytes());
|
||||
git(dir, &["add", "new.php"]);
|
||||
|
||||
let shown = chunks(&repo, "new.php", work);
|
||||
assert_eq!(shown.head_path.as_deref(), Some("old.php"));
|
||||
assert!(shown.unstaged.is_empty());
|
||||
assert_eq!(shown.staged.len(), 1);
|
||||
assert_eq!(shown.staged[0].lines, 9..10);
|
||||
|
||||
repo.unstage_chunk("new.php", work, 0, &shown.token)
|
||||
.unwrap();
|
||||
assert_eq!(index(dir, "new.php"), TEN);
|
||||
let status = git_raw(dir, &["status", "--porcelain"]);
|
||||
assert!(status.contains("RM old.php -> new.php"), "{status}");
|
||||
|
||||
let after = chunks(&repo, "new.php", work);
|
||||
repo.stage_chunk("new.php", work, 0, &after.token).unwrap();
|
||||
assert_eq!(index(dir, "new.php"), work);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn before_the_first_commit_everything_staged_is_one_chunk() {
|
||||
let Some(g) = installed() else { return };
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path();
|
||||
init(dir, "false");
|
||||
write(dir, "a.php", b"a\nb\n");
|
||||
git(dir, &["add", "a.php"]);
|
||||
let repo = g.open(dir).unwrap().unwrap();
|
||||
let shown = chunks(&repo, "a.php", "a\nb\n");
|
||||
assert_eq!(shown.staged.len(), 1);
|
||||
assert_eq!(shown.staged[0].lines, 0..2);
|
||||
repo.unstage_chunk("a.php", "a\nb\n", 0, &shown.token)
|
||||
.unwrap();
|
||||
assert_eq!(index(dir, "a.php"), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn binary_and_untracked_files_are_refused() {
|
||||
let Some(g) = installed() else { return };
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path();
|
||||
init(dir, "false");
|
||||
write(dir, "bin.dat", b"a\0b\n");
|
||||
git(dir, &["add", "-A"]);
|
||||
git(dir, &["commit", "-q", "-m", "init"]);
|
||||
write(dir, "new.php", b"x\n");
|
||||
let repo = g.open(dir).unwrap().unwrap();
|
||||
assert!(matches!(
|
||||
repo.chunks("bin.dat", "a\n"),
|
||||
Err(VcsError::ChunkRefused(m)) if m.contains("binary")
|
||||
));
|
||||
assert!(matches!(
|
||||
repo.chunks("new.php", "x\n"),
|
||||
Err(VcsError::ChunkRefused(m)) if m.contains("no staged version")
|
||||
));
|
||||
assert!(matches!(
|
||||
repo.chunks("../x", ""),
|
||||
Err(VcsError::InvalidPath(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_with_spaces_and_quotes_stages() {
|
||||
let Some(g) = installed() else { return };
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path();
|
||||
let name = if cfg!(windows) {
|
||||
"a b.php"
|
||||
} else {
|
||||
"a \"b\".php"
|
||||
};
|
||||
let repo = committed(&g, dir, "false", name, TEN);
|
||||
let work = "1\n2\n3\nfour\n5\n6\n7\n8\n9\n10\n";
|
||||
let shown = chunks(&repo, name, work);
|
||||
repo.stage_chunk(name, work, 0, &shown.token).unwrap();
|
||||
assert_eq!(index(dir, name), work);
|
||||
}
|
||||
|
||||
proptest::proptest! {
|
||||
#![proptest_config(proptest::prelude::ProptestConfig::with_cases(6))]
|
||||
|
||||
/// Staging every chunk one by one makes the index equal the working
|
||||
/// text (up to the final break, which no chunk carries alone).
|
||||
#[test]
|
||||
fn staging_every_chunk_reaches_the_working_text(
|
||||
old in proptest::collection::vec("[abc]", 0..8),
|
||||
new in proptest::collection::vec("[abc]", 0..8),
|
||||
old_open in proptest::bool::ANY,
|
||||
new_open in proptest::bool::ANY,
|
||||
) {
|
||||
let Some(g) = installed() else { return Ok(()) };
|
||||
let join = |lines: &[String], open: bool| {
|
||||
let mut text = lines.join("\n");
|
||||
if !open && !lines.is_empty() {
|
||||
text.push('\n');
|
||||
}
|
||||
text
|
||||
};
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path();
|
||||
let repo = committed(&g, dir, "false", "a.txt", &join(&old, old_open));
|
||||
let work = join(&new, new_open);
|
||||
for _ in 0..30 {
|
||||
let shown = chunks(&repo, "a.txt", &work);
|
||||
if shown.unstaged.is_empty() {
|
||||
break;
|
||||
}
|
||||
repo.stage_chunk("a.txt", &work, 0, &shown.token).unwrap();
|
||||
}
|
||||
let staged = index(dir, "a.txt");
|
||||
proptest::prop_assert_eq!(staged.trim_end_matches('\n'), work.trim_end_matches('\n'));
|
||||
for _ in 0..30 {
|
||||
let shown = chunks(&repo, "a.txt", &work);
|
||||
if shown.staged.is_empty() {
|
||||
break;
|
||||
}
|
||||
repo.unstage_chunk("a.txt", &work, 0, &shown.token).unwrap();
|
||||
}
|
||||
let back = index(dir, "a.txt");
|
||||
let original = join(&old, old_open);
|
||||
proptest::prop_assert_eq!(back.trim_end_matches('\n'), original.trim_end_matches('\n'));
|
||||
}
|
||||
}
|
||||
|
|
@ -628,6 +628,19 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
|
|||
- **Look:** both sides use the Lutra editor theme and the file's language; changed lines are tinted with `color-mix` of `--lt-vcs-deleted` (left) and `--lt-vcs-added` (right) into `--lt-editor-bg`, changed words more strongly, a change bar in each gutter, unchanged stretches over 8 lines collapse to a row (3 lines of context). No colour outside the tokens.
|
||||
- **Tests:** `ui/tests/vcs/DiffView.test.ts` (21 Vitest tests against a fake engine: params and `git.show` parsing, EOL normalisation, index and HEAD sides, one tab per side, the palette without a path, bad params and no file as toasts, disabled without a project, edits on the right reaching `buffer.edit`, engine changes reaching the right side, the left side refresh on `gitChanged`, closing with the buffer, binary / too large / git error / deleted / new file, switching between diff and file tabs, next/previous change with wrap-around, the tree context menu by right click and by Shift+F10 with Escape).
|
||||
|
||||
### Chunk staging (C8 C3)
|
||||
|
||||
- **Backend** (`crates/vcs/src/chunk.rs`, through the installed git, D20): `Repo::chunks(path, worktree)` reads the index blob (`:0:<path>`) and the HEAD blob (under the old path of a staged rename, from `git diff --cached --name-status -z -M HEAD`) as stored and diffs them with the caller's working text: *unstaged* chunks index → working text, *staged* chunks HEAD → index, the latter placed on the working-text lines their index lines map to through the unstaged changes. The diff is the one `git.lineChanges` uses (`chunk::line_hunks`: lines split at `\n`, `\r\n` and a lone `\r`, compared without their break, a blob's BOM ignored, Myers with the `Replace` hook and a 1 s deadline), so chunks and markers line up. At most 10,000 chunks per side and 500 shown lines per side of a chunk.
|
||||
- **Token:** FNV-1a over the path, the working text, the index blob, the HEAD path and the HEAD blob. `stage_chunk`, `unstage_chunk` and `revert_chunk (path, worktree, n, token)` recompute everything and refuse with `VcsError::Stale` ("the file or the index changed since the chunk was shown") on another token or a missing chunk. Stage and unstage hold the repository's mutation lock.
|
||||
- **Patches:** stage replaces the chunk's index lines with the working lines; unstage puts HEAD's lines back (the forward patch against the index, equivalent to `git apply --cached --reverse` of the staged chunk). `build_patch` writes a `diff --git` header (paths C-quoted like git when they hold control characters, quotes or backslashes), one hunk with up to 3 context lines from the target blob as stored, and git's "\ No newline at end of file" marker; `git apply --cached --whitespace=nowarn -` applies it, and git's own context check is a second guard. New lines take the target's first line break (else the source's, else `\n`), so a CRLF working copy over an LF (autocrlf) index stays LF and a CRLF blob stays CRLF; the final break follows the source when the chunk reaches the end of both texts. Two widenings keep patches valid: an insertion after a last line without a break takes that line along, and deleting the first lines of a blob with a BOM takes the next line along so the BOM survives. Refused (`VcsError::ChunkRefused`): binary or too large blobs, a path without a stage-0 entry (untracked, conflicted), lines broken by a lone `\r`.
|
||||
- **Revert** returns a byte edit of the working text (its own line break and final break kept); `lutra-vcs` writes nothing.
|
||||
- **Commands** (`crates/engine/src/cmd/git_chunks.rs`, `COMMAND_IDS` in the module, no default shortcuts): `git.chunks {id}` → `{version, token, headPath, unstaged, staged}` with `{kind, startLine, endLine, oldStart, oldEnd, newStart, newEnd, removed, added, truncated}` per chunk; `git.stageChunk`, `git.unstageChunk`, `git.revertChunk {id, index, token}`. All are pending outcomes started through `cmd::git::start_with` / `start_then` (new: a step under the lock after git answered); the working text is the open buffer's text taken under the lock, unsaved changes included. Stage and unstage send `gitChanged`. Revert's step checks that the buffer is still at the version the chunk was computed for and applies the edit through `buffer.edit` (journal, LSP and syntax see it like typing), leaving the buffer dirty.
|
||||
- **Gutter** (`gitGutter.ts`): besides `git.lineChanges`, the plugin reads `git.chunks` when the view shows the state and on every refresh (`gitChanged`), not while typing; lines of staged chunks that no unstaged chunk covers get a hollow marker (`--lt-vcs-modified` border), mapped through edits. A click on any marker opens the chunk popup for that line.
|
||||
- **Popup** (`chunkPopup.ts`, a CodeMirror tooltip at the line): the unstaged chunk at the line (removed and added lines tinted with `--lt-vcs-deleted` / `--lt-vcs-added`, Stage, Revert) and the staged one (Unstage), Previous / Next (caret to the previous or next chunk start, wrapping, scrolled into view) and a close button; Escape, an edit or a click elsewhere in the editor closes it. Actions pass the chunk's position and the token; a refusal shows inside the popup. After Stage or Unstage it re-reads and stays on the line, so a stage can be undone at once. Revert runs inside the buffer sync's `beginUndoableRemote` / `endUndoableRemote(version)`, so the editor's undo takes it back, then closes. `vcs.showChunk` (UI command, Git › Show Changed Chunk, no shortcut) opens it at the caret line of the editor shown last.
|
||||
- **Diff viewer:** its right side is an ordinary editor of the buffer, so the same gutter and popup work there; a hint line under the caption says so. **Changes window:** a partly staged file was already listed in Staged and in Changes; both rows now carry a "partly staged" badge (`ChangeRow.partial`).
|
||||
- **Shortcuts:** none. Lutra's `Alt+Shift+]` / `Alt+Shift+[` stay the diff's next/previous change; the popup has its own Previous / Next buttons.
|
||||
- **Tests:** `chunk.rs` unit tests (splitting, hunks without line breaks, line mapping, patches with context and missing final breaks, quoting, replacements, widening, rename parsing, tokens, staged placement); `crates/vcs/tests/chunk.rs` against real temp repositories (stage and unstage one of two chunks, a stale token and stale texts, CRLF with autocrlf and stored CRLF, no final newline both ways, a BOM, revert edits, a staged rename unstaged against the old path, the first commit, binary and untracked refusals, a path with spaces and quotes, and a property test: staging every chunk reaches the working text, unstaging every chunk returns to HEAD); `crates/engine/tests/git_chunks.rs` (an unsaved buffer staged, a stale token refused, revert as a dirty buffer edit, unstage, `gitChanged`, bad params); Vitest `ui/tests/editor/chunkPopup.test.ts` (11: parsing, coverage, previous/next, staged markers on show and refresh only, opening from a marker click, stage and unstage with the token, revert in an undo window, refusals, unreadable chunks, Next, Escape and closing on an edit), plus `gitGutter.test.ts` and the partial flag in `ChangesToolWindow.test.ts`.
|
||||
|
||||
### History (M4.6)
|
||||
|
||||
- **Backend (`crates/vcs/src/log.rs`, appended to `Repo`):**
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Gaps
|
||||
|
||||
> **Status:** M0 closed G1; G2 under way (text buffer, engine buffers, tabs and editor in the app, recovery journal, autosave); G3 M1 part done (project tree, palette, settings dialog with string and path controls, themes) plus the app menu (M3.9); G4 under way (tree-sitter outline and folding library, Lezer highlighting, Structure tool window); G5 under way (search backend, Find tool window, symbol index, go-to popup); G6 under way (LSP client library, PHP detection, Phpactor download, engine wiring and diagnostics, completion and hover, definition, references and rename, Phpactor dies with Lutra, faster indexing, progress and messages, `php -l` on Windows); G7 under way (`lutra` CLI and single instance, MCP server, integrated terminal); G8 under way (Git backend, M4.1; Changes window, M4.2; gutter markers and status colours, M4.4; diff viewer, M4.3; branch widget and popup, M4.5; merge conflicts, M4.8; remotes, M4.10; stash, M4.9); G14 English UI catalog in place · **Last updated:** 2026-10-26
|
||||
> **Status:** M0 closed G1; G2 under way (text buffer, engine buffers, tabs and editor in the app, recovery journal, autosave); G3 M1 part done (project tree, palette, settings dialog with string and path controls, themes) plus the app menu (M3.9); G4 under way (tree-sitter outline and folding library, Lezer highlighting, Structure tool window); G5 under way (search backend, Find tool window, symbol index, go-to popup); G6 under way (LSP client library, PHP detection, Phpactor download, engine wiring and diagnostics, completion and hover, definition, references and rename, Phpactor dies with Lutra, faster indexing, progress and messages, `php -l` on Windows); G7 under way (`lutra` CLI and single instance, MCP server, integrated terminal); G8 under way (Git backend, M4.1; Changes window, M4.2; gutter markers and status colours, M4.4; diff viewer, M4.3; branch widget and popup, M4.5; merge conflicts, M4.8; remotes, M4.10; stash, M4.9; chunk staging, C8 C3); G14 English UI catalog in place · **Last updated:** 2026-11-01
|
||||
|
||||
Every known shortfall, ranked. This is the work list: unless the owner gives a task, take the highest open gap. Hours are agent wall-clock hours for one agent, all estimated.
|
||||
|
||||
|
|
@ -13,7 +13,7 @@ Every known shortfall, ranked. This is the work list: unless the owner gives a t
|
|||
| G5 | Search and navigation: find in files, go to file/class/symbol, first index | M2 | ~35 h |
|
||||
| G6 | Language server: completion, definition, hover, rename via Phpactor (~~PHP detection and Phpactor download~~, M3.1; ~~engine wiring and diagnostics~~, M3.3; ~~completion, hover, signature help~~, M3.4; ~~definition, references, rename~~, M3.5) | M3 | ~15 h |
|
||||
| G7 | ~~Terminal~~ (M3.6: PTY sessions, xterm.js sub-tabs in the bottom panel; settings, persistence, links and search still open), ~~`lutra` CLI and single instance~~ (M3.7: open folders and files at a line, `--wait`, forwarding a second start, token-protected rendezvous), ~~MCP server~~ (M3.8: `lutra mcp` with list/execute every command, screenshot, read buffer, recent events, open buffers as resources; still missing: resource and tool change notifications, progress for long commands), files outside the open project (the CLI refuses them; needs out-of-project buffers or a second window), `lutra diff` | M3 | ~16 h |
|
||||
| G8 | Git integration: ~~backend through the installed git~~ (M4.1: status, stage/unstage, commit and amend, file contents at HEAD/index, branches, checkout, branch creation, `gitChanged`), ~~Changes window~~ (M4.2: staged/changes/untracked groups, stage and unstage per file and group, commit and amend after saving, amend prefilled with the last message (C6 F1), no chunk staging), ~~gutter markers and status colours~~ (M4.4: added/modified/deleted against the index, tree and tab colours; no chunk actions), ~~diff viewer~~ (M4.3: side by side against the index or HEAD, editable working copy, next/previous change; no unified view, chunk actions or other revisions), ~~branch popup~~ (M4.5: status-bar branch, popup with local and remote branches and a filter, checkout after saving, new branch from HEAD; no merge, rebase, rename or delete), ~~log~~ (M4.6: Log tab with graph lanes, filters, paging, commit details, diffs at a commit, file history; no date or branch filters, no actions on commits), ~~remotes~~ (M4.10: fetch, pull by merge or rebase, push with the upstream set on the first push, clone, manage remotes, progress and cancel, explained refusals, any HTTPS or SSH server through git's credential helper and the ssh agent; no force push, tags, per-branch push targets or hosting features such as pull requests), blame, ~~conflicts~~ (M4.8: `git.merge`, conflicts list, three-pane resolve view with accept left/right per chunk, mark resolved, abort; no ignore action, compare menu or rebase conflicts), ~~stash~~ (M4.9: stash with a message and optionally untracked files, list, apply, pop and drop after a question, refusals that say what to do; no partial stash, no stash diff, no "unstash as branch") | M4 | ~122 h |
|
||||
| G8 | Git integration: ~~backend through the installed git~~ (M4.1: status, stage/unstage, commit and amend, file contents at HEAD/index, branches, checkout, branch creation, `gitChanged`), ~~Changes window~~ (M4.2: staged/changes/untracked groups, stage and unstage per file and group, commit and amend after saving, amend prefilled with the last message (C6 F1), partly staged files marked in both groups (C8 C3)), ~~gutter markers and status colours~~ (M4.4: added/modified/deleted against the index, tree and tab colours; C8 C3: staged markers, a click shows the chunk with stage, unstage, revert and previous/next), ~~diff viewer~~ (M4.3: side by side against the index or HEAD, editable working copy, next/previous change, chunk stage/unstage/revert from its gutter (C8 C3); no unified view, line staging or other revisions), ~~branch popup~~ (M4.5: status-bar branch, popup with local and remote branches and a filter, checkout after saving, new branch from HEAD; no merge, rebase, rename or delete), ~~log~~ (M4.6: Log tab with graph lanes, filters, paging, commit details, diffs at a commit, file history; no date or branch filters, no actions on commits), ~~remotes~~ (M4.10: fetch, pull by merge or rebase, push with the upstream set on the first push, clone, manage remotes, progress and cancel, explained refusals, any HTTPS or SSH server through git's credential helper and the ssh agent; no force push, tags, per-branch push targets or hosting features such as pull requests), blame, ~~conflicts~~ (M4.8: `git.merge`, conflicts list, three-pane resolve view with accept left/right per chunk, mark resolved, abort; no ignore action, compare menu or rebase conflicts), ~~stash~~ (M4.9: stash with a message and optionally untracked files, list, apply, pop and drop after a question, refusals that say what to do; no partial stash, no stash diff, no "unstash as branch") | M4 | ~122 h |
|
||||
| G9 | Debugger, test runner, Composer, run configurations | M5 | ~300 h |
|
||||
| G10 | Own indexer, type inference, inspections, refactorings | M6 | ~800 h |
|
||||
| G11 | Stability: crash-free operation on real projects and machines (~~recovery journal~~, M1.7) | ongoing | ~95 h |
|
||||
|
|
@ -55,6 +55,7 @@ G6 progress: M3.2 landed the LSP client library in `crates/lsp`: JSON-RPC framin
|
|||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-01 | patch | G8: chunk staging, unstaging and revert from the gutter and the diff viewer (C8 C3) |
|
||||
| 2026-10-31 | patch | C7 review: stray revision rows moved here; installers (B1, B2) and the alpha checklist (A2) change no gap |
|
||||
| 2026-10-31 | patch | A1: macOS system menus (G3), Retina region for the macOS screenshot fallback |
|
||||
| 2026-10-30 | patch | C6 review: the foreground-grab item is not reproduced in 20 starts; cause outside Lutra |
|
||||
|
|
|
|||
File diff suppressed because one or more lines are too long
|
|
@ -1,6 +1,6 @@
|
|||
# UI parity checklist
|
||||
|
||||
> **Status:** main window layout (M1.5), project tree running against the engine (M1.4), editor tabs with a CodeMirror editor (M1.6), light and dark themes (M1.10), restore dialog for unsaved changes (M1.7), notification toasts (M1.12), command palette and global keymap (M1.8), settings dialog with search (M1.9b), syntax highlighting and `editor.reveal` (M2.2), Find tool window in the bottom panel (M2.4), go-to popup (M2.6), left stripe and Structure tool window (M2.7), app menu (M3.9), Terminal tool window and bottom panel tabs (M3.6), Problems tool window and editor diagnostics (M3.3), completion, quick documentation and parameter info (M3.4), string and path settings with completion and tooltip settings (H4), banner-aligned themes with diagnostic and VCS colours (H5), Changes tool window (M4.2), Git change markers and status colours (M4.4), diff viewer and the project tree's context menu (M4.3), branch widget and popup (M4.5), fetch/pull/push progress, the clone and remotes dialogs (M4.10) · **Last updated:** 2026-10-28
|
||||
> **Status:** main window layout (M1.5), project tree running against the engine (M1.4), editor tabs with a CodeMirror editor (M1.6), light and dark themes (M1.10), restore dialog for unsaved changes (M1.7), notification toasts (M1.12), command palette and global keymap (M1.8), settings dialog with search (M1.9b), syntax highlighting and `editor.reveal` (M2.2), Find tool window in the bottom panel (M2.4), go-to popup (M2.6), left stripe and Structure tool window (M2.7), app menu (M3.9), Terminal tool window and bottom panel tabs (M3.6), Problems tool window and editor diagnostics (M3.3), completion, quick documentation and parameter info (M3.4), string and path settings with completion and tooltip settings (H4), banner-aligned themes with diagnostic and VCS colours (H5), Changes tool window (M4.2), Git change markers and status colours (M4.4), diff viewer and the project tree's context menu (M4.3), branch widget and popup (M4.5), fetch/pull/push progress, the clone and remotes dialogs (M4.10) · **Last updated:** 2026-11-01
|
||||
|
||||
- [ ] Main window: tool window stripes, editor area, status bar, navigation bar
|
||||
- M2.7 (2026-10-17): a left stripe with one tab per left tool window (Project, Structure); the shown one is marked, clicking it again hides the window. Still missing: right docking, several bottom tool windows, drag to rearrange, navigation bar, layout persistence.
|
||||
|
|
@ -41,8 +41,8 @@
|
|||
- [ ] Terminal tool window
|
||||
- M3.6 (2026-10-18): a Terminal tab in the bottom panel (the panel shows Find and Terminal as tabs while both are open; Left/Right switch); xterm.js with the fit addon follows the panel size; several terminals as sub-tabs (Local, Local (2)…) with a close button each and a new-terminal button, Left/Right/Home/End/Delete on a sub-tab, an ended shell dims its tab and prints its exit code; output survives collapsing the panel; copy with `Mod+Shift+C` or `Ctrl+C` on a selection, paste with `Mod+Shift+V` or `Ctrl+V`; while a terminal has the focus plain Ctrl keys go to the shell and only Mod+Shift / Mod+Alt shortcuts reach Lutra; Lutra's own ANSI palette in both themes (text colours ≥ 4.5:1). `terminal.open` `Mod+Shift+T`. Missing: renaming and splitting tabs, a context menu, search, clickable links and paths, drag and drop, a key back to the editor, a confirmation before killing a running process, terminal settings.
|
||||
- [ ] Git tool window
|
||||
- M4.2 (2026-10-25): a Changes tab in the bottom panel (`vcs.openChanges` `Mod+Alt+Shift+G`, menu Git › Changes): Staged, Changes and Untracked groups with counts, file names coloured by status (`--lt-vcs-*`, deleted struck through, a staged rename shows its old path), a checkbox per file and per group to stage or unstage, Up/Down/Page/Home/End and Space in the list, double-click or Enter opens the diff (M4.3) or the file; a commit message box with Amend and Commit (`Mod+Enter`; `vcs.commit` `Mod+Alt+Shift+M` focuses it), saving open files first; a refresh button (`vcs.refresh`); hints when git is missing or the folder is not a repository. Vitest (19 tests). C7 A3: a row context menu (right click, Shift+F10, the context-menu key) with Open and Add to .gitignore for untracked files, and git's prepared merge message offered in an empty box during a merge. Missing: a tree view and grouping by directory or module, changelists, chunk staging, context menu actions to roll back or delete, recent commit messages, commit options (sign-off, author, skip hooks), commit and push, a commit preview of the diff. Behaviour notes: `plan/phpstorm/16-vcs-basics.md`.
|
||||
- M4.4 (2026-10-25): the editor gutter shows a bar beside lines added or changed since the staged version and a notch where lines were deleted (tooltips from the catalog), updated 150 ms after typing and whenever Git changes; file names in the project tree and the tabs take the Git status colour (added, modified, deleted, untracked, conflicted; ignored entries inside a repository). Vitest. Missing: clicking a marker to see the old text, revert or stage the chunk, next/previous change, markers against HEAD, coloured directories.
|
||||
- M4.2 (2026-10-25): a Changes tab in the bottom panel (`vcs.openChanges` `Mod+Alt+Shift+G`, menu Git › Changes): Staged, Changes and Untracked groups with counts, file names coloured by status (`--lt-vcs-*`, deleted struck through, a staged rename shows its old path), a checkbox per file and per group to stage or unstage, Up/Down/Page/Home/End and Space in the list, double-click or Enter opens the diff (M4.3) or the file; a commit message box with Amend and Commit (`Mod+Enter`; `vcs.commit` `Mod+Alt+Shift+M` focuses it), saving open files first; a refresh button (`vcs.refresh`); hints when git is missing or the folder is not a repository. Vitest (19 tests). C7 A3: a row context menu (right click, Shift+F10, the context-menu key) with Open and Add to .gitignore for untracked files, and git's prepared merge message offered in an empty box during a merge. Missing: a tree view and grouping by directory or module, changelists, line staging, context menu actions to roll back or delete, recent commit messages, commit options (sign-off, author, skip hooks), commit and push, a commit preview of the diff. Behaviour notes: `plan/phpstorm/16-vcs-basics.md`.
|
||||
- M4.4 (2026-10-25): the editor gutter shows a bar beside lines added or changed since the staged version and a notch where lines were deleted (tooltips from the catalog), updated 150 ms after typing and whenever Git changes; file names in the project tree and the tabs take the Git status colour (added, modified, deleted, untracked, conflicted; ignored entries inside a repository). Vitest. C8 C3: a click on a marker opens the chunk popup (old and new lines, Stage / Unstage / Revert, Previous / Next, Escape closes), staged changes get a hollow marker, partly staged files are marked in the Changes window. Missing: markers against HEAD, line-level staging, coloured directories.
|
||||
- M4.3 (2026-10-26): "Diff: <name>" tabs in the editor area after the file tabs (`vcs.showDiff` `Mod+Alt+Shift+D`, menu Git › Show Diff; double-click or Enter in Changes; right click or Shift+F10 on a file in the project tree → Show Diff): the staged version or the last commit on the left, read-only, and the working copy on the right, editable like its own tab; a caption says what is compared; changed lines and words tinted with the VCS tokens, a change bar in each gutter, unchanged stretches collapsed to a clickable row; next/previous change `Alt+Shift+]` / `Alt+Shift+[` (wrapping); notices for binary, too large and deleted files and for git's errors. The project tree got its first context menu (Open, Show Diff; WAI-ARIA menu, keyboard). Vitest. Missing: unified view, revert/stage arrows between the sides, synchronised horizontal scrolling, whitespace and highlighting options, comparing with any revision, a diff window of its own, more tree context menu items.
|
||||
- M4.5 (2026-10-26): the status bar shows the current branch (Lucide `git-branch`), or the short hash when detached, hidden outside a repository. A click or `vcs.branches` (menu Git › Branches…) opens a popup above it: a filter field, "New branch…", Local (current one checked, upstream beside it) and Remote headings; Up/Down/Page keys, Enter or a click checks out, Escape or a click outside closes and returns the focus. "New branch…" switches to a name field with a "Check out" checkbox; git's refusal shows under the field. An exclusive modal. Vitest (16 tests). Missing: merge, rebase, rename, delete, compare with current, favourites, recent branches first, incoming/outgoing markers, a submenu per branch.
|
||||
- M4.10 (2026-10-28): Git › Fetch / Pull / Push (`vcs.fetch`, `vcs.pull`, `vcs.push`, no default shortcuts) with a status-bar item left of the branch: "Fetching: Receiving objects 45%" and a Cancel button while one runs, otherwise `↑ahead ↓behind` against the upstream (hidden when in step); toasts for done, cancelled and git's explained refusal. Git › Clone Repository… (`vcs.clone`, also without a project): URL and folder fields, Browse… (native folder picker; the folder follows the repository name in the URL), git's refusal in the dialog, then the cloned project opens. Git › Manage Remotes… (`vcs.manageRemotes`): remotes with redacted URLs and push URLs, Edit URL, Remove (asked in the row), an add form. Both dialogs are exclusive modals. Vitest (11 tests). Missing: push dialog with the commits to push and a target branch, force push, tags, pull options per call, a clone dialog listing the user's repositories on a hosting service.
|
||||
|
|
@ -51,6 +51,7 @@
|
|||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-01 | patch | Chunk popup from the gutter and the diff viewer, staged markers, partly staged rows (C8 C3) |
|
||||
| 2026-10-31 | patch | Changes context menu with Add to .gitignore and the merge message prefill (C7 A3) |
|
||||
| 2026-10-28 | minor | Fetch/pull/push with progress, clone and remotes dialogs (M4.10) |
|
||||
| 2026-10-26 | minor | Branch widget and popup (M4.5) |
|
||||
|
|
|
|||
|
|
@ -55,6 +55,7 @@ export const UI_COMMANDS: readonly UiCommandSpec[] = [
|
|||
{ id: "vcs.showStashes", labelKey: "command.vcs.showStashes", menuPath: "Git/Stashes…" },
|
||||
{ id: "vcs.showCommit", labelKey: "command.vcs.showCommit" },
|
||||
{ id: "vcs.toggleBlame", labelKey: "command.vcs.toggleBlame", menuPath: "Git/Annotate with Git Blame" },
|
||||
{ id: "vcs.showChunk", labelKey: "command.vcs.showChunk", menuPath: "Git/Show Changed Chunk" },
|
||||
{ id: "vcs.showDiff", labelKey: "command.vcs.showDiff", menuPath: "Git/Show Diff", defaultShortcut: "Mod+Alt+Shift+D" },
|
||||
{ id: "vcs.nextChange", labelKey: "command.vcs.nextChange", menuPath: "Git/Next Change", defaultShortcut: "Alt+Shift+]" },
|
||||
{ id: "vcs.previousChange", labelKey: "command.vcs.previousChange", menuPath: "Git/Previous Change", defaultShortcut: "Alt+Shift+[" },
|
||||
|
|
|
|||
692
ui/src/components/editor/chunkPopup.ts
Normal file
692
ui/src/components/editor/chunkPopup.ts
Normal file
|
|
@ -0,0 +1,692 @@
|
|||
/**
|
||||
* The chunk popup (C8 C3): a click on a Git change marker in the gutter
|
||||
* (or `vcs.showChunk` at the caret) shows that chunk's diff with the
|
||||
* actions Stage, Unstage, Revert, Previous and Next.
|
||||
*
|
||||
* - **Source:** `git.chunks {id}` (a pending outcome, so through
|
||||
* `runWaiting`) after the buffer sync is idle. It lists the unstaged
|
||||
* chunks (index → buffer) and the staged ones (HEAD → index, placed on
|
||||
* the buffer lines they map to) with a token of the texts compared.
|
||||
* - **Sections:** the popup shows the unstaged chunk at the line (Stage,
|
||||
* Revert) and the staged chunk at the line (Unstage), whichever exist.
|
||||
* - **Actions** pass the chunk's position and the token back
|
||||
* (`git.stageChunk`, `git.unstageChunk`, `git.revertChunk`); the engine
|
||||
* refuses when the buffer, index or HEAD changed since, and the popup
|
||||
* shows the refusal. After Stage or Unstage the popup re-reads the chunks
|
||||
* and stays on the line, so a stage can be undone at once. Revert edits
|
||||
* the buffer; the edit enters the editor's undo history
|
||||
* ({@link ChunkTransport.undoable}) and the popup closes.
|
||||
* - **Previous / Next** move the caret to the start of the previous or
|
||||
* next chunk (unstaged and staged, in line order, wrapping) and show it.
|
||||
* - **Closing:** Escape, the close button, an edit of the document, or a
|
||||
* click elsewhere in the editor.
|
||||
* - **Untrusted input:** results are checked field by field.
|
||||
*
|
||||
* Colours come from `--lt-*` tokens only.
|
||||
*/
|
||||
import { EditorSelection, Prec, StateEffect, StateField, type Extension } from "@codemirror/state";
|
||||
import { EditorView, ViewPlugin, keymap, showTooltip, type Tooltip } from "@codemirror/view";
|
||||
import { t } from "../../i18n";
|
||||
import { runWaiting, type JsonValue } from "../../ipc";
|
||||
import { useEditorStore } from "../../stores/editor";
|
||||
import type { AssistBuffer } from "./assist";
|
||||
|
||||
/** UI command that opens the popup at the caret line. */
|
||||
export const SHOW_CHUNK_COMMAND = "vcs.showChunk";
|
||||
|
||||
/** What a chunk changed. */
|
||||
export type ChunkKind = "added" | "modified" | "deleted";
|
||||
|
||||
/** One chunk of `git.chunks`, checked. */
|
||||
export interface ChunkInfo {
|
||||
/** Its position in its list (what the actions take). */
|
||||
index: number;
|
||||
/** What it changed. */
|
||||
kind: ChunkKind;
|
||||
/** First buffer line (0-based). */
|
||||
startLine: number;
|
||||
/** Line after the last; equal to `startLine` for a deletion point. */
|
||||
endLine: number;
|
||||
/** Removed lines. */
|
||||
removed: string[];
|
||||
/** Added lines. */
|
||||
added: string[];
|
||||
/** Whether the lines were cut. */
|
||||
truncated: boolean;
|
||||
}
|
||||
|
||||
/** A `git.chunks` result, checked. */
|
||||
export interface ChunkList {
|
||||
/** The token of the texts compared. */
|
||||
token: string;
|
||||
/** Index → buffer. */
|
||||
unstaged: ChunkInfo[];
|
||||
/** HEAD → index. */
|
||||
staged: ChunkInfo[];
|
||||
}
|
||||
|
||||
/** The chunks at one line. */
|
||||
export interface ChunksAt {
|
||||
/** The unstaged chunk, if any. */
|
||||
unstaged: ChunkInfo | null;
|
||||
/** The staged chunk, if any. */
|
||||
staged: ChunkInfo | null;
|
||||
}
|
||||
|
||||
/** A command's outcome as the popup sees it. */
|
||||
export type ChunkResult = { ok: true; value: unknown } | { ok: false; error?: { message: string } };
|
||||
|
||||
/** How the popup reaches the engine; replaced in tests. */
|
||||
export interface ChunkTransport {
|
||||
/** Runs a command and resolves with its untrusted result. */
|
||||
query(command: string, params: JsonValue): Promise<ChunkResult>;
|
||||
/**
|
||||
* Makes the engine's next edits of a buffer undoable in its editor;
|
||||
* null when the buffer has no sync.
|
||||
*
|
||||
* @param id - the buffer.
|
||||
*/
|
||||
undoable?(id: number): { end(version: number | null): void } | null;
|
||||
}
|
||||
|
||||
/** The transport through the engine IPC and the editor store's syncs. */
|
||||
export const engineChunkTransport: ChunkTransport = {
|
||||
query: (command, params) => runWaiting<unknown>(command, params),
|
||||
undoable: (id) => {
|
||||
const sync = useEditorStore().syncOf(id);
|
||||
if (!sync) {
|
||||
return null;
|
||||
}
|
||||
sync.beginUndoableRemote();
|
||||
return {
|
||||
end: (version) => {
|
||||
sync.endUndoableRemote(version);
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
/** Whether a value is a non-negative integer. */
|
||||
function isLine(value: unknown): value is number {
|
||||
return typeof value === "number" && Number.isInteger(value) && value >= 0;
|
||||
}
|
||||
|
||||
/** Most lines of each side shown in the popup. */
|
||||
export const POPUP_LINES = 200;
|
||||
|
||||
/**
|
||||
* Reads one list of `git.chunks`; malformed chunks are skipped but keep
|
||||
* their positions.
|
||||
*
|
||||
* @param raw - untrusted.
|
||||
*/
|
||||
function readList(raw: unknown): ChunkInfo[] {
|
||||
if (!Array.isArray(raw)) {
|
||||
return [];
|
||||
}
|
||||
const out: ChunkInfo[] = [];
|
||||
(raw as unknown[]).forEach((item, index) => {
|
||||
if (typeof item !== "object" || item === null) {
|
||||
return;
|
||||
}
|
||||
const c = item as Record<string, unknown>;
|
||||
const kind = c.kind;
|
||||
if ((kind !== "added" && kind !== "modified" && kind !== "deleted") || !isLine(c.startLine) || !isLine(c.endLine) || c.endLine < c.startLine) {
|
||||
return;
|
||||
}
|
||||
const lines = (value: unknown): string[] =>
|
||||
Array.isArray(value) ? (value as unknown[]).filter((l): l is string => typeof l === "string").slice(0, POPUP_LINES) : [];
|
||||
out.push({
|
||||
index,
|
||||
kind,
|
||||
startLine: c.startLine,
|
||||
endLine: c.endLine,
|
||||
removed: lines(c.removed),
|
||||
added: lines(c.added),
|
||||
truncated: c.truncated === true,
|
||||
});
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a `git.chunks` result.
|
||||
*
|
||||
* @param value - untrusted.
|
||||
* @returns the lists, or null without a token.
|
||||
*/
|
||||
export function readChunks(value: unknown): ChunkList | null {
|
||||
if (typeof value !== "object" || value === null) {
|
||||
return null;
|
||||
}
|
||||
const v = value as Record<string, unknown>;
|
||||
if (typeof v.token !== "string") {
|
||||
return null;
|
||||
}
|
||||
return { token: v.token, unstaged: readList(v.unstaged), staged: readList(v.staged) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a chunk covers a line: a line of its range, or for a deletion
|
||||
* point the line after it (the last line when it is at the end), where
|
||||
* the gutter draws its marker.
|
||||
*
|
||||
* @param chunk - the chunk.
|
||||
* @param line - 0-based line.
|
||||
* @param lineCount - the document's line count.
|
||||
*/
|
||||
export function covers(chunk: ChunkInfo, line: number, lineCount: number): boolean {
|
||||
if (chunk.startLine === chunk.endLine) {
|
||||
const marked = chunk.startLine >= lineCount ? lineCount - 1 : chunk.startLine;
|
||||
return line === marked;
|
||||
}
|
||||
return line >= chunk.startLine && line < chunk.endLine;
|
||||
}
|
||||
|
||||
/**
|
||||
* The chunks at a line.
|
||||
*
|
||||
* @param list - the chunks.
|
||||
* @param line - 0-based line.
|
||||
* @param lineCount - the document's line count.
|
||||
*/
|
||||
export function chunksAt(list: ChunkList, line: number, lineCount: number): ChunksAt {
|
||||
return {
|
||||
unstaged: list.unstaged.find((c) => covers(c, line, lineCount)) ?? null,
|
||||
staged: list.staged.find((c) => covers(c, line, lineCount)) ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The line of the next or previous chunk start after or before `line`,
|
||||
* wrapping around; null without chunks.
|
||||
*
|
||||
* @param list - the chunks.
|
||||
* @param line - 0-based line.
|
||||
* @param direction - 1 for the next chunk, -1 for the previous one.
|
||||
* @param lineCount - the document's line count.
|
||||
*/
|
||||
export function neighbourLine(list: ChunkList, line: number, direction: 1 | -1, lineCount: number): number | null {
|
||||
const starts = [...new Set([...list.unstaged, ...list.staged].map((c) => Math.min(c.startLine, Math.max(lineCount - 1, 0))))].sort(
|
||||
(a, b) => a - b,
|
||||
);
|
||||
if (starts.length === 0) {
|
||||
return null;
|
||||
}
|
||||
if (direction > 0) {
|
||||
return starts.find((s) => s > line) ?? starts[0] ?? null;
|
||||
}
|
||||
return [...starts].reverse().find((s) => s < line) ?? starts[starts.length - 1] ?? null;
|
||||
}
|
||||
|
||||
/** What the popup shows. */
|
||||
interface Popup {
|
||||
/** 0-based line it is for. */
|
||||
line: number;
|
||||
/** Document position it is shown at (the line's start). */
|
||||
pos: number;
|
||||
/** The chunks read, null while loading. */
|
||||
list: ChunkList | null;
|
||||
/** An error to show, null if none. */
|
||||
error: string | null;
|
||||
/** Whether an action runs. */
|
||||
busy: boolean;
|
||||
}
|
||||
|
||||
/** Replaces the popup; null closes it. */
|
||||
const setPopup = StateEffect.define<Popup | null>();
|
||||
|
||||
/** How each view reaches the engine, and its buffer. */
|
||||
const owners = new WeakMap<EditorView, { buffer: AssistBuffer; transport: ChunkTransport }>();
|
||||
|
||||
/**
|
||||
* Builds a line of the diff.
|
||||
*
|
||||
* @param sign - `-` or `+`.
|
||||
* @param text - the line.
|
||||
*/
|
||||
function diffLine(sign: "-" | "+", text: string): HTMLElement {
|
||||
const row = document.createElement("div");
|
||||
row.className = `lt-chunk-popup__line lt-chunk-popup__line--${sign === "-" ? "removed" : "added"}`;
|
||||
row.dataset.test = sign === "-" ? "chunk-removed" : "chunk-added";
|
||||
row.textContent = `${sign} ${text}`;
|
||||
return row;
|
||||
}
|
||||
|
||||
/**
|
||||
* A button of the popup.
|
||||
*
|
||||
* @param label - its text.
|
||||
* @param test - its `data-test` value.
|
||||
* @param disabled - whether it is disabled.
|
||||
* @param run - what a click does.
|
||||
*/
|
||||
function button(label: string, test: string, disabled: boolean, run: () => void): HTMLButtonElement {
|
||||
const element = document.createElement("button");
|
||||
element.type = "button";
|
||||
element.className = "lt-chunk-popup__button";
|
||||
element.textContent = label;
|
||||
element.dataset.test = test;
|
||||
element.disabled = disabled;
|
||||
element.addEventListener("mousedown", (event) => {
|
||||
event.preventDefault();
|
||||
});
|
||||
element.addEventListener("click", (event) => {
|
||||
event.preventDefault();
|
||||
run();
|
||||
});
|
||||
return element;
|
||||
}
|
||||
|
||||
/**
|
||||
* One section: the chunk's diff and its actions.
|
||||
*
|
||||
* @param view - the editor.
|
||||
* @param popup - the popup state.
|
||||
* @param chunk - the chunk.
|
||||
* @param staged - whether it is a staged chunk.
|
||||
*/
|
||||
function section(view: EditorView, popup: Popup, chunk: ChunkInfo, staged: boolean): HTMLElement {
|
||||
const box = document.createElement("div");
|
||||
box.className = "lt-chunk-popup__section";
|
||||
box.dataset.test = staged ? "chunk-staged" : "chunk-unstaged";
|
||||
const title = document.createElement("div");
|
||||
title.className = "lt-chunk-popup__title";
|
||||
title.textContent = staged ? t("editor.chunk.staged") : t("editor.chunk.unstaged");
|
||||
const lines = document.createElement("div");
|
||||
lines.className = "lt-chunk-popup__diff";
|
||||
for (const text of chunk.removed) {
|
||||
lines.append(diffLine("-", text));
|
||||
}
|
||||
for (const text of chunk.added) {
|
||||
lines.append(diffLine("+", text));
|
||||
}
|
||||
if (chunk.truncated) {
|
||||
const more = document.createElement("div");
|
||||
more.className = "lt-chunk-popup__more";
|
||||
more.textContent = t("editor.chunk.truncated");
|
||||
lines.append(more);
|
||||
}
|
||||
const actions = document.createElement("div");
|
||||
actions.className = "lt-chunk-popup__actions";
|
||||
if (staged) {
|
||||
actions.append(
|
||||
button(t("editor.chunk.unstage"), "chunk-unstage", popup.busy, () => {
|
||||
void act(view, "git.unstageChunk", chunk);
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
actions.append(
|
||||
button(t("editor.chunk.stage"), "chunk-stage", popup.busy, () => {
|
||||
void act(view, "git.stageChunk", chunk);
|
||||
}),
|
||||
button(t("editor.chunk.revert"), "chunk-revert", popup.busy, () => {
|
||||
void act(view, "git.revertChunk", chunk);
|
||||
}),
|
||||
);
|
||||
}
|
||||
box.append(title, lines, actions);
|
||||
return box;
|
||||
}
|
||||
|
||||
/**
|
||||
* The popup's DOM.
|
||||
*
|
||||
* @param view - the editor.
|
||||
* @param popup - what it shows.
|
||||
*/
|
||||
function popupDom(view: EditorView, popup: Popup): HTMLElement {
|
||||
const dom = document.createElement("div");
|
||||
dom.className = "lt-chunk-popup";
|
||||
dom.dataset.test = "chunk-popup";
|
||||
dom.setAttribute("role", "dialog");
|
||||
dom.setAttribute("aria-label", t("editor.chunk.title"));
|
||||
const head = document.createElement("div");
|
||||
head.className = "lt-chunk-popup__head";
|
||||
const nav = (direction: 1 | -1): void => {
|
||||
move(view, direction);
|
||||
};
|
||||
head.append(
|
||||
button(t("editor.chunk.previous"), "chunk-previous", popup.list === null, () => {
|
||||
nav(-1);
|
||||
}),
|
||||
button(t("editor.chunk.next"), "chunk-next", popup.list === null, () => {
|
||||
nav(1);
|
||||
}),
|
||||
button("×", "chunk-close", false, () => {
|
||||
closeChunkPopup(view);
|
||||
}),
|
||||
);
|
||||
head.lastElementChild?.setAttribute("aria-label", t("editor.chunk.close"));
|
||||
dom.append(head);
|
||||
if (popup.list === null && popup.error === null) {
|
||||
const loading = document.createElement("div");
|
||||
loading.className = "lt-chunk-popup__status";
|
||||
loading.textContent = t("editor.chunk.loading");
|
||||
dom.append(loading);
|
||||
}
|
||||
if (popup.list !== null) {
|
||||
const at = chunksAt(popup.list, popup.line, view.state.doc.lines);
|
||||
if (at.unstaged) {
|
||||
dom.append(section(view, popup, at.unstaged, false));
|
||||
}
|
||||
if (at.staged) {
|
||||
dom.append(section(view, popup, at.staged, true));
|
||||
}
|
||||
if (!at.unstaged && !at.staged) {
|
||||
const none = document.createElement("div");
|
||||
none.className = "lt-chunk-popup__status";
|
||||
none.dataset.test = "chunk-none";
|
||||
none.textContent = t("editor.chunk.none");
|
||||
dom.append(none);
|
||||
}
|
||||
}
|
||||
if (popup.error !== null) {
|
||||
const error = document.createElement("div");
|
||||
error.className = "lt-chunk-popup__error";
|
||||
error.dataset.test = "chunk-error";
|
||||
error.setAttribute("role", "alert");
|
||||
error.textContent = popup.error;
|
||||
dom.append(error);
|
||||
}
|
||||
return dom;
|
||||
}
|
||||
|
||||
/** The popup of a state. */
|
||||
const popupState = StateField.define<Popup | null>({
|
||||
create: () => null,
|
||||
update(value, tr) {
|
||||
let next = value;
|
||||
if (next !== null && tr.docChanged) {
|
||||
next = null;
|
||||
}
|
||||
for (const effect of tr.effects) {
|
||||
if (effect.is(setPopup)) {
|
||||
next = effect.value;
|
||||
}
|
||||
}
|
||||
return next;
|
||||
},
|
||||
provide: (field) =>
|
||||
showTooltip.from(field, (popup): Tooltip | null => {
|
||||
if (popup === null) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
pos: popup.pos,
|
||||
above: false,
|
||||
create: (view) => ({ dom: popupDom(view, popup) }),
|
||||
};
|
||||
}),
|
||||
});
|
||||
|
||||
/**
|
||||
* Replaces the popup of a view that has an owner.
|
||||
*
|
||||
* @param view - the editor.
|
||||
* @param popup - the new state; null closes it.
|
||||
*/
|
||||
function setPopupAt(view: EditorView, popup: Popup | null): void {
|
||||
if (!owners.has(view)) {
|
||||
return;
|
||||
}
|
||||
view.dispatch({ effects: setPopup.of(popup) });
|
||||
}
|
||||
|
||||
/**
|
||||
* The start of a 0-based line, clamped to the document.
|
||||
*
|
||||
* @param view - the editor.
|
||||
* @param line - 0-based line.
|
||||
*/
|
||||
function lineStart(view: EditorView, line: number): number {
|
||||
const doc = view.state.doc;
|
||||
return doc.line(Math.min(Math.max(line + 1, 1), doc.lines)).from;
|
||||
}
|
||||
|
||||
/**
|
||||
* The popup a view shows, for tests and inspection.
|
||||
*
|
||||
* @param view - the editor.
|
||||
* @returns its 0-based line, or null when closed.
|
||||
*/
|
||||
export function chunkPopupLine(view: EditorView): number | null {
|
||||
return view.state.field(popupState, false)?.line ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the popup.
|
||||
*
|
||||
* @param view - the editor.
|
||||
*/
|
||||
export function closeChunkPopup(view: EditorView): void {
|
||||
if ((view.state.field(popupState, false) ?? null) !== null) {
|
||||
view.dispatch({ effects: setPopup.of(null) });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the chunks of a view's buffer.
|
||||
*
|
||||
* @param view - the editor.
|
||||
* @returns the chunks, or an error text.
|
||||
*/
|
||||
async function load(view: EditorView): Promise<ChunkList | string> {
|
||||
const owner = owners.get(view);
|
||||
if (!owner) {
|
||||
return t("editor.chunk.failed", { reason: "" });
|
||||
}
|
||||
await owner.buffer.idle();
|
||||
const result = await owner.transport.query("git.chunks", { id: owner.buffer.id });
|
||||
if (!result.ok) {
|
||||
return t("editor.chunk.failed", { reason: result.error?.message ?? "" });
|
||||
}
|
||||
return readChunks(result.value) ?? t("editor.chunk.failed", { reason: "" });
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows the popup for a line: loading first, then the chunks there.
|
||||
*
|
||||
* @param view - an editor built with {@link chunkPopupExtensions}.
|
||||
* @param line - 0-based line.
|
||||
* @param error - an error to keep showing, if any.
|
||||
*/
|
||||
export async function openChunkPopup(view: EditorView, line: number, error: string | null = null): Promise<void> {
|
||||
if (!owners.has(view)) {
|
||||
return;
|
||||
}
|
||||
const doc = view.state.doc;
|
||||
const pos = lineStart(view, line);
|
||||
setPopupAt(view, { line, pos, list: null, error: null, busy: false });
|
||||
const loaded = await load(view);
|
||||
if (view.state.doc !== doc || chunkPopupLine(view) !== line) {
|
||||
return;
|
||||
}
|
||||
setPopupAt(view, typeof loaded === "string" ? { line, pos, list: null, error: loaded, busy: false } : { line, pos, list: loaded, error, busy: false });
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves the caret to the previous or next chunk and shows it.
|
||||
*
|
||||
* @param view - the editor.
|
||||
* @param direction - 1 for the next chunk, -1 for the previous one.
|
||||
*/
|
||||
function move(view: EditorView, direction: 1 | -1): void {
|
||||
const popup = view.state.field(popupState, false);
|
||||
if (!popup?.list) {
|
||||
return;
|
||||
}
|
||||
const target = neighbourLine(popup.list, popup.line, direction, view.state.doc.lines);
|
||||
if (target === null) {
|
||||
return;
|
||||
}
|
||||
const pos = lineStart(view, target);
|
||||
view.dispatch({
|
||||
selection: EditorSelection.cursor(pos),
|
||||
effects: [EditorView.scrollIntoView(pos, { y: "center" }), setPopup.of({ ...popup, line: target, pos, error: null })],
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a chunk action and updates the popup.
|
||||
*
|
||||
* @param view - the editor.
|
||||
* @param command - `git.stageChunk`, `git.unstageChunk` or `git.revertChunk`.
|
||||
* @param chunk - the chunk.
|
||||
*/
|
||||
async function act(view: EditorView, command: string, chunk: ChunkInfo): Promise<void> {
|
||||
const owner = owners.get(view);
|
||||
const popup = view.state.field(popupState, false);
|
||||
if (!owner || !popup?.list) {
|
||||
return;
|
||||
}
|
||||
const { line } = popup;
|
||||
setPopupAt(view, { ...popup, busy: true, error: null });
|
||||
const revert = command === "git.revertChunk";
|
||||
const undo = revert ? (owner.transport.undoable?.(owner.buffer.id) ?? null) : null;
|
||||
const result = await owner.transport.query(command, { id: owner.buffer.id, index: chunk.index, token: popup.list.token });
|
||||
if (undo) {
|
||||
const version = result.ok && typeof result.value === "object" && result.value !== null ? (result.value as Record<string, unknown>).version : null;
|
||||
undo.end(typeof version === "number" ? version : null);
|
||||
}
|
||||
if (!result.ok) {
|
||||
if (chunkPopupLine(view) === line) {
|
||||
await openChunkPopup(view, line, t("editor.chunk.failed", { reason: result.error?.message ?? "" }));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (revert) {
|
||||
closeChunkPopup(view);
|
||||
return;
|
||||
}
|
||||
if (chunkPopupLine(view) === line) {
|
||||
await openChunkPopup(view, line);
|
||||
}
|
||||
}
|
||||
|
||||
/** Popup styles from the theme tokens. */
|
||||
const popupTheme: Extension = EditorView.theme({
|
||||
".lt-chunk-popup": {
|
||||
minWidth: "320px",
|
||||
maxWidth: "640px",
|
||||
fontSize: "var(--lt-font-size-ui)",
|
||||
color: "var(--lt-fg)",
|
||||
background: "var(--lt-bg)",
|
||||
},
|
||||
".lt-chunk-popup__head": {
|
||||
display: "flex",
|
||||
justifyContent: "flex-end",
|
||||
gap: "4px",
|
||||
padding: "4px",
|
||||
borderBottom: "1px solid var(--lt-border)",
|
||||
},
|
||||
".lt-chunk-popup__section + .lt-chunk-popup__section": {
|
||||
borderTop: "1px solid var(--lt-border)",
|
||||
},
|
||||
".lt-chunk-popup__title": {
|
||||
padding: "4px 8px 2px",
|
||||
color: "var(--lt-fg-muted)",
|
||||
},
|
||||
".lt-chunk-popup__diff": {
|
||||
maxHeight: "240px",
|
||||
overflow: "auto",
|
||||
fontFamily: "var(--lt-font-mono)",
|
||||
fontSize: "var(--lt-font-size-editor)",
|
||||
whiteSpace: "pre",
|
||||
background: "var(--lt-editor-bg)",
|
||||
},
|
||||
".lt-chunk-popup__line": {
|
||||
padding: "0 8px",
|
||||
},
|
||||
".lt-chunk-popup__line--removed": {
|
||||
background: "color-mix(in srgb, var(--lt-vcs-deleted) 18%, var(--lt-editor-bg))",
|
||||
},
|
||||
".lt-chunk-popup__line--added": {
|
||||
background: "color-mix(in srgb, var(--lt-vcs-added) 18%, var(--lt-editor-bg))",
|
||||
},
|
||||
".lt-chunk-popup__more, .lt-chunk-popup__status": {
|
||||
padding: "4px 8px",
|
||||
color: "var(--lt-fg-muted)",
|
||||
},
|
||||
".lt-chunk-popup__error": {
|
||||
padding: "4px 8px",
|
||||
color: "var(--lt-error)",
|
||||
whiteSpace: "pre-wrap",
|
||||
},
|
||||
".lt-chunk-popup__actions": {
|
||||
display: "flex",
|
||||
gap: "4px",
|
||||
padding: "4px 8px 6px",
|
||||
},
|
||||
".lt-chunk-popup__button": {
|
||||
color: "var(--lt-fg)",
|
||||
background: "var(--lt-bg)",
|
||||
border: "1px solid var(--lt-border)",
|
||||
borderRadius: "3px",
|
||||
padding: "1px 8px",
|
||||
cursor: "pointer",
|
||||
font: "inherit",
|
||||
},
|
||||
".lt-chunk-popup__button:hover:not(:disabled)": {
|
||||
background: "color-mix(in srgb, var(--lt-fg) 8%, var(--lt-bg))",
|
||||
},
|
||||
".lt-chunk-popup__button:disabled": {
|
||||
color: "var(--lt-fg-muted)",
|
||||
cursor: "default",
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Remembers a view's buffer and transport while the view lives.
|
||||
*
|
||||
* @param buffer - the buffer the view shows.
|
||||
* @param transport - how to reach the engine.
|
||||
*/
|
||||
function ownerPlugin(buffer: AssistBuffer, transport: ChunkTransport): Extension {
|
||||
return ViewPlugin.define((view) => {
|
||||
owners.set(view, { buffer, transport });
|
||||
return {
|
||||
destroy(): void {
|
||||
owners.delete(view);
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The chunk popup's extensions.
|
||||
*
|
||||
* @param buffer - the buffer the state shows.
|
||||
* @param transport - how to reach the engine.
|
||||
*/
|
||||
export function chunkPopupExtensions(buffer: AssistBuffer, transport: ChunkTransport): Extension {
|
||||
return [
|
||||
popupState,
|
||||
popupTheme,
|
||||
ownerPlugin(buffer, transport),
|
||||
EditorView.domEventHandlers({
|
||||
mousedown: (event, view) => {
|
||||
const target = event.target;
|
||||
if (target instanceof Element && (target.closest(".lt-chunk-popup") || target.closest(".lt-git-gutter"))) {
|
||||
return false;
|
||||
}
|
||||
closeChunkPopup(view);
|
||||
return false;
|
||||
},
|
||||
}),
|
||||
Prec.highest(
|
||||
keymap.of([
|
||||
{
|
||||
key: "Escape",
|
||||
run: (view) => {
|
||||
if ((view.state.field(popupState, false) ?? null) === null) {
|
||||
return false;
|
||||
}
|
||||
closeChunkPopup(view);
|
||||
return true;
|
||||
},
|
||||
},
|
||||
]),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
|
@ -18,15 +18,22 @@
|
|||
* (lines removed at the end) marks the bottom of the last line.
|
||||
* - Failures leave the markers as they are: markers are best effort while
|
||||
* typing, and the Changes window reports git problems.
|
||||
* - **Staged changes (C8 C3):** when the view shows the state and on every
|
||||
* refresh (not while typing), `git.chunks {id}` is read too; lines of a
|
||||
* staged chunk without an unstaged marker get a hollow `staged` marker,
|
||||
* mapped through edits like the others.
|
||||
* - **Click:** a click on a marker opens the chunk popup
|
||||
* (`chunkPopup.ts`) for that line: the chunk's diff with Stage,
|
||||
* Unstage, Revert, Previous and Next.
|
||||
*
|
||||
* Colours come from `--lt-vcs-added`, `--lt-vcs-modified` and
|
||||
* `--lt-vcs-deleted`.
|
||||
*/
|
||||
import { RangeSet, RangeSetBuilder, StateEffect, StateField, type EditorState, type Extension, type Text } from "@codemirror/state";
|
||||
import { EditorView, GutterMarker, ViewPlugin, gutter, type PluginValue, type ViewUpdate } from "@codemirror/view";
|
||||
import { runWaiting, type JsonValue } from "../../ipc";
|
||||
import { t } from "../../i18n";
|
||||
import type { AssistBuffer } from "./assist";
|
||||
import { chunkPopupExtensions, covers, engineChunkTransport, openChunkPopup, readChunks, type ChunkList, type ChunkTransport } from "./chunkPopup";
|
||||
|
||||
/** Delay between the last edit and the query. */
|
||||
export const GIT_GUTTER_DEBOUNCE_MS = 150;
|
||||
|
|
@ -44,16 +51,11 @@ export interface LineChange {
|
|||
endLine: number;
|
||||
}
|
||||
|
||||
/** How the gutter reaches the engine; replaced in tests. */
|
||||
export interface GitGutterTransport {
|
||||
/** Runs a command and resolves with its untrusted result. */
|
||||
query(command: string, params: JsonValue): Promise<{ ok: true; value: unknown } | { ok: false }>;
|
||||
}
|
||||
/** How the gutter and its chunk popup reach the engine; replaced in tests. */
|
||||
export type GitGutterTransport = ChunkTransport;
|
||||
|
||||
/** The transport through the engine IPC, off the shell's main thread. */
|
||||
export const engineGitGutterTransport: GitGutterTransport = {
|
||||
query: (command, params) => runWaiting<unknown>(command, params),
|
||||
};
|
||||
export const engineGitGutterTransport: GitGutterTransport = engineChunkTransport;
|
||||
|
||||
/** Whether a value is a non-negative integer. */
|
||||
function isLine(value: unknown): value is number {
|
||||
|
|
@ -88,8 +90,8 @@ export function readLineChanges(value: unknown): LineChange[] | null {
|
|||
return out;
|
||||
}
|
||||
|
||||
/** A marker class: the three kinds, plus deleted lines below the last line. */
|
||||
type MarkerClass = LineChangeKind | "deleted-end";
|
||||
/** A marker class: the three kinds, deleted lines below the last line, and staged lines. */
|
||||
type MarkerClass = LineChangeKind | "deleted-end" | "staged";
|
||||
|
||||
/** The tooltip of each marker class, from the catalog. */
|
||||
const TITLES: Record<MarkerClass, () => string> = {
|
||||
|
|
@ -97,6 +99,7 @@ const TITLES: Record<MarkerClass, () => string> = {
|
|||
modified: () => t("editor.gitGutter.modified"),
|
||||
deleted: () => t("editor.gitGutter.deleted"),
|
||||
"deleted-end": () => t("editor.gitGutter.deleted"),
|
||||
staged: () => t("editor.gitGutter.staged"),
|
||||
};
|
||||
|
||||
/** One gutter marker; equal markers share their DOM. */
|
||||
|
|
@ -134,6 +137,7 @@ const MARKERS: Record<MarkerClass, GitMarker> = {
|
|||
modified: new GitMarker("modified"),
|
||||
deleted: new GitMarker("deleted"),
|
||||
"deleted-end": new GitMarker("deleted-end"),
|
||||
staged: new GitMarker("staged"),
|
||||
};
|
||||
|
||||
/**
|
||||
|
|
@ -170,9 +174,53 @@ export function buildMarkers(doc: Text, ranges: readonly LineChange[]): RangeSet
|
|||
return builder.finish();
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the staged markers: every line of a staged chunk (the line after a
|
||||
* deletion point) that no unstaged chunk covers.
|
||||
*
|
||||
* @param doc - the document the chunks were computed for.
|
||||
* @param list - the chunks.
|
||||
*/
|
||||
export function buildStagedMarkers(doc: Text, list: ChunkList): RangeSet<GutterMarker> {
|
||||
const lines = new Set<number>();
|
||||
for (const chunk of list.staged) {
|
||||
const point = chunk.startLine === chunk.endLine;
|
||||
const first = point ? Math.min(chunk.startLine, doc.lines - 1) : chunk.startLine;
|
||||
const last = point ? first + 1 : Math.min(chunk.endLine, doc.lines);
|
||||
for (let line = Math.max(first, 0); line < last; line += 1) {
|
||||
if (!list.unstaged.some((c) => covers(c, line, doc.lines))) {
|
||||
lines.add(line);
|
||||
}
|
||||
}
|
||||
}
|
||||
const builder = new RangeSetBuilder<GutterMarker>();
|
||||
for (const line of [...lines].sort((a, b) => a - b)) {
|
||||
const from = doc.line(line + 1).from;
|
||||
builder.add(from, from, MARKERS.staged);
|
||||
}
|
||||
return builder.finish();
|
||||
}
|
||||
|
||||
/** Replaces the markers of a state. */
|
||||
const setGitMarkers = StateEffect.define<RangeSet<GutterMarker>>();
|
||||
|
||||
/** Replaces the staged markers of a state. */
|
||||
const setStagedMarkers = StateEffect.define<RangeSet<GutterMarker>>();
|
||||
|
||||
/** The staged markers of a state, mapped through edits between answers. */
|
||||
const stagedMarkers = StateField.define<RangeSet<GutterMarker>>({
|
||||
create: () => RangeSet.empty,
|
||||
update(value, tr) {
|
||||
let next = value.map(tr.changes);
|
||||
for (const effect of tr.effects) {
|
||||
if (effect.is(setStagedMarkers)) {
|
||||
next = effect.value;
|
||||
}
|
||||
}
|
||||
return next;
|
||||
},
|
||||
});
|
||||
|
||||
/** The markers of a state, mapped through edits between answers. */
|
||||
const gitMarkers = StateField.define<RangeSet<GutterMarker>>({
|
||||
create: () => RangeSet.empty,
|
||||
|
|
@ -196,22 +244,23 @@ const gitMarkers = StateField.define<RangeSet<GutterMarker>>({
|
|||
*/
|
||||
export function gitMarkerLines(state: EditorState): Record<number, string> {
|
||||
const out: Record<number, string> = {};
|
||||
const set = state.field(gitMarkers, false);
|
||||
if (set === undefined) {
|
||||
return out;
|
||||
}
|
||||
const cursor = set.iter();
|
||||
while (cursor.value !== null) {
|
||||
if (cursor.value instanceof GitMarker) {
|
||||
out[state.doc.lineAt(cursor.from).number] = cursor.value.kind;
|
||||
for (const set of [state.field(stagedMarkers, false), state.field(gitMarkers, false)]) {
|
||||
if (set === undefined) {
|
||||
continue;
|
||||
}
|
||||
const cursor = set.iter();
|
||||
while (cursor.value !== null) {
|
||||
if (cursor.value instanceof GitMarker) {
|
||||
out[state.doc.lineAt(cursor.from).number] = cursor.value.kind;
|
||||
}
|
||||
cursor.next();
|
||||
}
|
||||
cursor.next();
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Live plugins, refreshed by {@link refreshGitGutters}. */
|
||||
const live = new Set<{ schedule(delay: number): void }>();
|
||||
const live = new Set<{ schedule(delay: number, staged?: boolean): void }>();
|
||||
|
||||
/** Asks every editor shown now to query its markers again (`gitChanged`). */
|
||||
export function refreshGitGutters(): void {
|
||||
|
|
@ -231,6 +280,7 @@ function gitGutterPlugin(buffer: AssistBuffer, transport: GitGutterTransport): E
|
|||
const life = { alive: true };
|
||||
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||
let asked = 0;
|
||||
let withStaged = true;
|
||||
|
||||
/**
|
||||
* Whether the plugin still lives and the view still shows `doc`.
|
||||
|
|
@ -244,27 +294,43 @@ function gitGutterPlugin(buffer: AssistBuffer, transport: GitGutterTransport): E
|
|||
/** Queries the markers for the current document and applies them. */
|
||||
async function run(): Promise<void> {
|
||||
const doc = view.state.doc;
|
||||
const staged = withStaged;
|
||||
withStaged = false;
|
||||
await buffer.idle();
|
||||
if (!current(doc)) {
|
||||
withStaged ||= staged;
|
||||
return;
|
||||
}
|
||||
asked += 1;
|
||||
const mine = asked;
|
||||
const result = await transport.query("git.lineChanges", { id: buffer.id });
|
||||
if (!current(doc) || mine !== asked || !result.ok) {
|
||||
const [result, chunks] = await Promise.all([
|
||||
transport.query("git.lineChanges", { id: buffer.id }),
|
||||
staged ? transport.query("git.chunks", { id: buffer.id }) : Promise.resolve(null),
|
||||
]);
|
||||
if (!current(doc) || mine !== asked) {
|
||||
withStaged ||= staged;
|
||||
return;
|
||||
}
|
||||
const ranges = readLineChanges(result.value);
|
||||
const effects: StateEffect<RangeSet<GutterMarker>>[] = [];
|
||||
const ranges = result.ok ? readLineChanges(result.value) : null;
|
||||
if (ranges !== null) {
|
||||
view.dispatch({ effects: setGitMarkers.of(buildMarkers(doc, ranges)) });
|
||||
effects.push(setGitMarkers.of(buildMarkers(doc, ranges)));
|
||||
}
|
||||
if (chunks !== null) {
|
||||
const list = chunks.ok ? readChunks(chunks.value) : null;
|
||||
effects.push(setStagedMarkers.of(list === null ? RangeSet.of<GutterMarker>([]) : buildStagedMarkers(doc, list)));
|
||||
}
|
||||
if (effects.length > 0) {
|
||||
view.dispatch({ effects });
|
||||
}
|
||||
}
|
||||
|
||||
const handle = {
|
||||
schedule(delay: number): void {
|
||||
schedule(delay: number, staged = true): void {
|
||||
if (!life.alive) {
|
||||
return;
|
||||
}
|
||||
withStaged ||= staged;
|
||||
if (timer !== null) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
|
|
@ -279,7 +345,7 @@ function gitGutterPlugin(buffer: AssistBuffer, transport: GitGutterTransport): E
|
|||
return {
|
||||
update(update: ViewUpdate): void {
|
||||
if (update.docChanged) {
|
||||
handle.schedule(GIT_GUTTER_DEBOUNCE_MS);
|
||||
handle.schedule(GIT_GUTTER_DEBOUNCE_MS, false);
|
||||
}
|
||||
},
|
||||
destroy(): void {
|
||||
|
|
@ -315,6 +381,13 @@ const gitGutterTheme: Extension = EditorView.theme({
|
|||
".lt-git-marker--deleted-end": {
|
||||
background: "linear-gradient(to top, var(--lt-vcs-deleted) 0 3px, transparent 3px)",
|
||||
},
|
||||
".lt-git-marker--staged": {
|
||||
boxSizing: "border-box",
|
||||
border: "1px solid var(--lt-vcs-modified)",
|
||||
},
|
||||
".lt-git-gutter .cm-gutterElement:has(.lt-git-marker)": {
|
||||
cursor: "pointer",
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
|
|
@ -333,12 +406,24 @@ export function gitGutterExtensions(
|
|||
}
|
||||
return [
|
||||
gitMarkers,
|
||||
stagedMarkers,
|
||||
gutter({
|
||||
class: "lt-git-gutter",
|
||||
markers: (view) => view.state.field(gitMarkers),
|
||||
markers: (view) => [view.state.field(stagedMarkers), view.state.field(gitMarkers)],
|
||||
initialSpacer: () => MARKERS.added,
|
||||
domEventHandlers: {
|
||||
click: (view, block) => {
|
||||
const line = view.state.doc.lineAt(block.from).number;
|
||||
if (gitMarkerLines(view.state)[line] === undefined) {
|
||||
return false;
|
||||
}
|
||||
void openChunkPopup(view, line - 1);
|
||||
return true;
|
||||
},
|
||||
},
|
||||
}),
|
||||
gitGutterTheme,
|
||||
gitGutterPlugin(buffer, transport),
|
||||
chunkPopupExtensions(buffer, transport),
|
||||
];
|
||||
}
|
||||
|
|
|
|||
|
|
@ -36,7 +36,8 @@
|
|||
* `vcs.showCommit {hash}` (M4.7) shows the Log with that commit selected
|
||||
* (a click on a blame annotation); `vcs.toggleBlame {path?}` shows or
|
||||
* hides the blame annotations of a file (default: the active tab's, once
|
||||
* tabs for buffers just opened are adopted). No
|
||||
* tabs for buffers just opened are adopted). `vcs.showChunk` (C8 C3)
|
||||
* opens the chunk popup at the caret line of the editor shown last. No
|
||||
* default shortcuts.
|
||||
*
|
||||
* A slim header bar along the top (M3.9) holds the app menu
|
||||
|
|
@ -60,6 +61,8 @@ import LogToolWindow from "../vcs/log/LogToolWindow.vue";
|
|||
import { SHOW_HISTORY_COMMAND, SHOW_LOG_COMMAND, useLogStore } from "../vcs/log/log";
|
||||
import StashDialog from "../vcs/stash/StashDialog.vue";
|
||||
import { SHOW_COMMIT_COMMAND, TOGGLE_BLAME_COMMAND, setCommitOpener, toggleBlame } from "../editor/blame";
|
||||
import { SHOW_CHUNK_COMMAND, openChunkPopup } from "../editor/chunkPopup";
|
||||
import { activeView } from "../editor/nav/navExtension";
|
||||
import { useEditorStore } from "../../stores/editor";
|
||||
import { useProjectStore } from "../../stores/project";
|
||||
import ProjectToolWindow from "../project/ProjectToolWindow.vue";
|
||||
|
|
@ -261,6 +264,15 @@ onMounted(() => {
|
|||
},
|
||||
enabled: () => project.root !== null,
|
||||
}),
|
||||
commands.provide(SHOW_CHUNK_COMMAND, {
|
||||
run: async () => {
|
||||
const view = activeView();
|
||||
if (view) {
|
||||
await openChunkPopup(view, view.state.doc.lineAt(view.state.selection.main.head).number - 1);
|
||||
}
|
||||
},
|
||||
enabled: () => project.root !== null && activeView() !== null,
|
||||
}),
|
||||
commands.provide("view.toggleStructure", {
|
||||
run: () => {
|
||||
toggleLeft("structure");
|
||||
|
|
|
|||
|
|
@ -446,6 +446,12 @@ watch(
|
|||
:class="`changes__name--${stateColor(row.state)}`"
|
||||
>{{ baseName(row.file.path) }}</span>
|
||||
<span class="changes__dir">{{ detail(row) }}</span>
|
||||
<span
|
||||
v-if="row.partial"
|
||||
class="changes__partial"
|
||||
:title="t('vcs.changes.partlyStaged')"
|
||||
data-test="changes-row-partial"
|
||||
>{{ t("vcs.changes.partly") }}</span>
|
||||
<span class="changes__state">{{ stateLabel(row.state) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
|
@ -637,6 +643,20 @@ watch(
|
|||
color: var(--lt-fg-muted);
|
||||
}
|
||||
|
||||
.changes__partial {
|
||||
flex: none;
|
||||
margin-left: auto;
|
||||
padding: 0 4px;
|
||||
color: var(--lt-fg-muted);
|
||||
border: 1px solid var(--lt-border);
|
||||
border-radius: 3px;
|
||||
font-size: var(--lt-font-size-small);
|
||||
}
|
||||
|
||||
.changes__partial + .changes__state {
|
||||
margin-left: 6px;
|
||||
}
|
||||
|
||||
.changes__row--selected .changes__dir,
|
||||
.changes__row--selected .changes__state {
|
||||
color: var(--lt-fg);
|
||||
|
|
|
|||
|
|
@ -10,7 +10,8 @@
|
|||
* - **Groups:** a file is Staged when its index side changed, in Changes
|
||||
* when its work tree side changed or it is conflicted, and Untracked when
|
||||
* git does not track it. A partly staged file is in both Staged and
|
||||
* Changes. Ignored files are not listed by the backend.
|
||||
* Changes, and both rows say so (`partial`, C8 C3: chunks staged from
|
||||
* the gutter or the diff). Ignored files are not listed by the backend.
|
||||
* - **Ignoring (C7 A3):** `git.ignore {paths}` for untracked rows adds a
|
||||
* literal pattern per file to the root `.gitignore`, then re-reads.
|
||||
* - **Staging:** `git.stage` / `git.unstage` per file or per group.
|
||||
|
|
@ -69,6 +70,8 @@ export interface ChangeRow {
|
|||
file: ChangedFile;
|
||||
/** The state shown: the index side in Staged, the work tree side otherwise. */
|
||||
state: FileState;
|
||||
/** Whether the file is partly staged, so it has a row in Staged and in Changes too. */
|
||||
partial: boolean;
|
||||
}
|
||||
|
||||
/** What the window shows above the groups. */
|
||||
|
|
@ -92,7 +95,8 @@ function changed(state: FileState): boolean {
|
|||
export function groupFiles(files: ChangedFile[]): Record<GroupId, ChangeRow[]> {
|
||||
const out: Record<GroupId, ChangeRow[]> = { staged: [], changes: [], untracked: [] };
|
||||
const add = (group: GroupId, file: ChangedFile, state: FileState): void => {
|
||||
out[group].push({ key: `${group}:${file.path}`, group, file, state });
|
||||
const partial = state !== "untracked" && state !== "conflicted" && changed(file.index) && changed(file.worktree);
|
||||
out[group].push({ key: `${group}:${file.path}`, group, file, state, partial });
|
||||
};
|
||||
for (const file of files) {
|
||||
if (file.index === "untracked" || file.worktree === "untracked") {
|
||||
|
|
|
|||
|
|
@ -18,6 +18,10 @@
|
|||
* (`gitChanged` after staging).
|
||||
* - **Colours:** only `--lt-*` tokens; changed lines are tinted with
|
||||
* `--lt-vcs-deleted` (left) and `--lt-vcs-added` (right).
|
||||
* - **Chunk actions (C8 C3):** the right side is an ordinary editor of the
|
||||
* buffer, so its Git gutter shows unstaged and staged markers; a click
|
||||
* opens the chunk popup with Stage, Unstage and Revert. A hint line says
|
||||
* so.
|
||||
* - **Navigation:** a navigator over the merge view is registered for
|
||||
* `vcs.nextChange` / `vcs.previousChange` (`navigation.ts`): the focused
|
||||
* side, else the working copy, moves to the next or previous chunk.
|
||||
|
|
@ -270,6 +274,13 @@ onBeforeUnmount(() => {
|
|||
>
|
||||
{{ caption }}
|
||||
</div>
|
||||
<div
|
||||
v-if="diff.activeTab && !diff.activeTab.commit && diff.activeContent?.phase === 'ready' && diff.activeContent.bufferId !== null"
|
||||
class="diff-view__hint"
|
||||
data-test="diff-chunk-hint"
|
||||
>
|
||||
{{ t("vcs.diff.chunkHint") }}
|
||||
</div>
|
||||
<div
|
||||
v-if="notice"
|
||||
class="diff-view__notice"
|
||||
|
|
@ -314,6 +325,15 @@ onBeforeUnmount(() => {
|
|||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.diff-view__hint {
|
||||
flex-shrink: 0;
|
||||
padding: 2px 12px;
|
||||
color: var(--lt-fg-muted);
|
||||
background: var(--lt-bg);
|
||||
border-bottom: 1px solid var(--lt-border);
|
||||
font-size: var(--lt-font-size-small);
|
||||
}
|
||||
|
||||
.diff-view__notice {
|
||||
flex-shrink: 0;
|
||||
padding: 4px 12px;
|
||||
|
|
|
|||
|
|
@ -35,6 +35,7 @@
|
|||
"command.vcs.push": "Push",
|
||||
"command.vcs.refresh": "Refresh Changes",
|
||||
"command.vcs.resolveConflicts": "Resolve Conflicts…",
|
||||
"command.vcs.showChunk": "Show Changed Chunk at Caret",
|
||||
"command.vcs.showCommit": "Show Commit in Log",
|
||||
"command.vcs.showDiff": "Show Diff",
|
||||
"command.vcs.showHistory": "Show History",
|
||||
|
|
@ -87,10 +88,24 @@
|
|||
"editor.blame.clickHint": "Click to show this commit in the Log",
|
||||
"editor.blame.notCommitted": "Not committed yet",
|
||||
"editor.blame.notCommittedHint": "This line has changes that are not committed.",
|
||||
"editor.chunk.close": "Close",
|
||||
"editor.chunk.failed": "That did not work: {reason}",
|
||||
"editor.chunk.loading": "Reading the change…",
|
||||
"editor.chunk.next": "Next",
|
||||
"editor.chunk.none": "No change on this line any more.",
|
||||
"editor.chunk.previous": "Previous",
|
||||
"editor.chunk.revert": "Revert",
|
||||
"editor.chunk.stage": "Stage",
|
||||
"editor.chunk.staged": "Staged",
|
||||
"editor.chunk.title": "Changed chunk",
|
||||
"editor.chunk.truncated": "More lines are not shown.",
|
||||
"editor.chunk.unstage": "Unstage",
|
||||
"editor.chunk.unstaged": "Not staged",
|
||||
"editor.closePrompt.question": "Save changes to {name} before closing?",
|
||||
"editor.gitGutter.added": "Added since the staged version",
|
||||
"editor.gitGutter.deleted": "Lines deleted here since the staged version",
|
||||
"editor.gitGutter.modified": "Changed since the staged version",
|
||||
"editor.gitGutter.staged": "Staged change (click for the chunk)",
|
||||
"editor.notice.changedOnDisk": "{name} changed on disk. Your unsaved changes are kept; saving overwrites the file.",
|
||||
"editor.notice.removedOnDisk": "{name} was deleted on disk. Your text is kept; saving writes it again.",
|
||||
"editor.reveal.invalidParams": "editor.reveal needs a path (string), line and column (numbers)",
|
||||
|
|
@ -362,6 +377,8 @@
|
|||
"vcs.changes.noCommits": "no commits yet",
|
||||
"vcs.changes.noProject": "Open a project to see its changes",
|
||||
"vcs.changes.noRepo": "This project is not in a Git repository",
|
||||
"vcs.changes.partly": "partly staged",
|
||||
"vcs.changes.partlyStaged": "Partly staged: some changes of this file are staged, others are not",
|
||||
"vcs.changes.renamedFrom": "from {path}",
|
||||
"vcs.changes.repoError": "The Git repository cannot be read: {reason}",
|
||||
"vcs.changes.stageFile": "Stage {path}",
|
||||
|
|
@ -393,6 +410,7 @@
|
|||
"vcs.diff.captionCommit": "{path}: before (left) and after (right) commit {hash}",
|
||||
"vcs.diff.captionHead": "{path}: last commit (left) and working copy (right)",
|
||||
"vcs.diff.captionIndex": "{path}: staged version (left) and working copy (right)",
|
||||
"vcs.diff.chunkHint": "Click a change marker in the gutter to stage, unstage or revert that chunk.",
|
||||
"vcs.diff.closeTab": "Close the diff of {name}",
|
||||
"vcs.diff.failed": "The diff cannot be shown: {reason}",
|
||||
"vcs.diff.invalidParams": "vcs.showDiff takes {path?: string, staged?: boolean}",
|
||||
|
|
|
|||
297
ui/tests/editor/chunkPopup.test.ts
Normal file
297
ui/tests/editor/chunkPopup.test.ts
Normal file
|
|
@ -0,0 +1,297 @@
|
|||
/**
|
||||
* Tests of chunk staging in the editor (C8 C3, `chunkPopup.ts` and the
|
||||
* staged markers of `gitGutter.ts`): reading `git.chunks`, which chunk a
|
||||
* line belongs to, previous/next, staged markers (read on show and refresh,
|
||||
* not while typing), and the popup: opening from a marker click, its
|
||||
* sections, Stage and Unstage with the token, Revert as an undoable edit,
|
||||
* refusals shown in place, Next, Escape and closing on an edit.
|
||||
*/
|
||||
import { EditorState, Text } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
chunkPopupLine,
|
||||
chunksAt,
|
||||
closeChunkPopup,
|
||||
covers,
|
||||
neighbourLine,
|
||||
openChunkPopup,
|
||||
readChunks,
|
||||
type ChunkList,
|
||||
type ChunkResult,
|
||||
type ChunkTransport,
|
||||
} from "../../src/components/editor/chunkPopup";
|
||||
import { buildStagedMarkers, gitGutterExtensions, gitMarkerLines, refreshGitGutters } from "../../src/components/editor/gitGutter";
|
||||
import type { JsonValue } from "../../src/ipc";
|
||||
|
||||
/** Views created by a test, destroyed after it. */
|
||||
let views: EditorView[] = [];
|
||||
|
||||
/** A raw chunk of `git.chunks`. */
|
||||
function raw(kind: string, startLine: number, endLine: number, removed: string[] = [], added: string[] = []): Record<string, unknown> {
|
||||
return { kind, startLine, endLine, oldStart: 0, oldEnd: 0, newStart: 0, newEnd: 0, removed, added, truncated: false };
|
||||
}
|
||||
|
||||
/** A fake engine for the gutter and the popup. */
|
||||
class FakeEngine implements ChunkTransport {
|
||||
/** Every command with its params, in order. */
|
||||
readonly calls: { command: string; params: JsonValue }[] = [];
|
||||
/** What `git.chunks` answers. */
|
||||
chunks: unknown = { token: "t1", unstaged: [], staged: [] };
|
||||
/** Commands that fail, with their message. */
|
||||
failing = new Map<string, string>();
|
||||
/** What `git.lineChanges` answers. */
|
||||
ranges: unknown[] = [];
|
||||
/** Undo windows opened and how they ended. */
|
||||
readonly undo: (number | null)[] = [];
|
||||
|
||||
query(command: string, params: JsonValue): Promise<ChunkResult> {
|
||||
this.calls.push({ command, params });
|
||||
const message = this.failing.get(command);
|
||||
if (message !== undefined) {
|
||||
return Promise.resolve({ ok: false, error: { message } });
|
||||
}
|
||||
if (command === "git.lineChanges") {
|
||||
return Promise.resolve({ ok: true, value: { ranges: this.ranges, version: 1 } });
|
||||
}
|
||||
if (command === "git.chunks") {
|
||||
return Promise.resolve({ ok: true, value: this.chunks });
|
||||
}
|
||||
if (command === "git.revertChunk") {
|
||||
return Promise.resolve({ ok: true, value: { id: 7, version: 9, dirty: true } });
|
||||
}
|
||||
return Promise.resolve({ ok: true, value: {} });
|
||||
}
|
||||
|
||||
undoable(): { end(version: number | null): void } {
|
||||
return {
|
||||
end: (version) => {
|
||||
this.undo.push(version);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** The commands run, without the gutter's queries. */
|
||||
actions(): string[] {
|
||||
return this.calls.map((c) => c.command).filter((c) => c !== "git.lineChanges");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A view of buffer 7 showing `doc`.
|
||||
*
|
||||
* @param doc - the text.
|
||||
* @param engine - the fake engine.
|
||||
*/
|
||||
function viewOf(doc: string, engine: FakeEngine): EditorView {
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({ doc, extensions: gitGutterExtensions({ id: 7, idle: () => Promise.resolve() }, engine) }),
|
||||
parent: document.body,
|
||||
});
|
||||
views.push(view);
|
||||
return view;
|
||||
}
|
||||
|
||||
/** Lets timers and promises run. */
|
||||
async function flush(ms = 0): Promise<void> {
|
||||
await vi.advanceTimersByTimeAsync(ms);
|
||||
for (let i = 0; i < 8; i += 1) {
|
||||
await Promise.resolve();
|
||||
}
|
||||
}
|
||||
|
||||
/** The popup element, if shown. */
|
||||
function popup(view: EditorView): HTMLElement | null {
|
||||
return view.dom.querySelector<HTMLElement>("[data-test=chunk-popup]");
|
||||
}
|
||||
|
||||
/**
|
||||
* Clicks a popup button.
|
||||
*
|
||||
* @param view - the editor.
|
||||
* @param test - the button's `data-test`.
|
||||
*/
|
||||
function click(view: EditorView, test: string): void {
|
||||
const element = view.dom.querySelector<HTMLButtonElement>(`[data-test=${test}]`);
|
||||
expect(element, test).not.toBeNull();
|
||||
element?.click();
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
for (const view of views) {
|
||||
view.destroy();
|
||||
}
|
||||
views = [];
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe("reading and finding chunks", () => {
|
||||
it("checks every field and keeps positions", () => {
|
||||
const list = readChunks({
|
||||
token: "abc",
|
||||
unstaged: [raw("moved", 0, 1), raw("added", 2, 4, [], ["x", 3 as unknown as string]), null],
|
||||
staged: [raw("deleted", 5, 5, ["gone"])],
|
||||
});
|
||||
expect(list?.token).toBe("abc");
|
||||
expect(list?.unstaged).toEqual([{ index: 1, kind: "added", startLine: 2, endLine: 4, removed: [], added: ["x"], truncated: false }]);
|
||||
expect(list?.staged[0]?.index).toBe(0);
|
||||
expect(readChunks({ unstaged: [] })).toBeNull();
|
||||
expect(readChunks(null)).toBeNull();
|
||||
});
|
||||
|
||||
it("matches lines, deletion points and the end", () => {
|
||||
const list = readChunks({ token: "t", unstaged: [raw("modified", 1, 3), raw("deleted", 5, 5), raw("deleted", 8, 8)], staged: [] }) as ChunkList;
|
||||
const [first, point, end] = list.unstaged;
|
||||
expect(first && covers(first, 1, 8)).toBe(true);
|
||||
expect(first && covers(first, 3, 8)).toBe(false);
|
||||
expect(point && covers(point, 5, 8)).toBe(true);
|
||||
expect(point && covers(point, 4, 8)).toBe(false);
|
||||
expect(end && covers(end, 7, 8)).toBe(true);
|
||||
expect(chunksAt(list, 2, 8).unstaged).toBe(first);
|
||||
expect(chunksAt(list, 0, 8)).toEqual({ unstaged: null, staged: null });
|
||||
});
|
||||
|
||||
it("finds the previous and next chunk, wrapping", () => {
|
||||
const list = readChunks({ token: "t", unstaged: [raw("added", 2, 3), raw("modified", 6, 7)], staged: [raw("modified", 4, 5)] }) as ChunkList;
|
||||
expect(neighbourLine(list, 2, 1, 10)).toBe(4);
|
||||
expect(neighbourLine(list, 6, 1, 10)).toBe(2);
|
||||
expect(neighbourLine(list, 2, -1, 10)).toBe(6);
|
||||
expect(neighbourLine({ token: "t", unstaged: [], staged: [] }, 0, 1, 10)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("staged markers", () => {
|
||||
it("marks staged lines no unstaged chunk covers", () => {
|
||||
const doc = Text.of(["a", "b", "c", "d"]);
|
||||
const list = readChunks({ token: "t", unstaged: [raw("modified", 1, 2)], staged: [raw("modified", 0, 3), raw("deleted", 4, 4)] }) as ChunkList;
|
||||
const set = buildStagedMarkers(doc, list);
|
||||
const lines: number[] = [];
|
||||
const cursor = set.iter();
|
||||
while (cursor.value !== null) {
|
||||
lines.push(doc.lineAt(cursor.from).number);
|
||||
cursor.next();
|
||||
}
|
||||
expect(lines).toEqual([1, 3, 4]);
|
||||
});
|
||||
|
||||
it("are read when shown and on refresh, not while typing", async () => {
|
||||
const engine = new FakeEngine();
|
||||
engine.chunks = { token: "t", unstaged: [], staged: [raw("modified", 1, 2)] };
|
||||
const view = viewOf("a\nb\nc\n", engine);
|
||||
await flush();
|
||||
expect(gitMarkerLines(view.state)).toEqual({ 2: "staged" });
|
||||
const asked = () => engine.calls.filter((c) => c.command === "git.chunks").length;
|
||||
expect(asked()).toBe(1);
|
||||
view.dispatch({ changes: { from: 0, insert: "x\n" } });
|
||||
await flush(500);
|
||||
expect(asked()).toBe(1);
|
||||
expect(gitMarkerLines(view.state)).toEqual({ 3: "staged" });
|
||||
refreshGitGutters();
|
||||
await flush();
|
||||
expect(asked()).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("the chunk popup", () => {
|
||||
it("opens from a marker click and shows both sections", async () => {
|
||||
const engine = new FakeEngine();
|
||||
engine.chunks = {
|
||||
token: "t1",
|
||||
unstaged: [raw("modified", 0, 1, ["b"], ["B"])],
|
||||
staged: [raw("modified", 0, 1, ["old"], ["b"])],
|
||||
};
|
||||
engine.ranges = [{ kind: "modified", startLine: 0, endLine: 1 }];
|
||||
const view = viewOf("B\nc\n", engine);
|
||||
await flush();
|
||||
const marker = view.dom.querySelector<HTMLElement>(".lt-git-gutter .lt-git-marker");
|
||||
expect(marker).not.toBeNull();
|
||||
marker?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
await flush();
|
||||
expect(chunkPopupLine(view)).toBe(0);
|
||||
const dom = popup(view);
|
||||
expect(dom?.querySelector("[data-test=chunk-unstaged]")?.textContent).toContain("- b");
|
||||
expect(dom?.querySelector("[data-test=chunk-unstaged]")?.textContent).toContain("+ B");
|
||||
expect(dom?.querySelector("[data-test=chunk-staged]")?.textContent).toContain("- old");
|
||||
});
|
||||
|
||||
it("stages with the token, re-reads and stays open", async () => {
|
||||
const engine = new FakeEngine();
|
||||
engine.chunks = { token: "t1", unstaged: [raw("added", 0, 1), raw("modified", 2, 3, ["c"], ["C"])], staged: [] };
|
||||
const view = viewOf("x\nb\nC\n", engine);
|
||||
await flush();
|
||||
await openChunkPopup(view, 2);
|
||||
await flush();
|
||||
engine.chunks = { token: "t2", unstaged: [raw("added", 0, 1)], staged: [raw("modified", 2, 3, ["c"], ["C"])] };
|
||||
click(view, "chunk-stage");
|
||||
await flush();
|
||||
expect(engine.calls.find((c) => c.command === "git.stageChunk")?.params).toEqual({ id: 7, index: 1, token: "t1" });
|
||||
expect(chunkPopupLine(view)).toBe(2);
|
||||
expect(popup(view)?.querySelector("[data-test=chunk-staged]")).not.toBeNull();
|
||||
click(view, "chunk-unstage");
|
||||
await flush();
|
||||
expect(engine.calls.find((c) => c.command === "git.unstageChunk")?.params).toEqual({ id: 7, index: 0, token: "t2" });
|
||||
});
|
||||
|
||||
it("reverts inside an undo window and closes", async () => {
|
||||
const engine = new FakeEngine();
|
||||
engine.chunks = { token: "t1", unstaged: [raw("modified", 0, 1, ["a"], ["A"])], staged: [] };
|
||||
const view = viewOf("A\n", engine);
|
||||
await flush();
|
||||
await openChunkPopup(view, 0);
|
||||
await flush();
|
||||
click(view, "chunk-revert");
|
||||
await flush();
|
||||
expect(engine.calls.find((c) => c.command === "git.revertChunk")?.params).toEqual({ id: 7, index: 0, token: "t1" });
|
||||
expect(engine.undo).toEqual([9]);
|
||||
expect(chunkPopupLine(view)).toBeNull();
|
||||
});
|
||||
|
||||
it("shows a refusal in place", async () => {
|
||||
const engine = new FakeEngine();
|
||||
engine.chunks = { token: "t1", unstaged: [raw("modified", 0, 1, ["a"], ["A"])], staged: [] };
|
||||
engine.failing.set("git.stageChunk", "the file or the index changed since the chunk was shown; look at it again");
|
||||
const view = viewOf("A\n", engine);
|
||||
await flush();
|
||||
await openChunkPopup(view, 0);
|
||||
await flush();
|
||||
click(view, "chunk-stage");
|
||||
await flush();
|
||||
expect(popup(view)?.querySelector("[data-test=chunk-error]")?.textContent).toContain("changed since");
|
||||
expect(popup(view)?.querySelector("[data-test=chunk-unstaged]")).not.toBeNull();
|
||||
});
|
||||
|
||||
it("shows why chunks cannot be read", async () => {
|
||||
const engine = new FakeEngine();
|
||||
engine.failing.set("git.chunks", "x.bin: the staged version is binary; stage the whole file");
|
||||
const view = viewOf("a\n", engine);
|
||||
await flush();
|
||||
await openChunkPopup(view, 0);
|
||||
await flush();
|
||||
expect(popup(view)?.querySelector("[data-test=chunk-error]")?.textContent).toContain("binary");
|
||||
});
|
||||
|
||||
it("moves to the next chunk, closes on Escape and on an edit", async () => {
|
||||
const engine = new FakeEngine();
|
||||
engine.chunks = { token: "t1", unstaged: [raw("added", 0, 1), raw("modified", 3, 4)], staged: [] };
|
||||
const view = viewOf("a\nb\nc\nd\ne\n", engine);
|
||||
await flush();
|
||||
await openChunkPopup(view, 0);
|
||||
await flush();
|
||||
click(view, "chunk-next");
|
||||
await flush();
|
||||
expect(chunkPopupLine(view)).toBe(3);
|
||||
expect(view.state.doc.lineAt(view.state.selection.main.head).number).toBe(4);
|
||||
view.contentDOM.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
|
||||
expect(chunkPopupLine(view)).toBeNull();
|
||||
await openChunkPopup(view, 0);
|
||||
await flush();
|
||||
view.dispatch({ changes: { from: 0, insert: "z" } });
|
||||
expect(chunkPopupLine(view)).toBeNull();
|
||||
closeChunkPopup(view);
|
||||
expect(engine.actions().every((c) => c === "git.chunks")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
|
@ -38,7 +38,16 @@ class FakeEngine implements GitGutterTransport {
|
|||
/** Whether to hold answers until released. */
|
||||
hold = false;
|
||||
|
||||
/** The params of every `git.chunks` query, in order. */
|
||||
readonly chunkCalls: JsonValue[] = [];
|
||||
/** What `git.chunks` answers; null fails it. */
|
||||
chunks: unknown = null;
|
||||
|
||||
query(command: string, params: JsonValue): Promise<{ ok: true; value: unknown } | { ok: false }> {
|
||||
if (command === "git.chunks") {
|
||||
this.chunkCalls.push(params);
|
||||
return Promise.resolve(this.chunks === null ? { ok: false } : { ok: true, value: this.chunks });
|
||||
}
|
||||
expect(command).toBe("git.lineChanges");
|
||||
this.calls.push(params);
|
||||
const answer = this.answer;
|
||||
|
|
|
|||
|
|
@ -209,6 +209,8 @@ describe("reading git.status", () => {
|
|||
expect(groups.staged.map((r) => `${r.file.path}:${r.state}`)).toEqual(["a:modified", "b:added"]);
|
||||
expect(groups.changes.map((r) => `${r.file.path}:${r.state}`)).toEqual(["a:modified", "c:deleted", "d:conflicted"]);
|
||||
expect(groups.untracked.map((r) => r.file.path)).toEqual(["e"]);
|
||||
expect(groups.staged.map((r) => `${r.file.path}:${String(r.partial)}`)).toEqual(["a:true", "b:false"]);
|
||||
expect(groups.changes.map((r) => `${r.file.path}:${String(r.partial)}`)).toEqual(["a:true", "c:false", "d:false"]);
|
||||
});
|
||||
|
||||
it("unstages a staged rename with both paths", () => {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue