@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 437 lines 15.3 KB
Raw
1 import * as ssm from "@distilled.cloud/gcp/securesourcemanager_v1";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { tagRecord } from "alchemy/Tags";
7 import * as Effect from "effect/Effect";
8 import { GcpEnvironment } from "../Environment.ts";
9 import { createInternalLabels, diffLabels, hasAlchemyLabels } from "../Labels.ts";
10 import type { Providers } from "../Providers.ts";
11 import {
12 catchMissing,
13 collectPages,
14 desiredAnnotations,
15 expandName,
16 fieldMask,
17 fingerprint,
18 forEachRepository,
19 hasAlchemyLabelMap,
20 normalizeLocation,
21 PAGE_SIZE,
22 parseName,
23 replaceOnIdentity,
24 ResourceNotResolved,
25 retryConflict,
26 rfc1035,
27 sameText,
28 toPhysicalId,
29 userLabels,
30 waitForOperation,
31 waitUntilExists,
32 waitUntilGone,
33 } from "./internal.ts";
34
35 export type BranchRuleCheck = {
36 /** Required status-check context (GitHub-style check name). */
37 context?: string;
38 };
39
40 export type RepositoriesBranchRuleProps = {
41 /**
42 * Parent repository. Full name
43 * `projects/{project}/locations/{location}/repositories/{repository}`
44 * or the repository id (combined with `location`). Immutable —
45 * changing it replaces the rule.
46 */
47 repository: string;
48 /**
49 * Region used when `repository` is a bare id.
50 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
51 */
52 location?: string;
53 /**
54 * Branch rule id (the `{branchRule}` segment). If omitted, a unique
55 * RFC1035 name is generated. Immutable — changing it replaces the rule.
56 */
57 branchRuleId?: string;
58 /**
59 * Regex of branches this rule matches. `.*` matches every branch.
60 * @default ".*"
61 */
62 includePattern?: string;
63 /**
64 * When true, the rule is disabled.
65 * @default false
66 */
67 disabled?: boolean;
68 /**
69 * When true, matching branches require a pull request.
70 * @default false
71 */
72 requirePullRequest?: boolean;
73 /**
74 * Minimum number of approvals required before merge.
75 */
76 minimumApprovalsCount?: number;
77 /**
78 * Minimum number of reviews required before merge.
79 */
80 minimumReviewsCount?: number;
81 /**
82 * When true, reviews may be stale relative to the latest commit.
83 * @default false
84 */
85 allowStaleReviews?: boolean;
86 /**
87 * When true, require linear history before merge.
88 * @default false
89 */
90 requireLinearHistory?: boolean;
91 /**
92 * When true, require all comments resolved before merge.
93 * @default false
94 */
95 requireCommentsResolved?: boolean;
96 /**
97 * When true, require a code-owner approval before merge.
98 * @default false
99 */
100 requireCodeOwnerApproval?: boolean;
101 /**
102 * Required status checks before merging.
103 */
104 requiredStatusChecks?: BranchRuleCheck[];
105 /**
106 * User annotations. Alchemy ownership keys (`alchemy-stack`,
107 * `alchemy-stage`, `alchemy-id`) are merged in automatically. Branch
108 * rules have no labels field.
109 */
110 annotations?: Record<string, string>;
111 };
112
113 export type RepositoriesBranchRule = Resource<
114 "GCP.SecureSourceManager.RepositoriesBranchRule",
115 RepositoriesBranchRuleProps,
116 {
117 /** Full resource name. */
118 name: string;
119 /** Branch rule id (last path segment). */
120 branchRuleId: string;
121 /** Parent repository resource name. */
122 repository: string;
123 /** Project id. */
124 project: string;
125 /** Location id. */
126 location: string;
127 /** Branch-name regex this rule matches. */
128 includePattern: string | undefined;
129 /** Whether the rule is disabled. */
130 disabled: boolean;
131 /** Whether a pull request is required. */
132 requirePullRequest: boolean;
133 /** Minimum approvals required. */
134 minimumApprovalsCount: number | undefined;
135 /** Minimum reviews required. */
136 minimumReviewsCount: number | undefined;
137 /** Whether stale reviews are allowed. */
138 allowStaleReviews: boolean;
139 /** Whether linear history is required. */
140 requireLinearHistory: boolean;
141 /** Whether comments must be resolved. */
142 requireCommentsResolved: boolean;
143 /** Whether code-owner approval is required. */
144 requireCodeOwnerApproval: boolean;
145 /** Required status checks. */
146 requiredStatusChecks: BranchRuleCheck[];
147 /** User annotations (Alchemy ownership keys stripped). */
148 annotations: Record<string, string>;
149 /** Server-generated resource uid. */
150 uid: string | undefined;
151 /** RFC3339 creation timestamp. */
152 createTime: string | undefined;
153 /** RFC3339 last-update timestamp. */
154 updateTime: string | undefined;
155 /** Server etag. */
156 etag: string | undefined;
157 },
158 never,
159 Providers
160 >;
161
162 /**
163 * A Secure Source Manager branch protection rule.
164 *
165 * Changing `branchRuleId`, `repository`, or `location` replaces the rule.
166 * Pattern, flags, checks, and annotations update in place. Ownership for
167 * `list` / nuke is stamped into `annotations`.
168 *
169 * ### Creating a Branch Rule
170 * **Example:** Protect the default branch
171 * ```typescript
172 * const rule = yield* GCP.SecureSourceManager.RepositoriesBranchRule("Main", {
173 * repository: repo.name,
174 * includePattern: "main",
175 * requirePullRequest: true,
176 * minimumApprovalsCount: 1,
177 * });
178 * ```
179 *
180 * **Example:** Named rule with annotations
181 * ```typescript
182 * const rule = yield* GCP.SecureSourceManager.RepositoriesBranchRule("Main", {
183 * repository: repo.name,
184 * branchRuleId: "protect-main",
185 * includePattern: "main",
186 * requireCommentsResolved: true,
187 * annotations: { env: "prod" },
188 * });
189 * ```
190 *
191 * ### Updating a Branch Rule
192 * Re-declare the same logical id with changed props; the engine keeps the
193 * physical resource and updates it in place.
194 *
195 * **Example:** Raise the approval floor
196 * ```typescript
197 * const rule = yield* GCP.SecureSourceManager.RepositoriesBranchRule("Main", {
198 * repository: repo.name,
199 * includePattern: "main",
200 * requirePullRequest: true,
201 * minimumApprovalsCount: 2,
202 * annotations: { env: "prod", team: "platform" },
203 * });
204 * ```
205 *
206 * @resource
207 * @category SecureSourceManager
208 */
209 export const RepositoriesBranchRule = Resource<RepositoriesBranchRule>(
210 "GCP.SecureSourceManager.RepositoriesBranchRule",
211 );
212
213 const resourceName = (repository: string, branchRuleId: string) =>
214 `${repository}/branchRules/${branchRuleId}`;
215
216 const toChecks = (
217 checks: readonly ssm.Check[] | readonly BranchRuleCheck[] | undefined,
218 ): BranchRuleCheck[] =>
219 (checks ?? [])
220 .map((check) => ({ context: check.context }))
221 .sort((left, right) => (left.context ?? "").localeCompare(right.context ?? ""));
222
223 const toAttrs = (item: ssm.BranchRule, project: string, region: string) => {
224 const name = item.name ?? "";
225 const parsed = parseName(name, "branchRules", region);
226 return {
227 name,
228 branchRuleId: parsed.id,
229 repository: parsed.parent,
230 project: parsed.project || project,
231 location: parsed.location,
232 includePattern: item.includePattern,
233 disabled: item.disabled === true,
234 requirePullRequest: item.requirePullRequest === true,
235 minimumApprovalsCount: item.minimumApprovalsCount,
236 minimumReviewsCount: item.minimumReviewsCount,
237 allowStaleReviews: item.allowStaleReviews === true,
238 requireLinearHistory: item.requireLinearHistory === true,
239 requireCommentsResolved: item.requireCommentsResolved === true,
240 requireCodeOwnerApproval: item.requireCodeOwnerApproval === true,
241 requiredStatusChecks: toChecks(item.requiredStatusChecks),
242 annotations: userLabels(item.annotations),
243 uid: item.uid,
244 createTime: item.createTime,
245 updateTime: item.updateTime,
246 etag: item.etag,
247 };
248 };
249
250 const getByName = (name: string) =>
251 name.length === 0
252 ? Effect.undefined
253 : catchMissing(ssm.getProjectsLocationsRepositoriesBranchRules({ name }));
254
255 const listOnRepository = (repository: string) =>
256 collectPages(
257 ssm.listProjectsLocationsRepositoriesBranchRules.pages({
258 parent: repository,
259 pageSize: PAGE_SIZE,
260 }),
261 (page) => page.branchRules,
262 );
263
264 const listOwned = (project: string, region: string) =>
265 forEachRepository(project, region, (repository) =>
266 listOnRepository(repository).pipe(
267 Effect.map((items) => items.filter((item) => hasAlchemyLabelMap(item.annotations))),
268 ),
269 );
270
271 export const RepositoriesBranchRuleProvider = () =>
272 Provider.succeed(RepositoriesBranchRule, {
273 stables: ["name", "branchRuleId", "repository", "project", "location", "uid", "createTime"],
274
275 diff: Effect.fn(function* ({ news, olds, output }) {
276 if (!isResolved(news)) return undefined;
277 const env = yield* GcpEnvironment.current;
278 const location = normalizeLocation(
279 news.location ?? olds?.location ?? output?.location,
280 env.region,
281 );
282 return replaceOnIdentity({
283 previousId: olds?.branchRuleId ?? output?.branchRuleId,
284 nextId: news.branchRuleId
285 ? rfc1035(news.branchRuleId, "branchrule")
286 : (olds?.branchRuleId ?? output?.branchRuleId),
287 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
288 nextLocation: location,
289 previousParent: olds?.repository ?? output?.repository,
290 nextParent: expandName(news.repository, env.project, location, "repositories"),
291 });
292 }),
293
294 read: Effect.fn(function* ({ id, olds, output }) {
295 const env = yield* GcpEnvironment.current;
296 const branchRuleId = yield* toPhysicalId(
297 id,
298 olds?.branchRuleId,
299 output?.branchRuleId,
300 "branchrule",
301 );
302 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
303 const repository = expandName(
304 olds?.repository ?? output?.repository ?? "",
305 env.project,
306 location,
307 "repositories",
308 );
309 const name =
310 output?.name ?? (repository.length > 0 ? resourceName(repository, branchRuleId) : "");
311 const existing = yield* getByName(name);
312 if (existing === undefined) return undefined;
313 const attrs = toAttrs(existing, env.project, env.region);
314 return (yield* hasAlchemyLabels(id, tagRecord(existing.annotations)))
315 ? attrs
316 : Unowned(attrs);
317 }),
318
319 list: () =>
320 Effect.gen(function* () {
321 const env = yield* GcpEnvironment.current;
322 const items = yield* listOwned(env.project, env.region);
323 return items.map((item: ssm.BranchRule) => toAttrs(item, env.project, env.region));
324 }),
325
326 reconcile: Effect.fn(function* ({ id, news, output }) {
327 const env = yield* GcpEnvironment.current;
328 const branchRuleId = yield* toPhysicalId(
329 id,
330 news.branchRuleId,
331 output?.branchRuleId,
332 "branchrule",
333 );
334 const location = normalizeLocation(news.location ?? output?.location, env.region);
335 const repository = expandName(news.repository, env.project, location, "repositories");
336 const name = resourceName(repository, branchRuleId);
337 const ownership = yield* createInternalLabels(id);
338 const annotations = desiredAnnotations(news.annotations, ownership);
339 const includePattern = news.includePattern ?? ".*";
340 const requiredStatusChecks = toChecks(news.requiredStatusChecks);
341
342 let current = yield* getByName(output?.name ?? name);
343
344 if (current === undefined) {
345 const created = yield* ssm
346 .createProjectsLocationsRepositoriesBranchRules({
347 parent: repository,
348 branchRuleId,
349 body: {
350 includePattern,
351 disabled: news.disabled === true ? true : undefined,
352 requirePullRequest: news.requirePullRequest === true ? true : undefined,
353 minimumApprovalsCount: news.minimumApprovalsCount,
354 minimumReviewsCount: news.minimumReviewsCount,
355 allowStaleReviews: news.allowStaleReviews === true ? true : undefined,
356 requireLinearHistory: news.requireLinearHistory === true ? true : undefined,
357 requireCommentsResolved: news.requireCommentsResolved === true ? true : undefined,
358 requireCodeOwnerApproval: news.requireCodeOwnerApproval === true ? true : undefined,
359 requiredStatusChecks:
360 requiredStatusChecks.length > 0 ? requiredStatusChecks : undefined,
361 annotations,
362 },
363 })
364 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
365 if (created !== undefined) {
366 yield* waitForOperation(created);
367 }
368 current = yield* waitUntilExists(getByName(name), name);
369 }
370
371 if (current === undefined) {
372 return yield* new ResourceNotResolved({ resourceName: name });
373 }
374
375 const observed = tagRecord(current.annotations);
376 const { upsert, removed } = diffLabels(observed, annotations);
377 const mask = fieldMask([
378 (upsert.length > 0 || removed.length > 0) && "annotations",
379 !sameText(current.includePattern, includePattern) && "includePattern",
380 (current.disabled === true) !== (news.disabled === true) && "disabled",
381 (current.requirePullRequest === true) !== (news.requirePullRequest === true) &&
382 "requirePullRequest",
383 current.minimumApprovalsCount !== news.minimumApprovalsCount && "minimumApprovalsCount",
384 current.minimumReviewsCount !== news.minimumReviewsCount && "minimumReviewsCount",
385 (current.allowStaleReviews === true) !== (news.allowStaleReviews === true) &&
386 "allowStaleReviews",
387 (current.requireLinearHistory === true) !== (news.requireLinearHistory === true) &&
388 "requireLinearHistory",
389 (current.requireCommentsResolved === true) !== (news.requireCommentsResolved === true) &&
390 "requireCommentsResolved",
391 (current.requireCodeOwnerApproval === true) !== (news.requireCodeOwnerApproval === true) &&
392 "requireCodeOwnerApproval",
393 fingerprint(toChecks(current.requiredStatusChecks)) !== fingerprint(requiredStatusChecks) &&
394 "requiredStatusChecks",
395 ]);
396
397 if (mask.length > 0) {
398 const operation = yield* ssm.patchProjectsLocationsRepositoriesBranchRules({
399 name: current.name ?? name,
400 updateMask: mask,
401 body: {
402 etag: current.etag,
403 includePattern,
404 disabled: news.disabled === true,
405 requirePullRequest: news.requirePullRequest === true,
406 minimumApprovalsCount: news.minimumApprovalsCount,
407 minimumReviewsCount: news.minimumReviewsCount,
408 allowStaleReviews: news.allowStaleReviews === true,
409 requireLinearHistory: news.requireLinearHistory === true,
410 requireCommentsResolved: news.requireCommentsResolved === true,
411 requireCodeOwnerApproval: news.requireCodeOwnerApproval === true,
412 requiredStatusChecks,
413 annotations,
414 },
415 });
416 yield* waitForOperation(operation);
417 current = yield* waitUntilExists(getByName(current.name ?? name), current.name ?? name);
418 }
419
420 return toAttrs(current, env.project, env.region);
421 }),
422
423 delete: Effect.fn(function* ({ output }) {
424 const operation = yield* retryConflict(
425 ssm
426 .deleteProjectsLocationsRepositoriesBranchRules({
427 name: output.name,
428 allowMissing: true,
429 })
430 .pipe(Effect.catchTag("NotFound", () => Effect.undefined)),
431 );
432 if (operation !== undefined) {
433 yield* waitForOperation(operation, { notFoundOk: true });
434 }
435 yield* waitUntilGone(getByName(output.name), output.name);
436 }),
437 });