Lutra/ui/src/stores/vcsStatus.ts
danny 4bdfe521f2 F1: remote checkout without a remote, git.lastMessage, shared git status store
- vcs: checking out a remote-tracking branch reads remote.<name>.fetch;
  without a matching refspec it creates the local branch with --no-track
  instead of leaving a dirty tree after git fails to set up tracking.
- vcs + engine: git.lastMessage returns HEAD's full message (null before
  the first commit); the Changes window prefills Amend with it.
- ui: stores/vcsStatus.ts is the only git.status caller; the Changes
  window, tree/tab colours and the branch item read its snapshot, so a
  gitChanged costs one status query. RepoSummary carries upstream,
  ahead and behind.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 17:16:53 +01:00

440 lines
13 KiB
TypeScript

/**
* The project's Git status, shared by every view that shows it (M4.4,
* shared since C6 F1): the Changes window, the file name colours in the
* project tree and the editor tabs, and the branch in the status bar.
*
* - **Source:** this store is the only caller of `git.status` in the UI
* (a pending outcome, so through `runWaiting`): on start, when a project
* opens, on every `gitChanged` and on {@link refresh} (`vcs.refresh`,
* after staging); never polled. One query runs at a time; requests made
* while it runs share one more query after it, so a `gitChanged` costs
* one `git.status` however many views follow it. Later features (log,
* merge, stash, remotes) read {@link snapshot} and call {@link refresh};
* they never query `git.status` themselves.
* - **Snapshot:** {@link toStatus} reads the untrusted result: unknown
* states and malformed entries are dropped, at most {@link MAX_FILES}
* files, sorted by path. A failed query keeps the last snapshot and sets
* {@link loadError}; `disabled` (no project) drops it.
* - **Colour:** {@link statusColour} folds a file's index and work tree
* states into one of the `--lt-vcs-*` tokens. Ignored files are not in
* `git.status`; the tree colours its ignored entries itself while a
* repository is open.
* - **Gutters:** every `gitChanged` also asks the editors' change markers
* to refresh (`refreshGitGutters`), since the index may have changed.
* - **Lifetime:** {@link start} / {@link stop} are counted, so `App.vue`
* and the main layout can both hold the store; the subscription ends
* with the last holder.
*/
import { defineStore } from "pinia";
import { computed, ref, shallowRef } from "vue";
import { onEngineEvent, runWaiting, type EngineEventPayload } from "../ipc";
import { refreshGitGutters } from "../components/editor/gitGutter";
/** Most files kept from one status. */
export const MAX_FILES = 50_000;
/** States of one side of a file, as `git.status` names them. */
export const FILE_STATES = [
"unmodified",
"modified",
"added",
"deleted",
"renamed",
"copied",
"untracked",
"ignored",
"conflicted",
] as const;
/** A file state as `git.status` names it. */
export type GitFileState = (typeof FILE_STATES)[number];
/** The status token names (`--lt-vcs-<name>`). */
export type VcsColour = "added" | "modified" | "deleted" | "untracked" | "ignored" | "conflicted";
/** A changed file as `git.status` reports it. */
export interface ChangedFile {
/** Project-relative path with `/`. */
path: string;
/** The old path of a rename or copy. */
origPath?: string;
/** State in the index against HEAD. */
index: GitFileState;
/** State in the work tree against the index. */
worktree: GitFileState;
}
/** The repository summary of `git.status` (and of `gitChanged`). */
export interface RepoSummary {
/** Work tree root, absolute with `/`. */
root: string;
/** Current branch; absent when detached or unborn without a name. */
branch?: string;
/** Whether HEAD is detached. */
detached: boolean;
/** Full hash of HEAD; absent before the first commit. */
head?: string;
/** The current branch's upstream, e.g. `origin/main`. */
upstream?: string;
/** Commits ahead of the upstream. */
ahead?: number;
/** Commits behind the upstream. */
behind?: number;
}
/** A status as the store keeps it. */
export interface StatusSnapshot {
/** Whether a usable git was found. */
available: boolean;
/** Why git is unavailable or the repository could not be opened. */
error: string | null;
/** The repository, or null outside one. */
repo: RepoSummary | null;
/** Changed files sorted by path. */
files: ChangedFile[];
}
/**
* Whether a value is a file state.
*
* @param value - untrusted.
*/
function isState(value: unknown): value is GitFileState {
return FILE_STATES.some((s) => s === value);
}
/**
* Reads one file of `git.status`; null if malformed.
*
* @param raw - an untrusted entry of `files`.
*/
export function toFile(raw: unknown): ChangedFile | null {
if (typeof raw !== "object" || raw === null) {
return null;
}
const f = raw as Record<string, unknown>;
if (typeof f.path !== "string" || f.path === "" || !isState(f.index) || !isState(f.worktree)) {
return null;
}
const file: ChangedFile = { path: f.path, index: f.index, worktree: f.worktree };
if (typeof f.origPath === "string" && f.origPath !== "") {
file.origPath = f.origPath;
}
return file;
}
/**
* Reads a count; undefined unless it is a non-negative integer.
*
* @param raw - untrusted.
*/
function toCount(raw: unknown): number | undefined {
return typeof raw === "number" && Number.isSafeInteger(raw) && raw >= 0 ? raw : undefined;
}
/**
* Reads the repository summary; null when absent or malformed.
*
* @param raw - the untrusted `repo` field.
*/
export function toRepo(raw: unknown): RepoSummary | null {
if (typeof raw !== "object" || raw === null) {
return null;
}
const r = raw as Record<string, unknown>;
if (typeof r.root !== "string") {
return null;
}
const repo: RepoSummary = { root: r.root, detached: r.detached === true };
if (typeof r.branch === "string" && r.branch !== "") {
repo.branch = r.branch;
}
if (typeof r.head === "string" && r.head !== "") {
repo.head = r.head;
}
if (typeof r.upstream === "string" && r.upstream !== "") {
repo.upstream = r.upstream;
}
const ahead = toCount(r.ahead);
const behind = toCount(r.behind);
if (ahead !== undefined) {
repo.ahead = ahead;
}
if (behind !== undefined) {
repo.behind = behind;
}
return repo;
}
/**
* Reads the result of `git.status`; null if it is not an object.
*
* @param raw - untrusted.
*/
export function toStatus(raw: unknown): StatusSnapshot | null {
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
return null;
}
const s = raw as Record<string, unknown>;
const files: ChangedFile[] = [];
if (Array.isArray(s.files)) {
for (const entry of s.files as unknown[]) {
if (files.length >= MAX_FILES) {
break;
}
const file = toFile(entry);
if (file) {
files.push(file);
}
}
}
files.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
return {
available: s.available === true,
error: typeof s.error === "string" && s.error !== "" ? s.error : null,
repo: toRepo(s.repo),
files,
};
}
/**
* The colour of a file from its two states: conflicts first, then
* untracked, ignored, added, deleted, and any other change as modified.
*
* @param index - the staged side.
* @param worktree - the work tree side.
* @returns the token name, or null for an unchanged file.
*/
export function statusColour(index: GitFileState, worktree: GitFileState): VcsColour | null {
const sides = [index, worktree];
if (sides.includes("conflicted")) {
return "conflicted";
}
if (sides.includes("untracked")) {
return "untracked";
}
if (sides.includes("ignored")) {
return "ignored";
}
if (index === "added") {
return worktree === "deleted" ? null : "added";
}
if (sides.includes("deleted")) {
return "deleted";
}
if (sides.some((side) => side !== "unmodified")) {
return "modified";
}
return null;
}
/**
* The colours of a snapshot's files.
*
* @param snapshot - the snapshot, or null.
* @returns colour by project-relative path, changed files only.
*/
function coloursOf(snapshot: StatusSnapshot | null): Map<string, VcsColour> {
const colours = new Map<string, VcsColour>();
for (const file of snapshot?.files ?? []) {
const colour = statusColour(file.index, file.worktree);
if (colour !== null) {
colours.set(file.path, colour);
}
}
return colours;
}
/**
* Reads the colours of a `git.status` result.
*
* @param value - the untrusted result.
* @returns colour by project-relative path, and whether a repository is
* open; null when the result is not an object.
*/
export function readStatus(value: unknown): { colours: Map<string, VcsColour>; repo: boolean } | null {
const snapshot = toStatus(value);
if (snapshot === null) {
return null;
}
return { colours: coloursOf(snapshot), repo: snapshot.available && snapshot.repo !== null };
}
/** A failed `git.status` call, as the transport reports it. */
export interface StatusFailure {
/** The engine error code (`disabled` without a project). */
code: string;
/** Its message. */
message: string;
}
/** How the store reaches the engine; replaced in tests. */
export interface VcsStatusTransport {
/** Runs `git.status`. */
status(): Promise<{ ok: true; value: unknown } | { ok: false; error?: StatusFailure }>;
}
/** The transport through the engine IPC. */
const engineTransport: VcsStatusTransport = {
status: () => runWaiting<unknown>("git.status", {}),
};
export const useVcsStatusStore = defineStore("vcsStatus", () => {
/** The last status read; null before the first one or without a project. */
const snapshot = shallowRef<StatusSnapshot | null>(null);
/** Colour by project-relative path, for changed files only. */
const colours = shallowRef<ReadonlyMap<string, VcsColour>>(new Map());
/** Whether a `git.status` round runs. */
const loading = ref(false);
/** The error of the last `git.status` call itself (not git's state). */
const loadError = ref<string | null>(null);
/** Whether the project is inside a repository with a usable git. */
const repo = computed(() => snapshot.value?.available === true && snapshot.value.repo !== null);
let transport: VcsStatusTransport = engineTransport;
let running: Promise<void> | null = null;
let requests = 0;
let generation = 0;
let holders = 0;
let unsubscribe: (() => void) | null = null;
/**
* Replaces the transport (tests).
*
* @param next - the transport.
*/
function configure(next: VcsStatusTransport): void {
transport = next;
}
/**
* Takes a snapshot.
*
* @param next - the snapshot, or null to forget it.
*/
function apply(next: StatusSnapshot | null): void {
snapshot.value = next;
colours.value = coloursOf(next);
}
/** Runs `git.status` once and applies it unless the project changed. */
async function query(): Promise<void> {
const asked = generation;
const result = await transport.status();
if (asked !== generation) {
return;
}
if (!result.ok) {
loadError.value = result.error?.message ?? "git.status failed";
if (result.error?.code === "disabled") {
apply(null);
}
return;
}
const next = toStatus(result.value);
if (next === null) {
loadError.value = "unexpected result of git.status";
return;
}
loadError.value = null;
apply(next);
}
/**
* Refreshes the status: starts a round, or, while one runs, makes sure
* it queries once more and shares its promise.
*
* @returns resolves when the status is current.
*/
function refresh(): Promise<void> {
requests += 1;
if (running !== null) {
return running;
}
loading.value = true;
running = (async () => {
let seen: number;
do {
seen = requests;
await query();
} while (seen !== requests);
})().finally(() => {
running = null;
loading.value = false;
});
return running;
}
/** Forgets everything (project closed or opened). */
function clear(): void {
generation += 1;
loadError.value = null;
apply(null);
}
/**
* The colour of a file name.
*
* @param path - project-relative path with `/`.
* @returns the token name, or null when unchanged or unknown.
*/
function colourOf(path: string): VcsColour | null {
return colours.value.get(path) ?? null;
}
/** Handles one engine event. */
function handle(event: EngineEventPayload): void {
switch (event.kind) {
case "projectOpened":
clear();
void refresh();
break;
case "projectClosed":
clear();
break;
case "gitChanged":
void refresh();
refreshGitGutters();
break;
default:
break;
}
}
/**
* Starts following the engine and queries once; a further holder only
* counts.
*/
function start(): void {
holders += 1;
if (unsubscribe !== null) {
return;
}
unsubscribe = onEngineEvent(handle);
void refresh();
}
/** Releases one holder; the last one stops following the engine. */
function stop(): void {
holders = Math.max(0, holders - 1);
if (holders === 0) {
unsubscribe?.();
unsubscribe = null;
}
}
return {
snapshot,
colours,
repo,
loading,
loadError,
configure,
refresh,
clear,
colourOf,
handle,
start,
stop,
};
});