30 lines · 1.6 KBRaw
| 1 | import { matchesAny } from "../config/branch-pattern.ts"; |
| 2 | import type { Trust } from "./trust.ts"; |
| 3 | |
| 4 | export interface EnvironmentRules { |
| 5 | readonly name: string; |
| 6 | readonly allowedBranches: readonly string[]; |
| 7 | readonly requiresApproval: boolean; |
| 8 | readonly waitSeconds: number; |
| 9 | } |
| 10 | |
| 11 | export type GateDecision = |
| 12 | | { readonly kind: "open"; readonly waitSeconds: number } |
| 13 | | { readonly kind: "needs_approval"; readonly waitSeconds: number; readonly reason: string } |
| 14 | | { readonly kind: "closed"; readonly reason: string }; |
| 15 | |
| 16 | export interface GateContext { |
| 17 | readonly branch: string | null; |
| 18 | readonly trust: Trust; |
| 19 | } |
| 20 | |
| 21 | /** Decides whether a job that names an environment may start, must wait for a person, or must not run. */ |
| 22 | export function gateEnvironment(name: string, rules: EnvironmentRules | null, context: GateContext): GateDecision { |
| 23 | if (!rules) return { kind: "closed", reason: `The environment "${name}" does not exist. Create it in the repository settings.` }; |
| 24 | if (rules.allowedBranches.length && (context.branch === null || !matchesAny(rules.allowedBranches, context.branch))) { |
| 25 | return { kind: "closed", reason: `The environment "${name}" does not accept runs from ${context.branch ?? "this ref"}.` }; |
| 26 | } |
| 27 | if (context.trust === "untrusted") return { kind: "needs_approval", waitSeconds: rules.waitSeconds, reason: "The run is untrusted, so a person must approve this deploy." }; |
| 28 | if (rules.requiresApproval) return { kind: "needs_approval", waitSeconds: rules.waitSeconds, reason: `The environment "${name}" requires approval.` }; |
| 29 | return { kind: "open", waitSeconds: rules.waitSeconds }; |
| 30 | } |