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
191 changes: 191 additions & 0 deletions apps/code/src/main/services/git/create-pr-saga.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
import { getGitOperationManager } from "@posthog/git/operation-manager";
import { getHeadSha } from "@posthog/git/queries";
import { Saga, type SagaLogger } from "@posthog/shared";
import type {
ChangedFile,
CommitOutput,
CreatePrProgressPayload,
GitSyncStatus,
PublishOutput,
PushOutput,
} from "./schemas";

export interface CreatePrSagaInput {
directoryPath: string;
branchName?: string;
commitMessage?: string;
prTitle?: string;
prBody?: string;
draft?: boolean;
}

export interface CreatePrSagaOutput {
prUrl: string | null;
}

export interface CreatePrDeps {
getCurrentBranch(dir: string): Promise<string | null>;
createBranch(dir: string, name: string): Promise<void>;
checkoutBranch(
dir: string,
name: string,
): Promise<{ previousBranch: string; currentBranch: string }>;
getChangedFilesHead(dir: string): Promise<ChangedFile[]>;
generateCommitMessage(dir: string): Promise<{ message: string }>;
commit(dir: string, message: string): Promise<CommitOutput>;
getSyncStatus(dir: string): Promise<GitSyncStatus>;
push(dir: string): Promise<PushOutput>;
publish(dir: string): Promise<PublishOutput>;
generatePrTitleAndBody(dir: string): Promise<{ title: string; body: string }>;
createPr(
dir: string,
title?: string,
body?: string,
draft?: boolean,
): Promise<{ success: boolean; message: string; prUrl: string | null }>;
onProgress(
step: CreatePrProgressPayload["step"],
message: string,
prUrl?: string,
): void;
}

export class CreatePrSaga extends Saga<CreatePrSagaInput, CreatePrSagaOutput> {
readonly sagaName = "CreatePrSaga";
private deps: CreatePrDeps;

constructor(deps: CreatePrDeps, logger?: SagaLogger) {
super(logger);
this.deps = deps;
}

protected async execute(
input: CreatePrSagaInput,
): Promise<CreatePrSagaOutput> {
const { directoryPath, draft } = input;
let { commitMessage, prTitle, prBody } = input;

if (input.branchName) {
this.deps.onProgress(
"creating-branch",
`Creating branch ${input.branchName}...`,
);

const originalBranch = await this.readOnlyStep(
"get-original-branch",
() => this.deps.getCurrentBranch(directoryPath),
);

await this.step({
name: "creating-branch",
execute: () => this.deps.createBranch(directoryPath, input.branchName!),
rollback: async () => {
if (originalBranch) {
await this.deps.checkoutBranch(directoryPath, originalBranch);
}
},
});
}

const changedFiles = await this.readOnlyStep("check-changes", () =>
this.deps.getChangedFilesHead(directoryPath),
);

if (changedFiles.length > 0) {
if (!commitMessage) {
this.deps.onProgress("committing", "Generating commit message...");
const generated = await this.readOnlyStep(
"generate-commit-message",
async () => {
try {
return await this.deps.generateCommitMessage(directoryPath);
} catch {
return null;
}
},
);
if (generated) commitMessage = generated.message;
}

if (!commitMessage) {
throw new Error("Commit message is required.");
}

this.deps.onProgress("committing", "Committing changes...");

const preCommitSha = await this.readOnlyStep("get-pre-commit-sha", () =>
getHeadSha(directoryPath),
);

await this.step({
name: "committing",
execute: async () => {
const result = await this.deps.commit(directoryPath, commitMessage!);
if (!result.success) throw new Error(result.message);
return result;
},
rollback: async () => {
const manager = getGitOperationManager();
await manager.executeWrite(directoryPath, (git) =>
git.reset(["--soft", preCommitSha]),
);
},
});
}

this.deps.onProgress("pushing", "Pushing to remote...");

const syncStatus = await this.readOnlyStep("check-sync-status", () =>
this.deps.getSyncStatus(directoryPath),
);

await this.step({
name: "pushing",
execute: async () => {
const result = syncStatus.hasRemote
? await this.deps.push(directoryPath)
: await this.deps.publish(directoryPath);
if (!result.success) throw new Error(result.message);
return result;
},
rollback: async () => {}, // no meaningful rollback can happen here w/o force push
});

if (!prTitle || !prBody) {
this.deps.onProgress("creating-pr", "Generating PR description...");
const generated = await this.readOnlyStep(
"generate-pr-description",
async () => {
try {
return await this.deps.generatePrTitleAndBody(directoryPath);
} catch {
return null;
}
},
);
if (generated) {
if (!prTitle) prTitle = generated.title;
if (!prBody) prBody = generated.body;
}
}

this.deps.onProgress("creating-pr", "Creating pull request...");

const prResult = await this.step({
name: "creating-pr",
execute: async () => {
const result = await this.deps.createPr(
directoryPath,
prTitle || undefined,
prBody || undefined,
draft,
);
if (!result.success) throw new Error(result.message);
return result;
},
rollback: async () => {},
});

return { prUrl: prResult.prUrl };
}
}
28 changes: 26 additions & 2 deletions apps/code/src/main/services/git/schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,8 +228,11 @@ export type PrStatusOutput = z.infer<typeof prStatusOutput>;
// Create PR operation
export const createPrInput = z.object({
directoryPath: z.string(),
title: z.string().optional(),
body: z.string().optional(),
flowId: z.string(),
branchName: z.string().optional(),
commitMessage: z.string().optional(),
prTitle: z.string().optional(),
prBody: z.string().optional(),
draft: z.boolean().optional(),
});

Expand Down Expand Up @@ -372,10 +375,22 @@ export const syncOutput = z.object({

export type SyncOutput = z.infer<typeof syncOutput>;

export const createPrStep = z.enum([
"creating-branch",
"committing",
"pushing",
"creating-pr",
"complete",
"error",
]);

export type CreatePrStep = z.infer<typeof createPrStep>;

export const createPrOutput = z.object({
success: z.boolean(),
message: z.string(),
prUrl: z.string().nullable(),
failedStep: createPrStep.nullable(),
state: gitStateSnapshotSchema.optional(),
});

Expand Down Expand Up @@ -406,3 +421,12 @@ export const searchGithubIssuesInput = z.object({
});

export const searchGithubIssuesOutput = z.array(githubIssueSchema);

export const createPrProgressPayload = z.object({
flowId: z.string(),
step: createPrStep,
message: z.string(),
prUrl: z.string().optional(),
});

export type CreatePrProgressPayload = z.infer<typeof createPrProgressPayload>;
97 changes: 87 additions & 10 deletions apps/code/src/main/services/git/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,13 @@ import { MAIN_TOKENS } from "../../di/tokens";
import { logger } from "../../utils/logger";
import { TypedEventEmitter } from "../../utils/typed-event-emitter";
import type { LlmGatewayService } from "../llm-gateway/service";
import { CreatePrSaga } from "./create-pr-saga";
import type {
ChangedFile,
CloneProgressPayload,
CommitOutput,
CreatePrOutput,
CreatePrProgressPayload,
DetectRepoResult,
DiffStats,
DiscardFileChangesOutput,
Expand All @@ -60,10 +62,12 @@ const fsPromises = fs.promises;

export const GitServiceEvent = {
CloneProgress: "cloneProgress",
CreatePrProgress: "createPrProgress",
} as const;

export interface GitServiceEvents {
[GitServiceEvent.CloneProgress]: CloneProgressPayload;
[GitServiceEvent.CreatePrProgress]: CreatePrProgressPayload;
}

const log = logger.scope("git-service");
Expand Down Expand Up @@ -459,6 +463,87 @@ export class GitService extends TypedEventEmitter<GitServiceEvents> {
};
}

public async createPr(input: {
directoryPath: string;
flowId: string;
branchName?: string;
commitMessage?: string;
prTitle?: string;
prBody?: string;
draft?: boolean;
}): Promise<CreatePrOutput> {
const { directoryPath, flowId } = input;

const emitProgress = (
step: CreatePrProgressPayload["step"],
message: string,
prUrl?: string,
) => {
this.emit(GitServiceEvent.CreatePrProgress, {
flowId,
step,
message,
prUrl,
});
};

const saga = new CreatePrSaga(
{
getCurrentBranch: (dir) => getCurrentBranch(dir),
createBranch: (dir, name) => this.createBranch(dir, name),
checkoutBranch: (dir, name) => this.checkoutBranch(dir, name),
getChangedFilesHead: (dir) => this.getChangedFilesHead(dir),
generateCommitMessage: (dir) => this.generateCommitMessage(dir),
commit: (dir, msg) => this.commit(dir, msg),
getSyncStatus: (dir) => this.getGitSyncStatus(dir),
push: (dir) => this.push(dir),
publish: (dir) => this.publish(dir),
generatePrTitleAndBody: (dir) => this.generatePrTitleAndBody(dir),
createPr: (dir, title, body, draft) =>
this.createPrViaGh(dir, title, body, draft),
onProgress: emitProgress,
},
log,
);

const result = await saga.run({
directoryPath,
branchName: input.branchName,
commitMessage: input.commitMessage,
prTitle: input.prTitle,
prBody: input.prBody,
draft: input.draft,
});

if (!result.success) {
emitProgress("error", result.error);
return {
success: false,
message: result.error,
prUrl: null,
failedStep: result.failedStep as CreatePrOutput["failedStep"],
};
}

const state = await this.getStateSnapshot(directoryPath, {
includePrStatus: true,
});

emitProgress(
"complete",
"Pull request created",
result.data.prUrl ?? undefined,
);

return {
success: true,
message: "Pull request created",
prUrl: result.data.prUrl,
failedStep: null,
state,
};
}

public async getPrTemplate(
directoryPath: string,
): Promise<GetPrTemplateOutput> {
Expand Down Expand Up @@ -628,12 +713,12 @@ export class GitService extends TypedEventEmitter<GitServiceEvents> {
}
}

public async createPr(
private async createPrViaGh(
directoryPath: string,
title?: string,
body?: string,
draft?: boolean,
): Promise<CreatePrOutput> {
): Promise<{ success: boolean; message: string; prUrl: string | null }> {
const args = ["pr", "create"];
if (title) {
args.push("--title", title);
Expand All @@ -655,18 +740,10 @@ export class GitService extends TypedEventEmitter<GitServiceEvents> {
const prUrlMatch = result.stdout.match(/https:\/\/github\.com\/[^\s]+/);
const prUrl = prUrlMatch?.[0] ?? null;

const state = await this.getStateSnapshot(directoryPath, {
includeChangedFiles: false,
includeDiffStats: false,
includeLatestCommit: false,
includePrStatus: true,
});

return {
success: true,
message: "Pull request created",
prUrl,
state,
};
}

Expand Down
Loading
Loading