M4.9: Git stash (stash, list, apply, pop, drop) with clear refusals
- crates/vcs: stash.rs (append) with Repo::stash, stash_list, stash_apply
and stash_drop; refusals decided structurally (no commit, nothing to
stash, unmerged files, conflicts after apply, missing or changed entry)
plus hints for overwritten and untracked files. Works around git leaving
untracked files behind under --literal-pathspecs. Repo::lock is
pub(crate), as for M4.8.
- engine: git.stash, git.stashList, git.stashApply {index, pop, hash?},
git.stashDrop through the M4.6 hook; gitChanged after changes.
- ui: stash dialog (vcs.stash, vcs.showStashes; Git menu, no shortcuts),
two buttons in the Changes window, dirty buffers saved first, drop asks.
- Tests: vcs integration and property tests, engine test, 13 Vitest tests.
- Docs: architecture section, G8, tooling checklist, roadmap, Git row
evidence (score left to the PM).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
65907d925a
commit
e09ef8b8c0
23 changed files with 2681 additions and 13 deletions
|
|
@ -19,8 +19,8 @@
|
|||
* command but `menu.open` closes it.
|
||||
* - **Navigation (M3.5):** the definition picker and the inline rename field
|
||||
* are exclusive modals too. So is the branches popup (M4.5), and so are
|
||||
* "Clone Repository…" and "Manage Remotes…" (M4.10) and the merge
|
||||
* dialog (M4.8).
|
||||
* "Clone Repository…" and "Manage Remotes…" (M4.10), the merge
|
||||
* dialog (M4.8) and the stash dialog (M4.9).
|
||||
*/
|
||||
import { defineStore } from "pinia";
|
||||
import { ref, watch } from "vue";
|
||||
|
|
@ -38,7 +38,8 @@ export type ModalId =
|
|||
| "branches"
|
||||
| "clone"
|
||||
| "remotes"
|
||||
| "merge";
|
||||
| "merge"
|
||||
| "stash";
|
||||
|
||||
/** Store of the open exclusive modal. */
|
||||
export const useModalsStore = defineStore("modals", () => {
|
||||
|
|
|
|||
|
|
@ -51,6 +51,8 @@ export const UI_COMMANDS: readonly UiCommandSpec[] = [
|
|||
{ id: "vcs.refresh", labelKey: "command.vcs.refresh", menuPath: "Git/Refresh Changes" },
|
||||
{ id: "vcs.showLog", labelKey: "command.vcs.showLog", menuPath: "Git/Log" },
|
||||
{ id: "vcs.showHistory", labelKey: "command.vcs.showHistory", menuPath: "Git/Show History" },
|
||||
{ id: "vcs.stash", labelKey: "command.vcs.stash", menuPath: "Git/Stash Changes…" },
|
||||
{ id: "vcs.showStashes", labelKey: "command.vcs.showStashes", menuPath: "Git/Stashes…" },
|
||||
{ id: "vcs.showDiff", labelKey: "command.vcs.showDiff", menuPath: "Git/Show Diff", defaultShortcut: "Mod+Alt+Shift+D" },
|
||||
{ id: "vcs.nextChange", labelKey: "command.vcs.nextChange", menuPath: "Git/Next Change", defaultShortcut: "Alt+Shift+]" },
|
||||
{ id: "vcs.previousChange", labelKey: "command.vcs.previousChange", menuPath: "Git/Previous Change", defaultShortcut: "Alt+Shift+[" },
|
||||
|
|
|
|||
|
|
@ -53,6 +53,7 @@ import ChangesToolWindow from "../vcs/changes/ChangesToolWindow.vue";
|
|||
import { useChangesStore } from "../vcs/changes/changes";
|
||||
import LogToolWindow from "../vcs/log/LogToolWindow.vue";
|
||||
import { SHOW_HISTORY_COMMAND, SHOW_LOG_COMMAND, useLogStore } from "../vcs/log/log";
|
||||
import StashDialog from "../vcs/stash/StashDialog.vue";
|
||||
import { useEditorStore } from "../../stores/editor";
|
||||
import { useProjectStore } from "../../stores/project";
|
||||
import ProjectToolWindow from "../project/ProjectToolWindow.vue";
|
||||
|
|
@ -326,6 +327,7 @@ onBeforeUnmount(() => {
|
|||
/>
|
||||
</BottomPanel>
|
||||
<StatusBar />
|
||||
<StashDialog />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
|
|
|
|||
|
|
@ -7,7 +7,8 @@
|
|||
* - **Status line:** the branch (or the short hash when detached) and the
|
||||
* counts, or why there is nothing to show: git missing or too old (with
|
||||
* a hint to the setting `git.executable`), no repository, no changes.
|
||||
* A refresh button runs `vcs.refresh`.
|
||||
* A refresh button runs `vcs.refresh`; two more open the stash dialog
|
||||
* (M4.9) on its form (`vcs.stash`) and on its list (`vcs.showStashes`).
|
||||
* - **Groups:** a header with a checkbox that stages (Changes, Untracked)
|
||||
* or unstages (Staged) the whole group, then the files. Each file has a
|
||||
* checkbox doing the same for itself, its name coloured by its state
|
||||
|
|
@ -26,7 +27,7 @@
|
|||
* message survive hiding the window. Icons are Lucide's; colours are
|
||||
* tokens.
|
||||
*/
|
||||
import { RefreshCw } from "@lucide/vue";
|
||||
import { Archive, ArchiveRestore, RefreshCw } from "@lucide/vue";
|
||||
import { computed, nextTick, onMounted, ref, watch } from "vue";
|
||||
import { useCommandsStore } from "../../../commands/store";
|
||||
import { isMac } from "../../../commands/keymap";
|
||||
|
|
@ -325,6 +326,28 @@ watch(
|
|||
>
|
||||
<RefreshCw :size="14" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="changes__icon-button"
|
||||
:title="t('command.vcs.stash')"
|
||||
:aria-label="t('command.vcs.stash')"
|
||||
:disabled="changes.phase !== 'ready' || !commands.isEnabled('vcs.stash')"
|
||||
data-test="changes-stash"
|
||||
@click="commands.execute('vcs.stash')"
|
||||
>
|
||||
<Archive :size="14" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="changes__icon-button"
|
||||
:title="t('command.vcs.showStashes')"
|
||||
:aria-label="t('command.vcs.showStashes')"
|
||||
:disabled="changes.phase !== 'ready' || !commands.isEnabled('vcs.showStashes')"
|
||||
data-test="changes-stashes"
|
||||
@click="commands.execute('vcs.showStashes')"
|
||||
>
|
||||
<ArchiveRestore :size="14" />
|
||||
</button>
|
||||
</div>
|
||||
<div
|
||||
v-if="changes.phase === 'unavailable'"
|
||||
|
|
|
|||
619
ui/src/components/vcs/stash/StashDialog.vue
Normal file
619
ui/src/components/vcs/stash/StashDialog.vue
Normal file
|
|
@ -0,0 +1,619 @@
|
|||
<script setup lang="ts">
|
||||
/**
|
||||
* The stash dialog (M4.9), centred over the window.
|
||||
*
|
||||
* - **Stash form:** a message (optional), "Include untracked files" and
|
||||
* Stash. Enter in the message or Stash saves dirty buffers and stashes
|
||||
* (see the Stash store); a refusal shows under the form and the dialog
|
||||
* stays.
|
||||
* - **Stashes:** the entries, newest first: `stash@{n}`, the message (or
|
||||
* git's "WIP" text), the branch and the date. Up/Down, Home and End
|
||||
* move; Enter or Apply applies the selected entry, Pop applies and drops
|
||||
* it, Delete or Drop asks, then drops it. A refusal (conflicts, files in
|
||||
* the way, a changed stash) shows under the list.
|
||||
* - **Commands:** the dialog supplies the UI commands `vcs.stash` (the
|
||||
* form) and `vcs.showStashes` (the list), both enabled while `git.stash`
|
||||
* is (an open project). The Changes window has buttons for both.
|
||||
* - **Closing:** Escape (first it cancels a drop question), Cancel or a
|
||||
* click outside; the focus goes back where it was. The dialog is an
|
||||
* exclusive modal (`commands/modals.ts`).
|
||||
*/
|
||||
import { Archive } from "@lucide/vue";
|
||||
import { nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue";
|
||||
import { useModalsStore } from "../../../commands/modals";
|
||||
import { useCommandsStore } from "../../../commands/store";
|
||||
import { t } from "../../../i18n";
|
||||
import { useStashStore, type StashEntry } from "./stash";
|
||||
|
||||
const stash = useStashStore();
|
||||
const modals = useModalsStore();
|
||||
const commands = useCommandsStore();
|
||||
|
||||
/** The message field. */
|
||||
const messageInput = ref<HTMLInputElement | null>(null);
|
||||
/** The list. */
|
||||
const list = ref<HTMLElement | null>(null);
|
||||
/** The dialog box; it takes the focus while the list is empty. */
|
||||
const dialogBox = ref<HTMLElement | null>(null);
|
||||
/** The element that had the focus before the dialog opened. */
|
||||
let returnFocus: HTMLElement | null = null;
|
||||
|
||||
/**
|
||||
* The DOM id of an entry's row.
|
||||
*
|
||||
* @param index - its index in the list.
|
||||
*/
|
||||
function rowId(index: number): string {
|
||||
return `lt-stash-${String(index)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The name git gives an entry.
|
||||
*
|
||||
* @param entry - the entry.
|
||||
*/
|
||||
function refName(entry: StashEntry): string {
|
||||
return `stash@{${String(entry.index)}}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* A date for the list: the local date and time, short.
|
||||
*
|
||||
* @param iso - ISO 8601 date.
|
||||
*/
|
||||
function shortDate(iso: string): string {
|
||||
const date = new Date(iso);
|
||||
if (Number.isNaN(date.getTime())) {
|
||||
return iso;
|
||||
}
|
||||
return date.toLocaleString(undefined, { year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" });
|
||||
}
|
||||
|
||||
/**
|
||||
* What a row shows as its text.
|
||||
*
|
||||
* @param entry - the entry.
|
||||
*/
|
||||
function entryText(entry: StashEntry): string {
|
||||
return entry.wip ? t("vcs.stash.wip", { message: entry.message }) : entry.message;
|
||||
}
|
||||
|
||||
/** Closes the dialog. */
|
||||
function close(): void {
|
||||
if (stash.open) {
|
||||
stash.hide();
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => stash.open,
|
||||
(isOpen) => {
|
||||
if (isOpen) {
|
||||
const active = document.activeElement;
|
||||
returnFocus = active instanceof HTMLElement ? active : null;
|
||||
modals.opened("stash", close);
|
||||
} else {
|
||||
modals.closed("stash");
|
||||
returnFocus?.focus();
|
||||
returnFocus = null;
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
watch(
|
||||
() => stash.focusRequest,
|
||||
async () => {
|
||||
await nextTick();
|
||||
if (stash.mode === "stash") {
|
||||
messageInput.value?.focus();
|
||||
} else {
|
||||
dialogBox.value?.focus();
|
||||
focusList();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* Moves the focus into the list once it has entries, unless something in
|
||||
* the dialog other than the dialog itself has it.
|
||||
*/
|
||||
function focusList(): void {
|
||||
const active = document.activeElement;
|
||||
const inside = dialogBox.value?.contains(active) === true && active !== dialogBox.value;
|
||||
if (stash.open && stash.mode === "list" && (stash.list?.length ?? 0) > 0 && !inside) {
|
||||
list.value?.focus();
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => stash.list,
|
||||
async () => {
|
||||
await nextTick();
|
||||
focusList();
|
||||
},
|
||||
);
|
||||
|
||||
/** Keeps the selected row in view. */
|
||||
function scrollSelected(): void {
|
||||
void nextTick(() => {
|
||||
const row = list.value?.querySelector<HTMLElement>(`#${rowId(stash.selected)}`);
|
||||
if (row && typeof row.scrollIntoView === "function") {
|
||||
row.scrollIntoView({ block: "nearest" });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Keyboard handling of the dialog: Escape cancels a drop question, else
|
||||
* closes.
|
||||
*
|
||||
* @param event - the key press.
|
||||
*/
|
||||
function onDialogKey(event: KeyboardEvent): void {
|
||||
if (event.key !== "Escape") {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
if (stash.confirmDrop !== null) {
|
||||
stash.cancelDrop();
|
||||
list.value?.focus();
|
||||
} else {
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Keyboard handling of the list.
|
||||
*
|
||||
* @param event - the key press.
|
||||
*/
|
||||
function onListKey(event: KeyboardEvent): void {
|
||||
const count = stash.list?.length ?? 0;
|
||||
const moves: Record<string, number> = { ArrowDown: 1, ArrowUp: -1, Home: -count, End: count };
|
||||
const delta = moves[event.key];
|
||||
const entry = stash.current;
|
||||
if (delta !== undefined) {
|
||||
stash.move(delta);
|
||||
scrollSelected();
|
||||
} else if (event.key === "Enter" && entry) {
|
||||
void stash.apply(entry, false);
|
||||
} else if (event.key === "Delete" && entry) {
|
||||
stash.askDrop(entry);
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
}
|
||||
|
||||
/** Withdraws the command handlers; filled while mounted. */
|
||||
let withdraw: (() => void)[] = [];
|
||||
|
||||
onMounted(() => {
|
||||
const enabled = (): boolean => commands.isEnabled("git.stash");
|
||||
withdraw = [
|
||||
commands.provide("vcs.stash", { run: () => stash.show("stash"), enabled }),
|
||||
commands.provide("vcs.showStashes", { run: () => stash.show("list"), enabled }),
|
||||
];
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
for (const fn of withdraw) {
|
||||
fn();
|
||||
}
|
||||
withdraw = [];
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
v-if="stash.open"
|
||||
class="stash"
|
||||
data-test="stash"
|
||||
@mousedown.self.prevent="close()"
|
||||
>
|
||||
<div
|
||||
ref="dialogBox"
|
||||
class="stash__dialog"
|
||||
tabindex="-1"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="lt-stash-title"
|
||||
@keydown="onDialogKey"
|
||||
>
|
||||
<div class="stash__header">
|
||||
<Archive
|
||||
:size="14"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<h2
|
||||
id="lt-stash-title"
|
||||
class="stash__title"
|
||||
>
|
||||
{{ stash.mode === "stash" ? t("vcs.stash.title") : t("vcs.stash.listTitle") }}
|
||||
</h2>
|
||||
<button
|
||||
type="button"
|
||||
class="stash__link"
|
||||
data-test="stash-switch"
|
||||
@click="stash.show(stash.mode === 'stash' ? 'list' : 'stash')"
|
||||
>
|
||||
{{ stash.mode === "stash" ? t("vcs.stash.showList") : t("vcs.stash.newStash") }}
|
||||
</button>
|
||||
</div>
|
||||
<form
|
||||
v-if="stash.mode === 'stash'"
|
||||
class="stash__form"
|
||||
data-test="stash-form"
|
||||
@submit.prevent="stash.stash()"
|
||||
>
|
||||
<label
|
||||
class="stash__label"
|
||||
for="lt-stash-message"
|
||||
>{{ t("vcs.stash.message") }}</label>
|
||||
<input
|
||||
id="lt-stash-message"
|
||||
ref="messageInput"
|
||||
v-model="stash.message"
|
||||
class="stash__input"
|
||||
type="text"
|
||||
spellcheck="false"
|
||||
autocomplete="off"
|
||||
:placeholder="t('vcs.stash.messagePlaceholder')"
|
||||
:aria-describedby="stash.error !== null ? 'lt-stash-error' : undefined"
|
||||
data-test="stash-message"
|
||||
>
|
||||
<label class="stash__check">
|
||||
<input
|
||||
v-model="stash.includeUntracked"
|
||||
type="checkbox"
|
||||
data-test="stash-untracked"
|
||||
>
|
||||
{{ t("vcs.stash.includeUntracked") }}
|
||||
</label>
|
||||
<p class="stash__note">
|
||||
{{ t("vcs.stash.note") }}
|
||||
</p>
|
||||
<p
|
||||
v-if="stash.error !== null"
|
||||
id="lt-stash-error"
|
||||
class="stash__error"
|
||||
role="alert"
|
||||
data-test="stash-error"
|
||||
>
|
||||
{{ stash.error }}
|
||||
</p>
|
||||
<div class="stash__buttons">
|
||||
<button
|
||||
type="button"
|
||||
class="stash__button"
|
||||
data-test="stash-cancel"
|
||||
@click="close()"
|
||||
>
|
||||
{{ t("common.cancel") }}
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
class="stash__button stash__button--primary"
|
||||
:disabled="stash.busy"
|
||||
data-test="stash-submit"
|
||||
>
|
||||
{{ t("vcs.stash.stash") }}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
<template v-else>
|
||||
<p
|
||||
v-if="stash.list === null || stash.list.length === 0"
|
||||
class="stash__hint"
|
||||
role="status"
|
||||
data-test="stash-hint"
|
||||
>
|
||||
{{ stash.list === null ? (stash.loading ? t("vcs.stash.loading") : "") : t("vcs.stash.empty") }}
|
||||
</p>
|
||||
<ul
|
||||
v-show="(stash.list?.length ?? 0) > 0"
|
||||
ref="list"
|
||||
class="stash__list"
|
||||
role="listbox"
|
||||
tabindex="0"
|
||||
:aria-label="t('vcs.stash.listTitle')"
|
||||
:aria-activedescendant="rowId(stash.selected)"
|
||||
data-test="stash-list"
|
||||
@keydown="onListKey"
|
||||
>
|
||||
<li
|
||||
v-for="(entry, i) in stash.list"
|
||||
:id="rowId(i)"
|
||||
:key="entry.hash"
|
||||
class="stash__row"
|
||||
:class="{ 'stash__row--selected': stash.selected === i }"
|
||||
role="option"
|
||||
:aria-selected="stash.selected === i"
|
||||
:data-index="entry.index"
|
||||
data-test="stash-row"
|
||||
@click="stash.selected = i"
|
||||
@dblclick="stash.apply(entry, false)"
|
||||
>
|
||||
<span class="stash__ref">{{ refName(entry) }}</span>
|
||||
<span class="stash__text">{{ entryText(entry) }}</span>
|
||||
<span
|
||||
v-if="entry.branch !== null"
|
||||
class="stash__detail"
|
||||
>{{ entry.branch }}</span>
|
||||
<span class="stash__detail">{{ shortDate(entry.date) }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
<p
|
||||
v-if="stash.error !== null"
|
||||
class="stash__error"
|
||||
role="alert"
|
||||
data-test="stash-error"
|
||||
>
|
||||
{{ stash.error }}
|
||||
</p>
|
||||
<div
|
||||
v-if="stash.confirmDrop !== null"
|
||||
class="stash__confirm"
|
||||
role="alertdialog"
|
||||
aria-labelledby="lt-stash-confirm"
|
||||
data-test="stash-confirm"
|
||||
>
|
||||
<span id="lt-stash-confirm">{{ t("vcs.stash.dropQuestion", { name: refName(stash.confirmDrop) }) }}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="stash__button"
|
||||
data-test="stash-drop-cancel"
|
||||
@click="stash.cancelDrop()"
|
||||
>
|
||||
{{ t("common.cancel") }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="stash__button stash__button--danger"
|
||||
:disabled="stash.busy"
|
||||
data-test="stash-drop-confirm"
|
||||
@click="stash.drop()"
|
||||
>
|
||||
{{ t("vcs.stash.drop") }}
|
||||
</button>
|
||||
</div>
|
||||
<div
|
||||
v-else
|
||||
class="stash__buttons"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="stash__button"
|
||||
:disabled="stash.busy || stash.current === null"
|
||||
:title="t('vcs.stash.dropHint')"
|
||||
data-test="stash-drop"
|
||||
@click="stash.current && stash.askDrop(stash.current)"
|
||||
>
|
||||
{{ t("vcs.stash.drop") }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="stash__button"
|
||||
:disabled="stash.busy || stash.current === null"
|
||||
:title="t('vcs.stash.popHint')"
|
||||
data-test="stash-pop"
|
||||
@click="stash.current && stash.apply(stash.current, true)"
|
||||
>
|
||||
{{ t("vcs.stash.pop") }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="stash__button stash__button--primary"
|
||||
:disabled="stash.busy || stash.current === null"
|
||||
:title="t('vcs.stash.applyHint')"
|
||||
data-test="stash-apply"
|
||||
@click="stash.current && stash.apply(stash.current, false)"
|
||||
>
|
||||
{{ t("vcs.stash.apply") }}
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.stash {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: center;
|
||||
padding-top: 12vh;
|
||||
z-index: 30;
|
||||
}
|
||||
|
||||
.stash__dialog {
|
||||
width: min(560px, 92vw);
|
||||
max-height: 70vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
padding: 10px;
|
||||
background: var(--lt-bg);
|
||||
color: var(--lt-fg);
|
||||
border: 1px solid var(--lt-border);
|
||||
border-radius: 6px;
|
||||
outline: none;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.stash__header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
color: var(--lt-fg-muted);
|
||||
}
|
||||
|
||||
.stash__title {
|
||||
margin: 0;
|
||||
font-size: 1em;
|
||||
font-weight: 600;
|
||||
color: var(--lt-fg);
|
||||
}
|
||||
|
||||
.stash__link {
|
||||
margin-left: auto;
|
||||
padding: 0;
|
||||
font: inherit;
|
||||
color: var(--lt-accent);
|
||||
background: none;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.stash__link:focus-visible {
|
||||
outline: 2px solid var(--lt-accent);
|
||||
outline-offset: 1px;
|
||||
}
|
||||
|
||||
.stash__form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.stash__input {
|
||||
padding: 4px 8px;
|
||||
font: inherit;
|
||||
color: var(--lt-fg);
|
||||
background: var(--lt-editor-bg);
|
||||
border: 1px solid var(--lt-border);
|
||||
border-radius: var(--lt-radius, 4px);
|
||||
}
|
||||
|
||||
.stash__input:focus-visible {
|
||||
outline: 2px solid var(--lt-accent);
|
||||
outline-offset: -1px;
|
||||
}
|
||||
|
||||
.stash__check {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.stash__check input {
|
||||
accent-color: var(--lt-accent);
|
||||
}
|
||||
|
||||
.stash__note,
|
||||
.stash__hint {
|
||||
margin: 0;
|
||||
color: var(--lt-fg-muted);
|
||||
}
|
||||
|
||||
.stash__error {
|
||||
margin: 0;
|
||||
max-height: 8em;
|
||||
overflow-y: auto;
|
||||
white-space: pre-wrap;
|
||||
color: var(--lt-error);
|
||||
}
|
||||
|
||||
.stash__list {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
margin: 0;
|
||||
padding: 2px 0;
|
||||
list-style: none;
|
||||
overflow-y: auto;
|
||||
border: 1px solid var(--lt-border);
|
||||
border-radius: var(--lt-radius, 4px);
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.stash__list:focus-visible {
|
||||
box-shadow: inset 0 0 0 1px var(--lt-accent);
|
||||
}
|
||||
|
||||
.stash__row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 3px 8px;
|
||||
white-space: nowrap;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.stash__row:hover {
|
||||
background: color-mix(in srgb, var(--lt-fg) 6%, transparent);
|
||||
}
|
||||
|
||||
.stash__row--selected,
|
||||
.stash__row--selected:hover {
|
||||
background: var(--lt-editor-selection-bg);
|
||||
}
|
||||
|
||||
.stash__ref {
|
||||
flex: none;
|
||||
font-family: var(--lt-font-mono);
|
||||
color: var(--lt-fg-muted);
|
||||
}
|
||||
|
||||
.stash__text {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.stash__detail {
|
||||
flex: none;
|
||||
color: var(--lt-fg-muted);
|
||||
}
|
||||
|
||||
.stash__row--selected .stash__ref,
|
||||
.stash__row--selected .stash__detail {
|
||||
color: var(--lt-fg);
|
||||
}
|
||||
|
||||
.stash__buttons,
|
||||
.stash__confirm {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.stash__confirm span {
|
||||
margin-right: auto;
|
||||
}
|
||||
|
||||
.stash__button {
|
||||
padding: 2px 14px;
|
||||
font: inherit;
|
||||
color: var(--lt-fg);
|
||||
background: transparent;
|
||||
border: 1px solid var(--lt-border);
|
||||
border-radius: var(--lt-radius, 4px);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.stash__button--primary {
|
||||
background: color-mix(in srgb, var(--lt-accent) 18%, transparent);
|
||||
border-color: var(--lt-accent);
|
||||
}
|
||||
|
||||
.stash__button--danger {
|
||||
background: color-mix(in srgb, var(--lt-error) 18%, transparent);
|
||||
border-color: var(--lt-error);
|
||||
}
|
||||
|
||||
.stash__button:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.stash__button:focus-visible {
|
||||
outline: 2px solid var(--lt-fg);
|
||||
outline-offset: 1px;
|
||||
}
|
||||
</style>
|
||||
380
ui/src/components/vcs/stash/stash.ts
Normal file
380
ui/src/components/vcs/stash/stash.ts
Normal file
|
|
@ -0,0 +1,380 @@
|
|||
/**
|
||||
* The stash dialog's state (M4.9): stash the local changes, list the
|
||||
* stash, apply, pop or drop an entry.
|
||||
*
|
||||
* - **Stash:** a message (optional) and "Include untracked files". Dirty
|
||||
* buffers are saved first (`flushDirty`), so git stashes what the editor
|
||||
* shows and the editor reloads the reset files instead of keeping
|
||||
* unsaved edits on top of them; a save that failed cancels the stash.
|
||||
* Then `git.stash {message, includeUntracked}`.
|
||||
* - **List:** `git.stashList` each time the list shows and after every
|
||||
* change. Apply and pop save dirty buffers first for the same reason,
|
||||
* then run `git.stashApply {index, pop, hash}`; drop asks first, then
|
||||
* `git.stashDrop {index, hash}`. The hash makes the engine refuse when
|
||||
* the stash changed since the list was read.
|
||||
* - **Refusals** (nothing to stash, conflicts, overwritten files, a changed
|
||||
* stash) stay in the dialog as git's and the engine's sentence, so they
|
||||
* can be read next to the list; success closes the stash form or keeps
|
||||
* the list, with an info toast.
|
||||
* - **Untrusted input:** the list comes from git through the engine;
|
||||
* malformed entries are dropped ({@link toStashes}).
|
||||
*/
|
||||
import { defineStore } from "pinia";
|
||||
import { computed, ref, shallowRef } from "vue";
|
||||
import { t } from "../../../i18n";
|
||||
import { runWaiting, type JsonValue } from "../../../ipc";
|
||||
import { useAutosaveStore } from "../../../stores/autosave";
|
||||
import { useNotificationsStore } from "../../../stores/notifications";
|
||||
|
||||
/** Most entries kept from `git.stashList` (the engine sends at most 1,000). */
|
||||
export const MAX_STASHES = 1000;
|
||||
|
||||
/** One stash entry. */
|
||||
export interface StashEntry {
|
||||
/** Its position: 0 is `stash@{0}`, the newest. */
|
||||
index: number;
|
||||
/** The stash commit's hash. */
|
||||
hash: string;
|
||||
/** The branch it was made on, if known. */
|
||||
branch: string | null;
|
||||
/** The message, or git's `<hash> <subject>` for a "WIP" entry. */
|
||||
message: string;
|
||||
/** Whether it was made without a message. */
|
||||
wip: boolean;
|
||||
/** When it was made, ISO 8601. */
|
||||
date: string;
|
||||
}
|
||||
|
||||
/** Which part of the dialog shows. */
|
||||
export type StashMode = "stash" | "list";
|
||||
|
||||
/**
|
||||
* Reads one entry of `git.stashList`.
|
||||
*
|
||||
* @param raw - untrusted value.
|
||||
* @returns the entry, or null when the index or hash is missing.
|
||||
*/
|
||||
export function toStash(raw: unknown): StashEntry | null {
|
||||
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
|
||||
return null;
|
||||
}
|
||||
const r = raw as Record<string, unknown>;
|
||||
if (typeof r.index !== "number" || !Number.isInteger(r.index) || r.index < 0) {
|
||||
return null;
|
||||
}
|
||||
if (typeof r.hash !== "string" || r.hash === "") {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
index: r.index,
|
||||
hash: r.hash,
|
||||
branch: typeof r.branch === "string" && r.branch !== "" ? r.branch : null,
|
||||
message: typeof r.message === "string" ? r.message : "",
|
||||
wip: r.wip === true,
|
||||
date: typeof r.date === "string" ? r.date : "",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads `git.stashList`'s value.
|
||||
*
|
||||
* @param raw - untrusted value.
|
||||
* @returns the entries in index order, at most {@link MAX_STASHES}, or null
|
||||
* when the value has no `stashes` array.
|
||||
*/
|
||||
export function toStashes(raw: unknown): StashEntry[] | null {
|
||||
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
|
||||
return null;
|
||||
}
|
||||
const list = (raw as Record<string, unknown>).stashes;
|
||||
if (!Array.isArray(list)) {
|
||||
return null;
|
||||
}
|
||||
const out: StashEntry[] = [];
|
||||
for (const item of list.slice(0, MAX_STASHES)) {
|
||||
const entry = toStash(item);
|
||||
if (entry !== null) {
|
||||
out.push(entry);
|
||||
}
|
||||
}
|
||||
return out.sort((a, b) => a.index - b.index);
|
||||
}
|
||||
|
||||
/**
|
||||
* An engine error's text for people.
|
||||
*
|
||||
* @param message - the error message.
|
||||
*/
|
||||
function reasonOf(message: string): string {
|
||||
return message.trim() === "" ? "?" : message.trim();
|
||||
}
|
||||
|
||||
/** The Stash store. */
|
||||
export const useStashStore = defineStore("stash", () => {
|
||||
const notifications = useNotificationsStore();
|
||||
|
||||
/** Whether the dialog is open. */
|
||||
const open = ref(false);
|
||||
/** Which part of the dialog shows. */
|
||||
const mode = ref<StashMode>("stash");
|
||||
/** The message typed for a new entry. */
|
||||
const message = ref("");
|
||||
/** Whether untracked files are stashed too. */
|
||||
const includeUntracked = ref(false);
|
||||
/** The last list read; null before it arrived. */
|
||||
const list = shallowRef<StashEntry[] | null>(null);
|
||||
/** Whether `git.stashList` runs. */
|
||||
const loading = ref(false);
|
||||
/** Index in {@link list} of the selected entry. */
|
||||
const selected = ref(0);
|
||||
/** Whether a stash, apply, pop or drop runs. */
|
||||
const busy = ref(false);
|
||||
/** The last refusal or read failure, shown in the dialog. */
|
||||
const error = ref<string | null>(null);
|
||||
/** The entry waiting for the drop to be confirmed. */
|
||||
const confirmDrop = ref<StashEntry | null>(null);
|
||||
/** Bumped when the dialog's first field should take the focus. */
|
||||
const focusRequest = ref(0);
|
||||
|
||||
/** The selected entry. */
|
||||
const current = computed(() => list.value?.[selected.value] ?? null);
|
||||
|
||||
/** Counts loads, so an older answer never replaces a newer one. */
|
||||
let loads = 0;
|
||||
|
||||
/** Reads `git.stashList`. */
|
||||
async function load(): Promise<void> {
|
||||
loads += 1;
|
||||
const mine = loads;
|
||||
loading.value = true;
|
||||
const result = await runWaiting("git.stashList");
|
||||
if (mine !== loads) {
|
||||
return;
|
||||
}
|
||||
loading.value = false;
|
||||
if (!result.ok) {
|
||||
error.value = reasonOf(result.error.message);
|
||||
return;
|
||||
}
|
||||
const next = toStashes(result.value);
|
||||
if (next === null) {
|
||||
error.value = "unexpected result of git.stashList";
|
||||
return;
|
||||
}
|
||||
list.value = next;
|
||||
selected.value = Math.min(Math.max(0, selected.value), Math.max(0, next.length - 1));
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the dialog.
|
||||
*
|
||||
* @param as - `stash` for the form, `list` for the entries.
|
||||
* @returns when the list arrived (`list`), at once otherwise.
|
||||
*/
|
||||
function show(as: StashMode): Promise<void> {
|
||||
open.value = true;
|
||||
mode.value = as;
|
||||
error.value = null;
|
||||
confirmDrop.value = null;
|
||||
focusRequest.value += 1;
|
||||
if (as === "stash") {
|
||||
message.value = "";
|
||||
return Promise.resolve();
|
||||
}
|
||||
selected.value = 0;
|
||||
return load();
|
||||
}
|
||||
|
||||
/** Closes the dialog. */
|
||||
function hide(): void {
|
||||
open.value = false;
|
||||
confirmDrop.value = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves the selection by `delta` entries, clamped.
|
||||
*
|
||||
* @param delta - entries to move; positive is down.
|
||||
*/
|
||||
function move(delta: number): void {
|
||||
const count = list.value?.length ?? 0;
|
||||
confirmDrop.value = null;
|
||||
selected.value = Math.min(Math.max(0, selected.value + delta), Math.max(0, count - 1));
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves every dirty buffer.
|
||||
*
|
||||
* @returns whether every buffer was saved; otherwise the reason is in
|
||||
* {@link error}.
|
||||
*/
|
||||
async function saveFirst(): Promise<boolean> {
|
||||
const flushed = await useAutosaveStore().flushDirty();
|
||||
if (flushed.error !== null || flushed.failed.length > 0) {
|
||||
error.value = t("vcs.stash.notSaved");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a stash command, keeping its refusal in {@link error}.
|
||||
*
|
||||
* @param command - the command id.
|
||||
* @param params - its params.
|
||||
* @returns its value, or null when it failed.
|
||||
*/
|
||||
async function mutate(command: string, params: JsonValue): Promise<unknown> {
|
||||
const result = await runWaiting(command, params);
|
||||
if (!result.ok) {
|
||||
error.value = reasonOf(result.error.message);
|
||||
return null;
|
||||
}
|
||||
error.value = null;
|
||||
return result.value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves dirty buffers, then stashes the local changes with the form's
|
||||
* message and flag. Closes the dialog when it worked.
|
||||
*
|
||||
* @returns whether an entry was made.
|
||||
*/
|
||||
async function stash(): Promise<boolean> {
|
||||
if (busy.value) {
|
||||
return false;
|
||||
}
|
||||
busy.value = true;
|
||||
try {
|
||||
error.value = null;
|
||||
if (!(await saveFirst())) {
|
||||
return false;
|
||||
}
|
||||
const params: Record<string, JsonValue> = { includeUntracked: includeUntracked.value };
|
||||
if (message.value.trim() !== "") {
|
||||
params.message = message.value;
|
||||
}
|
||||
const value = await mutate("git.stash", params);
|
||||
if (value === null) {
|
||||
return false;
|
||||
}
|
||||
const entry =
|
||||
typeof value === "object" && !Array.isArray(value) ? toStash((value as Record<string, unknown>).entry) : null;
|
||||
notifications.notify({
|
||||
level: "info",
|
||||
messageKey: "notification.vcs.stashed",
|
||||
params: { message: entry?.message ?? "" },
|
||||
});
|
||||
message.value = "";
|
||||
hide();
|
||||
return true;
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves dirty buffers, then applies an entry; with `pop` it is dropped
|
||||
* when it applied cleanly. The list is read again either way (a
|
||||
* conflicted pop keeps the entry).
|
||||
*
|
||||
* @param entry - the entry.
|
||||
* @param pop - drop it afterwards.
|
||||
* @returns whether it applied.
|
||||
*/
|
||||
async function apply(entry: StashEntry, pop: boolean): Promise<boolean> {
|
||||
if (busy.value) {
|
||||
return false;
|
||||
}
|
||||
busy.value = true;
|
||||
confirmDrop.value = null;
|
||||
try {
|
||||
error.value = null;
|
||||
if (!(await saveFirst())) {
|
||||
return false;
|
||||
}
|
||||
const value = await mutate("git.stashApply", { index: entry.index, pop, hash: entry.hash });
|
||||
await load();
|
||||
if (value === null) {
|
||||
return false;
|
||||
}
|
||||
notifications.notify({
|
||||
level: "info",
|
||||
messageKey: pop ? "notification.vcs.stashPopped" : "notification.vcs.stashApplied",
|
||||
params: { name: `stash@{${String(entry.index)}}` },
|
||||
});
|
||||
return true;
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Asks to drop an entry: {@link confirmDrop} holds it until
|
||||
* {@link drop} or {@link cancelDrop}.
|
||||
*
|
||||
* @param entry - the entry.
|
||||
*/
|
||||
function askDrop(entry: StashEntry): void {
|
||||
error.value = null;
|
||||
confirmDrop.value = entry;
|
||||
}
|
||||
|
||||
/** Forgets the drop question. */
|
||||
function cancelDrop(): void {
|
||||
confirmDrop.value = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Drops the entry waiting in {@link confirmDrop}.
|
||||
*
|
||||
* @returns whether it was dropped.
|
||||
*/
|
||||
async function drop(): Promise<boolean> {
|
||||
const entry = confirmDrop.value;
|
||||
if (entry === null || busy.value) {
|
||||
return false;
|
||||
}
|
||||
busy.value = true;
|
||||
confirmDrop.value = null;
|
||||
try {
|
||||
const value = await mutate("git.stashDrop", { index: entry.index, hash: entry.hash });
|
||||
await load();
|
||||
if (value === null) {
|
||||
return false;
|
||||
}
|
||||
notifications.notify({
|
||||
level: "info",
|
||||
messageKey: "notification.vcs.stashDropped",
|
||||
params: { name: `stash@{${String(entry.index)}}` },
|
||||
});
|
||||
return true;
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
open,
|
||||
mode,
|
||||
message,
|
||||
includeUntracked,
|
||||
list,
|
||||
loading,
|
||||
selected,
|
||||
busy,
|
||||
error,
|
||||
confirmDrop,
|
||||
focusRequest,
|
||||
current,
|
||||
load,
|
||||
show,
|
||||
hide,
|
||||
move,
|
||||
stash,
|
||||
apply,
|
||||
askDrop,
|
||||
cancelDrop,
|
||||
drop,
|
||||
};
|
||||
});
|
||||
|
|
@ -38,6 +38,8 @@
|
|||
"command.vcs.showDiff": "Show Diff",
|
||||
"command.vcs.showHistory": "Show History",
|
||||
"command.vcs.showLog": "Log",
|
||||
"command.vcs.showStashes": "Stashes…",
|
||||
"command.vcs.stash": "Stash Changes…",
|
||||
"command.view.toggleProjectTree": "Show or Hide Project",
|
||||
"command.view.toggleStructure": "Show or Hide Structure",
|
||||
"common.cancel": "Cancel",
|
||||
|
|
@ -190,6 +192,10 @@
|
|||
"notification.vcs.pushedUpstream": "Pushed {branch} to {remote} and set it as the upstream",
|
||||
"notification.vcs.remoteCancelled": "Git operation cancelled",
|
||||
"notification.vcs.resolved": "Marked {path} as resolved",
|
||||
"notification.vcs.stashApplied": "Applied {name}",
|
||||
"notification.vcs.stashDropped": "Dropped {name}",
|
||||
"notification.vcs.stashPopped": "Applied and dropped {name}",
|
||||
"notification.vcs.stashed": "Stashed the local changes: {message}",
|
||||
"notification.vfs.pumpFailed": "Applying changes on disk failed: {reason}",
|
||||
"notification.watch.failed": "Lutra stopped watching the project for changes on disk: {reason}",
|
||||
"palette.label": "Command palette",
|
||||
|
|
@ -467,6 +473,26 @@
|
|||
"vcs.remotes.url": "URL of the new remote",
|
||||
"vcs.remotes.urlEmpty": "Enter the new URL.",
|
||||
"vcs.remotes.urlOf": "URL of {name}",
|
||||
"vcs.stash.apply": "Apply",
|
||||
"vcs.stash.applyHint": "Apply the selected entry and keep it (Enter)",
|
||||
"vcs.stash.drop": "Drop",
|
||||
"vcs.stash.dropHint": "Delete the selected entry (Delete)",
|
||||
"vcs.stash.dropQuestion": "Drop {name}? It cannot be restored.",
|
||||
"vcs.stash.empty": "The stash is empty.",
|
||||
"vcs.stash.includeUntracked": "Include untracked files",
|
||||
"vcs.stash.listTitle": "Stashes",
|
||||
"vcs.stash.loading": "Reading the stash…",
|
||||
"vcs.stash.message": "Message",
|
||||
"vcs.stash.messagePlaceholder": "Optional; Git names the entry after the last commit without one",
|
||||
"vcs.stash.newStash": "Stash changes…",
|
||||
"vcs.stash.notSaved": "Nothing was done: not every file could be saved first.",
|
||||
"vcs.stash.note": "Every local change of the repository is set aside and the files go back to the last commit. Unsaved files are saved first.",
|
||||
"vcs.stash.pop": "Pop",
|
||||
"vcs.stash.popHint": "Apply the selected entry and drop it if it applies cleanly",
|
||||
"vcs.stash.showList": "Show stashes…",
|
||||
"vcs.stash.stash": "Stash",
|
||||
"vcs.stash.title": "Stash Changes",
|
||||
"vcs.stash.wip": "WIP: {message}",
|
||||
"vcs.state.added": "added",
|
||||
"vcs.state.conflicted": "conflicted",
|
||||
"vcs.state.copied": "copied",
|
||||
|
|
|
|||
|
|
@ -86,6 +86,10 @@ const RUNTIME_KEYS = new Set([
|
|||
"notification.vcs.pushedUpstream",
|
||||
"notification.vcs.remoteCancelled",
|
||||
"notification.vcs.resolved",
|
||||
"notification.vcs.stashApplied",
|
||||
"notification.vcs.stashDropped",
|
||||
"notification.vcs.stashPopped",
|
||||
"notification.vcs.stashed",
|
||||
"notification.settings.corrupt",
|
||||
"notification.settings.corruptNotMoved",
|
||||
"notification.settings.unavailable",
|
||||
|
|
|
|||
|
|
@ -293,6 +293,8 @@ describe("AppMenu", () => {
|
|||
"vcs.resolveConflicts",
|
||||
"vcs.showDiff",
|
||||
"vcs.showHistory",
|
||||
"vcs.stash",
|
||||
"vcs.showStashes",
|
||||
"app.about",
|
||||
]);
|
||||
const close = document.querySelector("[data-command='buffer.close']");
|
||||
|
|
|
|||
|
|
@ -294,6 +294,8 @@ describe("CommandPalette", () => {
|
|||
"vcs.showHistory",
|
||||
"view.toggleProjectTree",
|
||||
"view.toggleStructure",
|
||||
"vcs.stash",
|
||||
"vcs.showStashes",
|
||||
"terminal.open",
|
||||
]);
|
||||
const quit = wrapper.find("[data-command='app.quit']");
|
||||
|
|
|
|||
328
ui/tests/vcs/Stash.test.ts
Normal file
328
ui/tests/vcs/Stash.test.ts
Normal file
|
|
@ -0,0 +1,328 @@
|
|||
/**
|
||||
* Tests of the stash feature (M4.9): reading an untrusted `git.stashList`,
|
||||
* the dialog's form (message, untracked flag, `flushDirty` first, a failed
|
||||
* save, git's refusal kept in the dialog), the list (entries, keyboard,
|
||||
* apply, pop with a conflict, drop after the question, Escape), the UI
|
||||
* commands `vcs.stash` and `vcs.showStashes` and the Changes window's
|
||||
* buttons. 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 { useModalsStore } from "../../src/commands/modals";
|
||||
import { useCommandsStore } from "../../src/commands/store";
|
||||
import { UI_COMMANDS } from "../../src/commands/uiCommands";
|
||||
import ChangesToolWindow from "../../src/components/vcs/changes/ChangesToolWindow.vue";
|
||||
import { useChangesStore } from "../../src/components/vcs/changes/changes";
|
||||
import StashDialog from "../../src/components/vcs/stash/StashDialog.vue";
|
||||
import { MAX_STASHES, toStash, toStashes, useStashStore } from "../../src/components/vcs/stash/stash";
|
||||
import { useNotificationsStore } from "../../src/stores/notifications";
|
||||
|
||||
/** A recorded engine call. */
|
||||
interface Call {
|
||||
/** Command id. */
|
||||
command: string;
|
||||
/** Its params. */
|
||||
params: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** Every engine call, in order. */
|
||||
let calls: Call[];
|
||||
/** What `git.stashList` answers. */
|
||||
let stashes: unknown[];
|
||||
/** Errors to throw, by command id. */
|
||||
let failures: Record<string, { code: string; message: string }>;
|
||||
/** What `file.saveAll` answers. */
|
||||
let saveAll: unknown;
|
||||
/** Pinia of the current test. */
|
||||
let pinia: Pinia;
|
||||
/** Mounted components, unmounted after each test. */
|
||||
let mounted: VueWrapper[];
|
||||
|
||||
/** Two entries as the engine sends them. */
|
||||
const ENTRIES = [
|
||||
{ index: 0, hash: "aaaa1111", branch: "main", message: "41aa1cf init", wip: true, date: "2026-10-28T18:08:36+01:00" },
|
||||
{ index: 1, hash: "bbbb2222", branch: "feature/x", message: "half done", wip: false, date: "2026-10-27T10:00:00Z" },
|
||||
];
|
||||
|
||||
/**
|
||||
* The calls of a command.
|
||||
*
|
||||
* @param command - the command id.
|
||||
*/
|
||||
function callsOf(command: string): Call[] {
|
||||
return calls.filter((c) => c.command === command);
|
||||
}
|
||||
|
||||
/** Mounts the dialog with the command store started. */
|
||||
async function mountDialog(): Promise<VueWrapper> {
|
||||
const wrapper = mount(StashDialog, { attachTo: document.body, global: { plugins: [pinia] } });
|
||||
mounted.push(wrapper);
|
||||
await useCommandsStore(pinia).start();
|
||||
await flushPromises();
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* The texts of the list's rows.
|
||||
*
|
||||
* @param wrapper - the dialog.
|
||||
*/
|
||||
function rows(wrapper: VueWrapper): string[] {
|
||||
return wrapper.findAll("[data-test=stash-row]").map((row) => row.text());
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
pinia = createPinia();
|
||||
setActivePinia(pinia);
|
||||
calls = [];
|
||||
mounted = [];
|
||||
failures = {};
|
||||
stashes = ENTRIES.map((e) => ({ ...e }));
|
||||
saveAll = { saved: [], failed: [], skipped: [] };
|
||||
Element.prototype.scrollIntoView = () => undefined;
|
||||
invoke.mockReset();
|
||||
listen.mockReset();
|
||||
listen.mockImplementation(() => Promise.resolve(() => undefined));
|
||||
invoke.mockImplementation((cmd: string, args?: { command: string; params: Record<string, unknown> }) => {
|
||||
if (cmd === "engine_list_commands") {
|
||||
return Promise.resolve([
|
||||
{ id: "git.status", label: "Git Status", enabled: true },
|
||||
{ id: "git.stash", label: "Git Stash", enabled: true },
|
||||
]);
|
||||
}
|
||||
if ((cmd !== "engine_execute" && cmd !== "engine_execute_waiting") || !args) {
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
calls.push({ command: args.command, params: args.params });
|
||||
const failure = failures[args.command];
|
||||
if (failure) {
|
||||
return Promise.reject(Object.assign(new Error(failure.message), failure));
|
||||
}
|
||||
switch (args.command) {
|
||||
case "git.status":
|
||||
return Promise.resolve({ available: true, repo: { root: "C:/p", branch: "main", detached: false }, files: [] });
|
||||
case "git.stashList":
|
||||
return Promise.resolve({ stashes });
|
||||
case "git.stash":
|
||||
return Promise.resolve({ entry: { ...ENTRIES[1], index: 0, message: typeof args.params.message === "string" ? args.params.message : "" } });
|
||||
case "file.saveAll":
|
||||
return Promise.resolve(saveAll);
|
||||
default:
|
||||
return Promise.resolve({});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
for (const wrapper of mounted) {
|
||||
wrapper.unmount();
|
||||
}
|
||||
useChangesStore(pinia).stop();
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
describe("reading git.stashList", () => {
|
||||
it("drops malformed entries, sorts by index and caps the count", () => {
|
||||
expect(
|
||||
toStashes({
|
||||
stashes: [
|
||||
{ index: 1, hash: "b", branch: "", message: 5, wip: "yes" },
|
||||
{ index: 0, hash: "a", branch: "main", message: "m", wip: true, date: "d" },
|
||||
{ index: -1, hash: "x" },
|
||||
{ index: 2.5, hash: "y" },
|
||||
{ index: 3, hash: "" },
|
||||
null,
|
||||
"z",
|
||||
],
|
||||
}),
|
||||
).toEqual([
|
||||
{ index: 0, hash: "a", branch: "main", message: "m", wip: true, date: "d" },
|
||||
{ index: 1, hash: "b", branch: null, message: "", wip: false, date: "" },
|
||||
]);
|
||||
expect(toStashes(null)).toBeNull();
|
||||
expect(toStashes({ stashes: "no" })).toBeNull();
|
||||
expect(toStash([1])).toBeNull();
|
||||
const many = Array.from({ length: MAX_STASHES + 5 }, (_, i) => ({ index: i, hash: `h${String(i)}` }));
|
||||
expect(toStashes({ stashes: many })).toHaveLength(MAX_STASHES);
|
||||
});
|
||||
});
|
||||
|
||||
describe("the stash form", () => {
|
||||
it("saves first, then stashes with the message and the untracked flag", async () => {
|
||||
const wrapper = await mountDialog();
|
||||
await useCommandsStore(pinia).execute("vcs.stash");
|
||||
await flushPromises();
|
||||
expect(useModalsStore(pinia).current).toBe("stash");
|
||||
expect(document.activeElement).toBe(wrapper.get("[data-test=stash-message]").element);
|
||||
await wrapper.get("[data-test=stash-message]").setValue("half done");
|
||||
await wrapper.get("[data-test=stash-untracked]").setValue(true);
|
||||
await wrapper.get("[data-test=stash-form]").trigger("submit");
|
||||
await flushPromises();
|
||||
const order = calls.map((c) => c.command).filter((c) => c === "file.saveAll" || c === "git.stash");
|
||||
expect(order).toEqual(["file.saveAll", "git.stash"]);
|
||||
expect(callsOf("git.stash")[0]?.params).toEqual({ message: "half done", includeUntracked: true });
|
||||
expect(wrapper.find("[data-test=stash]").exists()).toBe(false);
|
||||
const toast = useNotificationsStore(pinia).toasts.at(-1);
|
||||
expect(toast?.text).toContain("half done");
|
||||
expect(useModalsStore(pinia).current).toBeNull();
|
||||
});
|
||||
|
||||
it("leaves out a blank message", async () => {
|
||||
const wrapper = await mountDialog();
|
||||
await useStashStore(pinia).show("stash");
|
||||
await flushPromises();
|
||||
await wrapper.get("[data-test=stash-message]").setValue(" ");
|
||||
await wrapper.get("[data-test=stash-submit]").trigger("click");
|
||||
await flushPromises();
|
||||
expect(callsOf("git.stash")[0]?.params).toEqual({ includeUntracked: false });
|
||||
});
|
||||
|
||||
it("keeps git's refusal in the dialog", async () => {
|
||||
failures["git.stash"] = { code: "failed", message: "There are no local changes to stash." };
|
||||
const wrapper = await mountDialog();
|
||||
await useStashStore(pinia).show("stash");
|
||||
await flushPromises();
|
||||
await wrapper.get("[data-test=stash-form]").trigger("submit");
|
||||
await flushPromises();
|
||||
expect(wrapper.get("[data-test=stash-error]").text()).toBe("There are no local changes to stash.");
|
||||
expect(wrapper.find("[data-test=stash]").exists()).toBe(true);
|
||||
});
|
||||
|
||||
it("cancels when a save fails", async () => {
|
||||
saveAll = { saved: [], failed: [{ id: 1, path: "a.php", message: "denied" }], skipped: [] };
|
||||
const wrapper = await mountDialog();
|
||||
await useStashStore(pinia).show("stash");
|
||||
await flushPromises();
|
||||
await wrapper.get("[data-test=stash-form]").trigger("submit");
|
||||
await flushPromises();
|
||||
expect(callsOf("git.stash")).toHaveLength(0);
|
||||
expect(wrapper.get("[data-test=stash-error]").text()).toContain("could be saved");
|
||||
});
|
||||
|
||||
it("closes on Escape and gives the focus back", async () => {
|
||||
const before = document.createElement("button");
|
||||
document.body.append(before);
|
||||
before.focus();
|
||||
const wrapper = await mountDialog();
|
||||
await useStashStore(pinia).show("stash");
|
||||
await flushPromises();
|
||||
await wrapper.get("[data-test=stash-message]").trigger("keydown", { key: "Escape" });
|
||||
await flushPromises();
|
||||
expect(wrapper.find("[data-test=stash]").exists()).toBe(false);
|
||||
expect(document.activeElement).toBe(before);
|
||||
});
|
||||
});
|
||||
|
||||
describe("the list", () => {
|
||||
it("shows the entries and applies with Enter after saving", async () => {
|
||||
const wrapper = await mountDialog();
|
||||
await useCommandsStore(pinia).execute("vcs.showStashes");
|
||||
await flushPromises();
|
||||
const texts = rows(wrapper);
|
||||
expect(texts).toHaveLength(2);
|
||||
expect(texts[0]).toContain("stash@{0}");
|
||||
expect(texts[0]).toContain("WIP: 41aa1cf init");
|
||||
expect(texts[1]).toContain("half done");
|
||||
expect(texts[1]).toContain("feature/x");
|
||||
const list = wrapper.get("[data-test=stash-list]");
|
||||
expect(document.activeElement).toBe(list.element);
|
||||
await list.trigger("keydown", { key: "ArrowDown" });
|
||||
await list.trigger("keydown", { key: "Enter" });
|
||||
await flushPromises();
|
||||
expect(callsOf("file.saveAll")).toHaveLength(1);
|
||||
expect(callsOf("git.stashApply")[0]?.params).toEqual({ index: 1, pop: false, hash: "bbbb2222" });
|
||||
expect(callsOf("git.stashList")).toHaveLength(2);
|
||||
expect(useNotificationsStore(pinia).toasts.at(-1)?.text).toBe("Applied stash@{1}");
|
||||
});
|
||||
|
||||
it("shows a conflicted pop's message and reads the list again", async () => {
|
||||
failures["git.stashApply"] = {
|
||||
code: "failed",
|
||||
message: "The stash was applied with conflicts in 1 file. Resolve them in the Changes window.",
|
||||
};
|
||||
const wrapper = await mountDialog();
|
||||
await useStashStore(pinia).show("list");
|
||||
await flushPromises();
|
||||
await wrapper.get("[data-test=stash-pop]").trigger("click");
|
||||
await flushPromises();
|
||||
expect(callsOf("git.stashApply")[0]?.params).toEqual({ index: 0, pop: true, hash: "aaaa1111" });
|
||||
expect(wrapper.get("[data-test=stash-error]").text()).toContain("conflicts in 1 file");
|
||||
expect(callsOf("git.stashList")).toHaveLength(2);
|
||||
expect(rows(wrapper)).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("drops only after the question, and Escape cancels the question first", async () => {
|
||||
const wrapper = await mountDialog();
|
||||
await useStashStore(pinia).show("list");
|
||||
await flushPromises();
|
||||
const list = wrapper.get("[data-test=stash-list]");
|
||||
await list.trigger("keydown", { key: "Delete" });
|
||||
expect(wrapper.get("[data-test=stash-confirm]").text()).toContain("Drop stash@{0}?");
|
||||
expect(callsOf("git.stashDrop")).toHaveLength(0);
|
||||
await list.trigger("keydown", { key: "Escape" });
|
||||
expect(wrapper.find("[data-test=stash-confirm]").exists()).toBe(false);
|
||||
expect(wrapper.find("[data-test=stash]").exists()).toBe(true);
|
||||
|
||||
await wrapper.get("[data-test=stash-drop]").trigger("click");
|
||||
stashes = [ENTRIES[1]].map((e) => ({ ...e, index: 0 }));
|
||||
await wrapper.get("[data-test=stash-drop-confirm]").trigger("click");
|
||||
await flushPromises();
|
||||
expect(callsOf("git.stashDrop")[0]?.params).toEqual({ index: 0, hash: "aaaa1111" });
|
||||
expect(rows(wrapper)).toHaveLength(1);
|
||||
expect(callsOf("file.saveAll")).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("says when the stash is empty and switches to the form", async () => {
|
||||
stashes = [];
|
||||
const wrapper = await mountDialog();
|
||||
await useStashStore(pinia).show("list");
|
||||
await flushPromises();
|
||||
expect(wrapper.get("[data-test=stash-hint]").text()).toBe("The stash is empty.");
|
||||
expect(wrapper.get("[data-test=stash-apply]").attributes("disabled")).toBeDefined();
|
||||
await wrapper.get("[data-test=stash-switch]").trigger("click");
|
||||
await flushPromises();
|
||||
expect(wrapper.find("[data-test=stash-form]").exists()).toBe(true);
|
||||
});
|
||||
|
||||
it("shows a failed read", async () => {
|
||||
failures["git.stashList"] = { code: "failed", message: "fatal: bad object" };
|
||||
const wrapper = await mountDialog();
|
||||
await useStashStore(pinia).show("list");
|
||||
await flushPromises();
|
||||
expect(wrapper.get("[data-test=stash-error]").text()).toBe("fatal: bad object");
|
||||
});
|
||||
});
|
||||
|
||||
describe("commands and entry points", () => {
|
||||
it("registers vcs.stash and vcs.showStashes in the Git menu without shortcuts", () => {
|
||||
for (const id of ["vcs.stash", "vcs.showStashes"]) {
|
||||
const spec = UI_COMMANDS.find((c) => c.id === id);
|
||||
expect(spec?.menuPath?.startsWith("Git/")).toBe(true);
|
||||
expect(spec?.defaultShortcut).toBeUndefined();
|
||||
}
|
||||
});
|
||||
|
||||
it("opens the dialog from the Changes window's buttons", async () => {
|
||||
useChangesStore(pinia).start();
|
||||
const dialog = await mountDialog();
|
||||
const changes = mount(ChangesToolWindow, { attachTo: document.body, global: { plugins: [pinia] } });
|
||||
mounted.push(changes);
|
||||
await flushPromises();
|
||||
await changes.get("[data-test=changes-stash]").trigger("click");
|
||||
await flushPromises();
|
||||
expect(dialog.find("[data-test=stash-form]").exists()).toBe(true);
|
||||
useStashStore(pinia).hide();
|
||||
await flushPromises();
|
||||
await changes.get("[data-test=changes-stashes]").trigger("click");
|
||||
await flushPromises();
|
||||
expect(rows(dialog)).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue