1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
|
import { and, desc, eq } from "drizzle-orm";
import { db } from "../db";
import {
environments,
deploymentApprovals,
repositories,
} from "../db/schema";
import type { Environment, DeploymentApproval } from "../db/schema";
function normaliseRef(ref: string): string {
if (ref.startsWith("refs/heads/")) return ref.slice("refs/heads/".length);
if (ref.startsWith("refs/tags/")) return ref.slice("refs/tags/".length);
return ref;
}
export function matchGlob(value: string, pattern: string): boolean {
const v = normaliseRef(value);
const p = normaliseRef(pattern);
if (v === p) return true;
const re = p
.replace(/[.+^${}()|[\]\\]/g, "\\$&")
.replace(/\*\*/g, "::DOUBLESTAR::")
.replace(/\*/g, "[^/]*")
.replace(/::DOUBLESTAR::/g, ".*");
return new RegExp(`^${re}$`).test(v);
}
function matchesAny(value: string, patterns: string[]): boolean {
if (patterns.length === 0) return true;
return patterns.some((p) => matchGlob(value, p));
}
export async function listEnvironments(
repositoryId: string
): Promise<Environment[]> {
try {
return await db
.select()
.from(environments)
.where(eq(environments.repositoryId, repositoryId))
.orderBy(desc(environments.createdAt));
} catch (err) {
console.error("[environments] list failed:", err);
return [];
}
}
export async function getEnvironmentById(
repositoryId: string,
id: string
): Promise<Environment | null> {
try {
const [row] = await db
.select()
.from(environments)
.where(
and(eq(environments.id, id), eq(environments.repositoryId, repositoryId))
)
.limit(1);
return row || null;
} catch (err) {
console.error("[environments] getById failed:", err);
return null;
}
}
export async function getEnvironmentByName(
repositoryId: string,
name: string
): Promise<Environment | null> {
try {
const [row] = await db
.select()
.from(environments)
.where(
and(
eq(environments.repositoryId, repositoryId),
eq(environments.name, name)
)
)
.limit(1);
return row || null;
} catch (err) {
console.error("[environments] getByName failed:", err);
return null;
}
}
export async function getOrCreateEnvironment(
repositoryId: string,
name: string
): Promise<Environment> {
const existing = await getEnvironmentByName(repositoryId, name);
if (existing) return existing;
try {
const [inserted] = await db
.insert(environments)
.values({ repositoryId, name })
.returning();
if (inserted) return inserted;
} catch (err) {
console.error("[environments] create failed:", err);
}
const reread = await getEnvironmentByName(repositoryId, name);
if (reread) return reread;
return {
id: "",
repositoryId,
name,
requireApproval: false,
reviewers: "[]",
waitTimerMinutes: 0,
allowedBranches: "[]",
createdAt: new Date(),
updatedAt: new Date(),
} as Environment;
}
function parseJsonArray(raw: string | null | undefined): string[] {
if (!raw) return [];
try {
const v = JSON.parse(raw);
return Array.isArray(v) ? v.map(String) : [];
} catch {
return [];
}
}
export function reviewerIdsOf(env: Environment): string[] {
return parseJsonArray(env.reviewers);
}
export function allowedBranchesOf(env: Environment): string[] {
return parseJsonArray(env.allowedBranches);
}
export async function isReviewer(
env: Environment,
userId: string
): Promise<boolean> {
const reviewers = reviewerIdsOf(env);
if (reviewers.includes(userId)) return true;
if (reviewers.length === 0) {
try {
const [row] = await db
.select({ ownerId: repositories.ownerId })
.from(repositories)
.where(eq(repositories.id, env.repositoryId))
.limit(1);
return row?.ownerId === userId;
} catch (err) {
console.error("[environments] isReviewer owner lookup failed:", err);
return false;
}
}
return false;
}
export async function listApprovals(
deploymentId: string
): Promise<DeploymentApproval[]> {
try {
return await db
.select()
.from(deploymentApprovals)
.where(eq(deploymentApprovals.deploymentId, deploymentId))
.orderBy(desc(deploymentApprovals.createdAt));
} catch (err) {
console.error("[environments] listApprovals failed:", err);
return [];
}
}
export function reduceApprovalState(decided: DeploymentApproval[]): {
approved: boolean;
rejected: boolean;
decided: DeploymentApproval[];
} {
const rejected = decided.some((d) => d.decision === "rejected");
const approved = !rejected && decided.some((d) => d.decision === "approved");
return { approved, rejected, decided };
}
export async function computeApprovalState(
deploymentId: string,
_env: Environment
): Promise<{
approved: boolean;
rejected: boolean;
decided: DeploymentApproval[];
}> {
const decided = await listApprovals(deploymentId);
return reduceApprovalState(decided);
}
export async function recordApproval(opts: {
deploymentId: string;
userId: string;
decision: "approved" | "rejected";
comment?: string;
}): Promise<DeploymentApproval | null> {
try {
const [row] = await db
.insert(deploymentApprovals)
.values({
deploymentId: opts.deploymentId,
userId: opts.userId,
decision: opts.decision,
comment: opts.comment ?? null,
})
.returning();
return row || null;
} catch (err) {
console.error("[environments] recordApproval failed:", err);
return null;
}
}
export async function requiresApprovalFor(
repositoryId: string,
envName: string,
ref: string
): Promise<{ required: boolean; env: Environment | null }> {
const env = await getEnvironmentByName(repositoryId, envName);
if (!env) return { required: false, env: null };
const allowed = allowedBranchesOf(env);
if (allowed.length > 0 && !matchesAny(ref, allowed)) {
return { required: true, env };
}
if (env.requireApproval) return { required: true, env };
return { required: false, env };
}
|