Skip to content

The IDE you know, rebuilt in Rust. IntelliJ IDEA–style keymap, tool windows and search-everywhere in a fast native app: editor, code insight, debugger, Git, terminal, database and HTTP clients for 60+ languages.

feat(vcs): Default the Git Log to the current branch and remember the branch filter (#155)

itning11362a36f8cd
diff --git a/src/features/vcs/GitLog.tsx b/src/features/vcs/GitLog.tsx
index 5770b1d82..b11fd3981 100644
--- a/src/features/vcs/GitLog.tsx
+++ b/src/features/vcs/GitLog.tsx
@@ -40,6 +40,7 @@ import {
extendCommitSelection,
goToChild,
goToParent,
+ initLogBranchFilter,
isMine,
loadMore,
ME,
@@ -49,6 +50,7 @@ import {
selectCommit,
selectGitTab,
selectedCommits,
+ setLogBranches,
setLogFilters,
toggleCommitSelection,
updateLogOptions,
@@ -164,6 +166,7 @@ function LogView() {
const root = useVcs((s) => s.root);
const repo = useVcs((s) => s.repo);
const showBranches = useLogOptions((s) => s.showBranches);
+ const branchesLoaded = useVcs((s) => s.branchesLoaded);
const lastRefs = useRef<string | null>(null);
// On mount, when the window switches to another project and when another of its
@@ -174,6 +177,18 @@ function LogView() {
void loadBranches().catch(() => undefined);
}, [root, repo]);
+ // Once the repository's branches are known, settle the branch filter (the
+ // remembered refs, else the current branch) and load the log with it.
+ useEffect(() => {
+ if (!branchesLoaded) return;
+ // The refs the log is loaded with, so the first checkout or commit after this reloads it.
+ const { branch, branches } = useVcs.getState();
+ lastRefs.current = refsSignature(branch, branches);
+ const settled = initLogBranchFilter();
+ const { commits, loading } = useGitLog.getState();
+ if (settled || (!commits.length && !loading)) void reloadLog();
+ }, [root, repo, branchesLoaded]);
+
// HEAD or a branch tip moved (commit, undo, reset, rebase, fetch…): reload (keeps the selection).
useEffect(() => {
const { branch, branches, branchesLoaded } = useVcs.getState();
@@ -379,7 +394,7 @@ export function BranchesPanel() {
// selected one when it is part of a multi-selection; checking out stays in the context menu.
if (!n.ref) return;
const sel = selected.has(n.key) ? targets.map((r) => r.ref) : [n.ref];
- setLogFilters({ branches: sel });
+ setLogBranches(sel);
}}
onContextMenu={(n, _s, e) => {
const items = n?.branch ? branchMenu(n.branch, current) : [];
@@ -486,7 +501,7 @@ function FilterBar() {
initial: filters.branches,
customLabel: "Other revisions (comma-separated):",
});
- if (r) setLogFilters({ branches: r });
+ if (r) setLogBranches(r);
};
const openUser = (e: ReactMouseEvent<HTMLElement>) => {
@@ -578,7 +593,7 @@ function FilterBar() {
label="Branch"
value={filters.branches.join(", ") || null}
onOpen={(e) => setBranchAnchor(e.currentTarget)}
- onClear={() => setLogFilters({ branches: [] })}
+ onClear={() => setLogBranches([])}
/>
{branchAnchor && (
<BranchFilterPopup
@@ -587,7 +602,7 @@ function FilterBar() {
selected={filters.branches}
onClose={() => setBranchAnchor(null)}
onSelect={(branch) => {
- setLogFilters({ branches: [branch] });
+ setLogBranches([branch]);
setBranchAnchor(null);
}}
onSelectMany={() => void selectBranches()}
diff --git a/src/features/vcs/__tests__/logBranchMemory.test.ts b/src/features/vcs/__tests__/logBranchMemory.test.ts
new file mode 100644
index 000000000..a2da8bfd9
--- /dev/null
+++ b/src/features/vcs/__tests__/logBranchMemory.test.ts
@@ -0,0 +1,113 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { Branch } from "@/bindings";
+
+vi.mock("@/platform/ipc", async (importOriginal) => {
+ const real = await importOriginal<typeof import("@/platform/ipc")>();
+ return {
+ ...real,
+ commands: {
+ ...real.commands,
+ vcsLog: () => Promise.resolve({ status: "ok", data: [] }),
+ vcsConfigGet: () => Promise.resolve({ status: "ok", data: null }),
+ },
+ };
+});
+
+import {
+ emptyFilters,
+ initLogBranchFilter,
+ rememberedLogBranches,
+ resolveLogBranches,
+ setLogBranches,
+ useGitLog,
+} from "../logStore";
+import { useVcs } from "../store";
+
+const b = (name: string, opts: Partial<Branch> = {}): Branch => ({
+ name,
+ remote: false,
+ current: false,
+ upstream: null,
+ ahead: 0,
+ behind: 0,
+ lastCommitMs: 0,
+ commit: "",
+ ...opts,
+});
+
+const remember = (repo: string, branches: string[]) =>
+ localStorage.setItem(`openidea.vcs.logBranches:${repo}`, JSON.stringify(branches));
+
+/** A project and its selected repository with the given branches. */
+function project(root: string, repo = root, branches: readonly Branch[] = [b("main", { current: true })]) {
+ useVcs.setState({ root, roots: [repo], repo, branches: [...branches], branchesLoaded: true });
+ useGitLog.setState({ filters: emptyFilters(), branchScope: null, shownLog: "log", commits: [] });
+}
+
+beforeEach(() => localStorage.clear());
+
+describe("resolveLogBranches", () => {
+ it("defaults to HEAD (the current branch) when nothing was remembered", () => {
+ expect(resolveLogBranches(undefined, ["main", "feature"])).toEqual(["HEAD"]);
+ });
+
+ it("keeps a remembered local or remote branch", () => {
+ expect(resolveLogBranches(["feature"], ["main", "feature"])).toEqual(["feature"]);
+ expect(resolveLogBranches(["origin/es"], ["main", "origin/es"])).toEqual(["origin/es"]);
+ });
+
+ it("falls back to HEAD when every remembered branch is gone", () => {
+ expect(resolveLogBranches(["deleted"], ["main"])).toEqual(["HEAD"]);
+ });
+
+ it("keeps the remembered branches that still exist", () => {
+ expect(resolveLogBranches(["deleted", "feature"], ["main", "feature"])).toEqual(["feature"]);
+ });
+
+ it("keeps an empty list as all branches, and HEAD", () => {
+ expect(resolveLogBranches([], ["main"])).toEqual([]);
+ expect(resolveLogBranches(["HEAD"], ["main"])).toEqual(["HEAD"]);
+ });
+});
+
+describe("Git Log branch filter memory", () => {
+ it("shows the current branch on first open", () => {
+ project("/mem-first");
+ expect(initLogBranchFilter()).toBe(true);
+ expect(useGitLog.getState().filters.branches).toEqual(["HEAD"]);
+ expect(initLogBranchFilter()).toBe(false);
+ });
+
+ it("restores the remembered branch, dropping a deleted one", () => {
+ remember("/mem-restore", ["origin/es", "deleted"]);
+ project("/mem-restore", "/mem-restore", [b("main", { current: true }), b("origin/es", { remote: true })]);
+ initLogBranchFilter();
+ expect(useGitLog.getState().filters.branches).toEqual(["origin/es"]);
+ });
+
+ it("remembers a choice in the main Log, including all branches", () => {
+ project("/mem-save");
+ initLogBranchFilter();
+ setLogBranches(["feature"]);
+ expect(useGitLog.getState().filters.branches).toEqual(["feature"]);
+ expect(rememberedLogBranches("/mem-save")).toEqual(["feature"]);
+ setLogBranches([]);
+ expect(rememberedLogBranches("/mem-save")).toEqual([]);
+ });
+
+ it("does not remember a choice in another log tab", () => {
+ project("/mem-tab");
+ useGitLog.setState({ shownLog: "tab-1" });
+ setLogBranches(["feature"]);
+ expect(rememberedLogBranches("/mem-tab")).toBeUndefined();
+ });
+
+ it("keeps a separate choice for every repository", () => {
+ remember("/mem-multi", ["main"]);
+ remember("/mem-multi/backend", ["dev"]);
+ project("/mem-multi", "/mem-multi/backend", [b("dev", { current: true }), b("main")]);
+ initLogBranchFilter();
+ expect(useGitLog.getState().filters.branches).toEqual(["dev"]);
+ expect(useGitLog.getState().branchScope).toBe("/mem-multi/backend");
+ });
+});
diff --git a/src/features/vcs/logStore.ts b/src/features/vcs/logStore.ts
index a6656cc8f..e4417c3bb 100644
--- a/src/features/vcs/logStore.ts
+++ b/src/features/vcs/logStore.ts
@@ -6,7 +6,7 @@ import { workflowSettings } from "@/platform/workflowSettings";
import { collapseLinear, computeGraph, emptyGraphState, type GraphRow, type GraphState } from "./graph";
import { logOptions, setLogOptions, type LogOptions } from "./logOptions";
import { clearConsole, errorMessage } from "./ops";
-import { currentRepo, repoOf, selectRepo, useVcs } from "./store";
+import { currentRepo, currentRepoRoot, repoOf, selectRepo, useVcs } from "./store";
/** Date filter: commits made (committer time) after / before the given times (epoch ms). */
export interface LogDateFilter {
@@ -52,6 +52,8 @@ interface LogState {
logTabs: LogTab[];
/** The log tab whose commits / filters / selection the store holds ("log" or a `logTabs` id). */
shownLog: string;
+ /** Repository whose branch filter is settled (default or chosen); null until then. */
+ branchScope: string | null;
/** Bumped to ask the list to scroll the selection into view. */
revealTick: number;
/** The current user (`user.email`, else `user.name`), for View Options › Highlight › My Commits. */
@@ -138,12 +140,74 @@ const initialLog = (): Omit<LogState, "generation"> => ({
tab: "log",
logTabs: [],
shownLog: "log",
+ branchScope: null,
revealTick: 0,
user: null,
});
export const useGitLog = create<LogState>(() => ({ ...initialLog(), generation: 0 }));
+/**
+ * The refs the log shows: the remembered ones that still exist, else `HEAD` (the
+ * current branch, followed across checkouts). An empty list is a real choice: all branches.
+ */
+export function resolveLogBranches(remembered: readonly string[] | undefined, branches: readonly string[]): string[] {
+ if (remembered === undefined) return ["HEAD"];
+ if (!remembered.length) return [];
+ const valid = remembered.filter((ref) => ref === "HEAD" || branches.includes(ref));
+ return valid.length ? valid : ["HEAD"];
+}
+
+const branchMemoryKey = (repo: string) => `openidea.vcs.logBranches:${repo}`;
+
+/** The main Log's branch filter last chosen for `repo`; undefined when none was. */
+export function rememberedLogBranches(repo: string): string[] | undefined {
+ try {
+ const raw = localStorage.getItem(branchMemoryKey(repo));
+ const v: unknown = raw ? JSON.parse(raw) : undefined;
+ return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+function rememberLogBranches(repo: string, branches: readonly string[]) {
+ try {
+ localStorage.setItem(branchMemoryKey(repo), JSON.stringify(branches));
+ } catch {
+ // Storage unavailable: the choice lasts for the session only.
+ }
+}
+
+/**
+ * Settles the main Log's branch filter for the selected repository: its last
+ * choice, else the current branch. False when it was already settled.
+ */
+export function initLogBranchFilter(): boolean {
+ const s = useGitLog.getState();
+ const repo = currentRepoRoot();
+ if (s.shownLog !== "log" || !repo || s.branchScope === repo) return false;
+ const names = useVcs
+ .getState()
+ .branches.filter((b) => !b.name.endsWith("/HEAD"))
+ .map((b) => b.name);
+ const next = resolveLogBranches(rememberedLogBranches(repo), names);
+ useGitLog.setState({ filters: { ...s.filters, branches: next }, branchScope: repo });
+ return true;
+}
+
+/** The Branch filter's setter: a choice in the main Log is remembered for the repository. */
+export function setLogBranches(branches: readonly string[]) {
+ const s = useGitLog.getState();
+ const repo = s.shownLog === "log" ? currentRepoRoot() : null;
+ useGitLog.setState({
+ filters: { ...s.filters, branches: [...branches] },
+ ...(repo ? { branchScope: repo } : {}),
+ });
+ if (repo) rememberLogBranches(repo, branches);
+ void reloadLog();
+}
+
let loadPromise: Promise<void> | null = null;
/** What a log tab shows: the store fields swapped in and out when another log tab is selected. */
@@ -240,12 +304,30 @@ export function installGitLog(): () => void {
} else if (s.repo !== prev.repo && prev.repo !== null) {
// The parked log tabs load again when shown.
for (const [id, view] of parked) parked.set(id, freshView(view.filters));
- const l = useGitLog.getState();
- if (l.generation === 0 && !l.filters.path) return;
- const { path } = useGitLog.getState().filters;
- // A path filter belongs to the repository it is in.
- if (path && repoOf(path) !== s.repo) useGitLog.setState((l) => ({ filters: { ...l.filters, path: null } }));
- void reloadLog();
+ // Drops a page still loading for the old repository (its generation no longer matches).
+ loadPromise = null;
+ useGitLog.setState((l) => ({
+ // The shown log belonged to the old repository: it loads again once the new
+ // repository's branch filter is settled (see LogView).
+ commits: [],
+ rows: [],
+ graph: emptyGraphState(),
+ loading: false,
+ done: false,
+ error: null,
+ selected: null,
+ selection: [],
+ branchScope: null,
+ generation: l.generation + 1,
+ filters: {
+ ...l.filters,
+ // The main Log's branch filter belonged to the old repository; show all
+ // until the new repository's remembered/current branch is settled.
+ ...(l.shownLog === "log" ? { branches: [] } : {}),
+ // A path filter belongs to the repository it is in.
+ ...(l.filters.path && repoOf(l.filters.path) !== s.repo ? { path: null } : {}),
+ },
+ }));
}
});
}