дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-06 18:17:15 +02:00
fix(vcs): keep recent branches per repository (#6705)
Recent branches were stored once per project, so in a multi-repository project a branch checked out in one repository showed up under another's Recent Branches. They are now stored per repository root: checkout, New Branch, Rename, Checkout and Rebase and the multi-repository operations record each repository they ran in, and the popups read that repository's list. A single-repository project still reads the list saved before. Co-authored-by: audichuang <[email protected]>
Цей коміт міститься в:
1 джерело
fb97cdac03
коміт
802d9d26e2
5 files changed
+169
-38
No files matched your search
@@ -500,7 +500,7 @@ function BranchesPanel({ onClose, actions: baseActions, worktreeFor, root, fallb
|
||||
live ? (s.branch?.head ?? null) : root ? (s.heads[root]?.head ?? null) : (s.branch?.head ?? null),
|
||||
);
|
||||
const [query, setQuery] = useState("");
|
||||
const [recent] = useState(recentBranches);
|
||||
const recent = useMemo(() => recentBranches(root ?? selected), [root, selected]);
|
||||
const [active, setActive] = useState(0);
|
||||
const { menuFor, setMenuFor, openTagMenu } = useBranchSubmenu();
|
||||
const listRef = useRef<HTMLDivElement>(null);
|
||||
@@ -726,7 +726,8 @@ function MultiRepoPanel({
|
||||
const operations = useVcs((s) => s.operations);
|
||||
const version = useVcs((s) => s.version);
|
||||
const favorites = useFavoriteBranches((s) => s.names);
|
||||
const [recent] = useState(recentBranches);
|
||||
// The branches listed below are the current repository's, and so are its recent ones.
|
||||
const recent = useMemo(() => recentBranches(current), [current]);
|
||||
const [tags, setTags] = useState<string[]>([]);
|
||||
const [query, setQuery] = useState("");
|
||||
const [active, setActive] = useState(0);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { Branch, BranchInfo, ProjectInfo, Worktree } from "@/bindings";
|
||||
const mocks = vi.hoisted(() => ({
|
||||
prompt: vi.fn(),
|
||||
@@ -81,6 +81,7 @@ import {
|
||||
deleteTag,
|
||||
newBranch,
|
||||
newBranchInRepos,
|
||||
recentBranches,
|
||||
renameBranch,
|
||||
} from "../branchOps";
|
||||
import { useVcs } from "../store";
|
||||
@@ -678,3 +679,61 @@ it("keeps the local open action when another worktree holds the branch", async (
|
||||
expect(mocks.windowOpenRemote).not.toHaveBeenCalled();
|
||||
expect(mocks.checkout).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
describe("recent branches", () => {
|
||||
beforeEach(() => localStorage.clear());
|
||||
const head = (name: string | null) => ({ head: name, headCommit: "abc1234567890" });
|
||||
// Checking out moves the HEAD of the repository it ran in.
|
||||
const checkoutMovesHead = () =>
|
||||
mocks.checkout.mockImplementation(async (root: string, ref: string) => {
|
||||
const name = ref.replace(/^refs\/heads\//, "");
|
||||
const s = useVcs.getState();
|
||||
useVcs.setState({
|
||||
heads: { ...s.heads, [root]: head(name) },
|
||||
...(root === s.repo ? { branch: branch(name) } : {}),
|
||||
});
|
||||
return ok({ kind: "done" });
|
||||
});
|
||||
|
||||
it("are kept per repository, not per project", async () => {
|
||||
useVcs.setState({
|
||||
repo: "/p/front",
|
||||
roots: ["/p/front", "/p/back"],
|
||||
heads: { "/p/front": head("feature/ui"), "/p/back": head("main") },
|
||||
});
|
||||
checkoutMovesHead();
|
||||
await checkoutBranch(local("develop"), "/p/back");
|
||||
expect(recentBranches("/p/back")).toEqual(["develop", "main"]);
|
||||
expect(recentBranches("/p/front")).toEqual([]);
|
||||
expect(recentBranches()).toEqual([]);
|
||||
});
|
||||
|
||||
it("are recorded in every repository a multi-repository checkout moved", async () => {
|
||||
useVcs.setState({
|
||||
repo: "/p/front",
|
||||
roots: ["/p/front", "/p/back"],
|
||||
heads: { "/p/front": head("feature/ui"), "/p/back": head("main") },
|
||||
});
|
||||
checkoutMovesHead();
|
||||
await checkoutInRepos(local("develop"), ["/p/front", "/p/back"]);
|
||||
expect(recentBranches("/p/front")).toEqual(["develop", "feature/ui"]);
|
||||
expect(recentBranches("/p/back")).toEqual(["develop", "main"]);
|
||||
});
|
||||
|
||||
it("stay under the project's key in a single-repository project", async () => {
|
||||
useVcs.setState({ repo: "/p", roots: ["/p"], heads: { "/p": head("feature/ui") } });
|
||||
checkoutMovesHead();
|
||||
await checkoutBranch(local("develop"));
|
||||
expect(JSON.parse(localStorage.getItem("openidea.vcs.recentBranches:/p")!)).toEqual(["develop", "feature/ui"]);
|
||||
});
|
||||
|
||||
it("keep the list saved before when the only repository sits above the project", async () => {
|
||||
useProject.setState({ project: { root: "/repo/app", name: "app" } as ProjectInfo });
|
||||
useVcs.setState({ root: "/repo/app", repo: "/repo", roots: ["/repo"], heads: { "/repo": head("feature/ui") } });
|
||||
localStorage.setItem("openidea.vcs.recentBranches:/repo/app", JSON.stringify(["release"]));
|
||||
expect(recentBranches()).toEqual(["release"]);
|
||||
checkoutMovesHead();
|
||||
await checkoutBranch(local("develop"));
|
||||
expect(recentBranches()).toEqual(["develop", "feature/ui", "release"]);
|
||||
});
|
||||
});
|
||||
@@ -5,6 +5,7 @@ import { BranchesPopupHost, showBranchesPopup, useBranchesPopup } from "../Branc
|
||||
import { useVcs } from "../store";
|
||||
|
||||
const repoBranches = vi.hoisted(() => new Map<string, Branch[]>());
|
||||
const checkout = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock("@/platform/ipc", async (original) => {
|
||||
const real = await original<typeof import("@/platform/ipc")>();
|
||||
@@ -14,6 +15,7 @@ vi.mock("@/platform/ipc", async (original) => {
|
||||
...real.commands,
|
||||
vcsBranches: async (root: string) => ({ status: "ok", data: repoBranches.get(root) ?? [] }),
|
||||
vcsTags: async () => ({ status: "ok", data: [] }),
|
||||
vcsCheckout: checkout,
|
||||
},
|
||||
};
|
||||
});
|
||||
@@ -188,3 +190,46 @@ it("shows repository names as written in Chinese", async () => {
|
||||
_resetI18nForTests();
|
||||
}
|
||||
});
|
||||
|
||||
it("lists only the current repository's recent branches", async () => {
|
||||
const { checkoutBranch } = await import("../branchOps");
|
||||
const { useProject } = await import("@/platform/project");
|
||||
const a = "/work/a";
|
||||
const b = "/work/b";
|
||||
const branch = (name: string, current = false): Branch => ({
|
||||
name,
|
||||
current,
|
||||
remote: false,
|
||||
upstream: null,
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
lastCommitMs: null,
|
||||
});
|
||||
repoBranches.set(a, [branch("main", true), branch("develop")]);
|
||||
repoBranches.set(b, [branch("develop", true), branch("feature")]);
|
||||
// Repositories on different branches without synchronized branch operations list the current one's branches.
|
||||
useProject.setState({
|
||||
project: { root: "/work" } as never,
|
||||
settings: { vcs: { git: { syncBranchOperations: false } } } as never,
|
||||
});
|
||||
useVcs.setState({
|
||||
root: "/work",
|
||||
repo: a,
|
||||
roots: [a, b],
|
||||
branchesLoaded: true,
|
||||
branches: repoBranches.get(a)!,
|
||||
heads: { [a]: { head: "main", headCommit: "1" }, [b]: { head: "feature", headCommit: "2" } },
|
||||
});
|
||||
checkout.mockImplementation(async (root: string, ref: string) => {
|
||||
const s = useVcs.getState();
|
||||
useVcs.setState({ heads: { ...s.heads, [root]: { head: ref.replace("refs/heads/", ""), headCommit: "3" } } });
|
||||
return { status: "ok", data: { kind: "done" } };
|
||||
});
|
||||
// Checking develop out in b leaves a's recent branches empty.
|
||||
await checkoutBranch(branch("develop"), b);
|
||||
render(<BranchesPopupHost />);
|
||||
act(showBranchesPopup);
|
||||
const list = screen.getByRole("listbox", { name: "Repositories and branches" });
|
||||
await within(list).findByText("Local Branches in a");
|
||||
expect(within(list).queryByText("Recent Branches in a")).toBeNull();
|
||||
});
|
||||
@@ -461,25 +461,34 @@ describe("renaming a common branch", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
const recents = () => JSON.parse(localStorage.getItem("openidea.vcs.recentBranches:/p") ?? "[]");
|
||||
// Each repository keeps its own recent branches.
|
||||
const recents = (root: string) => JSON.parse(localStorage.getItem(`openidea.vcs.recentBranches:${root}`) ?? "[]");
|
||||
const keepRecents = () => {
|
||||
useVcs.setState({ root: "/p" });
|
||||
localStorage.setItem("openidea.vcs.recentBranches:/p", JSON.stringify(["feature", "main"]));
|
||||
for (const root of ["/a", "/b", "/c"])
|
||||
localStorage.setItem(`openidea.vcs.recentBranches:${root}`, JSON.stringify(["feature", "main"]));
|
||||
};
|
||||
|
||||
it("renames the branch in recent branches once it stayed renamed", async () => {
|
||||
keepRecents();
|
||||
await renameInRepos("feature", ["/a", "/c"], false);
|
||||
expect(recents()).toEqual(["feature2", "main"]);
|
||||
expect(["/a", "/b", "/c"].map(recents)).toEqual([
|
||||
["feature2", "main"],
|
||||
["feature", "main"],
|
||||
["feature2", "main"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("leaves recent branches alone when the rename failed or was rolled back", async () => {
|
||||
keepRecents();
|
||||
await renameInRepos("feature", ["/b"], false);
|
||||
expect(recents()).toEqual(["feature", "main"]);
|
||||
expect(recents("/b")).toEqual(["feature", "main"]);
|
||||
mocks.ask.mockResolvedValue({ button: "rollback" });
|
||||
await renameInRepos("feature", ["/a", "/b"], false);
|
||||
expect(recents()).toEqual(["feature", "main"]);
|
||||
expect(["/a", "/b"].map(recents)).toEqual([
|
||||
["feature", "main"],
|
||||
["feature", "main"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("unsets the upstream only after the branch was renamed in every repository", async () => {
|
||||
@@ -507,7 +516,11 @@ describe("renaming a common branch", () => {
|
||||
["/b", "feature", "feature2", false],
|
||||
["/a", "feature2", "feature2", true],
|
||||
]);
|
||||
expect(recents()).toEqual(["feature2", "feature", "main"]);
|
||||
// Renamed only where the rename was kept.
|
||||
expect(["/a", "/b"].map(recents)).toEqual([
|
||||
["feature2", "main"],
|
||||
["feature", "main"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("offers to unset the upstream only when the branch has one", async () => {
|
||||
|
||||
@@ -47,22 +47,36 @@ import { splitTracked } from "./pushTarget";
|
||||
import { chooseRevision } from "./RevisionChooser";
|
||||
import { branchRepositoryRoots } from "./repoBranches";
|
||||
|
||||
const recentKey = () => `openidea.vcs.recentBranches:${useVcs.getState().root ?? ""}`;
|
||||
/** Recent branches are kept per repository (unset: the selected one), like IDEA's per-repository reflog. */
|
||||
const recentKey = (repo?: string | null) => `openidea.vcs.recentBranches:${repo ?? currentRepoRoot() ?? ""}`;
|
||||
|
||||
export function recentBranches(): string[] {
|
||||
function readRecent(key: string): string[] | null {
|
||||
try {
|
||||
const raw = localStorage.getItem(recentKey());
|
||||
const v: unknown = raw ? JSON.parse(raw) : [];
|
||||
return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : [];
|
||||
const raw = localStorage.getItem(key);
|
||||
const v: unknown = raw ? JSON.parse(raw) : null;
|
||||
return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : null;
|
||||
} catch {
|
||||
return [];
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function rememberBranch(name: string | null | undefined) {
|
||||
/** Branches recently checked out in `repo` (unset: the selected repository), newest first. */
|
||||
export function recentBranches(repo?: string | null): string[] {
|
||||
const { roots, root } = useVcs.getState();
|
||||
// They used to be kept per project: a project's only repository still reads that list.
|
||||
return readRecent(recentKey(repo)) ?? (roots.length <= 1 ? readRecent(recentKey(root)) : null) ?? [];
|
||||
}
|
||||
|
||||
/** The branch checked out in `root` (unset: the selected repository). */
|
||||
function repoHead(root?: string | null) {
|
||||
const s = useVcs.getState();
|
||||
return root && root !== currentRepoRoot() ? s.heads[root]?.head : s.branch?.head;
|
||||
}
|
||||
|
||||
function rememberBranch(name: string | null | undefined, repo?: string | null) {
|
||||
if (!name) return;
|
||||
try {
|
||||
localStorage.setItem(recentKey(), JSON.stringify(pushRecent(recentBranches(), name)));
|
||||
localStorage.setItem(recentKey(repo), JSON.stringify(pushRecent(recentBranches(repo), name)));
|
||||
} catch {
|
||||
// Storage unavailable: recents are a convenience only.
|
||||
}
|
||||
@@ -285,10 +299,7 @@ export async function checkoutBranch(branch: NamedBranch, repo = currentRepo())
|
||||
const state = useVcs.getState();
|
||||
const project = useProject.getState().project;
|
||||
const root = repo ?? state.roots[0] ?? state.root;
|
||||
const head = () => {
|
||||
const s = useVcs.getState();
|
||||
return root && root !== currentRepoRoot() ? s.heads[root]?.head : s.branch?.head;
|
||||
};
|
||||
const head = () => repoHead(root);
|
||||
const previous = head();
|
||||
// A local namesake tracking another branch: IDEA asks for a new local name instead.
|
||||
if (remote) {
|
||||
@@ -298,9 +309,9 @@ export async function checkoutBranch(branch: NamedBranch, repo = currentRepo())
|
||||
}
|
||||
const ok = await performCheckout(branchRef(name, remote), () => `Checked out ${head() ?? name}`, repo);
|
||||
if (ok && useProject.getState().project === project) {
|
||||
rememberBranch(previous);
|
||||
rememberBranch(previous, root);
|
||||
await refreshNow();
|
||||
rememberBranch(head());
|
||||
rememberBranch(head(), root);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -524,10 +535,10 @@ async function createBranch(roots: readonly (string | null)[], from?: BranchSour
|
||||
checkout,
|
||||
)) > 0;
|
||||
if (!done || !checkout || useProject.getState().project !== project) return;
|
||||
const focused = currentRepoRoot();
|
||||
if (selected.includes(focused) || selected.includes(null)) {
|
||||
rememberBranch(head(focused));
|
||||
rememberBranch(r.value);
|
||||
// Each repository keeps its own recent branches.
|
||||
for (const repo of selected) {
|
||||
rememberBranch(head(repo), repo);
|
||||
rememberBranch(r.value, repo);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -763,7 +774,7 @@ export async function renameBranch(branch: Branch) {
|
||||
},
|
||||
);
|
||||
if (ok !== undefined && useProject.getState().project === project) {
|
||||
renameRecent(name, to);
|
||||
renameRecent(name, to, repo);
|
||||
// The log follows: its Branch filter and "Log: branch" tabs keep naming the branch.
|
||||
if (repo) renameBranchInLogFilters(repo, name, to);
|
||||
}
|
||||
@@ -814,9 +825,9 @@ async function promptBranchRename(
|
||||
return r ? { to: r.value.trim(), unsetUpstream: hasUpstream && r.checked } : null;
|
||||
}
|
||||
|
||||
function renameRecent(from: string, to: string) {
|
||||
function renameRecent(from: string, to: string, repo?: string | null) {
|
||||
try {
|
||||
localStorage.setItem(recentKey(), JSON.stringify(recentBranches().map((b) => (b === from ? to : b))));
|
||||
localStorage.setItem(recentKey(repo), JSON.stringify(recentBranches(repo).map((b) => (b === from ? to : b))));
|
||||
} catch {
|
||||
// Recents are best effort.
|
||||
}
|
||||
@@ -1372,10 +1383,10 @@ export async function checkoutAndRebase({ branch, repos }: CheckoutRebaseTarget)
|
||||
progress: title,
|
||||
success: tx`Checked out and rebased '${branchName}'`,
|
||||
failure: tx("Checkout and Rebase failed"),
|
||||
onRebased({ operation }) {
|
||||
onRebased({ root, operation }) {
|
||||
if (operation.op === "checkoutRebase") {
|
||||
rememberBranch(operation.plan.base.branch);
|
||||
rememberBranch(operation.plan.branch);
|
||||
rememberBranch(operation.plan.base.branch, root);
|
||||
rememberBranch(operation.plan.branch, root);
|
||||
}
|
||||
},
|
||||
});
|
||||
@@ -1632,7 +1643,7 @@ export async function checkoutInRepos(branch: NamedBranch, roots: readonly strin
|
||||
const elsewhere = remote ? roots : reposNotOn(name, roots);
|
||||
if (!elsewhere.length) return;
|
||||
const project = useProject.getState().project;
|
||||
const previous = useVcs.getState().branch?.head;
|
||||
const previous = new Map(elsewhere.map((root) => [root, repoHead(root)]));
|
||||
let label = name;
|
||||
if (remote) {
|
||||
const check = await remoteCheckoutTargets(name, elsewhere);
|
||||
@@ -1656,8 +1667,11 @@ export async function checkoutInRepos(branch: NamedBranch, roots: readonly strin
|
||||
{ undo: tx("check out the previous branch again"), run: (root, _, before) => checkoutBack(root, before) },
|
||||
true,
|
||||
);
|
||||
rememberBranch(previous);
|
||||
rememberBranch(useVcs.getState().branch?.head);
|
||||
// Each repository keeps its own recent branches.
|
||||
for (const root of elsewhere) {
|
||||
rememberBranch(previous.get(root), root);
|
||||
rememberBranch(repoHead(root), root);
|
||||
}
|
||||
}
|
||||
|
||||
/** New Branch in every repository of `roots` (from HEAD or `from`), checked out by default. */
|
||||
@@ -1765,8 +1779,7 @@ export async function renameInRepos(name: string, roots: readonly string[], upst
|
||||
false,
|
||||
async (title, complete, done) => {
|
||||
if (useProject.getState().project !== project) return;
|
||||
if (complete) renameRecent(name, to);
|
||||
else rememberBranch(to);
|
||||
for (const { root } of done) renameRecent(name, to, root);
|
||||
// The log follows the kept renames in every renamed repository.
|
||||
if (complete) for (const root of roots) renameBranchInLogFilters(root, name, to);
|
||||
// Only change tracking after the user has decided which renames to retain.
|
||||
|
||||
Reference in new issue
Заблокувати користувача