Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 106 additions & 0 deletions windows/tauri/src/features/git/api/git-remotes-api.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import { beforeEach, describe, expect, mock, test } from "bun:test";
import type { GitPullPreflight } from "../types/git.types";

const invoke = mock(async (_command: string, _args?: unknown): Promise<unknown> => null);
const emitGitChanged = mock((_change: unknown) => {});
const resolveRepositoryPath = mock(async (repoPath: string) => repoPath);
const resolveRepositoryPathOrThrow = mock(async (repoPath: string) => repoPath);
const getOperationState = mock(async () => null);
const getBranches = mock(async () => []);
const getGitHistory = mock(async () => null);
const getGitStatus = mock(async () => null);

mock.module("@/platform/tauri-core", () => ({ invoke }));
mock.module("../events/git-events", () => ({ emitGitChanged }));
mock.module("./git-repo-api", () => ({
isNotGitRepositoryError: () => false,
resolveRepositoryPath,
resolveRepositoryPathOrThrow,
}));
mock.module("./git-integration-api", () => ({ getOperationState }));
mock.module("./git-branches-api", () => ({ getBranches }));
mock.module("./git-commits-api", () => ({ getGitHistory }));
mock.module("./git-status-api", () => ({ getGitStatus }));

const { executePullChanges, fetchChanges, getGitPullWorkflow, getPullPreflight, pullChanges } =
await import("./git-remotes-api");

beforeEach(() => {
invoke.mockReset();
emitGitChanged.mockReset();
resolveRepositoryPath.mockReset();
resolveRepositoryPathOrThrow.mockReset();
getBranches.mockClear();
getGitHistory.mockClear();
getGitStatus.mockClear();
resolveRepositoryPath.mockImplementation(async (repoPath: string) => repoPath);
resolveRepositoryPathOrThrow.mockImplementation(async (repoPath: string) => repoPath);
});

describe("Git remote Pull API", () => {
test("shares a Pull workflow only within the same repository", () => {
expect(getGitPullWorkflow("C:/repo")).toBe(getGitPullWorkflow("C:/repo"));
expect(getGitPullWorkflow("C:/repo")).not.toBe(getGitPullWorkflow("C:/other-repo"));
});

test("calls the shared git.pullPreflight contract for the current branch", async () => {
const preflight: GitPullPreflight = {
upstream: "origin/main",
ahead: 1,
behind: 2,
diverged: true,
hasLocalChanges: false,
};
invoke.mockResolvedValue(preflight);

await expect(getPullPreflight("C:/repo")).resolves.toEqual(preflight);
expect(invoke).toHaveBeenCalledWith("git.pullPreflight", { repoPath: "C:/repo" });
});

test("executes Pull with only the selected Core mode", async () => {
invoke.mockResolvedValue(null);

await expect(executePullChanges("C:/repo", "rebase")).resolves.toEqual({ success: true });
expect(invoke).toHaveBeenCalledWith("git_pull", {
repoPath: "C:/repo",
mode: "rebase",
});
});

test("fetches the repository without an ignored remote parameter", async () => {
invoke.mockResolvedValue(null);

await expect(fetchChanges("C:/repo")).resolves.toEqual({ success: true });
expect(invoke).toHaveBeenCalledWith("git_fetch", { repoPath: "C:/repo" });
});

test("keeps a headless divergent Pull on the safe Cancel default", async () => {
invoke.mockImplementation(async (command: string) => {
if (command === "git.pullPreflight") {
return {
upstream: "origin/main",
ahead: 1,
behind: 1,
diverged: true,
hasLocalChanges: false,
} satisfies GitPullPreflight;
}
return null;
});

await expect(pullChanges("C:/repo")).resolves.toEqual({
success: false,
error: "Branches have diverged. Open Source Control and choose Merge or Rebase.",
});
expect(invoke).not.toHaveBeenCalledWith("git_pull", expect.anything());
expect(getGitStatus).toHaveBeenCalledWith("C:/repo");
expect(getGitHistory).toHaveBeenCalledWith("C:/repo", 50);
expect(getBranches).toHaveBeenCalledWith("C:/repo");
expect(invoke).toHaveBeenCalledWith("git_get_remotes", { repoPath: "C:/repo" });
expect(emitGitChanged).toHaveBeenLastCalledWith({
repoPath: "C:/repo",
scopes: ["working-tree", "history", "refs", "remotes"],
source: "pull-finished",
});
});
});
95 changes: 80 additions & 15 deletions windows/tauri/src/features/git/api/git-remotes-api.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import { invoke as tauriInvoke } from "@/platform/tauri-core";
import type { GitRemote } from "../types/git.types";
import type { GitPullPreflight, GitRemote, PullStrategy } from "../types/git.types";
import { emitGitChanged } from "../events/git-events";
import { GitPullWorkflow } from "../hooks/git-pull-workflow";
import { runGitRead } from "../runtime/git-read-coordinator";
import { getBranches } from "./git-branches-api";
import { getGitHistory } from "./git-commits-api";
import { getOperationState } from "./git-integration-api";
import { getGitStatus } from "./git-status-api";
import {
isNotGitRepositoryError,
resolveRepositoryPath,
Expand Down Expand Up @@ -88,19 +93,20 @@ export const pushChanges = async (
}
};

export const pullChanges = async (
export const getPullPreflight = async (repoPath: string): Promise<GitPullPreflight> => {
const resolvedRepoPath = await resolveRepositoryPathOrThrow(repoPath);
return tauriInvoke<GitPullPreflight>("git.pullPreflight", {
repoPath: resolvedRepoPath,
});
};

export const executePullChanges = async (
repoPath: string,
branch?: string,
remote: string = "origin",
strategy: PullStrategy,
): Promise<GitRemoteActionResult> => {
try {
const resolvedRepoPath = await resolveRepositoryPathOrThrow(repoPath);
await tauriInvoke("git_pull", { repoPath: resolvedRepoPath, branch, remote });
emitGitChanged({
repoPath: resolvedRepoPath,
scopes: ["working-tree", "history", "refs", "remotes"],
source: "pull",
});
await tauriInvoke("git_pull", { repoPath: resolvedRepoPath, mode: strategy });
return { success: true };
} catch (error) {
console.error("Failed to pull changes:", error);
Expand All @@ -111,13 +117,10 @@ export const pullChanges = async (
}
};

export const fetchChanges = async (
repoPath: string,
remote?: string,
): Promise<GitRemoteActionResult> => {
export const fetchChanges = async (repoPath: string): Promise<GitRemoteActionResult> => {
try {
const resolvedRepoPath = await resolveRepositoryPathOrThrow(repoPath);
await tauriInvoke("git_fetch", { repoPath: resolvedRepoPath, remote });
await tauriInvoke("git_fetch", { repoPath: resolvedRepoPath });
emitGitChanged({
repoPath: resolvedRepoPath,
scopes: ["refs", "remotes"],
Expand All @@ -132,3 +135,65 @@ export const fetchChanges = async (
};
}
};

const pullWorkflows = new Map<string, GitPullWorkflow>();

/** Returns the shared Pull coordinator for one repository. */
export const getGitPullWorkflow = (repoPath: string): GitPullWorkflow => {
const existingWorkflow = pullWorkflows.get(repoPath);
if (existingWorkflow) return existingWorkflow;

const workflow = new GitPullWorkflow({
fetch: fetchChanges,
preflight: getPullPreflight,
pull: executePullChanges,
operationState: getOperationState,
});
pullWorkflows.set(repoPath, workflow);
return workflow;
};

/**
* Safe compatibility entry point for non-Source-Control callers. Divergence
* cancels because only the Source Control workflow can present the choice UI.
*/
export const pullChanges = async (repoPath: string): Promise<GitRemoteActionResult> => {
const workflow = getGitPullWorkflow(repoPath);
const unsubscribe = workflow.subscribe(() => {
if (workflow.getSnapshot().pendingPreflight) {
workflow.chooseStrategy(null);
}
});
const resultPromise = workflow.run(repoPath, {
refresh: async () => {
const resolvedRepoPath = await resolveRepositoryPathOrThrow(repoPath);
// Cache invalidation must precede the explicit reads below; otherwise a
// failed or successful Pull could refresh the UI from stale snapshots.
emitGitChanged({
repoPath: resolvedRepoPath,
scopes: ["working-tree", "history", "refs", "remotes"],
source: "pull-finished",
});
await Promise.all([
getGitStatus(resolvedRepoPath),
getGitHistory(resolvedRepoPath, 50),
getBranches(resolvedRepoPath),
getRemotes(resolvedRepoPath),
]);
},
});
try {
const result = await resultPromise;
return result.status === "pulled"
? { success: true }
: {
success: false,
error:
result.status === "cancelled"
? "Branches have diverged. Open Source Control and choose Merge or Rebase."
: result.message,
};
} finally {
unsubscribe();
}
};
24 changes: 10 additions & 14 deletions windows/tauri/src/features/git/components/git-actions-menu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,7 @@ import { Spinner } from "@/ui/spinner";
import { showConfirmDialog } from "@/ui/dialog";
import { toast } from "sonner";
import { useTranslation } from "@/i18n/locale-provider";
import {
fetchChanges,
pullChanges,
pushChanges,
type GitRemoteActionResult,
} from "../api/git-remotes-api";
import { fetchChanges, pushChanges, type GitRemoteActionResult } from "../api/git-remotes-api";
import { discardAllChanges, initRepository } from "../api/git-status-api";
import { useGitStore } from "../stores/git.store";
import { type GitActionsMenuAnchorRect } from "../utils/git-actions-menu-position";
Expand All @@ -35,6 +30,8 @@ interface GitActionsMenuProps {
hasGitRepo: boolean;
repoPath?: string;
onRefresh?: () => void;
onPull?: () => Promise<unknown> | void;
isPulling?: boolean;
onOpenBranchManager?: () => void;
onShowBranchDiff?: () => void;
onOpenRemoteManager?: () => void;
Expand All @@ -53,6 +50,8 @@ const GitActionsMenu = ({
hasGitRepo,
repoPath,
onRefresh,
onPull,
isPulling = false,
onOpenBranchManager,
onShowBranchDiff,
onOpenRemoteManager,
Expand Down Expand Up @@ -122,11 +121,8 @@ const GitActionsMenu = ({
};

const handlePull = () => {
handleAction(() => pullChanges(repoPath!), "Pull", {
loading: "Pulling changes...",
success: "Changes pulled successfully.",
error: "Failed to pull changes.",
});
void onPull?.();
onClose();
};

const handleFetch = () => {
Expand Down Expand Up @@ -226,22 +222,22 @@ const GitActionsMenu = ({
id: "push",
label: t("git.pushChanges"),
icon: <Upload />,
disabled: isLoading,
disabled: isLoading || isPulling,
onClick: handlePush,
},
{ id: "sep-2", label: "", separator: true, onClick: () => {} },
{
id: "pull",
label: t("git.pullChanges"),
icon: <Download weight="fill" />,
disabled: isLoading,
disabled: isLoading || isPulling,
onClick: handlePull,
},
{
id: "fetch",
label: t("git.fetch"),
icon: <GitPullRequest />,
disabled: isLoading,
disabled: isLoading || isPulling,
onClick: handleFetch,
},
{ id: "sep-3", label: "", separator: true, onClick: () => {} },
Expand Down
Loading
Loading