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>
This commit is contained in:
danny 2026-10-27 17:16:53 +01:00
parent d567f3957d
commit 4bdfe521f2
14 changed files with 649 additions and 314 deletions

View file

@ -21,17 +21,17 @@ import { useCommandsStore } from "../../../commands/store";
import { t } from "../../../i18n";
import type { JsonValue } from "../../../ipc";
import { useNotificationsStore } from "../../../stores/notifications";
import { useChangesStore } from "../changes/changes";
import { useVcsStatusStore } from "../../../stores/vcsStatus";
import BranchPopup from "./BranchPopup.vue";
import { headLabel, useBranchesStore } from "./branches";
const changes = useChangesStore();
const vcs = useVcsStatusStore();
const branches = useBranchesStore();
const commands = useCommandsStore();
const notifications = useNotificationsStore();
/** The repository of the last status, if any. */
const repo = computed(() => (changes.status?.available ? changes.status.repo : null));
const repo = computed(() => (vcs.snapshot?.available ? vcs.snapshot.repo : null));
/** The text of the item, or null when it is hidden. */
const text = computed(() => headLabel(repo.value));

View file

@ -2,9 +2,9 @@
* The branches popup's state (M4.5): the repository's branches from
* `git.branches`, the filter, and switching to or creating a branch.
*
* - **Current branch:** the status-bar item reads it from the Changes
* store's `git.status` ({@link headLabel}), which already follows
* `gitChanged`, so there is no second status query.
* - **Current branch:** the status-bar item reads it from the shared
* status store (`stores/vcsStatus.ts`, {@link headLabel}), which already
* follows `gitChanged`, so there is no second status query.
* - **List:** `git.branches` (a pending outcome, so through `runWaiting`)
* each time the popup opens. Local branches come first, then remote
* ones; a filter keeps the names that contain every word of it,
@ -25,7 +25,8 @@ import { computed, ref, shallowRef } from "vue";
import { runWaiting, type JsonValue } from "../../../ipc";
import { useAutosaveStore } from "../../../stores/autosave";
import { useNotificationsStore } from "../../../stores/notifications";
import { SHORT_HASH, type RepoSummary } from "../changes/changes";
import { type RepoSummary } from "../../../stores/vcsStatus";
import { SHORT_HASH } from "../changes/changes";
/** Most branches kept per kind from one answer. */
export const MAX_BRANCHES = 10_000;

View file

@ -3,10 +3,10 @@
* `git.status`, grouped as Staged, Changes and Untracked, plus staging,
* unstaging and committing.
*
* - **Source:** `git.status` (a pending outcome, so through `runWaiting`)
* on start, when a project opens, on `gitChanged` and on `vcs.refresh`.
* Calls are serialised; a refresh asked for while one runs runs once
* more afterwards. A project close clears everything.
* - **Source:** the shared status store (`stores/vcsStatus.ts`, the only
* caller of `git.status`), which re-reads on start, when a project
* opens, on `gitChanged` and on `vcs.refresh`. A project close clears
* it, and with it the rows and the selection.
* - **Groups:** a file is Staged when its index side changed, in Changes
* when its work tree side changed or it is conflicted, and Untracked when
* git does not track it. A partly staged file is in both Staged and
@ -16,61 +16,36 @@
* - **Commit:** `flushDirty()` first, so the files on disk hold what the
* editor shows; a save that failed cancels the commit. Then `git.commit
* {message, amend}`; success toasts the short hash and clears the box.
* - **Amend:** checking Amend with an empty box fills it with the last
* commit's message (`git.lastMessage`); clearing Amend again empties a
* box that still holds exactly that text.
* - **Untrusted input:** the status comes from the engine and, through it,
* from git; malformed entries are dropped and the count capped
* ({@link MAX_FILES}).
*/
import { defineStore } from "pinia";
import { computed, ref, shallowRef } from "vue";
import { onEngineEvent, runWaiting, type EngineEventPayload, type JsonValue } from "../../../ipc";
import { computed, ref, watch } from "vue";
import { runWaiting, type JsonValue } from "../../../ipc";
import { useAutosaveStore } from "../../../stores/autosave";
import { useNotificationsStore } from "../../../stores/notifications";
import { useVcsStatusStore, type ChangedFile, type GitFileState } from "../../../stores/vcsStatus";
/** Most files kept from one status. */
export const MAX_FILES = 50_000;
export {
FILE_STATES,
MAX_FILES,
toFile,
toRepo,
toStatus,
type ChangedFile,
type RepoSummary,
type StatusSnapshot,
} from "../../../stores/vcsStatus";
/** Length of the short commit hash shown to people. */
export const SHORT_HASH = 7;
/** 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;
/** State of one side (index or work tree) of a file. */
export type FileState = (typeof FILE_STATES)[number];
/** 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: FileState;
/** State in the work tree against the index. */
worktree: FileState;
}
/** The repository summary of `git.status`. */
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;
}
export type FileState = GitFileState;
/** The groups of the window, in display order. */
export const GROUPS = ["staged", "changes", "untracked"] as const;
@ -93,103 +68,6 @@ export interface ChangeRow {
/** What the window shows above the groups. */
export type ChangesPhase = "idle" | "loading" | "unavailable" | "noRepo" | "ready";
/**
* Reads a state; null if unknown.
*
* @param raw - untrusted.
*/
function toState(raw: unknown): FileState | null {
return FILE_STATES.find((s) => s === raw) ?? null;
}
/**
* 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>;
const index = toState(f.index);
const worktree = toState(f.worktree);
if (typeof f.path !== "string" || f.path === "" || !index || !worktree) {
return null;
}
const file: ChangedFile = { path: f.path, index, worktree };
if (typeof f.origPath === "string" && f.origPath !== "") {
file.origPath = f.origPath;
}
return file;
}
/**
* 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;
}
return repo;
}
/** 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[];
}
/**
* 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,
};
}
/**
* Whether a side's state means "changed".
*
@ -249,17 +127,18 @@ export function unstagePaths(rows: ChangeRow[]): string[] {
/** The Changes store. */
export const useChangesStore = defineStore("changes", () => {
const notifications = useNotificationsStore();
const vcs = useVcsStatusStore();
/** Whether the tool window is shown in the bottom panel. */
const visible = ref(false);
/** Whether the panel is expanded while Changes is shown. */
const expanded = ref(true);
/** The last status read; null before the first one or without a project. */
const status = shallowRef<StatusSnapshot | null>(null);
/** Whether a `git.status` call runs. */
const loading = ref(false);
const status = computed(() => vcs.snapshot);
/** Whether a `git.status` round runs. */
const loading = computed(() => vcs.loading);
/** The error of the last `git.status` call itself (not git's state). */
const loadError = ref<string | null>(null);
const loadError = computed(() => vcs.loadError);
/** Whether a stage, unstage or commit runs. */
const busy = ref(false);
/** The commit message being written. */
@ -303,61 +182,60 @@ export const useChangesStore = defineStore("changes", () => {
(amend.value || groups.value.staged.length > 0),
);
/** Counts refresh requests, so a round knows whether another came in. */
let requests = 0;
/** Reads `git.status` once. */
async function loadOnce(): Promise<void> {
const result = await runWaiting("git.status");
if (!result.ok) {
loadError.value = result.error.message;
if (result.error.code === "disabled") {
status.value = null;
}
return;
}
const next = toStatus(result.value);
loadError.value = next ? null : "unexpected result of git.status";
status.value = next;
if (selectedKey.value !== null && !rows.value.some((row) => row.key === selectedKey.value)) {
watch(rows, (list) => {
if (selectedKey.value !== null && !list.some((row) => row.key === selectedKey.value)) {
selectedKey.value = null;
}
}
/** The `git.status` round running now, shared by callers. */
let running: Promise<void> | null = null;
});
/**
* Re-reads the status from git: `vcs.refresh`, `gitChanged`, project
* open. Serialised: a call while one runs makes it read once more
* afterwards and shares its promise.
* Re-reads the status from git (`vcs.refresh`, after staging): the
* shared store's serialised refresh.
*/
function refresh(): Promise<void> {
requests += 1;
if (running) {
return running;
}
loading.value = true;
running = (async () => {
let seen: number;
do {
seen = requests;
await loadOnce();
} while (seen !== requests);
})().finally(() => {
running = null;
loading.value = false;
});
return running;
return vcs.refresh();
}
/** Drops the status and the selection (project closed). */
function clear(): void {
status.value = null;
loadError.value = null;
selectedKey.value = null;
/** The message `git.lastMessage` put into the box, while it is unchanged there. */
let prefilled: string | null = null;
/**
* Fills an empty box with the last commit's message when Amend is
* checked; empties a box still holding that text when Amend is cleared.
* A failed `git.lastMessage` leaves the box empty.
*
* @param on - the new Amend state.
*/
async function onAmend(on: boolean): Promise<void> {
if (!on) {
if (prefilled !== null && message.value === prefilled) {
message.value = "";
}
prefilled = null;
return;
}
if (message.value.trim() !== "") {
return;
}
const result = await runWaiting("git.lastMessage");
if (!result.ok || !amend.value || message.value.trim() !== "") {
return;
}
const value = result.value;
const text =
typeof value === "object" && value !== null && !Array.isArray(value) && typeof value.message === "string"
? value.message
: null;
if (text !== null) {
message.value = text;
prefilled = text;
}
}
watch(amend, (on) => {
void onAmend(on);
});
/**
* Runs a mutating git command, toasting its failure.
*
@ -464,6 +342,7 @@ export const useChangesStore = defineStore("changes", () => {
messageKey: "notification.vcs.committed",
params: { hash: hash.slice(0, SHORT_HASH), summary },
});
prefilled = null;
message.value = "";
amend.value = false;
await refresh();
@ -473,35 +352,24 @@ export const useChangesStore = defineStore("changes", () => {
}
}
/**
* Applies one engine event.
*
* @param event - the event.
*/
function onEvent(event: EngineEventPayload): void {
if (event.kind === "gitChanged" || event.kind === "projectOpened") {
void refresh();
} else if (event.kind === "projectClosed") {
clear();
}
}
/** Whether this store holds the shared status store. */
let holding = false;
/** Ends the event subscription; set while started. */
let unsubscribe: (() => void) | null = null;
/** Subscribes to engine events and reads the status once. */
/** Starts the shared status store (which reads the status once). */
function start(): void {
if (unsubscribe) {
if (holding) {
return;
}
unsubscribe = onEngineEvent(onEvent);
void refresh();
holding = true;
vcs.start();
}
/** Ends the subscription. */
/** Releases the shared status store. */
function stop(): void {
unsubscribe?.();
unsubscribe = null;
if (holding) {
holding = false;
vcs.stop();
}
}
/** Shows the tool window: `vcs.openChanges`. */
@ -569,7 +437,6 @@ export const useChangesStore = defineStore("changes", () => {
toggle,
toggleGroup,
commit,
onEvent,
start,
stop,
open,

View file

@ -1,44 +1,40 @@
/**
* Git status of the project's files for colouring file names in the
* project tree and the editor tabs (M4.4).
* 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:** `git.status` (a pending outcome, so through `runWaiting`)
* on start, when a project opens and on every `gitChanged`; never
* polled. One query runs at a time; requests made while it runs share
* one more query after it.
* - **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.
*
* Results are untrusted: malformed files are skipped, a failed query
* keeps the last state and shows nothing (the Changes window reports git
* problems).
* - **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 { shallowRef } from "vue";
import { computed, ref, shallowRef } from "vue";
import { onEngineEvent, runWaiting, type EngineEventPayload } from "../ipc";
import { refreshGitGutters } from "../components/editor/gitGutter";
/** A file state as `git.status` names it. */
export type GitFileState =
| "unmodified"
| "modified"
| "added"
| "deleted"
| "renamed"
| "copied"
| "untracked"
| "ignored"
| "conflicted";
/** Most files kept from one status. */
export const MAX_FILES = 50_000;
/** The status token names (`--lt-vcs-<name>`). */
export type VcsColour = "added" | "modified" | "deleted" | "untracked" | "ignored" | "conflicted";
/** Every state `git.status` may report. */
const STATES = new Set<string>([
/** States of one side of a file, as `git.status` names them. */
export const FILE_STATES = [
"unmodified",
"modified",
"added",
@ -48,11 +44,157 @@ const STATES = new Set<string>([
"untracked",
"ignored",
"conflicted",
]);
] as const;
/** Whether a value is a file state. */
/** 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 typeof value === "string" && STATES.has(value);
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,
};
}
/**
@ -86,6 +228,23 @@ export function statusColour(index: GitFileState, worktree: GitFileState): VcsCo
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.
*
@ -94,33 +253,25 @@ export function statusColour(index: GitFileState, worktree: GitFileState): VcsCo
* open; null when the result is not an object.
*/
export function readStatus(value: unknown): { colours: Map<string, VcsColour>; repo: boolean } | null {
if (typeof value !== "object" || value === null || Array.isArray(value)) {
const snapshot = toStatus(value);
if (snapshot === null) {
return null;
}
const record = value as Record<string, unknown>;
const colours = new Map<string, VcsColour>();
const files = Array.isArray(record.files) ? (record.files as unknown[]) : [];
for (const file of files) {
if (typeof file !== "object" || file === null) {
continue;
}
const { path, index, worktree } = file as Record<string, unknown>;
if (typeof path !== "string" || !isState(index) || !isState(worktree)) {
continue;
}
const colour = statusColour(index, worktree);
if (colour !== null) {
colours.set(path, colour);
}
}
const repo = record.available === true && typeof record.repo === "object" && record.repo !== null;
return { colours, repo };
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 }>;
status(): Promise<{ ok: true; value: unknown } | { ok: false; error?: StatusFailure }>;
}
/** The transport through the engine IPC. */
@ -129,15 +280,22 @@ const engineTransport: VcsStatusTransport = {
};
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 = shallowRef(false);
const repo = computed(() => snapshot.value?.available === true && snapshot.value.repo !== null);
let transport: VcsStatusTransport = engineTransport;
let running: Promise<void> | null = null;
const queued = { again: false };
let requests = 0;
let generation = 0;
let holders = 0;
let unsubscribe: (() => void) | null = null;
/**
@ -149,51 +307,69 @@ export const useVcsStatusStore = defineStore("vcsStatus", () => {
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 (!result.ok || asked !== generation) {
if (asked !== generation) {
return;
}
const read = readStatus(result.value);
if (read !== null) {
colours.value = read.colours;
repo.value = read.repo;
if (!result.ok) {
loadError.value = result.error?.message ?? "git.status failed";
if (result.error?.code === "disabled") {
apply(null);
}
return;
}
}
/** Whether a refresh was asked for while the last query ran. */
function wantsAgain(): boolean {
return queued.again;
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 query, or, while one runs, makes sure
* one more runs after it.
* 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) {
queued.again = true;
return running;
}
loading.value = true;
running = (async () => {
let seen: number;
do {
queued.again = false;
seen = requests;
await query();
} while (wantsAgain());
} while (seen !== requests);
})().finally(() => {
running = null;
})();
loading.value = false;
});
return running;
}
/** Forgets everything (project closed). */
/** Forgets everything (project closed or opened). */
function clear(): void {
generation += 1;
colours.value = new Map();
repo.value = false;
loadError.value = null;
apply(null);
}
/**
@ -225,8 +401,12 @@ export const useVcsStatusStore = defineStore("vcsStatus", () => {
}
}
/** Starts following the engine and queries once; repeated calls do nothing. */
/**
* Starts following the engine and queries once; a further holder only
* counts.
*/
function start(): void {
holders += 1;
if (unsubscribe !== null) {
return;
}
@ -234,11 +414,27 @@ export const useVcsStatusStore = defineStore("vcsStatus", () => {
void refresh();
}
/** Stops following the engine. */
/** Releases one holder; the last one stops following the engine. */
function stop(): void {
unsubscribe?.();
unsubscribe = null;
holders = Math.max(0, holders - 1);
if (holders === 0) {
unsubscribe?.();
unsubscribe = null;
}
}
return { colours, repo, configure, refresh, clear, colourOf, handle, start, stop };
return {
snapshot,
colours,
repo,
loading,
loadError,
configure,
refresh,
clear,
colourOf,
handle,
start,
stop,
};
});

View file

@ -29,6 +29,7 @@ import {
type ChangedFile,
} from "../../src/components/vcs/changes/changes";
import { useNotificationsStore } from "../../src/stores/notifications";
import { useVcsStatusStore } from "../../src/stores/vcsStatus";
/** A recorded engine call. */
interface Call {
@ -142,6 +143,8 @@ beforeEach(() => {
switch (args.command) {
case "git.status":
return Promise.resolve(gitStatus);
case "git.lastMessage":
return Promise.resolve({ message: "Last subject\n\nLast body" });
case "git.commit":
return Promise.resolve({ commit: "fedcba9876543210", summary: String(args.params.message).split("\n")[0] });
case "file.saveAll":
@ -306,6 +309,35 @@ describe("the Changes store", () => {
expect(changes.amend).toBe(false);
});
it("shares one git.status per gitChanged with the status colours", async () => {
const vcs = useVcsStatusStore(pinia);
vcs.start();
useChangesStore(pinia).start();
await flushPromises();
expect(callsOf("git.status")).toHaveLength(1);
await emit({ kind: "gitChanged", available: true, repo: null, filesChanged: true });
expect(callsOf("git.status")).toHaveLength(2);
expect(vcs.colourOf("tmp.txt")).toBe("untracked");
vcs.stop();
});
it("prefills an empty box with the last message on Amend and empties it again", async () => {
const changes = useChangesStore(pinia);
await changes.refresh();
changes.amend = true;
await flushPromises();
expect(callsOf("git.lastMessage")).toHaveLength(1);
expect(changes.message).toBe("Last subject\n\nLast body");
changes.amend = false;
await flushPromises();
expect(changes.message).toBe("");
changes.message = "mine";
changes.amend = true;
await flushPromises();
expect(changes.message).toBe("mine");
expect(callsOf("git.lastMessage")).toHaveLength(1);
});
it("keeps the message when git refuses the commit", async () => {
const changes = useChangesStore(pinia);
await changes.refresh();