Lutra/ui/tests/vcs/Log.test.ts
danny 2f758d76b9 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>
2026-10-30 18:14:55 +01:00

515 lines
20 KiB
TypeScript

/**
* Tests of the Log (M4.6): graph lanes, reading the untrusted `git.log`
* and `git.showCommit` results, ref badges, paging, filters, reloading on
* `gitChanged` when HEAD moves, commit details, the Log window (rows,
* badges, keyboard, filters, history chip), a file's diff at a commit in
* the diff viewer (both sides read-only), `vcs.showHistory` and the tree's
* context menu, and `vcs.showCommit` / `vcs.toggleBlame` from the main
* layout (M4.7). The engine is a fake behind the mocked Tauri `invoke` and
* `listen`.
*/
import { flushPromises, mount, type VueWrapper } from "@vue/test-utils";
import { createPinia, setActivePinia, type Pinia } from "pinia";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const invoke = vi.hoisted(() => vi.fn());
const listen = vi.hoisted(() => vi.fn());
vi.mock("@tauri-apps/api/core", () => ({ invoke }));
vi.mock("@tauri-apps/api/event", () => ({ listen }));
import { useCommandsStore } from "../../src/commands/store";
import { UI_COMMANDS } from "../../src/commands/uiCommands";
import { isBlameShown, SHOW_COMMIT_COMMAND, TOGGLE_BLAME_COMMAND } from "../../src/components/editor/blame";
import EditorArea from "../../src/components/editor/EditorArea.vue";
import MainLayout from "../../src/components/layout/MainLayout.vue";
import TreeContextMenu from "../../src/components/project/TreeContextMenu.vue";
import { commitDiffKey, useDiffStore } from "../../src/components/vcs/diff/diff";
import { currentMerge } from "../../src/components/vcs/diff/navigation";
import { layoutGraph, MAX_LANES } from "../../src/components/vcs/log/graph";
import {
logParams,
PAGE_SIZE,
refBadges,
SHOW_HISTORY_COMMAND,
SHOW_LOG_COMMAND,
toCommits,
toDetails,
useLogStore,
} from "../../src/components/vcs/log/log";
import LogToolWindow from "../../src/components/vcs/log/LogToolWindow.vue";
import { useNotificationsStore } from "../../src/stores/notifications";
import { useProjectStore } from "../../src/stores/project";
/** A commit of the fake history. */
interface FakeCommit {
hash: string;
parents: string[];
author: string;
email: string;
date: string;
subject: string;
refs: string[];
}
/** The fake history, newest first. */
let history: FakeCommit[];
/** What `git.showAt` answers, by `rev:path`. */
let blobs: Record<string, string>;
/** Errors to throw, by command id. */
let failures: Record<string, { code: string; message: string }>;
/** Every engine call, in order. */
let calls: { command: string; params: Record<string, unknown> }[];
/** Engine event callbacks. */
let listeners: ((event: { payload: unknown }) => void)[];
/** Pinia of the current test. */
let pinia: Pinia;
/** Mounted components. */
let mounted: VueWrapper[];
/**
* A fake commit.
*
* @param hash - its hash.
* @param parents - its parents.
* @param refs - its decorations.
*/
function fake(hash: string, parents: string[], refs: string[] = []): FakeCommit {
return { hash, parents, author: `A ${hash}`, email: `${hash}@x`, date: "2026-10-27T10:00:00+01:00", subject: `Subject ${hash}`, refs };
}
/**
* A linear history of `count` commits, newest first.
*
* @param count - how many.
*/
function linear(count: number): FakeCommit[] {
return Array.from({ length: count }, (_, i) => {
const n = count - i;
return fake(`c${String(n)}`, n > 1 ? [`c${String(n - 1)}`] : []);
});
}
/**
* Sends an engine event.
*
* @param payload - the event.
*/
async function emit(payload: unknown): Promise<void> {
for (const listener of [...listeners]) {
listener({ payload });
}
await flushPromises();
}
/**
* The fake engine.
*
* @param command - command id.
* @param p - params.
*/
function execute(command: string, p: Record<string, unknown>): Promise<unknown> {
const failure = failures[command];
if (failure) {
return Promise.reject(Object.assign(new Error(failure.message), failure));
}
switch (command) {
case "git.log": {
const query = typeof p.query === "string" ? p.query.toLowerCase() : null;
const matching = history.filter((c) => query === null || c.subject.toLowerCase().includes(query));
const skip = Number(p.skip ?? 0);
return Promise.resolve({ commits: matching.slice(skip, skip + Number(p.limit ?? 100)) });
}
case "git.showCommit": {
const commit = history.find((c) => c.hash === p.hash);
if (!commit) {
return Promise.reject(Object.assign(new Error("no such commit"), { code: "failed", message: "no such commit" }));
}
return Promise.resolve({
hash: commit.hash,
parents: commit.parents,
author: commit.author,
email: commit.email,
date: commit.date,
message: `${commit.subject}\n\nBody`,
files: [
{ path: "src/New.php", status: "renamed", origPath: "src/Old.php" },
{ path: "gone.php", status: "deleted" },
{ path: "bad", status: "exploded" },
],
truncated: false,
});
}
case "git.showAt": {
const text = blobs[`${String(p.rev)}:${String(p.path)}`];
return Promise.resolve({ text: text ?? null, binary: false, tooLarge: false });
}
default:
return Promise.resolve({});
}
}
/**
* The calls of a command.
*
* @param command - the command id.
*/
function callsOf(command: string): Record<string, unknown>[] {
return calls.filter((c) => c.command === command).map((c) => c.params);
}
/** Mounts the Log window with an open project. */
async function mountLog(): Promise<VueWrapper> {
useProjectStore(pinia).root = { path: "/p", name: "p" };
const wrapper = mount(LogToolWindow, { attachTo: document.body, global: { plugins: [pinia] } });
mounted.push(wrapper);
await flushPromises();
return wrapper;
}
beforeEach(() => {
Range.prototype.getClientRects = () => Object.assign([] as DOMRect[], { item: () => null });
Range.prototype.getBoundingClientRect = () => new DOMRect(0, 0, 0, 0);
Element.prototype.scrollIntoView = () => undefined;
pinia = createPinia();
setActivePinia(pinia);
history = [fake("m", ["a", "b"], ["HEAD -> main", "tag: v2"]), fake("b", ["r"], ["origin/feature", "origin/HEAD"]), fake("a", ["r"]), fake("r", [], ["tag: v1"])];
blobs = {};
failures = {};
calls = [];
listeners = [];
mounted = [];
invoke.mockReset();
listen.mockReset();
listen.mockImplementation((_name: string, callback: (event: { payload: unknown }) => void) => {
listeners.push(callback);
return Promise.resolve(() => {
listeners = listeners.filter((l) => l !== callback);
});
});
invoke.mockImplementation((cmd: string, args?: { command: string; params: Record<string, unknown> }) => {
if (cmd === "engine_list_commands") {
return Promise.resolve([]);
}
if ((cmd === "engine_execute" || cmd === "engine_execute_waiting") && args) {
calls.push({ command: args.command, params: args.params });
return execute(args.command, args.params);
}
return Promise.resolve(null);
});
});
afterEach(async () => {
await flushPromises();
useCommandsStore(pinia).stop();
for (const wrapper of mounted) {
wrapper.unmount();
}
document.body.innerHTML = "";
});
describe("graph", () => {
it("draws a straight line for a linear history", () => {
const { rows, lanes } = layoutGraph(linear(3));
expect(rows.map((r) => r.column)).toEqual([0, 0, 0]);
expect(rows[0]?.up).toEqual([]);
expect(rows[0]?.down).toEqual([{ from: 0, to: 0, lane: 0 }]);
expect(rows[2]?.down).toEqual([]);
expect(lanes).toEqual([]);
});
it("branches out at a merge and joins again at the fork point", () => {
const { rows } = layoutGraph(history);
expect(rows[0]).toMatchObject({ column: 0, merge: true });
expect(rows[0]?.down).toEqual([
{ from: 0, to: 0, lane: 0 },
{ from: 0, to: 1, lane: 1 },
]);
expect(rows[1]?.column).toBe(1);
expect(rows[2]?.column).toBe(0);
expect(rows[3]?.column).toBe(0);
expect(rows[3]?.up).toEqual([
{ from: 0, to: 0, lane: 0 },
{ from: 1, to: 0, lane: 1 },
]);
expect(rows[3]?.width).toBe(2);
});
it("continues across pages without redrawing", () => {
const all = layoutGraph(history).rows;
const first = layoutGraph(history.slice(0, 2));
const second = layoutGraph(history.slice(2), first.lanes);
expect([...first.rows, ...second.rows]).toEqual(all);
});
it("caps the lanes", () => {
const tips = Array.from({ length: MAX_LANES + 5 }, (_, i) => ({ hash: `t${String(i)}`, parents: [`p${String(i)}`] }));
const { rows, lanes } = layoutGraph(tips);
expect(Math.max(...rows.map((r) => r.column))).toBe(MAX_LANES - 1);
expect(lanes.length).toBeLessThanOrEqual(MAX_LANES);
});
});
describe("parsing", () => {
it("reads commits and drops malformed ones", () => {
expect(toCommits({ commits: [history[0], { hash: "x" }, null, { ...history[1], refs: [1] }] })).toEqual([history[0]]);
expect(toCommits({ commits: "no" })).toBeNull();
expect(toCommits(null)).toBeNull();
});
it("reads details and drops unknown file states", () => {
const d = toDetails({ hash: "h", parents: ["p"], author: "A", email: "e", date: "d", message: "m", files: [{ path: "a", status: "added" }, { path: "b", status: "?" }, { path: "c", status: "renamed", origPath: "o" }] });
expect(d?.files).toEqual([
{ path: "a", status: "added", origPath: null },
{ path: "c", status: "renamed", origPath: "o" },
]);
expect(toDetails({ hash: "h" })).toBeNull();
});
it("splits decorations into badges", () => {
expect(refBadges(["HEAD -> main", "origin/main", "origin/HEAD", "tag: v1", "HEAD", "dev"])).toEqual([
{ name: "HEAD", kind: "head" },
{ name: "main", kind: "branch" },
{ name: "origin/main", kind: "remote" },
{ name: "v1", kind: "tag" },
{ name: "HEAD", kind: "head" },
{ name: "dev", kind: "branch" },
]);
});
it("builds git.log params from the filters", () => {
expect(logParams({ query: " fix ", author: "", path: null }, 200)).toEqual({ skip: 200, limit: PAGE_SIZE, query: "fix" });
expect(logParams({ query: "", author: "ada", path: "a.php" }, 0)).toEqual({ skip: 0, limit: PAGE_SIZE, author: "ada", path: "a.php" });
});
});
describe("store", () => {
it("pages lazily and stops at a short page", async () => {
history = linear(PAGE_SIZE + 20);
const log = useLogStore(pinia);
await log.open();
expect(log.commits).toHaveLength(PAGE_SIZE);
expect(log.complete).toBe(false);
expect(log.selected).toBe(history[0]?.hash);
await log.loadMore();
expect(log.commits).toHaveLength(PAGE_SIZE + 20);
expect(log.rows).toHaveLength(PAGE_SIZE + 20);
expect(log.complete).toBe(true);
await log.loadMore();
expect(callsOf("git.log").map((p) => p.skip)).toEqual([0, PAGE_SIZE]);
});
it("filters by text without a graph, and drops stale answers", async () => {
const log = useLogStore(pinia);
await log.open();
const first = log.setFilters({ query: "subject b" });
const second = log.setFilters({ query: "subject a" });
await Promise.all([first, second]);
expect(log.commits.map((c) => c.hash)).toEqual(["a"]);
expect(log.graphShown).toBe(false);
expect(log.rows).toEqual([]);
});
it("reloads on gitChanged only when HEAD or the branch moved", async () => {
const log = useLogStore(pinia);
log.start();
await log.open();
await emit({ kind: "gitChanged", available: true, repo: { head: "m", branch: "main" }, filesChanged: true });
const before = callsOf("git.log").length;
await emit({ kind: "gitChanged", available: true, repo: { head: "m", branch: "main" }, filesChanged: true });
expect(callsOf("git.log")).toHaveLength(before);
history.unshift(fake("n", ["m"], ["HEAD -> main"]));
await emit({ kind: "gitChanged", available: true, repo: { head: "n", branch: "main" }, filesChanged: true });
expect(callsOf("git.log")).toHaveLength(before + 1);
expect(log.commits[0]?.hash).toBe("n");
await emit({ kind: "projectClosed" });
expect(log.commits).toEqual([]);
log.stop();
});
it("shows git's error", async () => {
failures["git.log"] = { code: "failed", message: "the project is not inside a Git repository" };
const log = useLogStore(pinia);
await log.open();
expect(log.error).toBe("the project is not inside a Git repository");
expect(log.complete).toBe(true);
});
it("reads the selected commit's details", async () => {
const log = useLogStore(pinia);
await log.open();
expect(log.details?.message).toBe("Subject m\n\nBody");
expect(log.details?.files.map((f) => f.status)).toEqual(["renamed", "deleted"]);
failures["git.showCommit"] = { code: "failed", message: "gone" };
await log.select("b");
expect(log.detailsError).toBe("gone");
});
it("shows a file's history, or warns without a file", async () => {
const log = useLogStore(pinia);
await log.runShowHistory({ path: "src/a.php" }, null);
expect(log.visible).toBe(true);
expect(log.filters.path).toBe("src/a.php");
expect(callsOf("git.log").at(-1)).toMatchObject({ path: "src/a.php" });
await log.runShowHistory({}, "b.php");
expect(log.filters.path).toBe("b.php");
await log.runShowHistory({}, null);
expect(useNotificationsStore(pinia).toasts.at(-1)?.text).toContain("history");
});
});
describe("window", () => {
it("lists commits with badges, dots and details", async () => {
const log = useLogStore(pinia);
await log.open();
const wrapper = await mountLog();
const rows = wrapper.findAll("[data-test=log-row]");
expect(rows).toHaveLength(4);
expect(rows[0]?.text()).toContain("Subject m");
expect(rows[0]?.findAll("[data-test=log-badge]").map((b) => b.text())).toEqual(["HEAD", "main", "v2"]);
expect(rows[1]?.findAll("[data-test=log-badge]").map((b) => b.text())).toEqual(["origin/feature"]);
expect(wrapper.findAll("[data-test=log-dot]")).toHaveLength(4);
expect(wrapper.find("[data-test=log-message]").text()).toBe("Subject m\n\nBody");
expect(wrapper.findAll("[data-test=log-file]").map((f) => f.text())).toEqual([
expect.stringContaining("from src/Old.php"),
expect.stringContaining("gone.php"),
]);
});
it("moves the selection with the keyboard", async () => {
const log = useLogStore(pinia);
await log.open();
const wrapper = await mountLog();
const list = wrapper.find("[data-test=log-list]");
await list.trigger("keydown", { key: "ArrowDown" });
await flushPromises();
expect(log.selected).toBe("b");
await list.trigger("keydown", { key: "End" });
await flushPromises();
expect(log.selected).toBe("r");
await list.trigger("keydown", { key: "Home" });
await flushPromises();
expect(log.selected).toBe("m");
expect(callsOf("git.showCommit").map((p) => p.hash)).toEqual(["m", "b", "r", "m"]);
});
it("applies the text filter on Enter and clears a history's path", async () => {
const log = useLogStore(pinia);
await log.showHistory("a.php");
const wrapper = await mountLog();
expect(wrapper.find("[data-test=log-path]").text()).toContain("a.php");
const input = wrapper.find("[data-test=log-filter-text]");
await input.setValue("subject r");
await input.trigger("keydown", { key: "Enter" });
await flushPromises();
expect(callsOf("git.log").at(-1)).toMatchObject({ query: "subject r", path: "a.php" });
await wrapper.find("[data-test=log-path-clear]").trigger("click");
await flushPromises();
expect(log.filters.path).toBeNull();
expect(wrapper.find("[data-test=log-path]").exists()).toBe(false);
});
it("says when nothing matches or git fails", async () => {
history = [];
const log = useLogStore(pinia);
await log.open();
const wrapper = await mountLog();
expect(wrapper.find("[data-test=log-status]").text()).toBe("No commits match");
failures["git.log"] = { code: "failed", message: "boom" };
await log.reload();
await flushPromises();
expect(wrapper.find("[data-test=log-status]").text()).toContain("boom");
});
});
describe("diff at a commit", () => {
it("compares the file at the commit with its parent, read-only", async () => {
blobs = { "a:src/Old.php": "<?php\r\nold();\r\n", "m:src/New.php": "<?php\nnew();\n" };
await useCommandsStore(pinia).start();
useProjectStore(pinia).root = { path: "/p", name: "p" };
const area = mount(EditorArea, { attachTo: document.body, slots: { default: "empty" }, global: { plugins: [pinia] } });
mounted.push(area);
const log = useLogStore(pinia);
await log.open();
const wrapper = await mountLog();
const file = wrapper.findAll("[data-test=log-file]")[0];
await file?.trigger("dblclick");
await vi.dynamicImportSettled();
await flushPromises();
const diff = useDiffStore(pinia);
expect(diff.activeKey).toBe(commitDiffKey("src/New.php", "m"));
expect(callsOf("git.showAt")).toEqual([
{ path: "src/Old.php", rev: "a" },
{ path: "src/New.php", rev: "m" },
]);
const merge = currentMerge();
expect(merge?.a.state.doc.toString()).toBe("<?php\nold();\n");
expect(merge?.b.state.doc.toString()).toBe("<?php\nnew();\n");
expect(merge?.b.state.readOnly).toBe(true);
expect(area.find("[data-test=diff-tab]").text()).toBe("Diff: New.php (m)");
expect(area.find("[data-test=diff-caption]").text()).toContain("commit m");
expect(callsOf("file.open")).toEqual([]);
await emit({ kind: "gitChanged", available: true, repo: null, filesChanged: true });
expect(callsOf("git.showAt")).toHaveLength(2);
await log.openFile({ path: "gone.php", status: "deleted", origPath: null });
await flushPromises();
expect(callsOf("git.showAt").at(-1)).toEqual({ path: "gone.php", rev: "a" });
});
});
describe("commands", () => {
it("registers Log and Show History without default shortcuts", () => {
const specs = UI_COMMANDS.filter((c) => c.id === SHOW_LOG_COMMAND || c.id === SHOW_HISTORY_COMMAND);
expect(specs.map((c) => [c.id, c.menuPath, c.defaultShortcut])).toEqual([
["vcs.showLog", "Git/Log", undefined],
["vcs.showHistory", "Git/Show History", undefined],
]);
});
it("offers Show History in the tree's context menu", async () => {
const commands = useCommandsStore(pinia);
const run = vi.fn();
commands.provide(SHOW_HISTORY_COMMAND, { run });
const wrapper = mount(TreeContextMenu, {
attachTo: document.body,
props: { path: "src/a.php", name: "a.php", x: 0, y: 0 },
global: { plugins: [pinia] },
});
mounted.push(wrapper);
await flushPromises();
const item = wrapper.findAll("[data-test=tree-menu-item]").find((i) => i.text() === "Show History");
await item?.trigger("click");
await flushPromises();
expect(run).toHaveBeenCalledWith({ path: "src/a.php" });
});
});
describe("blame commands in the main layout (M4.7)", () => {
it("shows a commit in the Log and toggles a file's annotations", async () => {
useProjectStore(pinia).root = { path: "/p", name: "p" };
const wrapper = mount(MainLayout, {
attachTo: document.body,
global: { plugins: [pinia], stubs: { ProjectToolWindow: true, StatusBar: true } },
});
mounted.push(wrapper);
const commands = useCommandsStore(pinia);
await commands.start();
await flushPromises();
await commands.execute(SHOW_COMMIT_COMMAND, { hash: "a" });
await flushPromises();
expect(callsOf("git.showCommit")).toEqual([]);
await commands.execute(SHOW_COMMIT_COMMAND, { hash: "abcd" });
await flushPromises();
const log = useLogStore(pinia);
expect(log.visible).toBe(true);
expect(log.selected).toBe("abcd");
expect(callsOf("git.showCommit").at(-1)).toEqual({ hash: "abcd" });
await commands.execute(TOGGLE_BLAME_COMMAND, { path: "src/a.php" });
expect(isBlameShown("src/a.php")).toBe(true);
await commands.execute(TOGGLE_BLAME_COMMAND, { path: "src/a.php" });
expect(isBlameShown("src/a.php")).toBe(false);
});
});