Lutra/ui/src/components/vcs/log/log.ts
danny a8531825a3 M4.6: Git log and file history
- crates/vcs log.rs: Repo::log (topological, all refs, paging, literal
  message/author filters, a path's history with --follow), show_commit
  (message and files against the first parent, renames) and show_at
  (a file at any commit); parsers property-tested.
- Engine git.log, git.showCommit, git.showAt in cmd/git_log.rs through
  the step-1 hook.
- Log tab in the bottom panel: graph lanes carried across pages, ref
  badges, filters, lazy paging, keyboard; commit details whose files open
  a read-only diff at that commit in M4.3's viewer.
- vcs.showLog and vcs.showHistory (menu, tree context menu, active
  editor tab), no default shortcuts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 18:00:24 +01:00

556 lines
16 KiB
TypeScript

/**
* The Log tool window's state (M4.6): pages of `git.log`, the filters, the
* selected commit and its details.
*
* - **Pages:** {@link PAGE_SIZE} commits per `git.log` call (a pending
* outcome, so through `runWaiting`); {@link LogStore.loadMore} asks for
* the next page when the list is scrolled near its end. A page shorter
* than asked for ends the history. One load runs at a time; a filter
* change or a refresh starts over (a generation counter drops answers
* of older loads). At most {@link MAX_COMMITS} commits are kept.
* - **Filters:** text in the message, author, and a path (a file's or
* folder's history: `vcs.showHistory`). Text and author filters are
* applied by git; the graph is drawn only without them, because the
* filtered commits' parents are not in the list.
* - **Details:** selecting a commit reads `git.showCommit`; a file of it
* opens in the diff viewer at that commit (`useDiffStore().openAtCommit`).
* - **Refresh:** `gitChanged` reloads the first page when the HEAD or the
* branch moved (a commit, a checkout), not on every index change;
* opening a project clears everything, closing one too.
* - **Untrusted input:** results are checked field by field; malformed
* commits and files are dropped.
*/
import { defineStore } from "pinia";
import { computed, ref, shallowRef } from "vue";
import { t } from "../../../i18n";
import { onEngineEvent, runWaiting, type EngineEventPayload, type JsonValue } from "../../../ipc";
import { useNotificationsStore } from "../../../stores/notifications";
import { useDiffStore } from "../diff/diff";
import { layoutGraph, type GraphRow, type Lanes } from "./graph";
/** Commits per `git.log` page. */
export const PAGE_SIZE = 100;
/** Most commits kept in the list. */
export const MAX_COMMITS = 50_000;
/** Most files of a commit shown. */
export const MAX_FILES = 10_000;
/** Command id that shows the Log tab. */
export const SHOW_LOG_COMMAND = "vcs.showLog";
/** Command id that shows the history of a file or folder. */
export const SHOW_HISTORY_COMMAND = "vcs.showHistory";
/** One commit of the list. */
export interface LogCommit {
/** Full hash. */
hash: string;
/** Parent hashes, first parent first. */
parents: string[];
/** Author name. */
author: string;
/** Author email. */
email: string;
/** Author date, ISO 8601. */
date: string;
/** Subject line. */
subject: string;
/** Decorations: `HEAD -> main`, `origin/main`, `tag: v1`. */
refs: string[];
}
/** How a file changed in a commit. */
export type CommitFileStatus = "added" | "modified" | "deleted" | "renamed" | "copied";
/** A file changed by a commit. */
export interface CommitFile {
/** Project-relative path after the commit. */
path: string;
/** How it changed. */
status: CommitFileStatus;
/** Its path before a rename or copy. */
origPath: string | null;
}
/** A commit's details. */
export interface CommitDetails {
/** Full hash. */
hash: string;
/** Parent hashes. */
parents: string[];
/** Author name. */
author: string;
/** Author email. */
email: string;
/** Author date, ISO 8601. */
date: string;
/** The full message. */
message: string;
/** Changed files against the first parent. */
files: CommitFile[];
/** More files changed than listed. */
truncated: boolean;
}
/** The filters of the list. */
export interface LogFilters {
/** Text in the message. */
query: string;
/** Text in the author name or email. */
author: string;
/** A file or folder; null for the whole project. */
path: string | null;
}
/** The kind of a ref decoration, for its badge. */
export type RefKind = "head" | "branch" | "remote" | "tag";
/** A decoration, split for display. */
export interface RefBadge {
/** The name shown. */
name: string;
/** Its kind. */
kind: RefKind;
}
/** Statuses `git.showCommit` may report. */
const FILE_STATUSES: readonly CommitFileStatus[] = ["added", "modified", "deleted", "renamed", "copied"];
/**
* Narrows to a plain object.
*
* @param raw - anything.
*/
function record(raw: unknown): Record<string, unknown> | null {
return typeof raw === "object" && raw !== null && !Array.isArray(raw) ? (raw as Record<string, unknown>) : null;
}
/**
* A list of strings, or null when it is not one.
*
* @param raw - untrusted.
*/
function strings(raw: unknown): string[] | null {
return Array.isArray(raw) && raw.every((item) => typeof item === "string") ? raw : null;
}
/**
* Reads one commit of `git.log`; null when malformed.
*
* @param raw - untrusted.
*/
export function toCommit(raw: unknown): LogCommit | null {
const r = record(raw);
if (!r) {
return null;
}
const parents = strings(r.parents);
const refs = strings(r.refs);
const { hash, author, email, date, subject } = r;
if (
typeof hash !== "string" ||
hash === "" ||
parents === null ||
refs === null ||
typeof author !== "string" ||
typeof email !== "string" ||
typeof date !== "string" ||
typeof subject !== "string"
) {
return null;
}
return { hash, parents, author, email, date, subject, refs };
}
/**
* Reads a `git.log` result; null when malformed. Malformed commits are
* dropped.
*
* @param raw - untrusted.
*/
export function toCommits(raw: unknown): LogCommit[] | null {
const list = record(raw)?.commits;
if (!Array.isArray(list)) {
return null;
}
return list.map(toCommit).filter((c): c is LogCommit => c !== null);
}
/**
* Reads a `git.showCommit` result; null when malformed.
*
* @param raw - untrusted.
*/
export function toDetails(raw: unknown): CommitDetails | null {
const r = record(raw);
const parents = strings(r?.parents);
if (!r || parents === null || !Array.isArray(r.files)) {
return null;
}
const { hash, author, email, date, message } = r;
if (typeof hash !== "string" || typeof author !== "string" || typeof date !== "string" || typeof message !== "string") {
return null;
}
const files: CommitFile[] = [];
for (const item of r.files.slice(0, MAX_FILES)) {
const f = record(item);
const status = FILE_STATUSES.find((s) => s === f?.status);
if (!f || typeof f.path !== "string" || f.path === "" || status === undefined) {
continue;
}
files.push({ path: f.path, status, origPath: typeof f.origPath === "string" ? f.origPath : null });
}
return {
hash,
parents,
author,
email: typeof email === "string" ? email : "",
date,
message,
files,
truncated: r.truncated === true || r.files.length > MAX_FILES,
};
}
/**
* Splits git's decorations into badges.
*
* @param refs - `HEAD -> main`, `origin/main`, `tag: v1`, `HEAD`; a name
* with a `/` counts as a remote branch, `<remote>/HEAD` is left out.
*/
export function refBadges(refs: readonly string[]): RefBadge[] {
const badges: RefBadge[] = [];
for (const ref of refs) {
if (ref.startsWith("HEAD -> ")) {
badges.push({ name: "HEAD", kind: "head" }, { name: ref.slice("HEAD -> ".length), kind: "branch" });
} else if (ref === "HEAD") {
badges.push({ name: "HEAD", kind: "head" });
} else if (ref.startsWith("tag: ")) {
badges.push({ name: ref.slice("tag: ".length), kind: "tag" });
} else if (ref.endsWith("/HEAD")) {
continue;
} else {
badges.push({ name: ref, kind: ref.includes("/") ? "remote" : "branch" });
}
}
return badges;
}
/**
* The `git.log` params of a page.
*
* @param filters - the filters.
* @param skip - commits already loaded.
*/
export function logParams(filters: LogFilters, skip: number): Record<string, JsonValue> {
const params: Record<string, JsonValue> = { skip, limit: PAGE_SIZE };
if (filters.query.trim() !== "") {
params.query = filters.query.trim();
}
if (filters.author.trim() !== "") {
params.author = filters.author.trim();
}
if (filters.path !== null) {
params.path = filters.path;
}
return params;
}
/** The Log store. */
export const useLogStore = defineStore("log", () => {
const notifications = useNotificationsStore();
const diff = useDiffStore();
/** Whether the Log tab is shown. */
const visible = ref(false);
/** Whether the panel is expanded while the Log is shown. */
const expanded = ref(true);
/** The filters. */
const filters = ref<LogFilters>({ query: "", author: "", path: null });
/** Loaded commits, newest first. */
const commits = shallowRef<LogCommit[]>([]);
/** Graph rows, one per commit (empty while filtered by text or author). */
const rows = shallowRef<GraphRow[]>([]);
/** A page is loading. */
const loading = ref(false);
/** The history ended (the last page was short). */
const complete = ref(false);
/** The error of the last load; null if it worked. */
const error = ref<string | null>(null);
/** Hash of the selected commit. */
const selected = ref<string | null>(null);
/** The selected commit's details. */
const details = shallowRef<CommitDetails | null>(null);
/** The details are loading. */
const detailsLoading = ref(false);
/** Why the details could not be read; null if they could. */
const detailsError = ref<string | null>(null);
/** Something has been loaded since the last reset. */
const loaded = ref(false);
/** Lanes left after the loaded commits. */
let lanes: Lanes = [];
/** Bumped on every reset; answers of older loads are dropped. */
let generation = 0;
/** Bumped on every selection; answers for older ones are dropped. */
let detailsGeneration = 0;
/** HEAD and branch of the last `gitChanged`, to reload only when they move. */
let lastHead: string | null = null;
/** Whether the graph is drawn (no text or author filter). */
const graphShown = computed(() => filters.value.query.trim() === "" && filters.value.author.trim() === "");
/** The selected commit, null when none or not loaded. */
const selectedCommit = computed(() => commits.value.find((c) => c.hash === selected.value) ?? null);
/** Drops the list and starts over with the first page. */
async function reload(): Promise<void> {
generation += 1;
commits.value = [];
rows.value = [];
lanes = [];
complete.value = false;
error.value = null;
loading.value = false;
loaded.value = false;
await loadMore();
}
/** Loads the next page, unless one is loading or the history ended. */
async function loadMore(): Promise<void> {
if (loading.value || complete.value || commits.value.length >= MAX_COMMITS) {
return;
}
const mine = generation;
loading.value = true;
const result = await runWaiting("git.log", logParams(filters.value, commits.value.length));
if (mine !== generation) {
return;
}
loading.value = false;
loaded.value = true;
if (!result.ok) {
error.value = result.error.message;
complete.value = true;
return;
}
const page = toCommits(result.value);
if (page === null) {
error.value = t("common.error.unexpectedResult", { command: "git.log" });
complete.value = true;
return;
}
error.value = null;
if (graphShown.value) {
const laid = layoutGraph(page, lanes);
lanes = laid.lanes;
rows.value = [...rows.value, ...laid.rows];
}
commits.value = [...commits.value, ...page];
complete.value = page.length < PAGE_SIZE || commits.value.length >= MAX_COMMITS;
if (selected.value === null && commits.value.length > 0) {
void select(commits.value[0]?.hash ?? null);
}
}
/**
* Selects a commit and reads its details.
*
* @param hash - the commit, or null for none.
*/
async function select(hash: string | null): Promise<void> {
if (hash === selected.value && (details.value?.hash === hash || detailsLoading.value)) {
return;
}
selected.value = hash;
detailsGeneration += 1;
const mine = detailsGeneration;
details.value = null;
detailsError.value = null;
if (hash === null) {
detailsLoading.value = false;
return;
}
detailsLoading.value = true;
const result = await runWaiting("git.showCommit", { hash });
if (mine !== detailsGeneration) {
return;
}
detailsLoading.value = false;
if (!result.ok) {
detailsError.value = result.error.message;
return;
}
const read = toDetails(result.value);
if (read === null) {
detailsError.value = t("common.error.unexpectedResult", { command: "git.showCommit" });
return;
}
details.value = read;
}
/**
* Opens a file of the selected commit in the diff viewer.
*
* @param file - a file of {@link details}.
*/
async function openFile(file: CommitFile): Promise<void> {
const commit = details.value;
if (!commit) {
return;
}
await diff.openAtCommit(file.path, {
hash: commit.hash,
parent: commit.parents[0] ?? null,
origPath: file.origPath,
deleted: file.status === "deleted",
});
}
/**
* Changes the filters and reloads.
*
* @param change - the filters to change.
*/
async function setFilters(change: Partial<LogFilters>): Promise<void> {
filters.value = { ...filters.value, ...change };
selected.value = null;
details.value = null;
await reload();
}
/** Shows the tab (expanded) and loads the first page if nothing is loaded. */
async function open(): Promise<void> {
visible.value = true;
expanded.value = true;
if (!loaded.value && !loading.value) {
await reload();
}
}
/**
* Shows the history of a file or folder.
*
* @param path - project-relative path.
*/
async function showHistory(path: string): Promise<void> {
visible.value = true;
expanded.value = true;
await setFilters({ path, query: "", author: "" });
}
/** Hides the tab. */
function hide(): void {
visible.value = false;
}
/** Forgets everything (a project opened or closed). */
function clear(): void {
generation += 1;
detailsGeneration += 1;
commits.value = [];
rows.value = [];
lanes = [];
loading.value = false;
loaded.value = false;
complete.value = false;
error.value = null;
selected.value = null;
details.value = null;
detailsLoading.value = false;
detailsError.value = null;
filters.value = { query: "", author: "", path: null };
lastHead = null;
}
/**
* Applies one engine event.
*
* @param event - the event.
*/
function onEvent(event: EngineEventPayload): void {
if (event.kind === "projectOpened" || event.kind === "projectClosed") {
clear();
return;
}
if (event.kind !== "gitChanged") {
return;
}
const repo = record(event.repo);
const text = (value: unknown): string => (typeof value === "string" ? value : "");
const head = repo ? `${text(repo.head)}|${text(repo.branch)}` : null;
const moved = head !== lastHead;
lastHead = head;
if (moved && loaded.value) {
void reload();
}
}
/** Ends the event subscription; set while started. */
let unsubscribe: (() => void) | null = null;
/** Subscribes to engine events; calling it again has no effect. */
function start(): void {
unsubscribe ??= onEngineEvent(onEvent);
}
/** Ends the subscription. */
function stop(): void {
unsubscribe?.();
unsubscribe = null;
}
/**
* Runs `vcs.showHistory {path?}`: the given path, else the active
* editor tab's file.
*
* @param params - untrusted params.
* @param fallback - the path to use without one (the active file);
* with neither, a warning toast says so.
*/
async function runShowHistory(params: JsonValue, fallback: string | null): Promise<void> {
const p = record(params) ?? {};
const path = typeof p.path === "string" && p.path !== "" ? p.path : fallback;
if (path === null) {
notifications.notify({ level: "warning", messageKey: "notification.vcs.historyNoFile" });
return;
}
await showHistory(path);
}
return {
visible,
expanded,
filters,
commits,
rows,
loading,
complete,
error,
loaded,
selected,
selectedCommit,
details,
detailsLoading,
detailsError,
graphShown,
reload,
loadMore,
select,
openFile,
setFilters,
open,
showHistory,
runShowHistory,
hide,
clear,
onEvent,
start,
stop,
};
});
/** The Log store's type. */
export type LogStore = ReturnType<typeof useLogStore>;