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
118 changes: 118 additions & 0 deletions windows/tauri/src-tauri/src/platform.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,41 @@ fn translate(command: &str, args: Value) -> Result<(String, Value), String> {
);
"git.checkoutPreflight"
}
"git_merge" | "git_rebase" => {
let branch = take_text(&mut payload, "branchName")?;
payload.insert(
"reference".into(),
json!(local_branch_reference(&branch)),
);
payload.insert(
"operation".into(),
json!(if command == "git_merge" {
"merge"
} else {
"rebase"
}),
);
"git.write"
}
"git_integration_preflight" => {
let branch = take_text(&mut payload, "branchName")?;
payload.insert(
"reference".into(),
json!(local_branch_reference(&branch)),
);
"git.integrationPreflight"
}
"git_operation_state" => "git.operationState",
"git_operation_continue" | "git_operation_abort" | "git_operation_skip" => {
let operation = match command {
"git_operation_continue" => "operationContinue",
"git_operation_abort" => "operationAbort",
_ => "operationSkip",
};
payload.insert("operation".into(), json!(operation));
"git.write"
}
"git_conflict_markers" => "git.conflictMarkers",
"git_create_stash" => {
payload.insert("operation".into(), json!("stashPush"));
"git.write"
Expand Down Expand Up @@ -500,6 +535,89 @@ mod tests {
);
}

#[test]
fn translates_merge_and_rebase_to_qualified_references() {
let (merge_command, merge_payload) = translate(
"git_merge",
json!({ "repoPath": "C:/work", "branchName": "feature/demo" }),
)
.unwrap();
assert_eq!(merge_command, "git.write");
assert_eq!(
merge_payload,
json!({
"root": "C:/work",
"operation": "merge",
"reference": "refs/heads/feature/demo"
})
);

let (rebase_command, rebase_payload) = translate(
"git_rebase",
json!({ "repoPath": "C:/work", "branchName": "main" }),
)
.unwrap();
assert_eq!(rebase_command, "git.write");
assert_eq!(
rebase_payload,
json!({
"root": "C:/work",
"operation": "rebase",
"reference": "refs/heads/main"
})
);
}

#[test]
fn translates_integration_preflight_operation() {
let (command, payload) = translate(
"git_integration_preflight",
json!({ "repoPath": "C:/work", "branchName": "main", "operation": "rebase" }),
)
.unwrap();

assert_eq!(command, "git.integrationPreflight");
assert_eq!(
payload,
json!({
"root": "C:/work",
"reference": "refs/heads/main",
"operation": "rebase"
})
);
}

#[test]
fn translates_operation_state_and_resolution_commands() {
let (state_command, state_payload) =
translate("git_operation_state", json!({ "repoPath": "C:/work" })).unwrap();
assert_eq!(state_command, "git.operationState");
assert_eq!(state_payload, json!({ "root": "C:/work" }));

for (compat, operation) in [
("git_operation_continue", "operationContinue"),
("git_operation_abort", "operationAbort"),
("git_operation_skip", "operationSkip"),
] {
let (command, payload) =
translate(compat, json!({ "repoPath": "C:/work" })).unwrap();
assert_eq!(command, "git.write");
assert_eq!(
payload,
json!({ "root": "C:/work", "operation": operation })
);
}
}

#[test]
fn translates_conflict_markers_request() {
let (command, payload) =
translate("git_conflict_markers", json!({ "repoPath": "C:/work" })).unwrap();

assert_eq!(command, "git.conflictMarkers");
assert_eq!(payload, json!({ "root": "C:/work" }));
}

#[test]
fn translates_delete_branch_to_qualified_reference() {
let (command, payload) = translate(
Expand Down
82 changes: 82 additions & 0 deletions windows/tauri/src/features/git/api/git-integration-api.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { beforeEach, describe, expect, mock, test } from "bun:test";
import type { GitOperationState } from "../types/git.types";

const invoke = mock(async (_command: string, _args?: unknown): Promise<unknown> => null);
const emitGitChanged = mock((_change: unknown) => {});
const resolveRepositoryPathOrThrow = mock(async (repoPath: string) => repoPath);

mock.module("@/platform/tauri-core", () => ({ invoke }));
mock.module("../events/git-events", () => ({ emitGitChanged }));
mock.module("./git-repo-api", () => ({ resolveRepositoryPathOrThrow }));

const { getConflictMarkerPaths, getOperationState, mergeBranch, rebaseOntoBranch } = await import(
"./git-integration-api"
);

const operationState = (
kind: GitOperationState["kind"],
conflictedPaths: string[] = [],
): GitOperationState => ({
kind,
reference: null,
conflictedPaths,
step: null,
total: null,
});

beforeEach(() => {
invoke.mockReset();
emitGitChanged.mockReset();
resolveRepositoryPathOrThrow.mockReset();
resolveRepositoryPathOrThrow.mockImplementation(async (repoPath: string) => repoPath);
});

describe("Git integration state", () => {
test("reports a stopped rebase even when no conflicted paths remain", async () => {
invoke.mockImplementation(async (command: string) => {
if (command === "git_integration_preflight") {
return { blockingPaths: [], blocksEntirely: false };
}
if (command === "git_rebase") throw new Error("rebase stopped");
if (command === "git_operation_state") return operationState("rebase");
return null;
});

await expect(rebaseOntoBranch("C:/repo", "main")).resolves.toEqual({ status: "stopped" });
expect(emitGitChanged).toHaveBeenCalledWith({
repoPath: "C:/repo",
scopes: ["working-tree", "history", "refs"],
source: "rebase-rejected",
});
});

test("reports conflicted paths when a merge stops on conflicts", async () => {
invoke.mockImplementation(async (command: string) => {
if (command === "git_integration_preflight") {
return { blockingPaths: [], blocksEntirely: false };
}
if (command === "git_merge") throw new Error("merge stopped");
if (command === "git_operation_state") {
return operationState("merge", ["src/app.ts"]);
}
return null;
});

await expect(mergeBranch("C:/repo", "feature")).resolves.toEqual({
status: "conflicts",
conflictedPaths: ["src/app.ts"],
});
});

test("propagates operation state query failures", async () => {
invoke.mockRejectedValue(new Error("Core unavailable"));

await expect(getOperationState("C:/repo")).rejects.toThrow("Core unavailable");
});

test("propagates conflict marker query failures so commits fail closed", async () => {
invoke.mockRejectedValue(new Error("Core unavailable"));

await expect(getConflictMarkerPaths("C:/repo")).rejects.toThrow("Core unavailable");
});
});
142 changes: 142 additions & 0 deletions windows/tauri/src/features/git/api/git-integration-api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
import { invoke as tauriInvoke } from "@/platform/tauri-core";
import { emitGitChanged } from "../events/git-events";
import { resolveRepositoryPathOrThrow } from "./git-repo-api";
import type { GitOperationState } from "../types/git.types";

type IntegrationOperation = "merge" | "rebase";

interface IntegrationPreflightResult {
blockingPaths: string[];
blocksEntirely: boolean;
}

export type IntegrationOutcome =
| { status: "clean" }
| { status: "conflicts"; conflictedPaths: string[] }
| { status: "stopped" }
| { status: "blocked"; blockingPaths: string[]; blocksEntirely: boolean }
| { status: "error"; message: string };

export interface OperationResolution {
ok: boolean;
message: string;
}

const errorMessage = (error: unknown): string => {
const message = error instanceof Error ? error.message : String(error);
return message.trim() || "Git operation failed";
};

const notifyOperationChanged = (repoPath: string, source: string) => {
emitGitChanged({
repoPath,
scopes: ["working-tree", "history", "refs"],
source,
});
};

export const getOperationState = async (
repoPath: string,
): Promise<GitOperationState | null> => {
const resolvedRepoPath = await resolveRepositoryPathOrThrow(repoPath);
return tauriInvoke<GitOperationState | null>("git_operation_state", {
repoPath: resolvedRepoPath,
});
};

export const getConflictMarkerPaths = async (repoPath: string): Promise<string[]> => {
const resolvedRepoPath = await resolveRepositoryPathOrThrow(repoPath);
const result = await tauriInvoke<{ paths: string[] }>("git_conflict_markers", {
repoPath: resolvedRepoPath,
});
return result.paths;
};

const runIntegration = async (
repoPath: string,
branchName: string,
operation: IntegrationOperation,
): Promise<IntegrationOutcome> => {
const command = operation === "merge" ? "git_merge" : "git_rebase";
try {
await tauriInvoke(command, { repoPath, branchName });
notifyOperationChanged(repoPath, `${operation}-completed`);
return { status: "clean" };
} catch (error) {
// A conflict stop exits non-zero like a real failure; the authoritative
// distinction is whether Git left an operation state behind.
notifyOperationChanged(repoPath, `${operation}-rejected`);
try {
const state = await getOperationState(repoPath);
if (state?.kind === operation) {
if (state.conflictedPaths.length > 0) {
return { status: "conflicts", conflictedPaths: state.conflictedPaths };
}
return { status: "stopped" };
}
} catch (stateError) {
console.error(`Failed to read ${operation} state after Git rejected the operation:`, stateError);
}
return { status: "error", message: errorMessage(error) };
}
};

const startIntegration = async (
repoPath: string,
branchName: string,
operation: IntegrationOperation,
): Promise<IntegrationOutcome> => {
const resolvedRepoPath = await resolveRepositoryPathOrThrow(repoPath);

let preflight: IntegrationPreflightResult | null = null;
try {
preflight = await tauriInvoke<IntegrationPreflightResult>(
"git_integration_preflight",
{ repoPath: resolvedRepoPath, branchName, operation },
);
} catch {
// A failed preflight must not block the operation itself; Git will still
// refuse safely when the tree is dirty.
}

if (preflight && preflight.blockingPaths.length > 0) {
return {
status: "blocked",
blockingPaths: preflight.blockingPaths,
blocksEntirely: preflight.blocksEntirely,
};
}

return runIntegration(resolvedRepoPath, branchName, operation);
};

export const mergeBranch = (repoPath: string, branchName: string) =>
startIntegration(repoPath, branchName, "merge");

export const rebaseOntoBranch = (repoPath: string, branchName: string) =>
startIntegration(repoPath, branchName, "rebase");

const resolveOperation = async (
repoPath: string,
action: "git_operation_continue" | "git_operation_abort" | "git_operation_skip",
): Promise<OperationResolution> => {
const resolvedRepoPath = await resolveRepositoryPathOrThrow(repoPath);
try {
await tauriInvoke(action, { repoPath: resolvedRepoPath });
notifyOperationChanged(resolvedRepoPath, "operation-resolved");
return { ok: true, message: "Git operation finished" };
} catch (error) {
// Even a rejected continue can change repository state, so refresh anyway.
notifyOperationChanged(resolvedRepoPath, "operation-resolution-rejected");
return { ok: false, message: errorMessage(error) };
}
};

export const continueOperation = (repoPath: string) =>
resolveOperation(repoPath, "git_operation_continue");

export const abortOperation = (repoPath: string) =>
resolveOperation(repoPath, "git_operation_abort");

export const skipOperationStep = (repoPath: string) =>
resolveOperation(repoPath, "git_operation_skip");
Loading
Loading