Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -137,20 +137,25 @@ const fastForwardOnlySettings = {
default_merge_style: "fast-forward-only",
};
const fastForwardOnlyProvider = (
writes: Array<{ path: string; body: unknown }>,
writes: Array<{ path: string; body: unknown; method?: string }>,
mergeSettings: object = fastForwardOnlySettings,
timeline: ReadonlyArray<{ type: string }> = [],
) =>
ForgejoPullRequestProvider.make.pipe(
Effect.provide(
Layer.mock(ForgejoCli.ForgejoCli)({
api: (input) => {
const [path] = input.path.split("?");
const [path, query] = input.path.split("?");
const reply = (value: unknown) =>
Effect.succeed(TestSourceControlHost.processOutput(JSON.stringify(value)));
if (input.method === "POST") {
writes.push({ path: input.path, body: input.body });
return reply("");
}
if (input.method === "DELETE") {
writes.push({ path: input.path, body: input.body, method: "DELETE" });
return reply("");
}
switch (path) {
case "user":
return reply({ login: "maria" });
Expand Down Expand Up @@ -181,6 +186,9 @@ const fastForwardOnlyProvider = (
});
case "repos/maria/project/branches/main":
return reply({});
case "repos/maria/project/issues/3/timeline":
// Without a `link` header the provider pages until one comes back empty.
return reply(new URLSearchParams(query).get("page") === "1" ? timeline : []);
default:
return reply([]);
}
Expand Down Expand Up @@ -225,6 +233,78 @@ it.effect("merges with Forgejo's fast-forward-only style", () =>
}),
);

it.effect("schedules a squash merge for when checks succeed", () =>
Effect.gen(function* () {
const writes: Array<{ path: string; body: unknown }> = [];
const provider = yield* fastForwardOnlyProvider(writes, {});
yield* provider.runAction({
...fastForwardOnly,
action: "enable-auto-merge",
mergeMethod: "squash",
});
assert.deepStrictEqual(writes, [
{
path: "repos/maria/project/pulls/3/merge",
body: { Do: "squash", delete_branch_after_merge: false, merge_when_checks_succeed: true },
},
]);
}),
);

it.effect("cancels a scheduled merge", () =>
Effect.gen(function* () {
const writes: Array<{ path: string; body: unknown; method?: string }> = [];
const provider = yield* fastForwardOnlyProvider(writes, {});
yield* provider.runAction({ ...fastForwardOnly, action: "disable-auto-merge" });
assert.deepStrictEqual(writes, [
{ path: "repos/maria/project/pulls/3/merge", body: undefined, method: "DELETE" },
]);
}),
);

it.effect("reads auto-merge state from the latest timeline schedule event", () =>
Effect.gen(function* () {
const autoMerge = (timeline: ReadonlyArray<{ type: string }>) =>
fastForwardOnlyProvider([], {}, timeline).pipe(
Effect.flatMap((provider) => provider.getChangeRequest(fastForwardOnly)),
Effect.map((detail) => detail.autoMergeEnabled),
);
assert.strictEqual(yield* autoMerge([]), false);
assert.strictEqual(
yield* autoMerge([{ type: "comment" }, { type: "pull_scheduled_merge" }, { type: "label" }]),
true,
);
assert.strictEqual(
yield* autoMerge([{ type: "pull_scheduled_merge" }, { type: "pull_cancel_scheduled_merge" }]),
false,
);
}),
);

it.effect("offers auto-merge only to viewers who can merge", () =>
Effect.gen(function* () {
const provider = yield* fastForwardOnlyProvider([], {});
assert.includeMembers(
[...provider.capabilities.actions],
["enable-auto-merge", "disable-auto-merge"],
);
const detail = yield* provider.getChangeRequest(fastForwardOnly);
assert.includeMembers(
[...detail.viewerPermissions.actions],
["enable-auto-merge", "disable-auto-merge"],
);
// The author without push access can still close their pull request but not merge it.
const author = yield* fastForwardOnlyProvider([], {
permissions: { push: false, admin: false },
});
const authorActions = (yield* author.getChangeRequest(fastForwardOnly)).viewerPermissions
.actions;
assert.include([...authorActions], "close");
assert.notInclude([...authorActions], "enable-auto-merge");
assert.notInclude([...authorActions], "disable-auto-merge");
}),
);

// An empty `link` header marks the last page.
const labelPage = (value: unknown) =>
Effect.succeed({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@ import { resolvePullRequestAuthorFilter, SourceControlProviderKind } from "@t3to
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as Result from "effect/Result";
import type { PullRequestCapabilities, PullRequestViewerPermissions } from "@t3tools/contracts";
import type {
PullRequestAction,
PullRequestCapabilities,
PullRequestMergeMethod,
PullRequestViewerPermissions,
} from "@t3tools/contracts";
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
import * as ForgejoCli from "./ForgejoCli.ts";
import { parseDiffFileRevisions } from "@t3tools/source-control-core/server/diffFileRevisions";
Expand All @@ -24,7 +29,9 @@ import {
ForgejoStatus,
ForgejoLabel,
ForgejoReaction,
ForgejoTimelineEvent,
FORGEJO_REACTIONS,
forgejoAutoMergeScheduled,
forgejoChangeRequest,
forgejoActor,
forgejoComment,
Expand Down Expand Up @@ -61,6 +68,15 @@ const CAPABILITIES: PullRequestCapabilities = {
reviewers: { request: true, listCandidates: true, searchCandidates: false },
edit: { changeRequest: true, comment: true },
};
/** Merging, and scheduling or cancelling a merge, need write access; the author's own edits do not. */
const WRITE_ACTIONS: ReadonlySet<PullRequestAction> = new Set([
"merge",
"update-branch",
"enable-auto-merge",
"disable-auto-merge",
]);
/** Timeline rows read before giving up on finding the latest auto-merge event. */
const TIMELINE_LIMIT = 500;
const USER_SEARCH_LIMIT = 50;
const ForgejoUserSearch = Schema.Struct({
data: Schema.optional(Schema.NullOr(Schema.Array(ForgejoUser))),
Expand Down Expand Up @@ -222,9 +238,7 @@ export const make = Effect.gen(function* () {
const active = !repo.archived;
return {
actions: active
? CAPABILITIES.actions.filter((action) =>
action === "merge" || action === "update-branch" ? canWrite : canEdit,
)
? CAPABILITIES.actions.filter((action) => (WRITE_ACTIONS.has(action) ? canWrite : canEdit))
: [],
comment: active && (!pr.is_locked || canWrite),
resolve: false,
Expand Down Expand Up @@ -286,6 +300,59 @@ export const make = Effect.gen(function* () {
);
return markRequiredForgejoChecks(forgejoChecks(statuses.items, pr.html_url), policy);
});
/** Undefined when the timeline is too long to reach its end, or the server has none to read. */
const readAutoMerge = Effect.fn("ForgejoPullRequestProvider.readAutoMerge")(
function* (input: ProviderRepositoryRef & { readonly number: number }) {
const { items, truncated } = yield* page(
{ ...input, path: `${issuePath(input)}/timeline` },
ForgejoTimelineEvent,
TIMELINE_LIMIT,
);
return truncated ? undefined : forgejoAutoMergeScheduled(items);
},
Effect.catchTags({
PullRequestProviderError: (error) =>
Effect.logWarning("could not read Forgejo auto-merge state", { error }).pipe(
Effect.as(undefined),
),
}),
);
/** Forgejo's merge endpoint both merges and, with `merge_when_checks_succeed`, schedules one. */
const merge = Effect.fn("ForgejoPullRequestProvider.merge")(function* (
input: ProviderRepositoryRef & {
readonly number: number;
readonly mergeMethod?: PullRequestMergeMethod | undefined;
readonly expectedHeadSha?: string | undefined;
},
whenChecksSucceed: boolean,
) {
const deleteBranch = (yield* getRepo(input)).default_delete_branch_after_merge ?? false;
yield* write({
...input,
path: `${pullPath(input)}/merge`,
method: "POST",
body: {
Do:
input.mergeMethod === "fast-forward"
? "fast-forward-only"
: (input.mergeMethod ?? "merge"),
delete_branch_after_merge: deleteBranch,
...(input.expectedHeadSha === undefined ? {} : { head_commit_id: input.expectedHeadSha }),
...(whenChecksSucceed ? { merge_when_checks_succeed: true } : {}),
},
}).pipe(
Effect.catchTags({
// Forgejo merges before deleting the branch, so a refused deletion still merged.
PullRequestProviderError: (error) =>
deleteBranch
? getPull(input).pipe(
Effect.mapError(() => error),
Effect.flatMap((pr) => (pr.merged ? Effect.void : Effect.fail(error))),
)
: Effect.fail(error),
}),
);
});
const readLabels = Effect.fn("ForgejoPullRequestProvider.readLabels")(function* (
input: ProviderRepositoryRef,
) {
Expand Down Expand Up @@ -392,9 +459,14 @@ export const make = Effect.gen(function* () {
[getPull(input), getRepo(input), getViewer(input)],
{ concurrency: 3 },
);
const checks = yield* readChecks(input, pr);
const summary = forgejoChangeRequest(pr);
const [checks, autoMergeEnabled] = yield* Effect.all(
[readChecks(input, pr), summary.state === "open" ? readAutoMerge(input) : Effect.undefined],
{ concurrency: 2 },
);
return {
...forgejoChangeRequest(pr),
...summary,
...(autoMergeEnabled === undefined ? {} : { autoMergeEnabled }),
Comment thread
pat-s marked this conversation as resolved.
Resolved
headSha: pr.head.sha,
mergeCommitSha: pr.merge_commit_sha || null,
mergedBy: forgejoActor(pr.merged_by),
Expand Down Expand Up @@ -568,35 +640,11 @@ export const make = Effect.gen(function* () {
runAction: (input) => {
switch (input.action) {
case "merge":
return Effect.gen(function* () {
const deleteBranch = (yield* getRepo(input)).default_delete_branch_after_merge ?? false;
yield* write({
...input,
path: `${pullPath(input)}/merge`,
method: "POST",
body: {
Do:
input.mergeMethod === "fast-forward"
? "fast-forward-only"
: (input.mergeMethod ?? "merge"),
delete_branch_after_merge: deleteBranch,
...(input.expectedHeadSha === undefined
? {}
: { head_commit_id: input.expectedHeadSha }),
},
}).pipe(
Effect.catchTags({
// Forgejo merges before deleting the branch, so a refused deletion still merged.
PullRequestProviderError: (error) =>
deleteBranch
? getPull(input).pipe(
Effect.mapError(() => error),
Effect.flatMap((pr) => (pr.merged ? Effect.void : Effect.fail(error))),
)
: Effect.fail(error),
}),
);
});
return merge(input, false);
case "enable-auto-merge":
return merge(input, true);
case "disable-auto-merge":
return write({ ...input, path: `${pullPath(input)}/merge`, method: "DELETE" });
case "close":
case "reopen":
return request({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,8 @@ const requiredChecksLayer = (
return respond({ full_name: "acme/web", permissions: { push: true, admin: false } });
case "user":
return respond({ login: "maria" });
case "repos/acme/web/issues/7/timeline":
return respond([]);
default:
return Effect.die(`Unexpected Forgejo request: ${input.path}`);
}
Expand Down Expand Up @@ -742,6 +744,9 @@ it.effect.each([
case "repos/maria/project/branches/main":
response = { name: "main", protected: false };
break;
case "repos/maria/project/issues/42/timeline":
response = [];
break;
default:
return Effect.die(`Unexpected Forgejo request: ${input.path}`);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,22 @@ export const ForgejoPullRequest = Schema.Struct({
labels: Schema.NullOr(Schema.Array(ForgejoLabel)),
requested_reviewers: Schema.optional(Schema.NullOr(Schema.Array(ForgejoUser))),
});
export const ForgejoTimelineEvent = Schema.Struct({ type: Schema.String });

/**
* Forgejo's pull request reply never says whether auto-merge is scheduled; only the timeline
* records each schedule and cancellation, so the latest of the two decides.
*/
export function forgejoAutoMergeScheduled(
events: ReadonlyArray<typeof ForgejoTimelineEvent.Type>,
): boolean {
for (let index = events.length - 1; index >= 0; index--) {
const type = events[index]?.type;
if (type === "pull_scheduled_merge") return true;
if (type === "pull_cancel_scheduled_merge") return false;
}
return false;
}
export const ForgejoComment = Schema.Struct({
id: Schema.Int,
body: Schema.String,
Expand Down
9 changes: 8 additions & 1 deletion packages/source-control-forgejo/src/shared/definition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,14 @@ export const definition = defineSourceControl({
// Elsewhere the same path is a GitLab project nested under groups named `src` and `branch`.
return repositoryUrl === null || known ? repositoryUrl : url.href;
},
changeRequestActions: new Set(["merge", "close", "reopen", "update-branch"] as const),
changeRequestActions: new Set([
"merge",
"close",
"reopen",
"update-branch",
"enable-auto-merge",
"disable-auto-merge",
] as const),
// `fj` does not check out by number, so the command is one any clone can run.
checkoutCommand: ({ number, repositoryUrl }) =>
repositoryUrl
Expand Down
Loading