- 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>
297 lines
12 KiB
TypeScript
297 lines
12 KiB
TypeScript
/**
|
|
* 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);
|
|
});
|
|
});
|