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