feat(vcs): Shelve Silently and Unshelve Silently (#4620)

Shelving and unshelving always opened a dialog. As in IDEA, Shelve Silently (Changes toolbar, Ctrl+Shift+H / Shift+Cmd+H) shelves the Commit selection, or the active changelist, without a dialog, one shelf per changelist named as the Shelve dialog would suggest; Unshelve Silently (Ctrl+Alt+U / Opt+Cmd+U in the Shelf) applies the selected shelf or file into the matching changelist and honours Remove applied files from the shelf. The Shelve and Unshelve dialogs share the same helpers, and both actions are in the IntelliJ keymaps and IDEA_ACTIONS.

Closes #4619

Co-authored-by: mansur-akhmadi <10739460+mansur-akhmadi@users.noreply.github.com>
This commit is contained in:
Mansur Akhmadi
2026-11-20 06:39:35 +08:00
committed by GitHub
co-authored by mansur-akhmadi
parent 92ccfac192
commit 9f4731189d
11 changed files with 292 additions and 26 deletions
+1
View File
@@ -206,6 +206,7 @@ Limits: interactive rebase doesn't support ranges with merge commits, and **Undo
- **Shelve Changes…** lets you pick files and a name; the changes are then reverted.
- **Unshelve…** applies a shelf (or one file of it) with a three-way merge, into a changelist you choose.
- **Shelve Silently** (`⇧⌘H` / `Ctrl+Shift+H`, also on the Changes toolbar) shelves the selected changes, or the active changelist, without the dialog: one shelf per changelist, named after it. **Unshelve Silently** (`⌥⌘U` / `Ctrl+Alt+U` in the Shelf) applies the selected shelf or file into the changelist with the shelf's name, else the active one.
- The **Shelf** tab shows shelves with diff, compare with local, patch export, rename and delete.
Turn on **Combine stashes and shelves in one tab** in the Git settings to show both in one tab.
+1
View File
@@ -204,6 +204,7 @@ Git 工具窗口的 **日志** 标签页显示提交图。
- **搁置更改…**:选择文件并命名,之后这些更改会被还原。
- **取消搁置…**:以三方合并的方式把搁置(或其中某个文件)应用到你选择的更改列表。
- **静默搁置**(`⇧⌘H` / `Ctrl+Shift+H`,也在更改工具栏上)不弹对话框,直接搁置选中的更改(未选中时为活动更改列表):每个更改列表一个搁置,以列表名命名。**静默取消搁置**(在搁置中按 `⌥⌘U` / `Ctrl+Alt+U`)把选中的搁置或文件应用到与搁置同名的更改列表,没有则应用到活动更改列表。
- **搁置** 标签页列出所有搁置,支持查看差异、与本地比较、导出补丁、重命名和删除。
在 Git 设置中打开 **在同一个标签页中合并显示贮藏和搁置**,两者会显示在同一个标签页里。
+1
View File
@@ -772,6 +772,7 @@ export function ChangesTree({ mode }: { mode: "commit" | "local" | "dialog" }) {
{mode === "local" && <IconButton icon="commit" action="vcs.commit" size="small" />}
<IconButton icon="undo" action="vcs.rollback" size="small" />
{mode === "local" && <IconButton icon="changelist" action="vcs.changelist.new" size="small" />}
{mode !== "dialog" && <IconButton icon="shelve" action="vcs.shelveSilently" size="small" />}
{mode !== "dialog" && <IconButton icon="git-pull" action="vcs.update" size="small" />}
<IconButton
ref={viewRef}
+167 -1
View File
@@ -10,6 +10,7 @@ const mocks = vi.hoisted(() => ({
patch: vi.fn(),
probe: vi.fn(),
unshelve: vi.fn(),
shelve: vi.fn(),
}));
vi.mock("../diffInput", async (original) => ({
...(await original<typeof import("../diffInput")>()),
@@ -30,18 +31,32 @@ vi.mock("@/platform/ipc", async (original) => ({
fsProbe: mocks.probe,
vcsShelfPatch: mocks.patch,
vcsUnshelve: mocks.unshelve,
vcsShelve: mocks.shelve,
},
}));
import { ShelfPanel, copyShelfPatch, shelfDiffs, shelfTarget, showShelfDiff, unshelve, useShelf } from "../shelf";
import {
ShelfPanel,
copyShelfPatch,
shelfDiffs,
shelfTarget,
shelveSilently,
showShelfDiff,
unshelve,
unshelveSilently,
useShelf,
} from "../shelf";
import { useCommit } from "../commitStore";
import { useVcs } from "../store";
import { useChangelists } from "../changelists";
import { VcsDialogHost } from "../dialogs";
import { ContextMenuHost } from "@/ui";
import { registerVcsActions } from "../actions";
import { registerHistoryActions } from "../historyActions";
import { getAction, isActionKeyEnabled } from "@/platform/actions";
import { intellijWindows } from "@/platform/keymaps/intellij-windows";
import { intellijMacos } from "@/platform/keymaps/intellij-macos";
import { useProject } from "@/platform/project";
import { setContext } from "@/platform/context";
const entry: ShelvedChangeList = {
id: "work",
@@ -255,3 +270,154 @@ describe("shelf scope and diffs", () => {
expect(mocks.execute).toHaveBeenCalledWith("vcs.shelf.copyPatch", { id: "work", path: "a.txt" });
});
});
describe("Shelve Silently / Unshelve Silently", () => {
const change = (path: string) => ({
path,
relPath: path,
staged: null,
unstaged: "modified" as const,
renamedFrom: null,
});
const lists = (files: Record<string, string> = {}, active = "default") =>
useChangelists.setState({
loaded: false,
state: {
lists: [
{ id: "default", name: "Changes", comment: "" },
{ id: "work", name: "Work", comment: "" },
],
active,
files,
},
});
beforeEach(() => {
mocks.ipc.mockReset().mockImplementation(async (value: unknown) => (await value) ?? []);
mocks.shelve.mockImplementation(async (name: string, paths: string[]) => ({
...entry,
id: name,
name,
files: paths.map((path) => ({ path, kind: "modified", oldPath: null })),
}));
mocks.unshelve.mockResolvedValue({ applied: ["a.txt"], conflicts: [] });
useVcs.setState({
root: "/repo",
roots: ["/repo"],
available: true,
status: [change("/repo/a.txt"), change("/repo/b.txt"), change("/repo/c.txt")],
});
useProject.setState({ settings: {} });
});
it("shelves the selected changes without a dialog, one shelf per changelist named after it", async () => {
lists({ "b.txt": "work" });
render(<VcsDialogHost />);
await act(() => shelveSilently(["/repo/a.txt", "/repo/b.txt"]));
expect(mocks.shelve.mock.calls).toEqual([
["Changes", ["/repo/a.txt"]],
["Work", ["/repo/b.txt"]],
]);
expect(screen.queryByRole("dialog")).toBeNull();
});
it("shelves the active changelist's changes when nothing is selected", async () => {
lists({ "a.txt": "default", "b.txt": "work", "c.txt": "work" }, "work");
await shelveSilently();
expect(mocks.shelve.mock.calls).toEqual([["Work", ["/repo/b.txt", "/repo/c.txt"]]]);
});
it("names the shelf like the Shelve dialog when the project has one changelist", async () => {
useChangelists.setState({
loaded: false,
state: { lists: [{ id: "default", name: "Changes", comment: "" }], active: "default", files: {} },
});
await shelveSilently(["/repo/a.txt"]);
expect(mocks.shelve.mock.calls).toEqual([["Uncommitted changes", ["/repo/a.txt"]]]);
});
it("shelves nothing when there are no changes", async () => {
lists();
useVcs.setState({ status: [] });
await shelveSilently();
await shelveSilently(["/repo/missing.txt"]);
expect(mocks.shelve).not.toHaveBeenCalled();
});
it("stops after a shelf fails so later changelists stay in the working tree", async () => {
lists({ "b.txt": "work" });
mocks.shelve.mockRejectedValueOnce(new Error("disk full"));
await shelveSilently(["/repo/a.txt", "/repo/b.txt"]);
expect(mocks.shelve).toHaveBeenCalledTimes(1);
});
it("ignores the Changes tab's selection while another Commit tab is shown", async () => {
lists();
const off = registerHistoryActions();
setContext("activeToolWindow", "commit");
useCommit.setState({ tab: "stashes", selection: ["/repo/b.txt"] });
try {
await getAction("vcs.shelveSilently")!.run({ ctx: {} });
expect(mocks.shelve).not.toHaveBeenCalled();
useCommit.setState({ tab: "changes" });
await getAction("vcs.shelveSilently")!.run({ ctx: {} });
expect(mocks.shelve.mock.calls).toEqual([["Changes", ["/repo/b.txt"]]]);
} finally {
off();
setContext("activeToolWindow", null);
useCommit.setState({ tab: "changes", selection: [] });
}
});
it("does nothing for a shelf without files", async () => {
lists();
await unshelveSilently({ ...entry, files: [] });
expect(mocks.unshelve).not.toHaveBeenCalled();
});
it("unshelves into the changelist named like the shelf, without a dialog", async () => {
lists();
render(<VcsDialogHost />);
await act(() => unshelveSilently(entry));
expect(mocks.unshelve).toHaveBeenCalledWith("work", false, null);
expect(screen.queryByRole("dialog")).toBeNull();
expect(useChangelists.getState().state.files).toEqual({ "a.txt": "work" });
});
it("unshelves into the active changelist when no changelist has the shelf's name", async () => {
lists({}, "default");
await unshelveSilently({ ...entry, name: "Experiment" });
expect(useChangelists.getState().state.files).toEqual({ "a.txt": "default" });
});
it("unshelves only the selected file and follows the remove-applied setting", async () => {
lists();
useProject.setState({ settings: { vcs: { shelf: { removeApplied: true } } } });
await unshelveSilently(entry, "b.txt");
expect(mocks.unshelve.mock.calls).toEqual([["work", true, "b.txt"]]);
});
it("binds IDEA's shortcuts to the Commit tool window and the focused Shelf", async () => {
const off = registerHistoryActions();
try {
const shelve = getAction("vcs.shelveSilently")!;
const unshelveAction = getAction("vcs.unshelveSilently")!;
expect(intellijWindows[shelve.id]).toEqual(["Ctrl+Shift+H"]);
expect(intellijMacos[shelve.id]).toEqual(["Meta+Shift+H"]);
expect(intellijWindows[unshelveAction.id]).toEqual(["Ctrl+Alt+U"]);
expect(intellijMacos[unshelveAction.id]).toEqual(["Meta+Alt+U"]);
expect(isActionKeyEnabled(shelve, { vcsAvailable: true, activeToolWindow: "commit" })).toBe(true);
expect(isActionKeyEnabled(shelve, { vcsAvailable: true, activeToolWindow: "git" })).toBe(true);
expect(isActionKeyEnabled(shelve, { vcsAvailable: true, activeToolWindow: "commit", shelfFocus: true })).toBe(
false,
);
expect(isActionKeyEnabled(shelve, { vcsAvailable: true, editorTextFocus: true })).toBe(false);
expect(isActionKeyEnabled(unshelveAction, { vcsAvailable: true, shelfFocus: true })).toBe(true);
expect(isActionKeyEnabled(unshelveAction, { vcsAvailable: true, editorTextFocus: true })).toBe(false);
lists();
await unshelveAction.run({ ctx: {}, arg: { id: "work", path: "a.txt" } });
expect(mocks.unshelve).toHaveBeenCalledWith("work", false, "a.txt");
} finally {
off();
}
});
});
+30 -1
View File
@@ -6,7 +6,7 @@ import { commitKey, commitRepo } from "./multiRoot";
* and patches (ids are bound in keymaps/intellij-macos.ts where IDEA binds them).
*/
import type { Commit } from "@/bindings";
import { setContext } from "@/platform/context";
import { getContext, setContext } from "@/platform/context";
import { call, commands } from "@/platform/ipc";
import { notifications, toolWindowService } from "@/workbench/contributions";
import { executeAction, registerActions, type Action } from "@/platform/actions";
@@ -57,10 +57,12 @@ import {
loadShelves,
renameShelf,
shelveChanges,
shelveSilently,
shelfTarget,
showShelf,
showShelfDiff,
unshelve,
unshelveSilently,
} from "./shelf";
import { currentRepo, focusRepo, useVcs } from "./store";
@@ -622,6 +624,20 @@ export function registerHistoryActions(): () => void {
when: VCS,
run: ({ arg }) => shelveChanges(changePaths(arg)),
},
{
id: "vcs.shelveSilently",
title: "Shelve Silently",
category: "Git",
icon: "shelve",
when: VCS,
keyWhen: "vcsAvailable && (activeToolWindow == commit || activeToolWindow == git) && !shelfFocus",
run: ({ arg }) => {
// The Changes tab's selection is stale while the Shelf or Stash tab is shown.
if (arg === undefined && getContext().activeToolWindow === "commit" && useCommit.getState().tab !== "changes")
return;
return shelveSilently(changePaths(arg));
},
},
{ id: "vcs.showShelf", title: "Show Shelf", category: "Git", icon: "shelve", when: VCS, run: showShelf },
{
id: "vcs.unshelve",
@@ -635,6 +651,19 @@ export function registerHistoryActions(): () => void {
else showShelf();
},
},
{
id: "vcs.unshelveSilently",
title: "Unshelve Silently",
category: "Git",
icon: "unshelve",
when: VCS,
keyWhen: "vcsAvailable && shelfFocus",
run: ({ arg }) => {
const target = shelfTarget(arg);
if (target) return unshelveSilently(target.entry, target.path);
showShelf();
},
},
{
id: "vcs.shelf.delete",
title: "Delete Shelved Changes",
+80 -22
View File
@@ -6,7 +6,14 @@
import { writeClipboardText } from "@/platform/clipboard";
import { useEffect, useMemo, useState, type MouseEvent } from "react";
import { create } from "zustand";
import type { ApplyOutcome, ChangedFile, FileStatus, ShelvedChangeList, ShelfDiffFile } from "@/bindings";
import type {
ApplyOutcome,
ChangedFile,
ChangelistState,
FileStatus,
ShelvedChangeList,
ShelfDiffFile,
} from "@/bindings";
import { setContext } from "@/platform/context";
import { shortcutLabel } from "@/platform/keymap";
import { openDiff, openVcsDiff, withChain, type DiffData } from "./diffInput";
@@ -88,6 +95,13 @@ export function defaultChangeFiles(paths?: readonly string[]): FileStatus[] {
);
}
/** Name a shelf of `list`'s changes gets by default: the list's name once the project has several. */
function shelfName(state: ChangelistState, list: string): string {
return state.lists.length > 1
? (state.lists.find((l) => l.id === list) ?? activeList(state)).name
: "Uncommitted changes";
}
export function shelveChanges(paths?: readonly string[]) {
const files = defaultChangeFiles(paths);
if (!files.length) {
@@ -95,8 +109,42 @@ export function shelveChanges(paths?: readonly string[]) {
return;
}
const state = useChangelists.getState().state;
const name = state.lists.length > 1 ? activeList(state).name : "Uncommitted changes";
openDialog((close) => <ShelveDialog files={files} initialName={name} onClose={close} />);
openDialog((close) => <ShelveDialog files={files} initialName={shelfName(state, state.active)} onClose={close} />);
}
/** IDEA's Shelve Silently: no dialog, one shelf per changelist the changes belong to, named after it. */
export async function shelveSilently(paths?: readonly string[]) {
// Without a dialog to review the files, pick them after unsaved edits reach the disk.
await saveAll();
await refreshNow();
const files = defaultChangeFiles(paths);
if (!files.length) {
notifications().notify({ group: "vcs", level: "info", title: "No changes to shelve" });
return;
}
const state = useChangelists.getState().state;
const byList = new Map<string, string[]>();
for (const f of files) {
const list = listOf(state, relOf(f.path));
const own = byList.get(list);
if (own) own.push(stripSlash(f.path));
else byList.set(list, [stripSlash(f.path)]);
}
for (const [list, chosen] of byList) if (!(await shelveFiles(shelfName(state, list), chosen))) return;
}
async function shelveFiles(name: string, paths: string[]): Promise<ShelvedChangeList | undefined> {
const entry = await runOp(tx`Shelve changes “${name}”`, () => call(commands.vcsShelve(name, paths)));
if (!entry) return undefined;
void loadShelves().catch(() => undefined);
notifications().notify({
group: "vcs",
level: "info",
title: `Shelved ${entry.files.length} file${entry.files.length === 1 ? "" : "s"}`,
body: entry.name,
actions: [{ label: "Show Shelf", run: showShelf }],
});
return entry;
}
/** Files of `node` and everything below it. */
@@ -227,16 +275,7 @@ function ShelveDialog({
if (!chosen.length || !name.trim()) return;
onClose();
await saveAll();
const entry = await runOp(tx`Shelve changes “${name.trim()}”`, () => call(commands.vcsShelve(name.trim(), chosen)));
if (!entry) return;
void loadShelves().catch(() => undefined);
notifications().notify({
group: "vcs",
level: "info",
title: `Shelved ${entry.files.length} file${entry.files.length === 1 ? "" : "s"}`,
body: entry.name,
actions: [{ label: "Show Shelf", run: showShelf }],
});
await shelveFiles(name.trim(), chosen);
};
return (
<Dialog
@@ -304,6 +343,33 @@ async function unshelveFiles(entry: ShelvedChangeList, paths: readonly string[],
return outcome;
}
/** Unshelves `paths` of `entry` into the `target` changelist. */
async function applyShelf(entry: ShelvedChangeList, paths: readonly string[], remove: boolean, target: string) {
const outcome = await runOp(tx`Unshelve “${entry.name}”`, () => unshelveFiles(entry, paths, remove), {
refresh: false,
});
if (!outcome) return;
await refreshNow();
const repo = shelfRepository(entry);
const rels = [...outcome.applied, ...outcome.conflicts].map((p) => relOf(repositoryPath(repo, p)));
updateChangelists((s) => moveFiles(s, rels, target));
void loadShelves().catch(() => undefined);
await reportApply(outcome, `Unshelved “${entry.name}”`);
}
/**
* IDEA's Unshelve Silently: no dialog; into the changelist named like the shelf, else the active one,
* removing applied files from the shelf as the Shelf setting says.
*/
export async function unshelveSilently(entry: ShelvedChangeList, path?: string) {
const paths = path === undefined ? entry.files.map((f) => f.path) : [path];
if (!paths.length) return;
const state = useChangelists.getState().state;
const target = state.lists.find((l) => l.name === entry.name)?.id ?? state.active;
await saveAll();
await applyShelf(entry, paths, workflowSettings().vcs.shelf.removeApplied, target);
}
function UnshelveDialog({ entry, path, onClose }: { entry: ShelvedChangeList; path?: string; onClose: () => void }) {
const lists = useChangelists((s) => s.state);
const [target, setTarget] = useState(lists.active);
@@ -322,15 +388,7 @@ function UnshelveDialog({ entry, path, onClose }: { entry: ShelvedChangeList; pa
if (!chosen.length) return;
onClose();
await saveAll();
const outcome = await runOp(tx`Unshelve “${entry.name}”`, () => unshelveFiles(entry, chosen, remove), {
refresh: false,
});
if (!outcome) return;
await refreshNow();
const rels = [...outcome.applied, ...outcome.conflicts].map((p) => relOf(repositoryPath(repo, p)));
updateChangelists((s) => moveFiles(s, rels, target));
void loadShelves().catch(() => undefined);
await reportApply(outcome, `Unshelved “${entry.name}”`);
await applyShelf(entry, chosen, remove, target);
};
return (
<Dialog
+2
View File
@@ -99,4 +99,6 @@ export const IDEA_ACTIONS: Readonly<Record<string, string>> = {
VcsShowNextChangeMarker: "vcs.nextChange",
VcsShowPrevChangeMarker: "vcs.prevChange",
"Compare.SameVersion": "vcs.showDiff",
"ChangesView.ShelveSilently": "vcs.shelveSilently",
"ChangesView.UnshelveSilently": "vcs.unshelveSilently",
};
+2
View File
@@ -324,6 +324,8 @@ export const intellijMacos: Record<string, string[]> = {
"view.quickSwitchScheme": ["Ctrl+`"],
// Commit tool window (change lists) and Git log; keyWhen limits them to those tool windows.
"vcs.changelist.move": ["Meta+Shift+M"],
"vcs.shelveSilently": ["Meta+Shift+H"],
"vcs.unshelveSilently": ["Meta+Alt+U"],
"vcs.changelist.edit": ["F2", "Shift+F6"],
"vcs.log.copyRevision": ["Meta+Alt+Shift+C"],
"vcs.log.goToRef": ["Meta+F"],
+2
View File
@@ -322,6 +322,8 @@ export const intellijWindows: Record<string, string[]> = {
"runAnything.show": ["Ctrl Ctrl"],
"view.quickSwitchScheme": ["Ctrl+`"],
"vcs.changelist.move": ["Alt+Shift+M"],
"vcs.shelveSilently": ["Ctrl+Shift+H"],
"vcs.unshelveSilently": ["Ctrl+Alt+U"],
"vcs.changelist.edit": ["F2", "Shift+F6"],
"vcs.log.copyRevision": ["Ctrl+Alt+Shift+C"],
"vcs.log.goToRef": ["Ctrl+F"],
+3 -1
View File
@@ -2743,5 +2743,7 @@
"Resize right merge pane": "Resize right merge pane",
"Database and schema": "Database and schema",
"Loading…": "Loading…",
"<schema>": "<schema>"
"<schema>": "<schema>",
"Shelve Silently": "Shelve Silently",
"Unshelve Silently": "Unshelve Silently"
}
+3 -1
View File
@@ -9111,5 +9111,7 @@
"Sort by Duration": "按持续时间排序",
"Resize left merge pane": "调整左侧合并窗格宽度",
"Resize right merge pane": "调整右侧合并窗格宽度",
"Database and schema": "数据库和 schema"
"Database and schema": "数据库和 schema",
"Shelve Silently": "静默搁置",
"Unshelve Silently": "静默取消搁置"
}