diff --git a/src/features/vcs/GitLog.tsx b/src/features/vcs/GitLog.tsx index 8afd9b6c61..fe512c02fb 100644 --- a/src/features/vcs/GitLog.tsx +++ b/src/features/vcs/GitLog.tsx @@ -169,6 +169,7 @@ export function LogView() { const shown = useGitLog((s) => s.shownLog); const active = !scope || scope === shown; const version = useVcs((s) => s.version); + const refsVersion = useVcs((s) => s.refsVersion); const commits = useGitLog((s) => s.commits); const selection = useGitLog((s) => s.selection); const root = useVcs((s) => s.root); @@ -226,7 +227,7 @@ export function LogView() { return () => { live = false; }; - }, [repo, version, readOnly, scope]); + }, [repo, refsVersion, readOnly, scope]); useEffect(() => { if (!readOnly) return; let live = true; diff --git a/src/features/vcs/__tests__/logBranches.test.tsx b/src/features/vcs/__tests__/logBranches.test.tsx index 4e202f3826..ec091c7bba 100644 --- a/src/features/vcs/__tests__/logBranches.test.tsx +++ b/src/features/vcs/__tests__/logBranches.test.tsx @@ -13,6 +13,7 @@ const repoData = vi.hoisted(() => ({ /** Roots whose tags cannot be read (a working copy: Git's tags are not its). */ noTags: new Set(), branchReads: [] as string[], + tagReads: [] as string[], /** Holds back every branch list until it resolves. */ branchGate: null as Promise | null, })); @@ -27,12 +28,14 @@ vi.mock("@/platform/ipc", async (importOriginal) => { const data = repoData.branches[root] ?? []; return (repoData.branchGate ?? Promise.resolve()).then(() => ({ status: "ok", data })); }, - vcsTags: (root: string) => - Promise.resolve( + vcsTags: (root: string) => { + repoData.tagReads.push(root); + return Promise.resolve( repoData.noTags.has(root) ? { status: "error", error: { message: "not a git repository" } } : { status: "ok", data: repoData.tags[root] ?? [] }, - ), + ); + }, vcsLog, vcsConfigGet: () => Promise.resolve({ status: "ok", data: null }), }, @@ -47,6 +50,7 @@ vi.mock("@/platform/actions", async (importOriginal) => ({ import { ContextMenuHost, iconMarkup } from "@/ui"; import syncStyles from "../BranchSync.module.css"; +import { buildLogTree, type LogTreeInput } from "../log/branchTree"; import { BranchesPanel } from "../log/BranchesPanel"; import { FilterBar } from "../log/FilterBar"; import { setLogOptions } from "../logOptions"; @@ -485,10 +489,18 @@ describe("Git Log branches pane with several repositories", () => { fireEvent.change(screen.getByLabelText("Filter branches and tags"), { target: { value: "v2" } }); expect(await screen.findByText(/v2/)).toBeInTheDocument(); fireEvent.change(screen.getByLabelText("Filter branches and tags"), { target: { value: "" } }); + const gitReads = repoData.branchReads.filter((r) => r === "/p/a").length; + const tagReads = repoData.tagReads.length; const reads = repoData.branchReads.filter((r) => r === "/p/b").length; expect(reads).toBeGreaterThan(0); await act(async () => useVcs.setState({ version: useVcs.getState().version + 1 })); - await waitFor(() => expect(repoData.branchReads.filter((r) => r === "/p/a").length).toBeGreaterThan(1)); + expect(repoData.tagReads).toHaveLength(tagReads); + expect(repoData.branchReads.filter((r) => r === "/p/a")).toHaveLength(gitReads); + repoData.tags["/p/a"] = ["v3.0"]; + await act(async () => useVcs.setState((s) => ({ refsVersion: s.refsVersion + 1 }))); + fireEvent.change(screen.getByLabelText("Filter branches and tags"), { target: { value: "v3" } }); + expect(await screen.findByText(/v3/)).toBeInTheDocument(); + expect(repoData.tagReads.slice(tagReads)).toEqual(["/p/a"]); expect(repoData.branchReads.filter((r) => r === "/p/b")).toHaveLength(reads); } finally { repoData.noTags = new Set(); @@ -496,6 +508,43 @@ describe("Git Log branches pane with several repositories", () => { } }); + it("reuses a large tag tree across refreshes and rebuilds it when a tag changes", async () => { + const jobs: LogTreeInput[] = []; + class TestWorker { + onmessage?: (event: { data: ReturnType }) => void; + postMessage(input: LogTreeInput) { + jobs.push(input); + queueMicrotask(() => this.onmessage?.({ data: buildLogTree(input) })); + } + terminate() {} + } + vi.stubGlobal("Worker", TestWorker); + try { + const tags = Array.from({ length: 4096 }, (_, i) => `release-${i}`); + repoData.tags["/p/a"] = tags; + render(); + const search = screen.getByLabelText("Filter branches and tags"); + fireEvent.change(search, { target: { value: "release-4095" } }); + expect(await screen.findByText("release-4095")).toBeInTheDocument(); + const count = jobs.length; + expect(count).toBeGreaterThan(0); + const reads = repoData.tagReads.length; + repoData.tags["/p/a"] = [...tags]; + await act(async () => fireEvent.click(screen.getByRole("button", { name: "Refresh" }))); + expect(repoData.tagReads.slice(reads).sort()).toEqual(["/p/a", "/p/b"]); + expect(jobs).toHaveLength(count); + + repoData.tags["/p/a"] = [...tags.slice(0, -1), "release-new"]; + await act(async () => fireEvent.click(screen.getByRole("button", { name: "Refresh" }))); + expect(jobs).toHaveLength(count + 1); + expect(screen.queryByText("release-4095")).toBeNull(); + fireEvent.change(search, { target: { value: "release-new" } }); + expect(await screen.findByText("release-new")).toBeInTheDocument(); + } finally { + vi.unstubAllGlobals(); + } + }); + it("lists branches once, naming the repositories of partial ones", async () => { render(); const solo = await screen.findByText("solo"); diff --git a/src/features/vcs/branches.ts b/src/features/vcs/branches.ts index 4f09615dcf..2aa690b7dd 100644 --- a/src/features/vcs/branches.ts +++ b/src/features/vcs/branches.ts @@ -4,6 +4,17 @@ import { getAction, isActionVisible } from "@/platform/actions"; import { tx } from "@/platform/i18n"; import { workflowSettings } from "@/platform/workflowSettings"; import { wordMatch } from "@/ui/match"; +import { isFavoriteBranch, sortTags, type BranchTreeNode } from "./log/branchTree"; +export { + favoritesInAny, + isFavoriteBranch, + shortRemoteName, + sortTags, + buildBranchTree, + buildRepositoryBranchTree, + buildMergedBranchTree, + type BranchTreeNode, +} from "./log/branchTree"; export function isProtectedBranch(branch: string, patterns = workflowSettings().vcs.git.protectedBranches): boolean { return patterns @@ -207,12 +218,6 @@ export function sortRemote(branches: readonly Branch[], favorites: readonly stri return branches.filter((b) => b.remote && !b.name.endsWith("/HEAD")).sort(byRank(favorites)); } -/** `origin/feature/x` → `feature/x`. */ -export function shortRemoteName(name: string): string { - const i = name.indexOf("/"); - return i < 0 ? name : name.slice(i + 1); -} - /** * The folders of local branch names, shallowest first (`feat/ui/login` contributes `feat/` and * `feat/ui/`): what the New Branch dialog suggests while typing. Remote branches are left out. @@ -241,10 +246,6 @@ export function recentLocal(local: readonly Branch[], recent: readonly string[]) .slice(0, MAX_RECENT); } -/** Tags, newest version first. */ -export const sortTags = (tags: readonly string[]) => - [...tags].sort((a, b) => b.localeCompare(a, undefined, { numeric: true })); - /** * How well `name` matches `query`: at the start of its last segment, at a word start, matching the * segment to its end, then nearer the segment's start. @@ -399,34 +400,6 @@ export function pushRecent(list: readonly string[], name: string, max = 20): str return [name, ...list.filter((n) => n !== name)].slice(0, max); } -const DEFAULT_FAVORITES = ["main", "master"]; - -/** Favorite branches (★): the user's list, or `main` / `master` (local and remote) until they edit it. */ -export function isFavoriteBranch(b: Pick, stored: readonly string[] | null): boolean { - if (stored) return stored.includes(b.name); - return DEFAULT_FAVORITES.includes(b.remote ? shortRemoteName(b.name) : b.name); -} - -/** Names of `branches` that are a favorite in any of the repositories with the favorites `lists`, like IDEA's branches pane. */ -export function favoritesInAny(branches: readonly Branch[], lists: readonly (readonly string[] | null)[]): string[] { - return branches.filter((b) => lists.some((list) => isFavoriteBranch(b, list))).map((b) => b.name); -} - -export interface BranchTreeNode { - key: string; - label: string; - repo?: string; - kind: "repository" | "head" | "group" | "remote" | "folder" | "branch" | "tag"; - /** Branch name for `branch` / `head` (`HEAD`), tag name for `tag`. */ - ref: string | null; - branch?: Branch; - favorite?: boolean; - /** Merged tree: the repositories that have this branch or tag. */ - repos?: string[]; - branchesByRoot?: ReadonlyMap; - children?: BranchTreeNode[]; -} - /** * The Log's Branches pane for a Subversion root: its lines of development as they are in the * repository, `trunk` first, then the `branches` and `tags` folders. There is no HEAD, no @@ -490,208 +463,6 @@ export function isTagLine(name: string | null | undefined): boolean { return !!name?.startsWith("tags/"); } -/** - * Git Log Branches pane: HEAD, Local, Remote › and Tags. Names with `/` are - * grouped into folders (`feat/x` → feat › x); at each level the current branch and - * favorites come first, then folders, then the other branches. Tags: newest version first. - */ -export function buildBranchTree( - branches: readonly Branch[], - favorites: readonly string[] | null, - tags: readonly string[] = [], -): BranchTreeNode[] { - const local = branches.filter((b) => !b.remote); - const localNames = new Set(local.map((b) => b.name)); - const level = (list: { b: Branch; rest: string }[], keyPrefix: string): BranchTreeNode[] => { - const folders = new Map(); - const leaves: BranchTreeNode[] = []; - for (const item of list) { - const i = item.rest.indexOf("/"); - if (i > 0 && i < item.rest.length - 1) { - const seg = item.rest.slice(0, i); - folders.set(seg, [...(folders.get(seg) ?? []), { b: item.b, rest: item.rest.slice(i + 1) }]); - } else { - // Short-name filters keep addressing the local row when the two refs share a name. - const prefix = item.b.remote && localNames.has(item.b.name) ? "b-remote" : "b"; - leaves.push({ - key: `${prefix}:${item.b.name}`, - label: item.rest, - kind: "branch", - ref: item.b.name, - branch: item.b, - favorite: isFavoriteBranch(item.b, favorites), - }); - } - } - const byName = (a: BranchTreeNode, b: BranchTreeNode) => a.label.localeCompare(b.label); - const folderNodes = [...folders] - .map(([seg, items]): BranchTreeNode => { - const key = `${keyPrefix}/${seg}`; - return { key, label: seg, kind: "folder", ref: null, children: level(items, key) }; - }) - .sort(byName); - // IDEA: current branch, favorites, folders, the rest. - const rank = (n: BranchTreeNode) => (n.branch?.current ? 0 : n.favorite ? 1 : 2); - const top = leaves.filter((n) => rank(n) < 2).sort((a, b) => rank(a) - rank(b) || byName(a, b)); - return [...top, ...folderNodes, ...leaves.filter((n) => rank(n) === 2).sort(byName)]; - }; - const byRemote = new Map(); - for (const b of branches) { - if (!b.remote || b.name.endsWith("/HEAD")) continue; - const i = b.name.indexOf("/"); - const r = i > 0 ? b.name.slice(0, i) : b.name; - byRemote.set(r, [...(byRemote.get(r) ?? []), b]); - } - const out: BranchTreeNode[] = [{ key: "head", label: "HEAD (Current Branch)", kind: "head", ref: "HEAD" }]; - if (local.length) - out.push({ - key: "g:local", - label: "Local", - kind: "group", - ref: null, - children: level( - local.map((b) => ({ b, rest: b.name })), - "f:local", - ), - }); - if (byRemote.size) - out.push({ - key: "g:remote", - label: "Remote", - kind: "group", - ref: null, - children: [...byRemote].map(([r, list]) => ({ - key: `r:${r}`, - label: r, - kind: "remote", - ref: null, - children: level( - list.map((b) => ({ b, rest: b.name.slice(r.length + 1) })), - `f:r:${r}`, - ), - })), - }); - if (tags.length) - out.push({ - key: "g:tags", - label: "Tags", - kind: "group", - ref: null, - children: [...tags] - .sort((a, b) => b.localeCompare(a, undefined, { numeric: true })) - .map((t): BranchTreeNode => ({ key: `t:${t}`, label: t, kind: "tag", ref: t })), - }); - return out; -} - -/** Local / remote / tag groups contain a subtree for each registered repository. */ -export function buildRepositoryBranchTree( - repositories: readonly { root: string; name: string; branches: Branch[]; tags: string[] }[], - favoritesOf: (root: string) => readonly string[] | null, -): BranchTreeNode[] { - const scope = (nodes: BranchTreeNode[], repo: string): BranchTreeNode[] => - nodes.map((n) => ({ - ...n, - repo, - key: `${repo}:${n.key}`, - children: n.children && scope(n.children, repo), - })); - const trees = repositories.map((r) => ({ ...r, nodes: buildBranchTree(r.branches, favoritesOf(r.root), r.tags) })); - const groups = [ - { key: "g:local", label: "Local" }, - { key: "g:remote", label: "Remote" }, - { key: "g:tags", label: "Tags" }, - ]; - return [ - { key: "head", label: "HEAD (Current Branch)", kind: "head", ref: "HEAD" }, - ...groups.map(({ key, label }): BranchTreeNode => ({ - key, - label, - kind: "group", - ref: null, - children: byDirectory( - trees.map((r) => ({ - path: r.name.split("/"), - node: { - key: `${key}:${r.root}`, - label: r.name, - kind: "repository", - ref: null, - repo: r.root, - children: scope(r.nodes.find((n) => n.key === key)?.children ?? [], r.root), - }, - })), - `${key}:dir:`, - ), - })), - ]; -} - -/** - * Repositories under the directories their names share. A directory holding one repository - * or one directory joins its name to the child's, so repositories without shared directories - * keep their full name on one row. - */ -function byDirectory(entries: readonly { path: string[]; node: BranchTreeNode }[], key: string): BranchTreeNode[] { - const rows = new Map(); - entries.forEach((e, i) => { - const row = e.path.length > 1 ? `d:${e.path[0]}` : `r:${i}`; - rows.set(row, [...(rows.get(row) ?? []), e]); - }); - return [...rows].map(([row, inside]): BranchTreeNode => { - const dir = inside[0]!.path[0]!; - if (row.startsWith("r:")) return { ...inside[0]!.node, label: dir }; - const dirKey = `${key}${dir}`; - const children = byDirectory( - inside.map((e) => ({ ...e, path: e.path.slice(1) })), - `${dirKey}/`, - ); - const only = children.length === 1 ? children[0]! : null; - return only - ? { ...only, label: `${dir}/${only.label}` } - : { key: dirKey, label: dir, kind: "folder", ref: null, children }; - }); -} - -/** - * One tree for several repositories: each branch and tag listed once, with the - * repositories that have it (`repos`). Its `branch` is the `current` repository's when that - * one has it, else the first's; it counts as current when it is current in any of them. - */ -export function buildMergedBranchTree( - repositories: readonly { root: string; name: string; branches: Branch[]; tags: string[] }[], - favorites: readonly string[] | null, - current: string | null, -): BranchTreeNode[] { - const merged = new Map; current: boolean }>(); - const tagRoots = new Map(); - for (const r of repositories) { - for (const b of r.branches) { - const key = `${b.remote}:${b.name}`; - const entry = merged.get(key); - if (!entry) merged.set(key, { branch: b, byRoot: new Map([[r.root, b]]), current: b.current }); - else { - entry.byRoot.set(r.root, b); - entry.current ||= b.current; - if (r.root === current) entry.branch = b; - } - } - for (const t of r.tags) tagRoots.set(t, [...(tagRoots.get(t) ?? []), r.root]); - } - const branches = [...merged.values()].map((m) => ({ ...m.branch, current: m.current })); - const withRepos = (nodes: BranchTreeNode[]): BranchTreeNode[] => - nodes.map((n) => { - const byRoot = n.branch && merged.get(`${n.branch.remote}:${n.branch.name}`)?.byRoot; - return { - ...n, - repos: byRoot ? [...byRoot.keys()] : n.kind === "tag" ? tagRoots.get(n.ref!) : undefined, - branchesByRoot: byRoot, - children: n.children && withRepos(n.children), - }; - }); - return withRepos(buildBranchTree(branches, favorites, [...tagRoots.keys()])); -} - /** * Tooltip of a merged-tree ref in several repositories: one line per repository, sorted by * name; a local branch also shows the branch it tracks there. diff --git a/src/features/vcs/log/BranchesPanel.tsx b/src/features/vcs/log/BranchesPanel.tsx index 2c72d53394..3316d3afb4 100644 --- a/src/features/vcs/log/BranchesPanel.tsx +++ b/src/features/vcs/log/BranchesPanel.tsx @@ -9,10 +9,7 @@ import { useCallback, useContext, useEffect, useMemo, useState, type KeyboardEve import { branchFolderKeys, branchGroupKeys, - buildBranchTree, - buildMergedBranchTree, buildLineTree, - buildRepositoryBranchTree, filterBranchTree, favoritesInAny, isFavoriteBranch, @@ -28,13 +25,15 @@ import { BranchSync } from "../BranchSync"; import { summarizeBranchSync, type BranchSyncSummary } from "../branchSyncState"; import { FetchButton } from "../FetchButton"; import styles from "../GitLog.module.css"; +import { useLogTree } from "./useLogTree"; +import { invalidateLogRefs } from "../logRefresh"; import { LogIdContext } from "../logContext"; import { useLogOptions } from "../logOptions"; import { canUpdateBranch, useBranchesPane, type BranchTarget } from "../logPaneActions"; import { reloadLog, scopedLogRepositories, setLogBranches, setLogFilters, useGitLog } from "../logStore"; import { branchesByRepo } from "../multiRoot"; import { branchRepositoryRoots, commonBranches } from "../repoBranches"; -import { currentRepo, loadBranches, repoName, useVcs, useVcsKind } from "../store"; +import { currentRepo, loadBranches, repoName, sameBranches, useVcs, useVcsKind } from "../store"; import { useBranchWorktrees } from "../worktrees"; import { useLogRepositories, useReadOnlyLog } from "./logHooks"; @@ -65,6 +64,9 @@ function branchDetail(n: BranchTreeNode, total: number, sync: BranchSyncSummary ); } +const EMPTY_BRANCHES: Branch[] = []; +const EMPTY_TAGS: string[] = []; + const GROUP_KEY = "openidea.vcs.branchesPane.groupByRepository"; /** A merged ref acts in each repository that has it, with that repository's own branch. */ @@ -88,6 +90,16 @@ function sharedHead(roots: readonly string[]): string | null { return first && roots.every((r) => heads[r]?.head === first) ? first : null; } +function mergeBranchLists(old: Record, incoming: Record): Record { + let next = old; + for (const [repo, branches] of Object.entries(incoming)) { + if (sameBranches(old[repo], branches)) continue; + if (next === old) next = { ...old }; + next[repo] = branches; + } + return next; +} + export function BranchesPanel() { const scope = useContext(LogIdContext); const branchClickFilters = useLogOptions((s) => s.branchClickFilters); @@ -112,13 +124,9 @@ export function BranchesPanel() { ), [logRepositories, path, paths, repositoryFilter, branchRoots], ); - const queriedRepositories = useMemo( - () => [...new Set([...availableRepositories, ...repositories])], - [availableRepositories, repositories], - ); const readOnly = useReadOnlyLog(); const worktreeFor = useBranchWorktrees(active && !readOnly); - const version = useVcs((s) => s.version); + const refsVersion = useVcs((s) => s.refsVersion); const [allBranches, setAllBranches] = useState>({}); const [allTags, setAllTags] = useState>({}); const [grouped, setGrouped] = useState(loadGrouped); @@ -149,45 +157,55 @@ export function BranchesPanel() { const favoritesOf = useFavoriteBranchesOf(); const { branches: filterBranches, branchTargets } = filters; const [query, setQuery] = useState(""); - const [tags, setTags] = useState([]); + const kinds = useVcs((s) => s.kinds); // Tags are Git's (a working copy's tags/ folder is one of its lines); its lines are read from the // server (`svn list`), not on every refresh that moves Git's refs. const isGit = useCallback((repo: string | null) => (repo ? (kinds[repo] ?? "git") : "git") === "git", [kinds]); + const queriedRepositories = useMemo(() => { + if (!availableRepositories.length && !repositories.length && !allUnavailable && currentRepository) + return [currentRepository]; + return [...new Set([...availableRepositories, ...repositories])]; + }, [availableRepositories, repositories, allUnavailable, currentRepository]); const queriedGit = useMemo(() => queriedRepositories.filter(isGit), [queriedRepositories, isGit]); const queriedOther = useMemo(() => queriedRepositories.filter((repo) => !isGit(repo)), [queriedRepositories, isGit]); - // Branches reload when refs move (fetch, new tag…): the tags are re-read with them. - useEffect(() => { - const repo = availableRepositories[0] ?? currentRepo(); - if (allUnavailable || !isGit(repo)) return; - let live = true; - call(commands.vcsTags(repo)).then( - (t) => live && setTags(t), - () => live && setTags([]), - ); - return () => { - live = false; - }; - }, [root, selectedBranches, availableRepositories, allUnavailable, isGit]); + // External read-only logs poll for moved refs instead of receiving the project's watcher events. + const externalGeneration = readOnly ? logGeneration : 0; useEffect(() => { let live = true; void branchesByRepo(queriedGit) - .then((value) => live && setAllBranches((all) => ({ ...all, ...value }))) + .then((value) => { + if (live) setAllBranches((old) => mergeBranchLists(old, value)); + }) .catch(() => undefined); - // One repository's failure leaves the others' tags. void Promise.all( queriedGit.map(async (r) => [r, await call(commands.vcsTags(r)).catch(() => [] as string[])] as const), - ) - .then((value) => live && setAllTags(Object.fromEntries(value))) - .catch(() => undefined); + ).then((entries) => { + if (!live) return; + setAllTags((old) => { + const next = Object.fromEntries( + entries.map(([repo, tags]) => { + const prev = old[repo]; + return [ + repo, + prev && prev.length === tags.length && prev.every((name, i) => name === tags[i]) ? prev : tags, + ]; + }), + ); + return entries.length === Object.keys(old).length && entries.every(([repo]) => old[repo] === next[repo]) + ? old + : next; + }); + }); return () => { live = false; }; - }, [queriedGit, version, logGeneration]); + }, [root, queriedGit, refsVersion, externalGeneration]); useEffect(() => { let live = true; + if (!queriedOther.length) return; void branchesByRepo(queriedOther) - .then((value) => live && setAllBranches((all) => ({ ...all, ...value }))) + .then((value) => live && setAllBranches((all) => mergeBranchLists(all, value))) .catch(() => undefined); return () => { live = false; @@ -196,48 +214,55 @@ export function BranchesPanel() { const merged = repositories.length > 1 && !grouped; // A Subversion root lists its lines of development (trunk, branches, tags), not Git's groups. const lines = useVcsKind(listedRepo ?? scopedRepo ?? currentRepository) === "subversion" && repositories.length < 2; - const allRoots = useMemo(() => { - if (allUnavailable || (!repositories.length && availableRepositories.length)) return []; - // Tags wait for their repository's branches, so a name shared by both is never picked half-known. - const shownTags = (listedRepo ? !allBranches[listedRepo] : !branchesLoaded) - ? [] - : scopedRepo - ? (allTags[scopedRepo] ?? []) - : tags; - if (repositories.length < 2) - return lines - ? buildLineTree(branches, favoritesOf(listedRepo)) - : buildBranchTree(branches, favoritesOf(listedRepo), shownTags); - const list = repositories.map((repo) => ({ - root: repo, - name: repoName(branchRoots[repo] ?? repo), - branches: allBranches[repo] ?? [], - tags: allBranches[repo] ? (allTags[repo] ?? []) : [], - })); - return grouped - ? buildRepositoryBranchTree(list, favoritesOf) - : buildMergedBranchTree( - list, - list.flatMap((r) => favoritesInAny(r.branches, [favoritesOf(r.root)])), - currentRepository, - ); + const singleBranches = repositories.length <= 1 ? branches : EMPTY_BRANCHES; + const treeInput = useMemo(() => { + const repo = repositories[0] ?? currentRepository ?? root ?? ""; + const list = + repositories.length <= 1 + ? [ + { + root: repo, + name: repoName(repo), + branches: singleBranches, + favorites: favoritesOf(listedRepo), + tags: (listedRepo ? allBranches[listedRepo] : branchesLoaded) + ? (allTags[repo] ?? EMPTY_TAGS) + : EMPTY_TAGS, + }, + ] + : repositories.map((repo) => ({ + root: repo, + name: repoName(branchRoots[repo] ?? repo), + branches: allBranches[repo] ?? EMPTY_BRANCHES, + favorites: favoritesOf(repo), + tags: allBranches[repo] ? (allTags[repo] ?? EMPTY_TAGS) : EMPTY_TAGS, + })); + return { + repositories: lines || allUnavailable || (!repositories.length && availableRepositories.length) ? [] : list, + grouped, + current: currentRepository, + }; }, [ + root, + currentRepository, + lines, allUnavailable, - repositories, availableRepositories, + repositories, branchRoots, allBranches, allTags, - branches, + singleBranches, favoritesOf, listedRepo, - tags, - grouped, - currentRepository, - scopedRepo, - lines, branchesLoaded, + grouped, ]); + const gitTree = useLogTree(treeInput); + const allRoots = useMemo( + () => (lines && !allUnavailable ? buildLineTree(branches, favoritesOf(listedRepo)) : gitTree), + [lines, allUnavailable, branches, favoritesOf, listedRepo, gitTree], + ); const roots = useMemo(() => filterBranchTree(allRoots, query), [allRoots, query]); // A new search shows every match expanded; within that search the user can still collapse and // expand (IDEA), and clearing it brings back the expansion from before the search. @@ -481,7 +506,13 @@ export function BranchesPanel() { icon="refresh" title="Refresh" size="small" - onClick={() => (readOnly ? void reloadLog({ preserve: true }) : void loadBranches())} + onClick={() => { + if (readOnly) void reloadLog({ preserve: true }); + else { + invalidateLogRefs(); + void loadBranches(); + } + }} /> diff --git a/src/features/vcs/log/branchTree.ts b/src/features/vcs/log/branchTree.ts new file mode 100644 index 0000000000..a8e6a1a674 --- /dev/null +++ b/src/features/vcs/log/branchTree.ts @@ -0,0 +1,270 @@ +import type { Branch } from "@/bindings"; + +/** `origin/feature/x` → `feature/x`. */ +export function shortRemoteName(name: string): string { + const i = name.indexOf("/"); + return i < 0 ? name : name.slice(i + 1); +} + +const DEFAULT_FAVORITES = ["main", "master"]; + +/** Favorite branches (★): the user's list, or `main` / `master` (local and remote) until they edit it. */ +export function isFavoriteBranch(b: Pick, stored: readonly string[] | null): boolean { + if (stored) return stored.includes(b.name); + return DEFAULT_FAVORITES.includes(b.remote ? shortRemoteName(b.name) : b.name); +} + +/** Names of `branches` that are a favorite in any of the repositories with the favorites `lists`, like IDEA's branches pane. */ +export function favoritesInAny(branches: readonly Branch[], lists: readonly (readonly string[] | null)[]): string[] { + return branches.filter((b) => lists.some((list) => isFavoriteBranch(b, list))).map((b) => b.name); +} + +/** Tags, newest version first. */ +const tagOrder = new Intl.Collator(undefined, { numeric: true }); +export const sortTags = (tags: readonly string[]) => [...tags].sort((a, b) => tagOrder.compare(b, a)); + +export interface BranchTreeNode { + key: string; + label: string; + repo?: string; + kind: "repository" | "head" | "group" | "remote" | "folder" | "branch" | "tag"; + /** Branch name for `branch` / `head` (`HEAD`), tag name for `tag`. */ + ref: string | null; + branch?: Branch; + favorite?: boolean; + /** Merged tree: the repositories that have this branch or tag. */ + repos?: string[]; + branchesByRoot?: ReadonlyMap; + children?: BranchTreeNode[]; +} + +/** + * Git Log Branches pane: HEAD, Local, Remote › and Tags. Names with `/` are + * grouped into folders (`feat/x` → feat › x); at each level the current branch and + * favorites come first, then folders, then the other branches. Tags: newest version first. + */ +export function buildBranchTree( + branches: readonly Branch[], + favorites: readonly string[] | null, + tags: readonly string[] = [], +): BranchTreeNode[] { + const local = branches.filter((b) => !b.remote); + const localNames = new Set(local.map((b) => b.name)); + const level = (list: { b: Branch; rest: string }[], keyPrefix: string): BranchTreeNode[] => { + const folders = new Map(); + const leaves: BranchTreeNode[] = []; + for (const item of list) { + const i = item.rest.indexOf("/"); + if (i > 0 && i < item.rest.length - 1) { + const seg = item.rest.slice(0, i); + const child = { b: item.b, rest: item.rest.slice(i + 1) }; + const entries = folders.get(seg); + if (entries) entries.push(child); + else folders.set(seg, [child]); + } else { + // Short-name filters keep addressing the local row when the two refs share a name. + const prefix = item.b.remote && localNames.has(item.b.name) ? "b-remote" : "b"; + leaves.push({ + key: `${prefix}:${item.b.name}`, + label: item.rest, + kind: "branch", + ref: item.b.name, + branch: item.b, + favorite: isFavoriteBranch(item.b, favorites), + }); + } + } + const byName = (a: BranchTreeNode, b: BranchTreeNode) => a.label.localeCompare(b.label); + const folderNodes = [...folders] + .map(([seg, items]): BranchTreeNode => { + const key = `${keyPrefix}/${seg}`; + return { key, label: seg, kind: "folder", ref: null, children: level(items, key) }; + }) + .sort(byName); + // IDEA: current branch, favorites, folders, the rest. + const rank = (n: BranchTreeNode) => (n.branch?.current ? 0 : n.favorite ? 1 : 2); + const top = leaves.filter((n) => rank(n) < 2).sort((a, b) => rank(a) - rank(b) || byName(a, b)); + return [...top, ...folderNodes, ...leaves.filter((n) => rank(n) === 2).sort(byName)]; + }; + const byRemote = new Map(); + for (const b of branches) { + if (!b.remote || b.name.endsWith("/HEAD")) continue; + const i = b.name.indexOf("/"); + const r = i > 0 ? b.name.slice(0, i) : b.name; + const group = byRemote.get(r); + if (group) group.push(b); + else byRemote.set(r, [b]); + } + const out: BranchTreeNode[] = [{ key: "head", label: "HEAD (Current Branch)", kind: "head", ref: "HEAD" }]; + if (local.length) + out.push({ + key: "g:local", + label: "Local", + kind: "group", + ref: null, + children: level( + local.map((b) => ({ b, rest: b.name })), + "f:local", + ), + }); + if (byRemote.size) + out.push({ + key: "g:remote", + label: "Remote", + kind: "group", + ref: null, + children: [...byRemote].map(([r, list]) => ({ + key: `r:${r}`, + label: r, + kind: "remote", + ref: null, + children: level( + list.map((b) => ({ b, rest: b.name.slice(r.length + 1) })), + `f:r:${r}`, + ), + })), + }); + if (tags.length) + out.push({ + key: "g:tags", + label: "Tags", + kind: "group", + ref: null, + children: sortTags(tags).map((t): BranchTreeNode => ({ key: `t:${t}`, label: t, kind: "tag", ref: t })), + }); + return out; +} + +/** Local / remote / tag groups contain a subtree for each registered repository. */ +export function buildRepositoryBranchTree( + repositories: readonly { root: string; name: string; branches: Branch[]; tags: string[] }[], + favoritesOf: (root: string) => readonly string[] | null, +): BranchTreeNode[] { + const scope = (nodes: BranchTreeNode[], repo: string): BranchTreeNode[] => + nodes.map((n) => ({ + ...n, + repo, + key: `${repo}:${n.key}`, + children: n.children && scope(n.children, repo), + })); + const trees = repositories.map((r) => ({ ...r, nodes: buildBranchTree(r.branches, favoritesOf(r.root), r.tags) })); + const groups = [ + { key: "g:local", label: "Local" }, + { key: "g:remote", label: "Remote" }, + { key: "g:tags", label: "Tags" }, + ]; + return [ + { key: "head", label: "HEAD (Current Branch)", kind: "head", ref: "HEAD" }, + ...groups.map(({ key, label }): BranchTreeNode => ({ + key, + label, + kind: "group", + ref: null, + children: byDirectory( + trees.map((r) => ({ + path: r.name.split("/"), + node: { + key: `${key}:${r.root}`, + label: r.name, + kind: "repository", + ref: null, + repo: r.root, + children: scope(r.nodes.find((n) => n.key === key)?.children ?? [], r.root), + }, + })), + `${key}:dir:`, + ), + })), + ]; +} + +/** + * Repositories under the directories their names share. A directory holding one repository + * or one directory joins its name to the child's, so repositories without shared directories + * keep their full name on one row. + */ +function byDirectory(entries: readonly { path: string[]; node: BranchTreeNode }[], key: string): BranchTreeNode[] { + const rows = new Map(); + entries.forEach((e, i) => { + const row = e.path.length > 1 ? `d:${e.path[0]}` : `r:${i}`; + rows.set(row, [...(rows.get(row) ?? []), e]); + }); + return [...rows].map(([row, inside]): BranchTreeNode => { + const dir = inside[0]!.path[0]!; + if (row.startsWith("r:")) return { ...inside[0]!.node, label: dir }; + const dirKey = `${key}${dir}`; + const children = byDirectory( + inside.map((e) => ({ ...e, path: e.path.slice(1) })), + `${dirKey}/`, + ); + const only = children.length === 1 ? children[0]! : null; + return only + ? { ...only, label: `${dir}/${only.label}` } + : { key: dirKey, label: dir, kind: "folder", ref: null, children }; + }); +} + +/** + * One tree for several repositories: each branch and tag listed once, with the + * repositories that have it (`repos`). Its `branch` is the `current` repository's when that + * one has it, else the first's; it counts as current when it is current in any of them. + */ +export function buildMergedBranchTree( + repositories: readonly { root: string; name: string; branches: Branch[]; tags: string[] }[], + favorites: readonly string[] | null, + current: string | null, +): BranchTreeNode[] { + const merged = new Map; current: boolean }>(); + const tagRoots = new Map(); + for (const r of repositories) { + for (const b of r.branches) { + const key = `${b.remote}:${b.name}`; + const entry = merged.get(key); + if (!entry) merged.set(key, { branch: b, byRoot: new Map([[r.root, b]]), current: b.current }); + else { + entry.byRoot.set(r.root, b); + entry.current ||= b.current; + if (r.root === current) entry.branch = b; + } + } + for (const t of r.tags) tagRoots.set(t, [...(tagRoots.get(t) ?? []), r.root]); + } + const branches = [...merged.values()].map((m) => ({ ...m.branch, current: m.current })); + const withRepos = (nodes: BranchTreeNode[]): BranchTreeNode[] => + nodes.map((n) => { + const byRoot = n.branch && merged.get(`${n.branch.remote}:${n.branch.name}`)?.byRoot; + return { + ...n, + repos: byRoot ? [...byRoot.keys()] : n.kind === "tag" ? tagRoots.get(n.ref!) : undefined, + branchesByRoot: byRoot, + children: n.children && withRepos(n.children), + }; + }); + return withRepos(buildBranchTree(branches, favorites, [...tagRoots.keys()])); +} + +export interface LogTreeInput { + repositories: { + root: string; + name: string; + branches: Branch[]; + tags: string[]; + favorites: readonly string[] | null; + }[]; + grouped: boolean; + current: string | null; +} + +export function buildLogTree({ repositories, grouped, current }: LogTreeInput): BranchTreeNode[] { + if (!repositories.length) return []; + if (repositories.length === 1) { + const r = repositories[0]!; + return buildBranchTree(r.branches, r.favorites, r.tags); + } + if (grouped) { + const favorites = new Map(repositories.map((r) => [r.root, r.favorites])); + return buildRepositoryBranchTree(repositories, (root) => favorites.get(root) ?? null); + } + const favorites = repositories.flatMap((r) => favoritesInAny(r.branches, [r.favorites])); + return buildMergedBranchTree(repositories, favorites, current); +} diff --git a/src/features/vcs/log/branchTree.worker.ts b/src/features/vcs/log/branchTree.worker.ts new file mode 100644 index 0000000000..a556471453 --- /dev/null +++ b/src/features/vcs/log/branchTree.worker.ts @@ -0,0 +1,3 @@ +import { buildLogTree, type LogTreeInput } from "./branchTree"; + +self.onmessage = (event: MessageEvent) => self.postMessage(buildLogTree(event.data)); diff --git a/src/features/vcs/log/useLogTree.ts b/src/features/vcs/log/useLogTree.ts new file mode 100644 index 0000000000..2de6fb1167 --- /dev/null +++ b/src/features/vcs/log/useLogTree.ts @@ -0,0 +1,41 @@ +import { useEffect, useMemo, useState } from "react"; +import { buildLogTree, type BranchTreeNode, type LogTreeInput } from "./branchTree"; + +const EMPTY: BranchTreeNode[] = []; +// Most repositories can render immediately. Large ref sets must not occupy the WebView thread. +const WORKER_THRESHOLD = 4_096; + +export function useLogTree(input: LogTreeInput) { + const large = + input.repositories.reduce((count, r) => count + r.tags.length + r.branches.length, 0) >= WORKER_THRESHOLD; + const smallTree = useMemo(() => (large ? null : buildLogTree(input)), [input, large]); + const [loaded, setLoaded] = useState(); + if (!large && loaded) setLoaded(undefined); + useEffect(() => { + if (!large) return; + const fallback = () => setLoaded(buildLogTree(input)); + let worker: Worker | undefined; + try { + worker = new Worker(new URL("./branchTree.worker.ts", import.meta.url), { type: "module" }); + worker.onmessage = (e: MessageEvent) => { + worker?.terminate(); + setLoaded(e.data); + }; + worker.onerror = () => { + worker?.terminate(); + fallback(); + }; + worker.postMessage(input); + } catch { + worker?.terminate(); + fallback(); + } + return () => { + if (!worker) return; + worker.onmessage = worker.onerror = null; + worker.terminate(); + }; + }, [input, large]); + // Until the worker answers, keep the previous tree rather than blanking the pane. + return smallTree ?? loaded ?? EMPTY; +} diff --git a/src/features/vcs/logRefresh.ts b/src/features/vcs/logRefresh.ts index c0c5acc337..7e6718fa8b 100644 --- a/src/features/vcs/logRefresh.ts +++ b/src/features/vcs/logRefresh.ts @@ -2,10 +2,15 @@ import { refreshLogDetails } from "./logDetails"; import { logState, reloadLog, useGitLog } from "./logStore"; import { useVcs } from "./store"; +export function invalidateLogRefs() { + useVcs.setState((s) => ({ refsVersion: s.refsVersion + 1 })); +} + export function refreshLogView(id = useGitLog.getState().shownLog) { if (logState(id).loading) return; const tab = useGitLog.getState().logTabs.find((entry) => entry.id === id); const roots = tab?.repositories?.length ? tab.repositories : tab?.repo ? [tab.repo] : useVcs.getState().roots; + invalidateLogRefs(); void reloadLog({ preserve: true }, id); void refreshLogDetails(roots); } diff --git a/src/features/vcs/store.switch.test.ts b/src/features/vcs/store.switch.test.ts index 9c9d8efa30..56be050e4a 100644 --- a/src/features/vcs/store.switch.test.ts +++ b/src/features/vcs/store.switch.test.ts @@ -259,6 +259,22 @@ describe("VCS status ownership", () => { } }); + it("checks refs on a metadata refresh, including one queued behind file changes", async () => { + useProject.setState({ project: git }); + await refreshNow(); + const { refsVersion } = useVcs.getState(); + // An empty path batch falls back to reading the whole worktree's status. + await refreshPathsNow([]); + expect(useVcs.getState().refsVersion).toBe(refsVersion); + const reply = deferred>(); + vi.spyOn(commands, "vcsStatusPaths").mockReturnValueOnce(reply.promise); + const changed = refreshPathsNow([modified.path]); + const metadata = refreshNow(); + reply.resolve(ok([modified])); + await Promise.all([changed, metadata]); + expect(useVcs.getState().refsVersion).toBe(refsVersion + 1); + }); + it("drains a queued refresh for the new project without retrying the old incremental refresh", async () => { useProject.setState({ project: git }); await refreshNow(); diff --git a/src/features/vcs/store.ts b/src/features/vcs/store.ts index 61090c3553..cf306b1980 100644 --- a/src/features/vcs/store.ts +++ b/src/features/vcs/store.ts @@ -19,6 +19,14 @@ import { setFileDecorations } from "@/workbench/contributions"; import { renamedFromPath } from "./changes"; import { effectiveKind, repoLabel, rootOf, setIndexless, statusDecorations, stripSlash } from "./model"; +/** Keep consumers of the ref list idle while fresh IPC results describe the same branches. */ +export function sameBranches(previous: Branch[] | undefined, branches: Branch[]): boolean { + return ( + previous === branches || + (previous?.length === branches.length && JSON.stringify(previous) === JSON.stringify(branches)) + ); +} + export interface RepoHead { head: string | null; headCommit: string | null; @@ -66,6 +74,8 @@ export interface VcsState { stashesLoaded: boolean; /** Bumped after each refresh; gutters re-query hunks when it changes. */ version: number; + /** Git metadata changed, or the user requested fresh Log refs. */ + refsVersion: number; loading: boolean; error: string | null; /** A network operation (fetch / pull / push) is running. */ @@ -95,6 +105,7 @@ const initial: VcsState = { stashes: [], stashesLoaded: false, version: 0, + refsVersion: 0, loading: false, error: null, remoteBusy: null, @@ -268,6 +279,7 @@ let projectGeneration = 0; let timer: ReturnType | undefined; /** A full refresh is queued; it answers for every path an incremental one would. */ let pendingFull = false; +let pendingRefs = false; /** Paths of watcher batches waiting for an incremental refresh. */ const pendingPaths = new Set(); /** Above this many paths one full read is cheaper than a pathspec that big. */ @@ -288,9 +300,10 @@ export function onConflictsCleared(fn: (files: FileStatus[]) => void) { conflictsClearedListener = fn; } -export function scheduleRefresh(delay = 200) { +export function scheduleRefresh(delay = 200, checkRefs = true) { if (!useVcs.getState().available) return; pendingFull = true; + pendingRefs ||= checkRefs; pendingPaths.clear(); clearTimeout(timer); timer = setTimeout(() => void runScheduled(), delay); @@ -311,7 +324,7 @@ export function schedulePathsRefresh(paths: readonly string[], delay = 250) { async function runScheduled(): Promise { const full = pendingFull; pendingFull = false; - if (full || pendingPaths.size === 0) return refreshNow(); + if (full || pendingPaths.size === 0) return refreshStatus(pendingRefs); const paths = [...pendingPaths]; pendingPaths.clear(); return refreshPathsNow(paths); @@ -323,7 +336,12 @@ async function runScheduled(): Promise { * that await it read the state their operation produced. */ export function refreshNow(): Promise { + return refreshStatus(true); +} + +function refreshStatus(checkRefs: boolean): Promise { if (!useVcs.getState().available) return Promise.resolve(); + pendingRefs ||= checkRefs; if (inflight) { // A full refresh answers for every path: queue it as one, drained after the running read, so a // pending batch of paths cannot swallow it (and the caller still reads the state it produced). @@ -335,6 +353,8 @@ export function refreshNow(): Promise { return followUp; } const generation = projectGeneration; + const refreshRefs = pendingRefs; + pendingRefs = false; inflight = (async () => { useVcs.setState({ loading: true }); try { @@ -450,7 +470,10 @@ export function refreshNow(): Promise { unavailableRoots: nextUnavailable, operations, heads, - kinds, + kinds: + Object.keys(s.kinds).length === vcsRoots.length && vcsRoots.every((r) => s.kinds[r.root] === r.kind) + ? s.kinds + : kinds, resolvedConflicts, branchRoots: sameBranchRoots ? s.branchRoots : branchRoots, }); @@ -481,7 +504,11 @@ export function refreshNow(): Promise { .join("\n"), ); applyStatus(status.files, branch, s.repo ?? roots[0] ?? null); - useVcs.setState({ branches, stashes, error: null }); + useVcs.setState({ + branches: sameBranches(s.branches, branches) ? s.branches : branches, + stashes, + error: null, + }); // Branch info and branches above are of another repository: load the selected one's. if (repo !== shown || (s.repo && repo !== s.repo)) { useVcs.setState({ branchesLoaded: false, stashesLoaded: false }); @@ -493,7 +520,11 @@ export function refreshNow(): Promise { } } finally { if (generation === projectGeneration) { - useVcs.setState((st) => ({ loading: false, version: st.version + 1 })); + useVcs.setState((st) => ({ + loading: false, + version: st.version + 1, + refsVersion: refreshRefs ? st.refsVersion + 1 : st.refsVersion, + })); } inflight = null; } @@ -515,7 +546,7 @@ export function refreshPathsNow(paths: readonly string[]): Promise { paths.length > PATH_BATCH_LIMIT || state.unavailableRoots.length > 0 ) { - return refreshNow(); + return refreshStatus(false); } if (inflight) { // Coalesce with the running refresh: the queued run drains every path that arrived meanwhile, @@ -543,7 +574,7 @@ export function refreshPathsNow(paths: readonly string[]): Promise { })(); const done = run.then((ok) => { inflight = null; - return ok || generation !== projectGeneration ? undefined : refreshNow(); + return ok || generation !== projectGeneration ? undefined : refreshStatus(false); }); inflight = done; return done; @@ -642,7 +673,10 @@ export async function loadBranches(refresh = true): Promise { const repo = currentRepo(); const branches = await branchLines(repo, refresh); if (gen === projectGeneration && repo === currentRepo() && useVcs.getState().roots.length > 0) { - useVcs.setState({ branches, branchesLoaded: true }); + useVcs.setState((s) => ({ + branches: sameBranches(s.branches, branches) ? s.branches : branches, + branchesLoaded: true, + })); } return branches; } @@ -718,6 +752,7 @@ export function installVcsStore(): () => void { const root = project?.root ?? null; if (useVcs.getState().root === root && useVcs.getState().available === available) return; projectGeneration++; + pendingRefs = false; clearTimeout(timer); pendingPaths.clear(); useVcs.setState({ ...initial, available, root, version: useVcs.getState().version + 1 }); @@ -745,7 +780,7 @@ export function installVcsStore(): () => void { const offFs = onIdeEvent("fsChanged", (e) => { // Ignore-rule changes re-filter every path: only a full status answers for them. if (e.ignoreRules?.length) { - scheduleRefresh(250); + scheduleRefresh(250, false); return; } const changed = [...e.created, ...e.modified, ...e.removed].filter((p) => !/(^|[/\\])\.git([/\\]|$)/.test(p));