diff --git a/crates/ide-host/src/ops/vcs/commands.rs b/crates/ide-host/src/ops/vcs/commands.rs index 75afbac1d..f4fe1f24a 100644 --- a/crates/ide-host/src/ops/vcs/commands.rs +++ b/crates/ide-host/src/ops/vcs/commands.rs @@ -151,6 +151,8 @@ impl LogAccess { pub struct VcsRoot { /// Worktree root. pub root: ide_core::IpcPath, + /// Root representing all mapped worktrees of the same Git repository in branch lists. + pub branch_root: ide_core::IpcPath, /// Merge / rebase / cherry-pick / revert in progress. pub operation: Option, /// Current branch; `None` when HEAD is detached (or unreadable). @@ -348,11 +350,28 @@ pub fn vcs_roots(host: &Host, window: &str) -> IdeResult> { let primary = repos.primary().map(|r| r.root().to_path_buf()); let mut all: Vec<&std::sync::Arc> = repos.all().iter().collect(); all.sort_by_key(|r| Some(r.root()) != primary.as_deref()); - Ok(all - .into_iter() - .map(|r| { + let roots: Vec<_> = all.into_iter().map(|repo| (repo, repo.metadata_dirs().ok())).collect(); + let mut branch_roots = std::collections::HashMap::new(); + for (repo, dirs) in &roots { + if let Some([git_dir, common_dir]) = dirs { + let first = branch_roots.entry(common_dir).or_insert(repo.root()); + if git_dir == common_dir { + *first = repo.root(); + } + } + } + Ok(roots + .iter() + .map(|(r, dirs)| { let (head, head_commit) = r.head().unwrap_or_default(); - VcsRoot { root: r.root().to_path_buf().into(), operation: r.operation().ok().flatten(), head, head_commit } + let branch_root = dirs.as_ref().and_then(|[_, common_dir]| branch_roots.get(common_dir)); + VcsRoot { + root: r.root().into(), + branch_root: branch_root.copied().unwrap_or_else(|| r.root()).into(), + operation: r.operation().ok().flatten(), + head, + head_commit, + } }) .collect()) } diff --git a/crates/ide-host/tests/vcs_worktrees.rs b/crates/ide-host/tests/vcs_worktrees.rs index ad6554405..ba5991d18 100644 --- a/crates/ide-host/tests/vcs_worktrees.rs +++ b/crates/ide-host/tests/vcs_worktrees.rs @@ -70,6 +70,13 @@ async fn command_added_worktree_joins_the_repository_set() { let roots = f.project.repos().roots(); assert!(roots.contains(&linked), "worktree below the project did not join the repository set: {roots:?}"); assert_eq!(roots.len(), 2); + let roots = vcs::vcs_roots(&f.host, "main").unwrap(); + assert_eq!(roots[0].root, f.root); + assert_eq!(roots[0].branch_root, f.root); + assert_eq!(roots[0].head.as_deref(), Some("main")); + assert_eq!(roots[1].root, linked); + assert_eq!(roots[1].branch_root, f.root); + assert_eq!(roots[1].head.as_deref(), Some("topic")); } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] diff --git a/src/bindings.ts b/src/bindings.ts index 8a7a151d3..321176248 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -12609,6 +12609,8 @@ export type VcsMappings = { export type VcsRoot = { /** Worktree root. */ root: IpcPath, + /** Root representing all mapped worktrees of the same Git repository in branch lists. */ + branchRoot: IpcPath, /** Merge / rebase / cherry-pick / revert in progress. */ operation: string | null, /** Current branch; `None` when HEAD is detached (or unreadable). */ diff --git a/src/features/vcs/BranchWidget.tsx b/src/features/vcs/BranchWidget.tsx index 29ff594d7..37e08d4d0 100644 --- a/src/features/vcs/BranchWidget.tsx +++ b/src/features/vcs/BranchWidget.tsx @@ -39,6 +39,7 @@ import { branchMenu, commonBranchMenu, inRepo, tagMenu } from "./branchMenu"; import { loadFavoriteBranches, recentBranches, toggleFavoriteBranch, useFavoriteBranches } from "./branchOps"; import { inProgress, operationTitle, type InProgress } from "./operations"; import { + branchRepositoryRoots, buildMultiRepoRows, currentRepoFor, preferredRepoRow, @@ -86,22 +87,32 @@ function useCurrentRepo(): string | null { return useVcs((s) => currentRepoFor(path, s.roots, s.repo)); } +function useBranchRepositories(current: string | null) { + const roots = useVcs((s) => s.roots); + const branchRoots = useVcs((s) => s.branchRoots); + return useMemo(() => branchRepositoryRoots(roots, branchRoots, current), [roots, branchRoots, current]); +} + export function BranchWidget() { const available = useVcs((s) => s.available); const selected = useVcs((s) => s.branch); - const count = useVcs((s) => s.roots.length); const current = useCurrentRepo(); + const roots = useBranchRepositories(current); + const heads = useVcs((s) => s.heads); + const branchRoot = useVcs((s) => (current ? (s.branchRoots[current] ?? current) : null)); // Several repositories on different branches: the widget names the current one. - const diverged = useVcs((s) => widgetShowsRepo(s.roots.map((r) => ({ head: s.heads[r]?.head ?? null })))); + const diverged = widgetShowsRepo(roots.map((r) => ({ head: heads[r]?.head ?? null }))); // The current repository is not the selected one: its HEAD from the last scan (no upstream). - const other = useVcs((s) => (diverged && current && current !== s.repo ? (s.heads[current] ?? null) : null)); + const other = useVcs((s) => + (diverged || roots.length === 1) && current && current !== s.repo ? (s.heads[current] ?? null) : null, + ); const otherOp = useVcs((s) => (current ? (s.operations[current] ?? null) : null)); const open = useBranchesPopup((s) => s.open); const extensions = useBranchWidgetExtensions((s) => s.extensions); if (!available || !selected) return null; // Another feature presents the current branch (the GitHub pull request on it). const presented = other ? null : branchPresentation(extensions); - const repo = diverged && current ? repoName(current) : null; + const repo = diverged && branchRoot ? repoName(branchRoot) : null; const branch: BranchInfo = other ? { head: other.head, headCommit: other.headCommit, upstream: null, ahead: 0, behind: 0, operation: otherOp } : selected; @@ -119,7 +130,7 @@ export function BranchWidget() { repo ? tx`Repository: ${repo}` : "", tx`Git branch: ${head}`, branch.upstream ? tx`Tracking ${branch.upstream}` : "", - count > 1 && !repo ? tx`In all ${count} repositories` : "", + roots.length > 1 && !repo ? tx`In all ${roots.length} repositories` : "", sync, ] .filter(Boolean) @@ -175,12 +186,14 @@ const POPUP_ACTIONS: PopupAction[] = [ { id: "vcs.push", label: "Push…", icon: "git-push", group: "sync" }, { id: "vcs.syncCommits", label: "Incoming and Outgoing Commits…", icon: "history", group: "sync" }, { id: "vcs.newBranch", label: "New Branch…", icon: "plus", group: "branch" }, + { id: "vcs.newWorktree", label: "New Worktree…", group: "branch" }, { id: "vcs.checkoutRevision", label: "Checkout Tag or Revision…", icon: "branch", group: "branch" }, ]; /** A single repository's own entries (its submenu in the popup with several repositories). */ const REPO_ACTIONS: PopupAction[] = [ { id: "vcs.newBranch", label: "New Branch…", icon: "plus", group: "branch" }, + { id: "vcs.newWorktree", label: "New Worktree…", group: "branch" }, { id: "vcs.checkoutRevision", label: "Checkout Tag or Revision…", icon: "branch", group: "branch" }, ]; @@ -394,7 +407,10 @@ const caretAt = (e: KeyboardEvent, where: "start" | "end") => { }; function BranchesPopup({ anchor, onClose }: { anchor: PopupAnchor; onClose: () => void }) { - const multi = useVcs((s) => s.roots.length > 1); + const current = useCurrentRepo(); + const roots = useBranchRepositories(current); + const selected = useVcs((s) => s.repo); + const multi = roots.length > 1; const extensions = useBranchWidgetExtensions((s) => s.extensions); const actions = useMemo(() => [...POPUP_ACTIONS, ...extensionPopupActions(extensions)], [extensions]); // ⌥⌘N is also Inline (enabled while a popup is open over an editor): the search field handles it here. @@ -417,9 +433,13 @@ function BranchesPopup({ anchor, onClose }: { anchor: PopupAnchor; onClose: () = onResized={savePopupSize} > {multi ? ( - + ) : ( - + )} ); @@ -443,8 +463,10 @@ function BranchesPanel({ onClose, actions: baseActions, root, fallback, onBack } const live = root === undefined || selected === root; const storeBranches = useVcs((s) => s.branches); const storeLoaded = useVcs((s) => s.branchesLoaded); - const branches = live && (storeLoaded || !fallback) ? storeBranches : (fallback ?? NO_BRANCHES); - const loaded = (live && storeLoaded) || !!fallback; + const [fetched, setFetched] = useState<{ root: string; branches: Branch[] }>(); + const otherBranches = fallback ?? (fetched && fetched.root === root ? fetched.branches : undefined); + const branches = live && (storeLoaded || !otherBranches) ? storeBranches : (otherBranches ?? NO_BRANCHES); + const loaded = (live && storeLoaded) || !!otherBranches; const current = useVcs((s) => live ? (s.branch?.head ?? null) : root ? (s.heads[root]?.head ?? null) : (s.branch?.head ?? null), ); @@ -456,9 +478,20 @@ function BranchesPanel({ onClose, actions: baseActions, root, fallback, onBack } const favorites = useFavoriteBranches((s) => s.names); const [tags, setTags] = useState([]); useEffect(() => { - if (root === undefined) void loadBranches().catch(() => undefined); + if (live) void loadBranches().catch(() => undefined); loadFavoriteBranches(); - }, [root]); + }, [root, live]); + useEffect(() => { + if (!root || live || fallback) return; + let active = true; + call(commands.vcsBranches(root)).then( + (branches) => active && setFetched({ root, branches }), + () => undefined, + ); + return () => { + active = false; + }; + }, [root, live, fallback]); useEffect(() => { let live = true; call(commands.vcsTags(root ?? currentRepo())).then( @@ -634,14 +667,23 @@ function SubMenu({ * each opening its own branches (on hover or →); then the branches they all have * (acting on all of them) or, when their branches differ, the current repository's. */ -function MultiRepoPanel({ onClose, actions: popupActions }: { onClose: () => void; actions: readonly PopupAction[] }) { +function MultiRepoPanel({ + onClose, + actions: popupActions, + roots, + current, +}: { + onClose: () => void; + actions: readonly PopupAction[]; + roots: readonly string[]; + current: string | null; +}) { const rowHeight = useRowHeight(ROW_HEIGHT); - const roots = useVcs((s) => s.roots); + const branchRoots = useVcs((s) => s.branchRoots); const heads = useVcs((s) => s.heads); const operations = useVcs((s) => s.operations); const version = useVcs((s) => s.version); const favorites = useFavoriteBranches((s) => s.names); - const current = useCurrentRepo(); const [recent] = useState(recentBranches); const [tags, setTags] = useState([]); const [query, setQuery] = useState(""); @@ -687,20 +729,24 @@ function MultiRepoPanel({ onClose, actions: popupActions }: { onClose: () => voi () => roots.map((root) => ({ root, - name: repoName(root), + name: repoName(branchRoots[root] ?? root), head: heads[root]?.head ?? null, headCommit: heads[root]?.headCommit ?? null, })), - [roots, heads], + [roots, heads, branchRoots], ); const op = useVcs((s) => inProgress(s.branch?.operation)); const conflicts = useVcs((s) => s.status.filter((f) => f.unstaged === "conflicted").length); const actions = useMemo( () => [ ...operationActions(op, conflicts), - ...popupActions.map((a) => (a.id === "vcs.newBranch" && sync ? { ...a, arg: { repos: roots } } : a)), + ...popupActions.map((a) => { + if (a.id === "vcs.newBranch" && sync) return { ...a, arg: { repos: roots } }; + if (a.id === "vcs.newWorktree") return { ...a, arg: { repo: current } }; + return a; + }), ], - [op, conflicts, roots, popupActions, sync], + [op, conflicts, roots, popupActions, sync, current], ); const rows = useMemo( () => diff --git a/src/features/vcs/__tests__/logBranches.test.tsx b/src/features/vcs/__tests__/logBranches.test.tsx index db113c7ea..ae8523194 100644 --- a/src/features/vcs/__tests__/logBranches.test.tsx +++ b/src/features/vcs/__tests__/logBranches.test.tsx @@ -96,6 +96,18 @@ describe("Git Log branches pane", () => { expect(screen.getByText("feature").closest("[data-row]")).toHaveAttribute("aria-selected", "true"); }); + it("passes the selected branch to New Worktree", async () => { + render( + <> + + + , + ); + fireEvent.contextMenu(screen.getByText("feature")); + fireEvent.click(await screen.findByRole("menuitem", { name: "New Worktree from 'feature'…" })); + expect(execute).toHaveBeenCalledWith("vcs.newWorktree", { repo: "/p", branch: branches[1] }); + }); + it.each([ [2, 0], [0, 3], @@ -206,7 +218,7 @@ describe("Git Log branches pane with several repositories", () => { branches: aBranches, }); }); - afterEach(() => useVcs.setState({ roots: [], heads: {} })); + afterEach(() => useVcs.setState({ roots: [], branchRoots: {}, heads: {} })); it("lists branches once, naming the repositories of partial ones", async () => { render(); @@ -235,6 +247,31 @@ describe("Git Log branches pane with several repositories", () => { expect(screen.getByText("other")).toBeInTheDocument(); }); + it("groups linked worktrees together and honors an explicit worktree path filter", async () => { + const linked = "/p/linked"; + const worktreeBranches = aBranches.map((branch) => ({ ...branch, current: branch.name === "dev" })); + repoData.branches[linked] = worktreeBranches; + useVcs.setState({ roots: [linked, "/p/a", "/p/b"], branchRoots: { [linked]: "/p/a" } }); + render( + <> + + + , + ); + expect((await screen.findByText("solo")).closest("[data-row]")).toHaveTextContent("(a)"); + expect(screen.queryByText("(a, linked)")).toBeNull(); + fireEvent.click(screen.getByRole("button", { name: "Group by Repository" })); + expect(await screen.findAllByText("dev")).toHaveLength(2); + expect(screen.queryByText("linked")).toBeNull(); + + act(() => useGitLog.setState({ filters: { ...emptyFilters(), paths: [linked] } })); + expect(await screen.findByText("solo")).toBeInTheDocument(); + expect(screen.queryByText("other")).toBeNull(); + expect(screen.getByText("dev").closest("[data-row]")).toHaveTextContent(/dev\s*current/); + fireEvent.doubleClick(screen.getByText("dev")); + expect(useGitLog.getState().filters).toMatchObject({ branches: ["dev"], paths: [linked], repositories: [linked] }); + }); + it("keeps the current marker ahead of the repository names, which may be cut off", async () => { repoData.branches = { "/p/a": [b("main", { current: true }), b("dev")], "/p/b": [b("dev", { current: true })] }; render(); diff --git a/src/features/vcs/__tests__/worktreesPanel.test.tsx b/src/features/vcs/__tests__/worktreesPanel.test.tsx index 49c663f06..70a542111 100644 --- a/src/features/vcs/__tests__/worktreesPanel.test.tsx +++ b/src/features/vcs/__tests__/worktreesPanel.test.tsx @@ -1,8 +1,10 @@ import { afterEach, beforeEach, expect, it, vi } from "vitest"; import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; -const { list, move, remove, open, confirm, windowOpenRemote } = vi.hoisted(() => ({ +const { list, add, branches, move, remove, open, confirm, windowOpenRemote } = vi.hoisted(() => ({ list: vi.fn(), + add: vi.fn(), + branches: vi.fn(), move: vi.fn(), remove: vi.fn(), open: vi.fn(), @@ -16,6 +18,8 @@ vi.mock("@/platform/ipc", async (original) => { commands: { ...real.commands, vcsWorktrees: list, + vcsAddWorktree: add, + vcsBranches: branches, vcsMoveWorktree: move, vcsRemoveWorktree: remove, windowOpenRemote, @@ -28,7 +32,8 @@ vi.mock("../dialogs", async (original) => ({ confirmDialog: confirm, })); -import { WorktreesPanel } from "../gitMenuDialogs"; +import { showNewWorktree, WorktreesPanel } from "../gitMenuDialogs"; +import { VcsDialogHost } from "../dialogs"; import { useVcs } from "../store"; import { useProject } from "@/platform/project"; import { useRemote } from "@/platform/remote"; @@ -49,6 +54,8 @@ const rowAt = async (path: string) => beforeEach(() => { useProject.setState({ project: { root: "/work/app-feature" } as never }); list.mockReset().mockResolvedValue(ok(worktrees)); + add.mockReset().mockResolvedValue(ok(null)); + branches.mockReset().mockResolvedValue(ok([])); move.mockReset(); remove.mockReset(); open.mockReset(); @@ -56,6 +63,43 @@ beforeEach(() => { useVcs.setState({ root: "/work/app-feature", roots: ["/work/app-feature"], repo: null }); }); +it("creates and opens a worktree from the selected branch, requiring a new branch when it is already checked out", async () => { + const run = vi.fn(); + const dispose = registerAction({ id: "file.openProjectPath", title: "Open Project Path", run }); + try { + render(); + act(() => + showNewWorktree({ + repo: "/work/app", + branch: { name: "feature", current: false, remote: false }, + open: true, + }), + ); + expect(await screen.findByRole("dialog", { name: "New Worktree" })).toBeInTheDocument(); + const newBranch = screen.getByRole("checkbox", { name: "Create a new branch" }); + await waitFor(() => expect(newBranch).toBeDisabled()); + expect(newBranch).toBeChecked(); + expect(screen.getByRole("textbox", { name: "New branch name" })).toHaveAttribute("placeholder", "feature-wt"); + expect(screen.getByRole("textbox", { name: "Folder" })).toHaveValue("/work/app-feature-wt"); + fireEvent.click(screen.getByRole("button", { name: "Create and Open Worktree" })); + await waitFor(() => + expect(run).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + arg: { path: "/work/app-feature-wt", newWindow: true }, + }), + ), + ); + expect(add).toHaveBeenCalledExactlyOnceWith( + "/work/app", + "/work/app-feature-wt", + "refs/heads/feature", + "feature-wt", + ); + } finally { + dispose(); + } +}); + it("marks the linked project root current when its main worktree is also listed", async () => { render(); expect((await rowAt("/work/app-feature")).getByRole("img", { name: "current" })).toBeInTheDocument(); diff --git a/src/features/vcs/actions.tsx b/src/features/vcs/actions.tsx index b874bc0ef..0f6d3e415 100644 --- a/src/features/vcs/actions.tsx +++ b/src/features/vcs/actions.tsx @@ -1,5 +1,6 @@ import { showShelfDiff } from "./shelf"; import { commitRepo } from "./multiRoot"; +import type { Branch } from "@/bindings"; /** VCS actions (ids match keymaps/intellij-macos.ts where bound). */ import { executeAction, registerActions, type Action } from "@/platform/actions"; import { getContext } from "@/platform/context"; @@ -354,7 +355,10 @@ export function registerVcsActions(): () => void { category: "Git", when: VCS, keywords: ["worktree"], - run: () => showNewWorktree(), + run: ({ arg }) => { + const branch = (arg as { branch?: Pick } | undefined)?.branch; + showNewWorktree({ repo: operationRepo(arg), branch, open: true }); + }, }, { id: "vcs.worktrees", diff --git a/src/features/vcs/branchMenu.ts b/src/features/vcs/branchMenu.ts index c16cad6fa..05d93bbca 100644 --- a/src/features/vcs/branchMenu.ts +++ b/src/features/vcs/branchMenu.ts @@ -65,6 +65,13 @@ function historyMenuItem(name: string, run: Run): MenuItem { return { label: "Show History", icon: "history", run: run(() => executeAction("vcs.showLog", { branch: name })) }; } +function worktreeMenuItem(branch: Pick, run: Run, repo?: string): MenuItem { + return { + label: tx`New Worktree from '${branch.name}'…`, + run: run(() => executeAction("vcs.newWorktree", { repo: repo ?? currentRepo(), branch })), + }; +} + /** The Branches pane's context menu: `selected` carries the multi-selection, which Update Selected and Delete act on as a whole. */ export function branchMenu( b: Branch, @@ -92,6 +99,7 @@ export function branchMenu( if (b.current) { return [ { label: tx`New Branch from '${b.name}'…`, icon: "branch", run: run(() => newBranch()) }, + worktreeMenuItem(b, run), { kind: "separator" }, update, { label: "Push…", icon: "git-push", run: run(() => executeAction("vcs.push", { repo: currentRepo() })) }, @@ -104,6 +112,7 @@ export function branchMenu( const items: MenuItem[] = [ { label: "Checkout", run: run(() => checkoutBranch(b.name)) }, { label: tx`New Branch from '${b.name}'…`, icon: "branch", run: run(() => newBranch(b.name)) }, + worktreeMenuItem(b, run), ...(current ? [{ label: tx`Checkout and Rebase onto '${cur}'`, run: run(() => checkoutAndRebase(b.name)) }] : []), { kind: "separator" }, { label: tx`Compare with '${cur}'`, icon: "diff", run: run(() => showCompareBranches(b.name)) }, @@ -185,9 +194,12 @@ export function commonBranchMenu( run: run(() => newBranchInRepos(roots, b.name)), }; const rename: MenuItem = { label: "Rename…", run: run(() => renameInRepos(b.name, roots, b.upstream)) }; + const currentRoot = currentRepo(); + const worktree = worktreeMenuItem(b, run, roots.find((root) => root === currentRoot) ?? roots[0]); if (b.current) return [ newFrom, + worktree, { kind: "separator" }, { label: "Update", icon: "git-pull", run: run(() => executeAction("vcs.update")) }, { label: "Push…", icon: "git-push", run: run(() => executeAction("vcs.push")) }, @@ -197,6 +209,7 @@ export function commonBranchMenu( const items: MenuItem[] = [ { label: "Checkout", run: run(() => checkoutInRepos(b.name, roots)) }, newFrom, + worktree, ...(current ? [ { diff --git a/src/features/vcs/gitMenuDialogs.tsx b/src/features/vcs/gitMenuDialogs.tsx index ea8e0817b..55f566d56 100644 --- a/src/features/vcs/gitMenuDialogs.tsx +++ b/src/features/vcs/gitMenuDialogs.tsx @@ -25,7 +25,8 @@ import { } from "@/ui"; import { useRowHeight } from "@/ui/density"; import { sortLocal, sortRemote } from "./branches"; -import { conflictActions, openConflictsInstead, validateBranchName } from "./branchOps"; +import { branchRef, conflictActions, openConflictsInstead, validateBranchName } from "./branchOps"; +import { joinPath } from "./clone"; import { cleanUpBranchNameOnTyping } from "@/platform/gitRefName"; import { confirmDialog, openDialog } from "./dialogs"; import { errorMessage, runOp, runRemote, saveAll } from "./ops"; @@ -797,10 +798,24 @@ export function showWorktrees() { openDialog((close) => ); } -export function showNewWorktree(onCreated?: () => void, repo?: string | null) { +type WorktreeSource = Pick; + +export function showNewWorktree({ + onCreated, + repo, + branch, + open = false, +}: { + onCreated?: () => void; + repo?: string | null; + branch?: WorktreeSource; + open?: boolean; +} = {}) { openDialog((close) => ( { close(); if (created) onCreated?.(); @@ -960,7 +975,9 @@ export function WorktreesPanel({ className, listClassName }: { className?: strin icon="plus" title="New Worktree…" size="small" - onClick={() => showNewWorktree(() => void reload(), currentGroup?.root ?? repo ?? repos[0])} + onClick={() => + showNewWorktree({ onCreated: () => void reload(), repo: currentGroup?.root ?? repo ?? repos[0] }) + } /> void; }) { const [repo] = useState(() => initialRepo ?? currentRepo()); const [root] = useState(() => initialRepo ?? useVcs.getState().repo ?? useVcs.getState().root ?? ""); const branches = useBranches(repo); - const [source, setSource] = useState(null); - const [createBranch, setCreateBranch] = useState(true); + const initialRef = branch ? branchRef(branch.name, branch.remote) : null; + const [source, setSource] = useState(initialRef); + const [createBranchChoice, setCreateBranch] = useState(null); const [newBranch, setNewBranch] = useState(""); - const { ref: branchRef, clean: cleanBranch } = useSanitizedField(cleanUpBranchNameOnTyping); + const { ref: branchInput, clean: cleanBranch } = useSanitizedField(cleanUpBranchNameOnTyping); const [path, setPath] = useState(null); const [error, setError] = useState(null); - const options = useMemo( - () => [...branchOptions(sortLocal(branches)), ...branchOptions(sortRemote(branches))], + const [busy, setBusy] = useState(false); + const [worktrees, setWorktrees] = useState([]); + useEffect(() => { + let live = true; + call(commands.vcsWorktrees(repo)).then( + (worktrees) => live && setWorktrees(worktrees), + () => undefined, + ); + return () => { + live = false; + }; + }, [repo]); + const sources = useMemo( + () => [...sortLocal(branches), ...sortRemote(branches)].filter((b) => !b.remote || !b.name.endsWith("/HEAD")), [branches], ); - const sourceRemote = branches.find((b) => b.name === source)?.remote ?? false; - // A remote branch `origin/x` suggests the local name `x`. - const shortSource = source && sourceRemote ? source.slice(source.indexOf("/") + 1) : (source ?? ""); - const suggestedBranch = source ? (sourceRemote ? shortSource : `${shortSource}-wt`) : ""; + const options: SelectOption[] = sources.map((b) => ({ + value: branchRef(b.name, b.remote), + label: b.name, + icon: "branch", + })); + if (branch && initialRef && !options.some((option) => option.value === initialRef)) { + options.unshift({ value: initialRef, label: branch.name, icon: "branch" }); + } + const selected = + sources.find((b) => branchRef(b.name, b.remote) === source) ?? (source === initialRef ? branch : null); + const checkedOut = + !!selected && !selected.remote && (selected.current || worktrees.some((w) => w.branch === selected.name)); + const createBranch = checkedOut || selected?.remote || (createBranchChoice ?? !branch); + const shortSource = selected?.remote ? selected.name.slice(selected.name.indexOf("/") + 1) : (selected?.name ?? ""); + const suggestedBranch = + selected?.remote && !sources.some((b) => !b.remote && b.name === shortSource) + ? shortSource + : shortSource && `${shortSource}-wt`; const branchName = newBranch.trim() || suggestedBranch; const target = path ?? (source ? defaultWorktreePath(root, createBranch ? branchName : shortSource) : ""); const invalid = !source ? "Choose what to check out" - : createBranch - ? validateBranchName(branchName) - : !target.trim() - ? "Enter a folder" + : !target.trim() + ? "Enter a folder" + : createBranch + ? validateBranchName(branchName) : null; const create = async () => { - if (invalid || !source) return; + if (invalid || !source || !selected || busy) return; + const folder = target.trim(); + const absolute = /^([a-zA-Z]:)?[\\/]/.test(folder) ? folder : joinPath(root, folder); + setBusy(true); + setError(null); try { - await call(commands.vcsAddWorktree(repo, target.trim(), source, createBranch ? branchName : null)); - notifications().notify({ group: "vcs", level: "info", title: `Created worktree at ${target.trim()}` }); - void loadBranches().catch(() => undefined); - onClose(true); + await call( + commands.vcsAddWorktree( + repo, + absolute, + createBranch ? source : selected.name, + createBranch ? branchName : null, + ), + ); } catch (e) { setError(errorMessage(e)); + setBusy(false); + return; } + notifications().notify({ group: "vcs", level: "info", title: `Created worktree at ${absolute}` }); + void loadBranches().catch(() => undefined); + onClose(true); + if (openAfterCreate) void openWorktree(absolute, true); }; return ( @@ -1127,7 +1189,12 @@ function NewWorktreeDialog({ onClose={() => onClose(false)} width={520} buttons={[ - { label: "Create", role: "default", disabled: !!invalid, onClick: () => void create() }, + { + label: openAfterCreate ? "Create and Open Worktree" : "Create", + role: "default", + disabled: busy || !!invalid, + onClick: () => void create(), + }, { label: "Cancel", role: "cancel" }, ]} > @@ -1142,10 +1209,15 @@ function NewWorktreeDialog({ options={options} onChange={setSource} /> - + {createBranch && ( s.generation); const selectedBranches = useVcs((s) => s.branches); - const availableRepositories = useLogRepositories(); + const logRepositories = useLogRepositories(); + const branchRoots = useVcs((s) => s.branchRoots); + const availableRepositories = useMemo( + () => branchRepositoryRoots(logRepositories, branchRoots), + [logRepositories, branchRoots], + ); const filters = useGitLog((s) => s.filters); + const { path, paths, repositories: repositoryFilter } = filters; const repositories = useMemo( - () => scopedLogRepositories(availableRepositories, filters, availableRepositories), - [availableRepositories, filters], + () => + branchRepositoryRoots( + scopedLogRepositories(logRepositories, { path, paths, repositories: repositoryFilter }, logRepositories), + branchRoots, + ), + [logRepositories, path, paths, repositoryFilter, branchRoots], + ); + const queriedRepositories = useMemo( + () => [...new Set([...availableRepositories, ...repositories])], + [availableRepositories, repositories], ); - const scopedRepo = availableRepositories.length > 1 && repositories.length === 1 ? repositories[0] : undefined; const readOnly = useReadOnlyLog(); const version = useVcs((s) => s.version); const [allBranches, setAllBranches] = useState>({}); @@ -100,6 +113,10 @@ export function BranchesPanel() { } }; const currentRepository = currentRepo(); + const scopedRepo = + repositories.length === 1 && (logRepositories.length > 1 || repositories[0] !== currentRepository) + ? repositories[0] + : undefined; const branches = useMemo( () => repositories.length === 1 && repositories[0] !== currentRepository @@ -128,16 +145,16 @@ export function BranchesPanel() { }, [root, selectedBranches, availableRepositories]); useEffect(() => { let live = true; - void branchesByRepo(availableRepositories) + void branchesByRepo(queriedRepositories) .then((value) => live && setAllBranches(value)) .catch(() => undefined); - void Promise.all(availableRepositories.map(async (r) => [r, await call(commands.vcsTags(r))] as const)) + void Promise.all(queriedRepositories.map(async (r) => [r, await call(commands.vcsTags(r))] as const)) .then((value) => live && setAllTags(Object.fromEntries(value))) .catch(() => undefined); return () => { live = false; }; - }, [availableRepositories, version, logGeneration]); + }, [queriedRepositories, version, logGeneration]); const merged = repositories.length > 1 && !grouped; const allRoots = useMemo(() => { if (!repositories.length && availableRepositories.length) return []; @@ -145,7 +162,7 @@ export function BranchesPanel() { return buildBranchTree(branches, favorites, scopedRepo ? (allTags[scopedRepo] ?? []) : tags); const list = repositories.map((repo) => ({ root: repo, - name: repoName(repo), + name: repoName(branchRoots[repo] ?? repo), branches: allBranches[repo] ?? [], tags: allTags[repo] ?? [], })); @@ -155,6 +172,7 @@ export function BranchesPanel() { }, [ repositories, availableRepositories, + branchRoots, allBranches, allTags, branches, diff --git a/src/features/vcs/openWorktree.ts b/src/features/vcs/openWorktree.ts index c456c4a0a..265c3a37f 100644 --- a/src/features/vcs/openWorktree.ts +++ b/src/features/vcs/openWorktree.ts @@ -8,10 +8,10 @@ import { notifications } from "@/workbench/contributions"; * Opens worktree `path` in a new window. In an SSH or WSL session the path is on that * machine, so the window connects there instead of opening it as a local folder. */ -export async function openWorktree(path: string): Promise { +export async function openWorktree(path: string, newWindow = false): Promise { const target = useRemote.getState().session?.target; if (target?.kind !== "ssh" && target?.kind !== "wsl") { - await executeAction("file.openProjectPath", path); + await executeAction("file.openProjectPath", newWindow ? { path, newWindow } : path); return; } try { diff --git a/src/features/vcs/repoBranches.ts b/src/features/vcs/repoBranches.ts index f28cddbf0..de7ba6da1 100644 --- a/src/features/vcs/repoBranches.ts +++ b/src/features/vcs/repoBranches.ts @@ -63,6 +63,20 @@ export function widgetShowsRepo(repos: readonly Pick[]): bool return !first || repos.some((r) => r.head !== first); } +export function branchRepositoryRoots( + roots: readonly string[], + branchRoots: Readonly>, + current?: string | null, +): string[] { + const repositories = new Map(); + for (const root of roots) { + const group = branchRoots[root] ?? root; + const previous = repositories.get(group); + if (!previous || root === current || (root === group && previous !== current)) repositories.set(group, root); + } + return [...repositories.values()]; +} + export interface CommonBranch { name: string; remote: boolean; diff --git a/src/features/vcs/store.switch.test.ts b/src/features/vcs/store.switch.test.ts index 5d800afee..addbbf3b9 100644 --- a/src/features/vcs/store.switch.test.ts +++ b/src/features/vcs/store.switch.test.ts @@ -29,7 +29,9 @@ const branch: BranchInfo = { behind: 0, operation: "merge", }; -const roots: VcsRoot[] = [{ root: git.root, head: branch.head, headCommit: branch.headCommit, operation: "merge" }]; +const roots: VcsRoot[] = [ + { root: git.root, branchRoot: git.root, head: branch.head, headCommit: branch.headCommit, operation: "merge" }, +]; const conflicted: FileStatus = { path: "/a/src/conflict.ts", relPath: "src/conflict.ts", @@ -174,7 +176,15 @@ describe("VCS status ownership", () => { await vi.waitFor(() => expect(request).toHaveBeenCalledWith([conflicted.path])); const nextBranch = { ...branch, head: "main", operation: null }; vi.mocked(commands.vcsRoots).mockResolvedValue( - ok([{ root: nonGit.root, head: nextBranch.head, headCommit: nextBranch.headCommit, operation: null }]), + ok([ + { + root: nonGit.root, + branchRoot: nonGit.root, + head: nextBranch.head, + headCommit: nextBranch.headCommit, + operation: null, + }, + ]), ); vi.mocked(commands.vcsStatus).mockResolvedValue(ok([])); vi.mocked(commands.vcsBranchInfo).mockResolvedValue(ok(nextBranch)); @@ -248,7 +258,7 @@ describe("VCS status ownership", () => { }; const remainingStatus = { ...modified, path: remaining + "/src/edited.ts" }; vi.mocked(commands.vcsRoots).mockResolvedValue( - ok([{ root: remaining, head: "main", headCommit: "def1234", operation: null }]), + ok([{ root: remaining, branchRoot: remaining, head: "main", headCommit: "def1234", operation: null }]), ); vi.mocked(commands.vcsStatus).mockResolvedValue(ok([remainingStatus])); vi.mocked(commands.vcsBranchInfo).mockImplementation(async (repo) => { diff --git a/src/features/vcs/store.ts b/src/features/vcs/store.ts index 69ac2e2d9..3d6f80d9a 100644 --- a/src/features/vcs/store.ts +++ b/src/features/vcs/store.ts @@ -28,6 +28,7 @@ export interface VcsState { root: string | null; /** Repository roots, the project's own repository first. */ roots: string[]; + branchRoots: Record; /** Root → merge / rebase / cherry-pick / revert in progress there. */ operations: Record; /** Root → its current branch (`head` null when detached) and HEAD commit. */ @@ -56,6 +57,7 @@ const initial: VcsState = { available: false, root: null, roots: [], + branchRoots: {}, operations: {}, heads: {}, repo: null, @@ -267,8 +269,10 @@ export function refreshNow(): Promise { const shown = s.repo && roots.includes(s.repo) ? s.repo : (roots[0] ?? null); const repo = attentionRepo(shown, s.operations, operations) ?? shown; const heads = Object.fromEntries(vcsRoots.map((r) => [r.root, { head: r.head, headCommit: r.headCommit }])); - useVcs.setState({ operations, heads }); const sameRoots = roots.join("\n") === s.roots.join("\n"); + const branchRoots = Object.fromEntries(vcsRoots.map((r) => [r.root, r.branchRoot])); + const sameBranchRoots = sameRoots && roots.every((root) => branchRoots[root] === s.branchRoots[root]); + useVcs.setState({ operations, heads, branchRoots: sameBranchRoots ? s.branchRoots : branchRoots }); if (repo !== s.repo || !sameRoots) useVcs.setState({ roots: sameRoots ? s.roots : roots, repo }); applyStatus(status.files, branch); useVcs.setState({ branches, stashes, error: null }); diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index a35f4407a..ecbc7a55d 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -161,6 +161,8 @@ "A finished pinned tab stays open: a later run opens a new tab instead of taking its place.": "A finished pinned tab stays open: a later run opens a new tab instead of taking its place.", "Cannot paste the image into {name}": "Cannot paste the image into {name}", "Worktree Conflict": "Worktree Conflict", + "New Worktree from '{name}'…": "New Worktree from '{name}'…", + "Create and Open Worktree": "Create and Open Worktree", "Branch '{branch}' is already checked out in a worktree at:\n{path}": "Branch '{branch}' is already checked out in a worktree at:\n{path}", "Checkout Anyway": "Checkout Anyway", "Open Existing Worktree": "Open Existing Worktree", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 8c347cdbf..6affa6d5d 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -3558,6 +3558,7 @@ "Worktrees…": "工作树…", "Worktrees": "工作树", "New Worktree": "新建工作树", + "Create and Open Worktree": "创建并打开工作树", "Git Remotes": "Git 远程", "Define Remote": "定义远程", "Edit Remote": "编辑远程", @@ -5122,6 +5123,7 @@ "Revert from Local History": "从本地历史记录还原", "{submodule} points to another commit. Check out the recorded commit in the submodule (git submodule update) to revert it.": "{submodule} 指向另一个提交。请在子模块中签出记录的提交 (git submodule update) 以还原它。", "New Branch from '{name}'…": "从 '{name}' 新建分支…", + "New Worktree from '{name}'…": "从 '{name}' 新建工作树…", "Rebase Current onto '{name}'": "将当前分支变基到 '{name}'", "Merge '{name}' into Current": "将 '{name}' 合并到当前分支", "Checkout and Rebase onto '{current}'": "签出并变基到 '{current}'",