import { matchesAny } from "../config/branch-pattern.ts"; import type { Trust } from "./trust.ts"; export interface EnvironmentRules { readonly name: string; readonly allowedBranches: readonly string[]; readonly requiresApproval: boolean; readonly waitSeconds: number; } export type GateDecision = | { readonly kind: "open"; readonly waitSeconds: number } | { readonly kind: "needs_approval"; readonly waitSeconds: number; readonly reason: string } | { readonly kind: "closed"; readonly reason: string }; export interface GateContext { readonly branch: string | null; readonly trust: Trust; } /** Decides whether a job that names an environment may start, must wait for a person, or must not run. */ export function gateEnvironment(name: string, rules: EnvironmentRules | null, context: GateContext): GateDecision { if (!rules) return { kind: "closed", reason: `The environment "${name}" does not exist. Create it in the repository settings.` }; if (rules.allowedBranches.length && (context.branch === null || !matchesAny(rules.allowedBranches, context.branch))) { return { kind: "closed", reason: `The environment "${name}" does not accept runs from ${context.branch ?? "this ref"}.` }; } if (context.trust === "untrusted") return { kind: "needs_approval", waitSeconds: rules.waitSeconds, reason: "The run is untrusted, so a person must approve this deploy." }; if (rules.requiresApproval) return { kind: "needs_approval", waitSeconds: rules.waitSeconds, reason: `The environment "${name}" requires approval.` }; return { kind: "open", waitSeconds: rules.waitSeconds }; }