diff --git a/crates/ide-vcs/src/lib.rs b/crates/ide-vcs/src/lib.rs index e194f69e6..2ad9a6103 100644 --- a/crates/ide-vcs/src/lib.rs +++ b/crates/ide-vcs/src/lib.rs @@ -360,6 +360,10 @@ pub struct Stash { pub index: u32, pub message: String, pub time_ms: f64, + /// The stash commit; its changes are those against `base`. + pub id: String, + /// The commit the stash was made on (the stash commit's first parent). + pub base: Option, } /// Push dialog › Push tags: every tag, or only annotated tags on the pushed commits. diff --git a/crates/ide-vcs/src/refs.rs b/crates/ide-vcs/src/refs.rs index 01baaaeb8..833e35c2d 100644 --- a/crates/ide-vcs/src/refs.rs +++ b/crates/ide-vcs/src/refs.rs @@ -158,7 +158,15 @@ pub(crate) fn stashes(r: &Repo) -> IdeResult> { for (index, line) in lines.enumerate() { let line = line.map_err(gx)?; let time_ms = line.signature.time.seconds as f64 * 1000.0; - out.push(Stash { index: index as u32, message: to_string(line.message.as_ref()), time_ms }); + let id = line.new_oid.to_owned(); + let base = repo.find_commit(id).ok().and_then(|c| c.parent_ids().next().map(|p| p.to_string())); + out.push(Stash { + index: index as u32, + message: to_string(line.message.as_ref()), + time_ms, + id: id.to_string(), + base, + }); } Ok(out) } diff --git a/crates/ide-vcs/tests/repo.rs b/crates/ide-vcs/tests/repo.rs index b8a540ddc..5d60bdbd2 100644 --- a/crates/ide-vcs/tests/repo.rs +++ b/crates/ide-vcs/tests/repo.rs @@ -849,6 +849,11 @@ fn stash_push_list_apply_pop() { assert!(stashes[0].message.contains("WIP on main"), "{stashes:?}"); assert!(stashes[1].message.contains("first stash"), "{stashes:?}"); assert!(stashes[0].time_ms > 0.0); + // Each stash lists the files it changed against the commit it was made on. + let head = repo.head().unwrap().1.unwrap(); + assert!(stashes.iter().all(|s| s.base.as_deref() == Some(head.as_str())), "{stashes:?}"); + let files = repo.commit_files(&stashes[1].id).unwrap(); + assert_eq!(files.iter().map(|f| f.path.as_str()).collect::>(), ["s.txt"]); repo.stash_apply(1, false, false).unwrap(); assert_eq!(fx.read("s.txt"), "change 1\n"); diff --git a/src/bindings.ts b/src/bindings.ts index aa69dea86..7c5d17e80 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -10797,6 +10797,10 @@ export type Stash = { index: number, message: string, timeMs: number | null, + /** The stash commit; its changes are those against `base`. */ + id: string, + /** The commit the stash was made on (the stash commit's first parent). */ + base: string | null, }; /** A plugin's status bar item. */ diff --git a/src/features/vcs/CommitView.tsx b/src/features/vcs/CommitView.tsx index 2a6cab034..0f54eb2d6 100644 --- a/src/features/vcs/CommitView.tsx +++ b/src/features/vcs/CommitView.tsx @@ -26,7 +26,6 @@ import { EmptyState, Icon, IconButton, - List, Menu, Select, SplitGroup, @@ -103,7 +102,8 @@ import { import { DiffEditor } from "./DiffEditor"; import { KIND_COLOR, KIND_LABEL, fileCount, formatTime, stashLabel, stripSlash } from "./model"; import { call, commands } from "@/platform/ipc"; -import type { FileStatus } from "@/bindings"; +import type { Commit, FileStatus, Stash } from "@/bindings"; +import { showChangesDiff, toLogChanges, type LogChange } from "./logChanges"; import { OperationBanner } from "./operations"; import { runOp } from "./ops"; import { ShelfPanel, loadShelves, useShelf } from "./shelf"; @@ -1334,18 +1334,33 @@ function CommitPanel({ included }: { included: number }) { // --------------------------------------------------------------------------- +type StashEntry = Stash & { repo: string | null }; +type StashNode = { key: string; stash: StashEntry; change?: LogChange }; + +const stashKey = (s: StashEntry) => `${s.repo}:${s.index}:${s.id}`; +const STASH_PREVIEW_DELAY = 120; + +/** A stash's changes against the commit it was made on, as Git Log changes (diffs, line counts). */ +async function stashFileChanges(stash: StashEntry): Promise { + const files = await call(commands.vcsCommitFiles(stash.repo, stash.id)); + const commit = { id: stash.id, shortId: stash.id.slice(0, 8), parents: stash.base ? [stash.base] : [] }; + return toLogChanges(files, commit as unknown as Commit, stash.repo, true); +} + export function StashesPanel() { const repo = useVcs((s) => s.repo); const repos = useVcs((s) => s.roots); const version = useVcs((s) => s.version); const [tick, setTick] = useState(0); - const [active, setActive] = useState(0); + const [selectedKey, setSelectedKey] = useState(null); const request = useMemo(() => ({ repos, repo, version, tick }), [repos, repo, version, tick]); const [result, setResult] = useState<{ request: typeof request; - stashes: (import("@/bindings").Stash & { repo: string | null })[]; + stashes: StashEntry[]; error: string | null; } | null>(null); + const [files, setFiles] = useState>(new Map()); + const previewTimer = useRef | undefined>(undefined); const loaded = result?.request === request; const stashes = loaded ? result.stashes : []; const error = loaded ? result.error : null; @@ -1366,7 +1381,29 @@ export function StashesPanel() { live = false; }; }, [request]); - const current = stashes[active]; + useEffect(() => () => clearTimeout(previewTimer.current), []); + const roots = useMemo(() => stashes.map((stash) => ({ key: stashKey(stash), stash })), [stashes]); + const childrenOf = (node: StashNode): StashNode[] | undefined => + node.change + ? undefined + : files.get(node.key)?.map((change) => ({ key: `${node.key}\u0000${change.path}`, stash: node.stash, change })); + const loadFiles = async (node: StashNode) => { + if (files.has(node.key)) return; + const changes = await stashFileChanges(node.stash).catch(() => []); + setFiles((prev) => new Map(prev).set(node.key, changes)); + }; + const nodeOf = (key: string | null): StashNode | undefined => { + if (!key) return undefined; + const root = roots.find((r) => key === r.key || key.startsWith(`${r.key}\u0000`)); + if (!root || key === root.key) return root; + return childrenOf(root)?.find((n) => n.key === key); + }; + const selectedNode = nodeOf(selectedKey); + const current = selectedNode?.stash ?? stashes[0]; + const showDiff = (node: StashNode, preview: boolean) => { + const chain = files.get(stashKey(node.stash)) ?? []; + if (node.change) void showChangesDiff([node.change], preview, chain).catch(() => undefined); + }; return (
@@ -1378,7 +1415,15 @@ export function StashesPanel() { options={repos.map((root) => ({ value: root, label: repoName(root) }))} /> )} - setTick((n) => n + 1)} /> + { + setFiles(new Map()); + setTick((n) => n + 1); + }} + /> void stashChanges()} /> current && void dropStash(current.index, current.message, current.repo)} />
- `${s.repo}:${s.index}`} - activeIndex={Math.min(active, Math.max(0, stashes.length - 1))} - onActiveChange={setActive} - rowHeight={22} - aria-label="Stashes" - className={styles.stashList} - empty={{error ?? (loaded ? tx("No stashes") : tx("Loading…"))}} - onActivate={(s, _i, e) => { - if (e.type === "click" && (e as MouseEvent).detail < 2) return; - void applyStash(s.index, false, s.repo); - }} - onContextMenu={(s, i, e) => { - e.preventDefault(); - setActive(i); - showContextMenu(e, [ - { label: "Apply Stash", icon: "check", run: () => void applyStash(s.index, false, s.repo) }, - { label: "Pop Stash", icon: "undo", run: () => void applyStash(s.index, true, s.repo) }, - { label: "Unstash…", run: () => showUnstashDialog(s.index, s.repo) }, - { kind: "separator" }, - { label: "Drop Stash", icon: "trash", run: () => void dropStash(s.index, s.message, s.repo) }, - ]); - }} - renderItem={(s) => { - const { branch, text } = stashLabel(s.message); - return ( - - - {repos.length > 1 && s.repo ? `${repoName(s.repo)} · ` : ""} - {text} +
+ + roots={roots} + getKey={(n) => n.key} + getLabel={(n) => (n.change ? basename(n.change.path) : n.stash.message)} + getChildren={childrenOf} + isExpandable={(n) => !n.change} + loadChildren={loadFiles} + selected={useMemo(() => new Set(selectedKey ? [selectedKey] : []), [selectedKey])} + multiSelect={false} + rowHeight={22} + aria-label="Stashes" + className={styles.stashList} + empty={{error ?? (loaded ? tx("No stashes") : tx("Loading…"))}} + onSelectionChange={(sel) => { + const key = [...sel][0] ?? null; + setSelectedKey(key); + clearTimeout(previewTimer.current); + const node = nodeOf(key); + // With Show Diff Preview on, the selection walks a preview tab through the stash's files. + if (node?.change && useCommit.getState().diffPreview && !vcsDiffInFront()) + previewTimer.current = setTimeout(() => showDiff(node, true), STASH_PREVIEW_DELAY); + }} + onActivate={(n) => showDiff(n, false)} + onContextMenu={(n, _sel, e) => { + if (!n) return; + e.preventDefault(); + setSelectedKey(n.key); + const s = n.stash; + showContextMenu(e, [ + ...(n.change + ? [ + { label: "Show Diff", icon: "diff", run: () => showDiff(n, false) } as MenuItem, + { kind: "separator" } as MenuItem, + ] + : []), + { label: "Apply Stash", icon: "check", run: () => void applyStash(s.index, false, s.repo) }, + { label: "Pop Stash", icon: "undo", run: () => void applyStash(s.index, true, s.repo) }, + { label: "Unstash…", run: () => showUnstashDialog(s.index, s.repo) }, + { kind: "separator" }, + { label: "Drop Stash", icon: "trash", run: () => void dropStash(s.index, s.message, s.repo) }, + ]); + }} + renderNode={(n) => { + if (n.change) { + const kind = n.change.kind === "untracked" ? "added" : n.change.kind; + return ( + <> + + + {basename(n.change.path)} + + {dirname(n.change.path)} + + ); + } + const s = n.stash; + const { branch, text } = stashLabel(s.message); + return ( + + + {repos.length > 1 && s.repo ? `${repoName(s.repo)} · ` : ""} + {text} + + {branch && {branch}} + {formatTime(s.timeMs)} - {branch && {branch}} - {formatTime(s.timeMs)} - - ); - }} - /> + ); + }} + /> +
); } diff --git a/src/features/vcs/__tests__/multiRootStashes.test.tsx b/src/features/vcs/__tests__/multiRootStashes.test.tsx index eb4458cf9..d47015104 100644 --- a/src/features/vcs/__tests__/multiRootStashes.test.tsx +++ b/src/features/vcs/__tests__/multiRootStashes.test.tsx @@ -1,6 +1,11 @@ import { beforeEach, expect, it, vi } from "vitest"; import { act, fireEvent, render, screen } from "@testing-library/react"; -const { apply, list } = vi.hoisted(() => ({ apply: vi.fn(), list: vi.fn() })); +const { apply, list, files, diff } = vi.hoisted(() => ({ + apply: vi.fn(), + list: vi.fn(), + files: vi.fn(), + diff: vi.fn(), +})); vi.mock("@/platform/ipc", async (original) => { const real = await original(); return { @@ -8,6 +13,7 @@ vi.mock("@/platform/ipc", async (original) => { commands: { ...real.commands, vcsStashes: list, + vcsCommitFiles: files, }, }; }); @@ -15,15 +21,32 @@ vi.mock("../changeOps", async (original) => ({ ...(await original()), applyStash: apply, })); +vi.mock("../logChanges", async (original) => ({ + ...(await original()), + showChangesDiff: diff, +})); import { StashesPanel } from "../CommitView"; import { useVcs } from "../store"; beforeEach(() => { apply.mockReset(); + diff.mockReset().mockResolvedValue(undefined); + files.mockReset().mockResolvedValue({ + status: "ok", + data: [{ path: "src/app.ts", kind: "modified", oldPath: null }], + }); list.mockReset().mockImplementation((repo: string) => Promise.resolve({ status: "ok", - data: [{ index: 0, message: `On main: ${repo.endsWith("front") ? "First" : "Second"}`, timeMs: 0 }], + data: [ + { + index: 0, + message: `On main: ${repo.endsWith("front") ? "First" : "Second"}`, + timeMs: 0, + id: `${repo}-stash`, + base: `${repo}-base`, + }, + ], }), ); useVcs.setState({ root: "/p", roots: ["/p/front", "/p/back"], repo: "/p/front" }); @@ -53,9 +76,24 @@ it("disables stale stash actions while another repository is loading", async () expect(screen.queryByText("front · First")).not.toBeInTheDocument(); expect(screen.getByRole("button", { name: "Apply Stash" })).toBeDisabled(); await act(async () => { - resolve({ status: "ok", data: [{ index: 0, message: "On main: New project", timeMs: 0 }] }); + resolve({ status: "ok", data: [{ index: 0, message: "On main: New project", timeMs: 0, id: "n", base: "b" }] }); }); await screen.findByText("New project"); fireEvent.click(screen.getByRole("button", { name: "Apply Stash" })); expect(apply).toHaveBeenCalledWith(0, false, "/other"); }); + +it("lists a stash's changed files and opens their diff instead of applying the stash", async () => { + render(); + const row = await screen.findByText("front · First"); + // Double-clicking a stash expands it; it never applies the stash. + fireEvent.doubleClick(row); + expect(await screen.findByText("app.ts")).toBeInTheDocument(); + expect(files).toHaveBeenCalledWith("/p/front", "/p/front-stash"); + expect(apply).not.toHaveBeenCalled(); + fireEvent.doubleClick(screen.getByText("app.ts")); + expect(diff).toHaveBeenCalledTimes(1); + const [[change], preview] = diff.mock.calls[0]!; + expect(preview).toBe(false); + expect(change).toMatchObject({ path: "src/app.ts", before: "/p/front-base", after: "/p/front-stash" }); +}); diff --git a/src/features/vcs/__tests__/unstashViewDrop.test.tsx b/src/features/vcs/__tests__/unstashViewDrop.test.tsx index 15ca073f9..1245afaf1 100644 --- a/src/features/vcs/__tests__/unstashViewDrop.test.tsx +++ b/src/features/vcs/__tests__/unstashViewDrop.test.tsx @@ -48,7 +48,7 @@ import { VcsDialogHost } from "../dialogs"; import { showUnstashDialog } from "../changeOps"; import { useVcs } from "../store"; -const stash = (index: number, message: string): Stash => ({ index, message, timeMs: null }); +const stash = (index: number, message: string): Stash => ({ index, message, timeMs: null, id: `s${index}`, base: "b" }); beforeEach(() => { mocks.stashes = new Map([