Files
openidea/src/features/vcs/gitMenuDialogs.tsx
T
Mansur Akhmadiandmansur-akhmadi 3c91adfae2 feat(vcs): choose the repository in the Rebase dialog when the project has several (#3351)
Git > Rebase… always rebased the repository selected in the branch widget. With two or more repositories the dialog now has the repository combo: picking one reloads its branches and the label, clears the chosen upstream and --onto base, and Rebase runs in that repository.

Co-authored-by: mansur-akhmadi <10739460+mansur-akhmadi@users.noreply.github.com>
2026-11-14 22:12:34 +08:00

940 lines
32 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/** Git menu dialogs: Pull…, Merge…, Rebase…, Manage Remotes… and Worktrees. */
import { useEffect, useMemo, useRef, useState } from "react";
import clsx from "clsx";
import type { Branch, BranchInfo, MergeOptions, Remote, Worktree } from "@/bindings";
import { executeAction } from "@/platform/actions";
import { call, commands } from "@/platform/ipc";
import { notifications } from "@/workbench/contributions";
import {
Checkbox,
Dialog,
HighlightedText,
Icon,
IconButton,
Input,
Select,
T,
Tree,
useSanitizedField,
type SelectOption,
} from "@/ui";
import { sortLocal, sortRemote } from "./branches";
import { conflictActions, openConflictsInstead, validateBranchName } from "./branchOps";
import { cleanUpBranchNameOnTyping } from "@/platform/gitRefName";
import { confirmDialog, openDialog } from "./dialogs";
import { errorMessage, runOp, runRemote, saveAll } from "./ops";
import { currentRepo, loadBranches, refreshNow, repoName, useVcs } from "./store";
import {
groupWorktrees,
isCurrentWorktree,
worktreeContainsProject,
worktreeMoveTarget,
type RepoWorktrees,
} from "./worktrees";
import styles from "./common.module.css";
import { tx } from "@/platform/i18n";
import { useProject } from "@/platform/project";
// --- shared -----------------------------------------------------------------
export type MergeFlag = "noFf" | "ffOnly" | "squash" | "noCommit";
/** Flags git refuses together with `flag`. */
const EXCLUSIVE: Record<MergeFlag, MergeFlag[]> = {
noFf: ["ffOnly", "squash"],
ffOnly: ["noFf", "squash", "noCommit"],
squash: ["noFf", "ffOnly"],
noCommit: ["ffOnly"],
};
/** Merge flags that cannot be turned on next to the `on` ones (and with `--rebase`). */
export function disabledMergeFlags(on: ReadonlySet<MergeFlag>, rebase = false): Set<MergeFlag> {
if (rebase) return new Set<MergeFlag>(["noFf", "ffOnly", "squash", "noCommit"]);
const out = new Set<MergeFlag>();
for (const f of on) for (const x of EXCLUSIVE[f]) out.add(x);
return out;
}
export function mergeOptionsOf(on: ReadonlySet<MergeFlag>, message: string | null = null): MergeOptions {
return {
noFf: on.has("noFf"),
ffOnly: on.has("ffOnly"),
squash: on.has("squash"),
noCommit: on.has("noCommit"),
message: message?.trim() || null,
};
}
const FLAG_LABELS: Array<[MergeFlag, string]> = [
["noFf", "--no-ff"],
["ffOnly", "--ff-only"],
["squash", "--squash"],
["noCommit", "--no-commit"],
];
function MergeFlags({
on,
setOn,
rebase = false,
}: {
on: Set<MergeFlag>;
setOn: (next: Set<MergeFlag>) => void;
rebase?: boolean;
}) {
const disabled = disabledMergeFlags(on, rebase);
return (
<div className={styles.optionGrid} role="group" aria-label={tx("Merge options")}>
{FLAG_LABELS.map(([flag, label]) => (
<Checkbox
key={flag}
label={label}
checked={on.has(flag)}
disabled={disabled.has(flag) && !on.has(flag)}
onChange={(v) => {
const next = new Set(on);
if (v) next.add(flag);
else next.delete(flag);
setOn(next);
}}
/>
))}
</div>
);
}
function useBranches(repo: string | null): Branch[] {
const [branches, setBranches] = useState<Branch[]>([]);
useEffect(() => {
let live = true;
void call(commands.vcsBranches(repo))
.then((b) => live && setBranches(b))
.catch(() => undefined);
return () => {
live = false;
};
}, [repo]);
return branches;
}
const branchOptions = (list: readonly Branch[]): SelectOption[] =>
list.filter((b) => !b.name.endsWith("/HEAD")).map((b) => ({ value: b.name, label: b.name, icon: "branch" }));
/** Remote branches of `remote` without the remote prefix (`origin/main` → `main`). */
export function remoteBranchesOf(branches: readonly Branch[], remote: string): string[] {
const prefix = `${remote}/`;
return sortRemote(branches)
.filter((b) => b.name.startsWith(prefix) && b.name !== `${prefix}HEAD`)
.map((b) => b.name.slice(prefix.length));
}
// --- Pull -------------------------------------------------------------------
export function showPullDialog() {
openDialog((close) => <PullDialog onClose={close} />);
}
/** IDEA's Git Root choice: shown only when the project holds several repositories. */
function RepoPicker({ repo, onChange }: { repo: string | null; onChange: (root: string) => void }) {
const [roots] = useState(() => useVcs.getState().roots);
if (roots.length < 2) return null;
return (
<Select
aria-label="Repository"
value={repo ?? roots[0] ?? null}
options={roots.map((root) => ({ value: root, label: repoName(root), verbatim: true }))}
onChange={onChange}
/>
);
}
/** The repository's branch info: the store's for the selected repository, else read from git. */
function useBranchInfo(repo: string | null) {
const [initial] = useState(() => ({ repo: currentRepo(), info: useVcs.getState().branch }));
const [loaded, setLoaded] = useState<{ repo: string | null; info: BranchInfo | null } | null>(null);
useEffect(() => {
if (repo === initial.repo) return;
let live = true;
void call(commands.vcsBranchInfo(repo))
.then((info) => live && setLoaded({ repo, info }))
.catch(() => live && setLoaded({ repo, info: null }));
return () => {
live = false;
};
}, [repo, initial.repo]);
if (repo === initial.repo) return initial.info;
return loaded?.repo === repo ? loaded.info : null;
}
function PullDialog({ onClose }: { onClose: () => void }) {
const [repo, setRepo] = useState(currentRepo);
const info = useBranchInfo(repo);
const branches = useBranches(repo);
const [remotes, setRemotes] = useState<Remote[] | null>(null);
const [remote, setRemote] = useState<string | null>(null);
const [chosenBranch, setBranch] = useState<string | null>(null);
const [rebase, setRebase] = useState(false);
const [flags, setFlags] = useState<Set<MergeFlag>>(() => new Set());
const chooseRepo = (root: string) => {
if (root === repo) return;
setRepo(root);
setRemotes(null);
setRemote(null);
setBranch(null);
};
useEffect(() => {
let alive = true;
call(commands.vcsRemotes(repo))
.then((list) => {
if (!alive) return;
setRemotes(list);
const upstreamRemote = info?.upstream?.split("/")[0];
setRemote(list.find((r) => r.name === upstreamRemote)?.name ?? list[0]?.name ?? null);
})
.catch(() => alive && setRemotes([]));
return () => {
alive = false;
};
}, [repo, info?.upstream]);
const remoteBranches = useMemo(() => (remote ? remoteBranchesOf(branches, remote) : []), [branches, remote]);
// Default: the upstream's branch, else the same name as the current branch.
const upstream = remote && info?.upstream?.startsWith(`${remote}/`) ? info.upstream.slice(remote.length + 1) : null;
const preferred = upstream ?? info?.head ?? null;
const branch =
chosenBranch && remoteBranches.includes(chosenBranch)
? chosenBranch
: preferred && remoteBranches.includes(preferred)
? preferred
: (remoteBranches[0] ?? null);
const run = async () => {
if (!remote) return;
onClose();
await saveAll();
await runRemote(
{
op: "pullFrom",
remote,
branches: branch ? [branch] : [],
rebase,
options: mergeOptionsOf(rebase ? new Set() : flags),
},
`${info?.head ?? "HEAD"} ← ${remote}${branch ? `/${branch}` : ""}`,
[repo],
);
};
return (
<Dialog
open
title={tx`Pull to ${info?.head ?? "HEAD"}`}
onClose={onClose}
width={460}
buttons={[
{ label: "Pull", role: "default", disabled: !remote, onClick: () => void run() },
{ label: "Cancel", role: "cancel" },
]}
>
<div className={styles.form}>
{remotes && !remotes.length ? (
<>
<RepoPicker repo={repo} onChange={chooseRepo} />
<div className={styles.hint}>
<T>No remotes are configured. Add one with Git › Manage Remotes….</T>
</div>
</>
) : (
<div className={styles.fieldRow}>
<RepoPicker repo={repo} onChange={chooseRepo} />
<Select
aria-label="Remote"
value={remote}
options={(remotes ?? []).map((r) => ({ value: r.name, label: r.name, detail: r.url }))}
onChange={setRemote}
/>
<Select
aria-label="Remote branch"
className={styles.grow}
value={branch}
placeholder="Branch"
options={remoteBranches.map((b) => ({ value: b, label: b, icon: "branch" }))}
onChange={setBranch}
/>
</div>
)}
<div className={styles.fieldLabel}>
<T>Options:</T>
</div>
<Checkbox label="--rebase" checked={rebase} onChange={setRebase} />
<MergeFlags on={flags} setOn={setFlags} rebase={rebase} />
<div className={styles.hint}>
<T>Uncommitted changes are stashed before the pull and restored afterwards.</T>
</div>
</div>
</Dialog>
);
}
// --- Merge ------------------------------------------------------------------
export function showMergeDialog() {
openDialog((close) => <MergeDialog onClose={close} />);
}
function MergeDialog({ onClose }: { onClose: () => void }) {
const [repo, setRepo] = useState(currentRepo);
const head = useBranchInfo(repo)?.head ?? null;
const branches = useBranches(repo);
const [branch, setBranch] = useState<string | null>(null);
const [flags, setFlags] = useState<Set<MergeFlag>>(() => new Set());
const [withMessage, setWithMessage] = useState(false);
const [message, setMessage] = useState("");
const options = useMemo(
() => [...branchOptions(sortLocal(branches).filter((b) => !b.current)), ...branchOptions(sortRemote(branches))],
[branches],
);
const chooseRepo = (root: string) => {
if (root === repo) return;
setRepo(root);
setBranch(null);
};
const run = async () => {
if (!branch) return;
onClose();
await saveAll();
const target = head ?? "HEAD";
await runOp(
tx`Merge ${branch} into ${target}`,
() => call(commands.vcsMergeWith(repo, [branch], mergeOptionsOf(flags, withMessage ? message : null))),
{ success: tx`Merged ${branch} into ${target}`, errorActions: conflictActions, onError: openConflictsInstead },
);
await refreshNow();
};
return (
<Dialog
open
title={tx`Merge into ${head ?? "HEAD"}`}
onClose={onClose}
width={460}
buttons={[
{ label: "Merge", role: "default", disabled: !branch, onClick: () => void run() },
{ label: "Cancel", role: "cancel" },
]}
>
<div className={styles.form}>
<RepoPicker repo={repo} onChange={chooseRepo} />
<div className={styles.fieldLabel}>
<T>Branch to merge:</T>
</div>
<Select
aria-label="Branch to merge"
value={branch}
placeholder="Select branch"
options={options}
onChange={setBranch}
/>
<div className={styles.fieldLabel}>
<T>Options:</T>
</div>
<MergeFlags on={flags} setOn={setFlags} />
<Checkbox label="-m (commit message)" checked={withMessage} onChange={setWithMessage} />
{withMessage && (
<Input
aria-label="Commit message"
value={message}
placeholder={branch ? tx`Merge branch '${branch}' into ${head ?? "HEAD"}` : ""}
onChange={(e) => setMessage(e.target.value)}
/>
)}
</div>
</Dialog>
);
}
// --- Rebase -----------------------------------------------------------------
export function showRebaseDialog() {
openDialog((close) => <RebaseDialog onClose={close} />);
}
function RebaseDialog({ onClose }: { onClose: () => void }) {
const [repo, setRepo] = useState(currentRepo);
const head = useBranchInfo(repo)?.head ?? null;
const branches = useBranches(repo);
const [upstream, setUpstream] = useState<string | null>(null);
const [useOnto, setUseOnto] = useState(false);
const [onto, setOnto] = useState<string | null>(null);
const [rebaseMerges, setRebaseMerges] = useState(false);
const [keepEmpty, setKeepEmpty] = useState(false);
const options = useMemo(
() => [...branchOptions(sortLocal(branches).filter((b) => !b.current)), ...branchOptions(sortRemote(branches))],
[branches],
);
const ready = !!upstream && (!useOnto || !!onto);
const chooseRepo = (root: string) => {
if (root === repo) return;
setRepo(root);
setUpstream(null);
setOnto(null);
};
const run = async () => {
if (!upstream) return;
onClose();
await saveAll();
const target = useOnto && onto ? onto : upstream;
const current = head ?? "HEAD";
await runOp(
tx`Rebase ${current} onto ${target}`,
() =>
call(
commands.vcsRebaseWith(repo, upstream, {
onto: useOnto ? onto : null,
rebaseMerges,
keepEmpty,
}),
),
{ success: tx`Rebased ${current} onto ${target}`, errorActions: conflictActions, onError: openConflictsInstead },
);
await refreshNow();
};
return (
<Dialog
open
title="Rebase"
onClose={onClose}
width={460}
buttons={[
{ label: "Rebase", role: "default", disabled: !ready, onClick: () => void run() },
{ label: "Cancel", role: "cancel" },
]}
>
<div className={styles.form}>
<RepoPicker repo={repo} onChange={chooseRepo} />
<div className={styles.fieldLabel}>
{useOnto ? tx`Rebase commits of ${head ?? "HEAD"} not on:` : `Rebase ${head ?? "HEAD"} onto:`}
</div>
<Select
aria-label="Upstream"
value={upstream}
placeholder="Select branch"
options={options}
onChange={setUpstream}
/>
<Checkbox label="--onto" checked={useOnto} onChange={setUseOnto} />
{useOnto && (
<Select aria-label="New base" value={onto} placeholder="New base" options={options} onChange={setOnto} />
)}
<Checkbox label="--rebase-merges" checked={rebaseMerges} onChange={setRebaseMerges} />
<Checkbox label="--keep-empty" checked={keepEmpty} onChange={setKeepEmpty} />
<div className={styles.hint}>
<T>Uncommitted changes are stashed before the rebase and restored afterwards.</T>
</div>
</div>
</Dialog>
);
}
// --- Manage Remotes ---------------------------------------------------------
/** Error for a remote name, or null (`existing`: the other remotes' names). */
export function validateRemoteName(name: string, existing: readonly string[]): string | null {
const n = name.trim();
if (!n) return "Enter a remote name";
if (/\s/.test(n) || n.startsWith("-") || /[~^:?*[\\]/.test(n) || n.includes("..")) return "Invalid remote name";
if (existing.includes(n)) return `Remote '${n}' already exists`;
return null;
}
export function showManageRemotes() {
openDialog((close) => <RemotesDialog onClose={close} />);
}
function RemotesDialog({ onClose }: { onClose: () => void }) {
const [repo] = useState(currentRepo);
const [remotes, setRemotes] = useState<Remote[]>([]);
const [selected, setSelected] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const reload = () =>
call(commands.vcsRemotes(repo))
.then((list) => {
setRemotes(list);
setSelected((s) => (s && list.some((r) => r.name === s) ? s : (list[0]?.name ?? null)));
})
.catch((e) => setError(errorMessage(e)));
useEffect(() => {
void reload();
}, []);
const apply = async (edit: Parameters<typeof commands.vcsEditRemote>[1]) => {
try {
await call(commands.vcsEditRemote(repo, edit));
setError(null);
} catch (e) {
setError(errorMessage(e));
}
await reload();
void loadBranches().catch(() => undefined);
};
const edit = (remote?: Remote) =>
openDialog((close) => (
<RemoteEditDialog
remote={remote}
existing={remotes.map((r) => r.name).filter((n) => n !== remote?.name)}
onDone={(r) => {
close();
if (!r) return;
void apply(
remote
? { op: "edit", name: remote.name, new_name: r.name, url: r.url }
: { op: "add", name: r.name, url: r.url },
);
}}
/>
));
const remove = async () => {
if (!selected) return;
const ok = await confirmDialog({
title: "Remove Remote",
message: tx`Remove remote '${selected}'? Its remote-tracking branches are deleted.`,
okLabel: "Remove",
danger: true,
});
if (ok) await apply({ op: "remove", name: selected });
};
const current = remotes.find((r) => r.name === selected);
return (
<Dialog
open
title="Git Remotes"
onClose={onClose}
width={560}
buttons={[{ label: "OK", role: "default", autoFocus: true, onClick: onClose }]}
>
<div className={styles.form}>
<div className={styles.manageBar} role="toolbar" aria-label={tx("Remotes")}>
<IconButton icon="plus" title="Add Remote…" size="small" onClick={() => edit()} />
<IconButton
icon="minus"
title="Remove Remote"
size="small"
disabled={!current}
onClick={() => void remove()}
/>
<IconButton icon="edit" title="Edit Remote…" size="small" disabled={!current} onClick={() => edit(current)} />
</div>
<div className={styles.choiceList} role="listbox" aria-label={tx("Remotes")}>
{!remotes.length && (
<div className={styles.empty}>
<T>No remotes</T>
</div>
)}
{remotes.map((r) => (
<button
key={r.name}
type="button"
role="option"
aria-selected={r.name === selected}
className={clsx(styles.manageRow, r.name === selected && styles.manageRowSelected)}
onClick={() => setSelected(r.name)}
onDoubleClick={() => edit(r)}
>
<span className={styles.fileName}>{r.name}</span>
<span className={clsx(styles.fileDir, styles.mono)}>{r.url}</span>
</button>
))}
</div>
{error && <div className={styles.error}>{error}</div>}
</div>
</Dialog>
);
}
function RemoteEditDialog({
remote,
existing,
onDone,
}: {
remote?: Remote;
existing: readonly string[];
onDone: (r: { name: string; url: string } | null) => void;
}) {
const [name, setName] = useState(remote?.name ?? (existing.includes("origin") ? "" : "origin"));
const [url, setUrl] = useState(remote?.url ?? "");
const error = validateRemoteName(name, existing) ?? (url.trim() ? null : "Enter the remote URL");
const submit = () => {
if (!error) onDone({ name: name.trim(), url: url.trim() });
};
return (
<Dialog
open
title={remote ? "Edit Remote" : "Define Remote"}
onClose={() => onDone(null)}
width={460}
buttons={[
{ label: "OK", role: "default", disabled: !!error, onClick: submit },
{ label: "Cancel", role: "cancel" },
]}
>
<form
className={styles.form}
onSubmit={(e) => {
e.preventDefault();
submit();
}}
>
<label className={styles.fieldLabel}>
<T>Name:</T>
</label>
<Input data-autofocus aria-label="Name" value={name} onChange={(e) => setName(e.target.value)} />
<label className={styles.fieldLabel}>
<T>URL:</T>
</label>
<Input aria-label="URL" mono value={url} onChange={(e) => setUrl(e.target.value)} />
{error && (name || url) && <div className={styles.error}>{error}</div>}
</form>
</Dialog>
);
}
// --- Worktrees --------------------------------------------------------------
/** Default folder of a new worktree: next to the repository, `<repo>-<branch>`. */
export function defaultWorktreePath(repoRoot: string, branch: string): string {
const sep = repoRoot.includes("\\") && !repoRoot.includes("/") ? "\\" : "/";
const trimmed = repoRoot.replace(/[\\/]+$/, "");
const cut = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));
const parent = cut > 0 ? trimmed.slice(0, cut) : trimmed;
const name = trimmed.slice(cut + 1);
const suffix = branch.replace(/[\\/]/g, "-");
return `${parent}${sep}${name}-${suffix || "worktree"}`;
}
export function showWorktrees() {
openDialog((close) => <WorktreesDialog onClose={close} />);
}
export function showNewWorktree(onCreated?: () => void, repo?: string | null) {
openDialog((close) => (
<NewWorktreeDialog
repo={repo}
onClose={(created) => {
close();
if (created) onCreated?.();
}}
/>
));
}
function WorktreesDialog({ onClose }: { onClose: () => void }) {
return (
<Dialog
open
title="Worktrees"
onClose={onClose}
width={620}
buttons={[{ label: "Close", role: "default", autoFocus: true, onClick: onClose }]}
>
<WorktreesPanel className={styles.form} />
</Dialog>
);
}
/** A repository section of the Worktrees tree; its children are the repository's worktrees. */
interface WorktreeNode {
key: string;
label: string;
worktree?: Worktree;
children?: WorktreeNode[];
}
/**
* The worktrees of every repository of the project as one tree, styled like the Log's
* Branches pane, with New / Remove / Open: the Worktrees dialog's content and the Git
* tool window's Worktrees tab. `listClassName` replaces the dialog's default height.
*/
export function WorktreesPanel({ className, listClassName }: { className?: string; listClassName?: string }) {
const projectRoot = useProject((s) => s.project?.root);
const repo = useVcs((s) => s.repo);
const repos = useVcs((s) => s.roots);
const [groups, setGroups] = useState<RepoWorktrees[]>([]);
/** The selected tree row (`r:` repository, `w:` worktree). */
const [selected, setSelected] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
/** The last reload wins: a scan of the roots may change them while it runs. */
const run = useRef(0);
const reload = () => {
const id = ++run.current;
return Promise.all(
repos.map((root) =>
call(commands.vcsWorktrees(root)).then(
(worktrees): RepoWorktrees => ({ root, worktrees }),
(e): RepoWorktrees => ({ root, worktrees: [], error: errorMessage(e) }),
),
),
).then((lists) => {
if (id !== run.current) return;
setGroups(groupWorktrees(lists));
setError(null);
});
};
useEffect(() => {
void reload();
}, [repos]);
const tree = useMemo(
() =>
groups.map((group): WorktreeNode => ({
// The main worktree names a repository across reloads (its linked roots come and go).
key: `r:${group.worktrees.find((w) => w.main)?.path ?? group.root}`,
label: repoName(group.root),
children: group.worktrees.map((w): WorktreeNode => ({
key: `w:${w.path}`,
label: w.branch ?? (w.head ? w.head.slice(0, 8) : tx("(bare)")),
worktree: w,
})),
})),
[groups],
);
const currentGroup = selected?.startsWith("w:")
? groups.find((g) => g.worktrees.some((w) => `w:${w.path}` === selected))
: undefined;
const current = currentGroup?.worktrees.find((w) => `w:${w.path}` === selected);
const containsProject = !!current && worktreeContainsProject(current.path, projectRoot);
const selectedKeys = useMemo(() => new Set(selected ? [selected] : []), [selected]);
const isCurrent = (path: string) => repos.some((root) => isCurrentWorktree(path, root));
const icon = (node: WorktreeNode) =>
node.worktree ? (isCurrent(node.worktree.path) ? "current-branch" : "branch") : "folder";
const detail = (node: WorktreeNode) => {
const w = node.worktree;
if (!w) return "";
const current = isCurrent(w.path);
// "main" only when the main worktree is not the one this window works in.
const flags = [
current ? tx("current") : w.main ? "main" : w.locked ? tx("locked") : w.prunable ? tx("prunable") : "",
].filter(Boolean);
return [...flags, w.path].join(" ");
};
const remove = async () => {
if (!current || !currentGroup || current.main || containsProject) return;
const ok = await confirmDialog({
title: "Remove Worktree",
message: tx`Remove the worktree at ${current.path}? Its folder is deleted.`,
okLabel: "Remove",
danger: true,
});
if (!ok) return;
try {
await call(commands.vcsRemoveWorktree(currentGroup.root, current.path, false));
} catch (e) {
const force = await confirmDialog({
title: "Remove Worktree",
message: tx`${errorMessage(e)}\n\nRemove it anyway, discarding its changes?`,
okLabel: "Force Remove",
danger: true,
});
if (force)
await call(commands.vcsRemoveWorktree(currentGroup.root, current.path, true)).catch((x) =>
setError(errorMessage(x)),
);
}
setSelected(null);
await reload();
};
const move = async () => {
if (!current || !currentGroup || current.main || containsProject) return;
const { open } = await import("@/platform/dialog");
const picked = await open({
directory: true,
multiple: false,
title: tx("Move Worktree"),
defaultPath: current.path.replace(/[\\/][^\\/]+[\\/]?$/, "") || undefined,
});
const folder = Array.isArray(picked) ? picked[0] : picked;
if (!folder) return;
const to = worktreeMoveTarget(current.path, folder);
if (isCurrentWorktree(to, current.path)) return;
const ok = await confirmDialog({
title: "Move Worktree",
message: tx`Move the worktree at ${current.path} to ${to}?`,
okLabel: "Move",
});
if (!ok) return;
try {
await call(commands.vcsMoveWorktree(currentGroup.root, current.path, to));
setSelected(`w:${to}`);
} catch (e) {
setError(errorMessage(e));
}
await reload();
};
return (
<div className={className}>
<div className={styles.manageBar} role="toolbar" aria-label={tx("Worktrees")}>
<IconButton icon="refresh" title="Refresh" size="small" onClick={() => void reload()} />
<IconButton
icon="plus"
title="New Worktree…"
size="small"
onClick={() => showNewWorktree(() => void reload(), currentGroup?.root ?? repo ?? repos[0])}
/>
<IconButton
icon="minus"
title={containsProject ? "Cannot remove a worktree containing the open project." : "Remove Worktree"}
aria-label="Remove Worktree"
size="small"
disabled={!current || current.main || containsProject}
onClick={() => void remove()}
/>
<IconButton
icon="export"
title={containsProject ? "Cannot move a worktree containing the open project." : "Move Worktree…"}
aria-label="Move Worktree…"
size="small"
disabled={!current || current.main || containsProject}
onClick={() => void move()}
/>
<IconButton
icon="folder"
title="Open in New Window"
size="small"
disabled={!current}
onClick={() => current && void executeAction("file.openProjectPath", current.path)}
/>
</div>
<Tree<WorktreeNode>
// A new set of repositories starts with every section expanded.
key={tree.map((n) => n.key).join("|")}
roots={tree}
getKey={(n) => n.key}
getLabel={(n) => n.label}
getChildren={(n) => n.children}
isExpandable={(n) => !!n.children}
renderNode={(node, state) => (
<>
<Icon name={icon(node)} size={16} className={styles.worktreeIcon} />
<HighlightedText className={styles.worktreeLabel} text={node.label} indices={state.matches} tone="accent" />
{node.worktree && <span className={styles.worktreeDetail}>{detail(node)}</span>}
</>
)}
defaultExpanded={tree.map((n) => n.key)}
selected={selectedKeys}
multiSelect={false}
onSelectionChange={(selection) => setSelected([...selection][0] ?? null)}
onActivate={(n) => n.worktree && void executeAction("file.openProjectPath", n.worktree.path)}
className={listClassName ?? styles.worktreeListDialog}
aria-label="Worktrees"
/>
{groups.map(
(group) =>
group.error && (
<div key={group.root} className={styles.error}>
{group.error}
</div>
),
)}
{error && <div className={styles.error}>{error}</div>}
</div>
);
}
function NewWorktreeDialog({
repo: initialRepo,
onClose,
}: {
/** The repository to add the worktree to; the selected one when omitted. */
repo?: string | null;
onClose: (created: boolean) => void;
}) {
const [repo] = useState(() => initialRepo ?? currentRepo());
const [root] = useState(() => initialRepo ?? useVcs.getState().repo ?? useVcs.getState().root ?? "");
const branches = useBranches(repo);
const [source, setSource] = useState<string | null>(null);
const [createBranch, setCreateBranch] = useState(true);
const [newBranch, setNewBranch] = useState("");
const { ref: branchRef, clean: cleanBranch } = useSanitizedField(cleanUpBranchNameOnTyping);
const [path, setPath] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const options = useMemo(
() => [...branchOptions(sortLocal(branches)), ...branchOptions(sortRemote(branches))],
[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 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"
: null;
const create = async () => {
if (invalid || !source) return;
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);
} catch (e) {
setError(errorMessage(e));
}
};
return (
<Dialog
open
title="New Worktree"
onClose={() => onClose(false)}
width={520}
buttons={[
{ label: "Create", role: "default", disabled: !!invalid, onClick: () => void create() },
{ label: "Cancel", role: "cancel" },
]}
>
<div className={styles.form}>
<div className={styles.fieldLabel}>
<T>Check out:</T>
</div>
<Select
aria-label="Check out"
value={source}
placeholder="Select branch"
options={options}
onChange={setSource}
/>
<Checkbox label="Create a new branch" checked={createBranch} onChange={setCreateBranch} />
{createBranch && (
<Input
ref={branchRef}
aria-label="New branch name"
mono
value={newBranch}
placeholder={suggestedBranch}
onChange={(e) => setNewBranch(cleanBranch(e))}
/>
)}
<div className={styles.fieldLabel}>
<T>Folder:</T>
</div>
<Input aria-label="Folder" mono value={target} onChange={(e) => setPath(e.target.value)} />
{(error ?? (source && invalid)) && <div className={styles.error}>{error ?? invalid}</div>}
</div>
</Dialog>
);
}