import { assert, describe, it } from "@effect/vitest"; import { Effect, Layer, Option, Schema } from "effect"; import { GitHubError } from "../src/GitHubError.js"; import { Repo } from "../src/Repo.js"; import { PageOptions } from "../src/Rest.js"; import type { BranchRule } from "../src/Ruleset.js"; import { BranchRulesSummary, Ruleset } from "../src/Ruleset.js"; import type { Reply } from "./fixtures.js"; import { linkNext } from "./fixtures.js"; import { REPO, defectMessage, harness } from "./harness.js"; const ORIGIN = { ruleset_source_type: "Repository", ruleset_source: "acme/widget", ruleset_id: 7 }; /** The shape of GitHub's live answer for a protected default branch (recorded 2026-12-01, trimmed). */ const LIVE_RULES = [ { type: "required_status_checks", parameters: { strict_required_status_checks_policy: true, do_not_enforce_on_create: true, required_status_checks: [{ context: "Tests", integration_id: 15368 }, { context: "Lint" }], }, ...ORIGIN, }, { type: "deletion", ...ORIGIN }, { type: "required_linear_history", ...ORIGIN }, { type: "required_signatures", ...ORIGIN }, { type: "non_fast_forward", ...ORIGIN }, { type: "pull_request", parameters: { required_approving_review_count: 1, dismiss_stale_reviews_on_push: false, required_reviewers: [], require_code_owner_review: false, require_last_push_approval: false, required_review_thread_resolution: false, // Undocumented in GitHub's description; must be ignored, not fatal. require_extra_approval_for_unattributed_changes: true, allowed_merge_methods: ["squash", "rebase"], }, ...ORIGIN, }, { type: "required_status_checks", parameters: { strict_required_status_checks_policy: false, required_status_checks: [{ context: "Tests" }, { context: "CodeQL" }], }, ruleset_source_type: "Organization", ruleset_source: "acme", ruleset_id: 3, }, ]; const drive = (replies: ReadonlyArray, branch = "main", page?: PageOptions) => Effect.gen(function* () { const { script, base } = harness(replies); const value = yield* Effect.provide( Effect.flatMap(Ruleset, (rulesets) => rulesets.branchRules(branch, page !== undefined ? { page } : undefined)), Ruleset.layer.pipe(Layer.provideMerge(base)), ); return { value, script }; }); const driveFailure = (reply: Reply) => Effect.gen(function* () { const { base } = harness([reply]); return yield* Effect.flip( Effect.provide( Effect.flatMap(Ruleset, (rulesets) => rulesets.branchRules("main")), Ruleset.layer.pipe(Layer.provideMerge(base)), ), ); }); const tags = (rules: ReadonlyArray): ReadonlyArray => rules.map((rule) => rule._tag); describe("Ruleset.branchRules", () => { it.effect("reads the branch-rules route and decodes one class per rule type", () => Effect.gen(function* () { const { value, script } = yield* drive([{ status: 200, body: LIVE_RULES }], "release/1.x"); assert.strictEqual(script.calls[0]?.method, "GET"); assert.strictEqual(script.calls[0]?.path, "/repos/acme/widget/rules/branches/release/1.x"); assert.deepStrictEqual(tags(value), [ "RequiredStatusChecksRule", "DeletionRule", "RequiredLinearHistoryRule", "RequiredSignaturesRule", "NonFastForwardRule", "PullRequestRule", "RequiredStatusChecksRule", ]); const checks = value[0]; if (checks?._tag !== "RequiredStatusChecksRule") return assert.fail("expected a status-checks rule first"); assert.strictEqual(checks.strict, true); assert.strictEqual(checks.doNotEnforceOnCreate, true); assert.deepStrictEqual( checks.checks.map((check) => [check.context, check.integrationId]), [ ["Tests", 15368], ["Lint", undefined], ], ); assert.strictEqual(checks.origin.rulesetId, 7); assert.strictEqual(checks.origin.sourceType, "Repository"); const pull = value[5]; if (pull?._tag !== "PullRequestRule") return assert.fail("expected a pull-request rule"); assert.strictEqual(pull.requiredApprovingReviewCount, 1); assert.deepStrictEqual(pull.allowedMergeMethods, ["squash", "rebase"]); assert.strictEqual(value[6]?.origin.sourceType, "Organization"); }), ); it.effect("decodes merge_queue, update, creation and required_deployments", () => Effect.gen(function* () { const { value } = yield* drive([ { status: 200, body: [ { type: "merge_queue", parameters: { merge_method: "SQUASH", grouping_strategy: "ALLGREEN", check_response_timeout_minutes: 60, max_entries_to_build: 5, max_entries_to_merge: 5, min_entries_to_merge: 1, min_entries_to_merge_wait_minutes: 5, }, }, { type: "update", parameters: { update_allows_fetch_and_merge: true } }, { type: "creation" }, { type: "required_deployments", parameters: { required_deployment_environments: ["prod"] } }, ], }, ]); assert.deepStrictEqual(tags(value), ["MergeQueueRule", "UpdateRule", "CreationRule", "RequiredDeploymentsRule"]); const [queue, update, , deployments] = value; if (queue?._tag !== "MergeQueueRule") return assert.fail("expected a merge-queue rule"); // GitHub's capitals decode into the kit's lowercase MergeMethod. assert.strictEqual(queue.mergeMethod, "squash"); assert.strictEqual(queue.groupingStrategy, "ALLGREEN"); assert.strictEqual(queue.checkResponseTimeoutMinutes, 60); if (update?._tag !== "UpdateRule") return assert.fail("expected an update rule"); assert.strictEqual(update.updateAllowsFetchAndMerge, true); if (deployments?._tag !== "RequiredDeploymentsRule") return assert.fail("expected a deployments rule"); assert.deepStrictEqual(deployments.environments, ["prod"]); }), ); it.effect("keeps an unmodelled rule type, with its raw parameters, instead of failing", () => Effect.gen(function* () { const { value } = yield* drive([ { status: 200, body: [ { type: "file_path_restriction", parameters: { restricted_file_paths: ["secrets/**"] }, ...ORIGIN }, { type: "some_future_rule" }, ], }, ]); assert.deepStrictEqual(tags(value), ["OtherBranchRule", "OtherBranchRule"]); const [restriction, future] = value; if (restriction?._tag !== "OtherBranchRule" || future?._tag !== "OtherBranchRule") { return assert.fail("expected two kept rules"); } assert.strictEqual(restriction.type, "file_path_restriction"); assert.deepStrictEqual(restriction.parameters, { restricted_file_paths: ["secrets/**"] }); assert.strictEqual(restriction.origin.rulesetId, 7); assert.strictEqual(future.type, "some_future_rule"); assert.isFalse("parameters" in future); }), ); it.effect("reads GitHub's defaults when a parameterized rule arrives without parameters", () => Effect.gen(function* () { const { value } = yield* drive([{ status: 200, body: [{ type: "pull_request" }, { type: "update" }] }]); const [pull, update] = value; if (pull?._tag !== "PullRequestRule") return assert.fail("expected a pull-request rule"); assert.strictEqual(pull.requiredApprovingReviewCount, 0); assert.isFalse("allowedMergeMethods" in pull); if (update?._tag !== "UpdateRule") return assert.fail("expected an update rule"); assert.strictEqual(update.updateAllowsFetchAndMerge, false); }), ); it.effect("walks every page, and forwards the page options", () => Effect.gen(function* () { const { value, script } = yield* drive( [ { status: 200, body: [{ type: "deletion" }], headers: linkNext("https://api.github.com/repos/acme/widget/rules/branches/main?page=2"), }, { status: 200, body: [{ type: "required_signatures" }] }, ], "main", PageOptions.make({ perPage: 1 }), ); assert.deepStrictEqual(tags(value), ["DeletionRule", "RequiredSignaturesRule"]); assert.strictEqual(script.count(), 2); assert.strictEqual(script.queryOf(0).get("per_page"), "1"); }), ); it.effect("stops at maxPages", () => Effect.gen(function* () { const { value, script } = yield* drive( [ { status: 200, body: [{ type: "deletion" }], headers: linkNext("https://api.github.com/repos/acme/widget/rules/branches/main?page=2"), }, { status: 200, body: [{ type: "required_signatures" }] }, ], "main", PageOptions.first(1), ); assert.deepStrictEqual(tags(value), ["DeletionRule"]); assert.strictEqual(script.count(), 1); }), ); it.effect("fails kind notFound on a 404, so a caller can say the rules were not checked", () => Effect.gen(function* () { const error = yield* driveFailure({ status: 404, body: { message: "Not Found" } }); assert.strictEqual(error.kind, "notFound"); assert.strictEqual(error.status, 404); assert.isTrue(GitHubError.hasKind("notFound", "unauthorized")(error)); }), ); it.effect("fails kind unauthorized on a 403", () => Effect.gen(function* () { const error = yield* driveFailure({ status: 403, body: { message: "Resource not accessible by integration" } }); assert.strictEqual(error.kind, "unauthorized"); assert.strictEqual(error.status, 403); assert.isTrue(GitHubError.hasKind("notFound", "unauthorized")(error)); }), ); it.effect("fails kind transport on a 5xx, apart from the not-checked kinds", () => Effect.gen(function* () { const error = yield* driveFailure({ status: 502, body: { message: "Bad Gateway" } }); assert.strictEqual(error.kind, "transport"); assert.isFalse(GitHubError.hasKind("notFound", "unauthorized")(error)); }), ); it.effect("fails kind decode when a known rule's parameters break GitHub's description", () => Effect.gen(function* () { const error = yield* driveFailure({ status: 200, body: [{ type: "pull_request", parameters: { required_approving_review_count: "two" } }], }); assert.strictEqual(error.kind, "decode"); assert.strictEqual(error.operation, "Ruleset.branchRules"); }), ); it.effect("fails kind decode on a merge queue method outside GitHub's capitals", () => Effect.gen(function* () { const error = yield* driveFailure({ status: 200, body: [{ type: "merge_queue", parameters: { merge_method: "squash" } }], }); assert.strictEqual(error.kind, "decode"); }), ); it.effect("fails kind decode when an entry has no type", () => Effect.gen(function* () { const error = yield* driveFailure({ status: 200, body: [{ parameters: {} }] }); assert.strictEqual(error.kind, "decode"); }), ); it.effect("answers an empty array for a branch with no rules", () => Effect.gen(function* () { const { value } = yield* drive([{ status: 200, body: [] }]); assert.deepStrictEqual(value, []); }), ); }); describe("BranchRulesSummary.fromRules", () => { it.effect("summarizes the live shape", () => Effect.gen(function* () { const { value } = yield* drive([{ status: 200, body: LIVE_RULES }]); const summary = BranchRulesSummary.fromRules(value); assert.strictEqual(summary.mergeQueue, false); assert.strictEqual(summary.signedCommits, true); assert.deepStrictEqual(summary.pullRequest, Option.some({ approvals: 1 })); // De-duplicated across rulesets, in first-seen order. assert.deepStrictEqual(summary.requiredChecks, ["Tests", "Lint", "CodeQL"]); assert.strictEqual(summary.directPushBlocked, true); }), ); it.effect("takes the largest approval count across pull_request rules", () => Effect.gen(function* () { const { value } = yield* drive([ { status: 200, body: [ { type: "pull_request", parameters: { ...pullParameters, required_approving_review_count: 2 } }, { type: "pull_request", parameters: { ...pullParameters, required_approving_review_count: 1 } }, { type: "merge_queue" }, ], }, ]); const summary = BranchRulesSummary.fromRules(value); assert.deepStrictEqual(summary.pullRequest, Option.some({ approvals: 2 })); assert.strictEqual(summary.mergeQueue, true); }), ); it.effect("blocks direct pushes for each blocking rule type alone, and for no other", () => Effect.gen(function* () { const blocking = ["pull_request", "merge_queue", "required_status_checks", "required_deployments", "update"]; const nonBlocking = [ "non_fast_forward", "required_signatures", "required_linear_history", "creation", "deletion", "file_path_restriction", ]; for (const type of [...blocking, ...nonBlocking]) { const { value } = yield* drive([{ status: 200, body: [{ type }] }]); assert.strictEqual( BranchRulesSummary.fromRules(value).directPushBlocked, blocking.includes(type), `directPushBlocked for ${type}`, ); } }), ); it.effect("answers an all-clear summary for no rules", () => Effect.sync(() => { const summary = BranchRulesSummary.fromRules([]); assert.strictEqual(summary.mergeQueue, false); assert.strictEqual(summary.signedCommits, false); assert.isTrue(Option.isNone(summary.pullRequest)); assert.deepStrictEqual(summary.requiredChecks, []); assert.strictEqual(summary.directPushBlocked, false); }), ); }); describe("Ruleset.makeTest", () => { it.effect("dies naming branchRules when it is not stubbed", () => Effect.gen(function* () { const exit = yield* Effect.exit( Ruleset.makeTest() .branchRules("main") .pipe(Effect.provide(Repo.layer(REPO))), ); assert.include(defectMessage(exit) ?? "", "branchRules()"); }), ); }); const pullParameters = { required_approving_review_count: 0, dismiss_stale_reviews_on_push: false, require_code_owner_review: false, require_last_push_approval: false, required_review_thread_resolution: false, }; describe("BranchRulesSummary JSON caching", () => { const summary = BranchRulesSummary.make({ mergeQueue: true, signedCommits: true, pullRequest: Option.some({ approvals: 2 }), requiredChecks: ["Tests"], directPushBlocked: true, }); it.effect("round-trips through Schema.toCodecJson, Some and None alike", () => Effect.gen(function* () { const SummaryJson = Schema.fromJsonString(Schema.toCodecJson(BranchRulesSummary)); for (const value of [summary, BranchRulesSummary.fromRules([])]) { const text = yield* Schema.encodeEffect(SummaryJson)(value); assert.notInclude(text, '"_id"'); const back = yield* Schema.decodeEffect(SummaryJson)(text); assert.instanceOf(back, BranchRulesSummary); assert.deepStrictEqual(back, value); } }), ); it.effect("does not round-trip through a plain fromJsonString, as the TSDoc warns", () => Effect.gen(function* () { const Plain = Schema.fromJsonString(BranchRulesSummary); const text = yield* Schema.encodeEffect(Plain)(summary); const result = yield* Effect.result(Schema.decodeEffect(Plain)(text)); assert.strictEqual(result._tag, "Failure"); }), ); });