M4.7: blame annotations in the editor gutter

- crates/vcs: blame.rs (git blame --porcelain, --contents - from a
  buffer, revisions, untracked files and empty repositories give no
  lines; property-tested parser, ISO dates without a date crate)
- engine: git.blame {path, rev?} -> {lines, version} through start_with;
  an open buffer is blamed as it would be saved (line ending, BOM)
- ui: blame.ts gutter toggled per file (vcs.toggleBlame, Git menu, no
  shortcut), date + author per run, bar coloured by age from tokens,
  hover card with the full commit message, click opens the commit in
  the Log (vcs.showCommit); refreshed on edits and gitChanged
- docs: architecture "Blame (M4.7)"

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-30 17:52:44 +01:00
parent dc4a00ea0b
commit 2f758d76b9
18 changed files with 2003 additions and 3 deletions

View file

@ -0,0 +1,321 @@
/**
* Tests of the blame annotations (M4.7, `blame.ts`): reading `git.blame`,
* age levels, building annotations (runs, uncommitted lines, clamping),
* the per-file toggle, the query when shown, the debounce after edits,
* dropping answers for an old document, `refreshBlame` and `clearBlame`,
* annotations mapped through edits, the hover card with the full message,
* a click opening the commit, the commands, and colours from tokens only.
*/
import { EditorState, Text } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
BLAME_DEBOUNCE_MS,
BLAME_HOVER_MS,
SHOW_COMMIT_COMMAND,
TOGGLE_BLAME_COMMAND,
ageLevel,
blameExtensions,
blameMarkerLines,
buildBlameMarkers,
clearBlame,
isBlameShown,
isUncommitted,
readBlame,
refreshBlame,
setBlameShown,
shortDate,
toggleBlame,
type BlameLine,
type BlameTransport,
} from "../../src/components/editor/blame";
import { UI_COMMANDS } from "../../src/commands/uiCommands";
import type { JsonValue } from "../../src/ipc";
const A = "a".repeat(40);
const B = "b".repeat(40);
const ZERO = "0".repeat(40);
const NOW = Date.parse("2026-10-29T12:00:00Z");
/** Views created by a test, destroyed after it. */
let views: EditorView[] = [];
/** A blame line. */
function line(hash: string, date = "2026-10-29T10:00:00+01:00", author = "Ann", summary = "Subject"): BlameLine {
return { hash, author, date, summary, origLine: 1 };
}
/** A fake engine answering `git.blame` and `git.showCommit`. */
class FakeEngine implements BlameTransport {
/** Every query, in order. */
readonly calls: { command: string; params: JsonValue }[] = [];
/** What `git.blame` answers. */
answer: unknown = { lines: [], version: 1 };
/** Whether queries fail. */
fail = false;
/** Commits opened. */
readonly opened: string[] = [];
query(command: string, params: JsonValue): Promise<{ ok: true; value: unknown } | { ok: false }> {
this.calls.push({ command, params });
if (this.fail) {
return Promise.resolve({ ok: false });
}
if (command === "git.showCommit") {
return Promise.resolve({ ok: true, value: { message: "Subject\n\nThe full body." } });
}
expect(command).toBe("git.blame");
return Promise.resolve({ ok: true, value: this.answer });
}
openCommit(hash: string): void {
this.opened.push(hash);
}
/** The `git.blame` queries. */
blames(): JsonValue[] {
return this.calls.filter((c) => c.command === "git.blame").map((c) => c.params);
}
}
/**
* A view of `src/a.php` (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: blameExtensions("src/a.php", { id: 7, idle: () => Promise.resolve() }, engine),
}),
parent: document.body,
});
views.push(view);
return view;
}
/** Hashes of the annotations a view shows, by 1-based line. */
function hashes(view: EditorView): Record<number, string> {
const out: Record<number, string> = {};
for (const [number, marker] of Object.entries(blameMarkerLines(view.state))) {
out[Number(number)] = marker.hash;
}
return out;
}
/** Lets timers and promises run. */
async function flush(ms = 0): Promise<void> {
await vi.advanceTimersByTimeAsync(ms);
for (let i = 0; i < 5; i += 1) {
await Promise.resolve();
}
}
beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime(NOW);
});
afterEach(() => {
for (const view of views) {
view.destroy();
}
views = [];
clearBlame();
vi.useRealTimers();
});
describe("reading", () => {
it("keeps line positions and drops malformed entries", () => {
expect(
readBlame({
lines: [line(A), { hash: "nothex!", author: "x", date: "d" }, null, { hash: B, author: "Bo", date: "d", origLine: -2 }],
}),
).toEqual([line(A), null, null, { hash: B, author: "Bo", date: "d", summary: "", origLine: 0 }]);
expect(readBlame({})).toBeNull();
expect(readBlame("x")).toBeNull();
});
it("knows uncommitted hashes, ages and short dates", () => {
expect(isUncommitted(ZERO)).toBe(true);
expect(isUncommitted(A)).toBe(false);
expect(isUncommitted("")).toBe(false);
expect(ageLevel("2026-10-29T08:00:00Z", NOW)).toBe(0);
expect(ageLevel("2026-10-25T08:00:00Z", NOW)).toBe(1);
expect(ageLevel("2026-10-10T08:00:00Z", NOW)).toBe(2);
expect(ageLevel("2026-03-01T08:00:00Z", NOW)).toBe(3);
expect(ageLevel("2020-01-01T08:00:00Z", NOW)).toBe(4);
expect(ageLevel("not a date", NOW)).toBe(4);
expect(ageLevel("2027-01-01T00:00:00Z", NOW)).toBe(0);
expect(shortDate("2026-10-29T12:00:00")).toBe("2026-10-29");
expect(shortDate("garbage")).toBe("garbage");
});
});
describe("buildBlameMarkers", () => {
it("shows text on the first line of each run and clamps to the document", () => {
const doc = Text.of(["a", "b", "c", "d"]);
const set = buildBlameMarkers(doc, [line(A), line(A), null, line(A), line(ZERO), line(B)], NOW);
const out: Record<number, [boolean, number | string]> = {};
const cursor = set.iter();
while (cursor.value !== null) {
const marker = cursor.value as unknown as { first: boolean; level: number | string };
out[doc.lineAt(cursor.from).number] = [marker.first, marker.level];
cursor.next();
}
expect(out).toEqual({ 1: [true, 0], 2: [false, 0], 4: [true, 0] });
const withNew = buildBlameMarkers(Text.of(["x", "y"]), [line(A), line(ZERO)], NOW);
const levels: (number | string)[] = [];
withNew.between(0, 3, (_f, _t, m) => {
levels.push((m as unknown as { level: number | string }).level);
});
expect(levels).toEqual([0, "new"]);
});
it("renders date and author, or a not-committed label", () => {
const view = viewOf("a\nb\nc", new FakeEngine());
const doc = view.state.doc;
const set = buildBlameMarkers(doc, [line(A, "2026-10-29T10:00:00", "Ann"), line(A), line(ZERO)], NOW);
const texts: string[] = [];
set.between(0, doc.length, (_f, _t, marker) => {
texts.push((marker.toDOM?.(view) as HTMLElement).textContent);
});
expect(texts).toEqual(["2026-10-29 Ann", "", "Not committed yet"]);
});
});
describe("the gutter", () => {
it("queries only while the file's annotations are shown", async () => {
const engine = new FakeEngine();
engine.answer = { lines: [line(A), line(B)], version: 1 };
const view = viewOf("x\ny", engine);
await flush();
expect(engine.blames()).toEqual([]);
expect(isBlameShown("src/a.php")).toBe(false);
expect(toggleBlame("src/a.php")).toBe(true);
await flush();
expect(engine.blames()).toEqual([{ path: "src/a.php" }]);
expect(hashes(view)).toEqual({ 1: A, 2: B });
expect(view.dom.querySelectorAll("[data-test=blame-marker]")).toHaveLength(2);
setBlameShown("src/other.php", true);
await flush();
expect(engine.blames()).toHaveLength(1);
expect(toggleBlame("src/a.php")).toBe(false);
await flush();
expect(hashes(view)).toEqual({});
expect(engine.blames()).toHaveLength(1);
});
it("debounces edits, maps annotations through them and drops stale answers", async () => {
const engine = new FakeEngine();
engine.answer = { lines: [line(A), line(B)], version: 1 };
setBlameShown("src/a.php", true);
const view = viewOf("x\ny", engine);
await flush();
expect(hashes(view)).toEqual({ 1: A, 2: B });
view.dispatch({ changes: { from: 0, insert: "new\n" } });
expect(hashes(view)).toEqual({ 2: A, 3: B });
await flush(BLAME_DEBOUNCE_MS - 1);
expect(engine.blames()).toHaveLength(1);
engine.answer = { lines: [line(ZERO), line(A), line(B)], version: 2 };
await flush(1);
expect(engine.blames()).toHaveLength(2);
expect(hashes(view)).toEqual({ 1: ZERO, 2: A, 3: B });
// An answer for a document that changed meanwhile is dropped.
let release: () => void = () => undefined;
const original = engine.query.bind(engine);
engine.query = (command, params) =>
new Promise((resolve) => {
release = () => {
void original(command, params).then(resolve);
};
});
refreshBlame();
await flush();
view.dispatch({ changes: { from: 0, insert: "z" } });
engine.answer = { lines: [line(B), line(B), line(B)], version: 3 };
release();
await flush();
expect(hashes(view)).toEqual({ 1: ZERO, 2: A, 3: B });
});
it("keeps annotations when a query fails and refreshes on gitChanged", async () => {
const engine = new FakeEngine();
engine.answer = { lines: [line(A)], version: 1 };
setBlameShown("src/a.php", true);
const view = viewOf("x", engine);
await flush();
engine.fail = true;
refreshBlame();
await flush();
expect(engine.blames()).toHaveLength(2);
expect(hashes(view)).toEqual({ 1: A });
clearBlame();
await flush();
expect(hashes(view)).toEqual({});
expect(isBlameShown("src/a.php")).toBe(false);
refreshBlame();
await flush();
expect(engine.blames()).toHaveLength(2);
});
it("opens the commit on click, but not for uncommitted lines", async () => {
const engine = new FakeEngine();
engine.answer = { lines: [line(A), line(ZERO)], version: 1 };
setBlameShown("src/a.php", true);
const view = viewOf("x\ny", engine);
await flush();
const markers = view.dom.querySelectorAll<HTMLElement>("[data-test=blame-marker]");
markers[1]?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
markers[0]?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
expect(engine.opened).toEqual([A]);
});
it("shows a hover card with the full message after a delay", async () => {
const engine = new FakeEngine();
engine.answer = { lines: [line(A, "2026-10-29T10:00:00+01:00", "Ann", "Subject")], version: 1 };
setBlameShown("src/a.php", true);
const view = viewOf("x", engine);
await flush();
const marker = view.dom.querySelector<HTMLElement>("[data-test=blame-marker]");
marker?.dispatchEvent(new MouseEvent("mousemove", { bubbles: true }));
await flush(BLAME_HOVER_MS - 1);
expect(document.querySelector("[data-test=blame-tooltip]")).toBeNull();
await flush(1);
const card = document.querySelector("[data-test=blame-tooltip]");
expect(card?.textContent).toContain(`${A.slice(0, 8)} · Ann`);
expect(card?.textContent).toContain("The full body.");
expect(engine.calls.filter((c) => c.command === "git.showCommit")).toEqual([{ command: "git.showCommit", params: { hash: A } }]);
view.contentDOM.dispatchEvent(new MouseEvent("mouseover", { bubbles: true }));
await flush();
expect(document.querySelector("[data-test=blame-tooltip]")).toBeNull();
});
});
describe("commands", () => {
it("registers Show Commit and Annotate without default shortcuts", () => {
const specs = UI_COMMANDS.filter((c) => c.id === SHOW_COMMIT_COMMAND || c.id === TOGGLE_BLAME_COMMAND);
expect(specs.map((c) => [c.id, c.menuPath, c.defaultShortcut])).toEqual([
["vcs.showCommit", undefined, undefined],
["vcs.toggleBlame", "Git/Annotate with Git Blame", undefined],
]);
});
});
describe("colours", () => {
it("come from tokens only", () => {
const source = readFileSync(join(__dirname, "../../src/components/editor/blame.ts"), "utf8");
expect(source).not.toMatch(/#[0-9a-f]{3,8}\b|rgba?\(/i);
});
});