-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathBranchesPresenter.server.ts
More file actions
277 lines (248 loc) · 7.61 KB
/
BranchesPresenter.server.ts
File metadata and controls
277 lines (248 loc) · 7.61 KB
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
import { GitMeta } from "@trigger.dev/core/v3";
import { type z } from "zod";
import { type Prisma, type PrismaClient, prisma } from "~/db.server";
import { type Project } from "~/models/project.server";
import { type User } from "~/models/user.server";
import { type BranchesOptions } from "~/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.branches/route";
import { getCurrentPlan, getPlans } from "~/services/platform.v3.server";
import { checkBranchLimit } from "~/services/upsertBranch.server";
type Result = Awaited<ReturnType<BranchesPresenter["call"]>>;
export type Branch = Result["branches"][number];
const BRANCHES_PER_PAGE = 25;
type Options = z.infer<typeof BranchesOptions>;
export type GitMetaLinks = {
/** The cleaned repository URL without any username/password */
repositoryUrl: string;
/** The branch name */
branchName: string;
/** Link to the specific branch */
branchUrl: string;
/** Link to the specific commit */
commitUrl: string;
/** Link to the pull request (if available) */
pullRequestUrl?: string;
/** The pull request number (if available) */
pullRequestNumber?: number;
/** The pull request title (if available) */
pullRequestTitle?: string;
/** Link to compare this branch with main */
compareUrl: string;
/** Shortened commit SHA (first 7 characters) */
shortSha: string;
/** Whether the branch has uncommitted changes */
isDirty: boolean;
/** The commit message */
commitMessage: string;
/** The commit author */
commitAuthor: string;
/** The git provider, e.g., `github` */
provider?: string;
source?: "trigger_github_app" | "github_actions" | "local";
ghUsername?: string;
ghUserAvatarUrl?: string;
};
export class BranchesPresenter {
#prismaClient: PrismaClient;
constructor(prismaClient: PrismaClient = prisma) {
this.#prismaClient = prismaClient;
}
public async call({
userId,
projectSlug,
showArchived = false,
search,
page = 1,
}: {
userId: User["id"];
projectSlug: Project["slug"];
} & Options) {
const project = await this.#prismaClient.project.findFirst({
select: {
id: true,
organizationId: true,
},
where: {
slug: projectSlug,
organization: {
members: {
some: {
userId,
},
},
},
},
});
if (!project) {
throw new Error("Project not found");
}
const branchableEnvironment = await this.#prismaClient.runtimeEnvironment.findFirst({
select: {
id: true,
},
where: {
projectId: project.id,
isBranchableEnvironment: true,
},
});
const hasFilters = !!showArchived || (search !== undefined && search !== "");
if (!branchableEnvironment) {
return {
branchableEnvironment: null,
currentPage: page,
totalPages: 0,
hasBranches: false,
branches: [],
hasFilters: false,
limits: {
used: 0,
limit: 0,
isAtLimit: true,
},
canPurchaseBranches: false,
extraBranches: 0,
branchPricing: null,
maxBranchQuota: 0,
planBranchLimit: 0,
};
}
const visibleCount = await this.#prismaClient.runtimeEnvironment.count({
where: {
projectId: project.id,
branchName: search
? {
contains: search,
mode: "insensitive",
}
: {
not: null,
},
...(showArchived ? {} : { archivedAt: null }),
},
});
// Limits
const limits = await checkBranchLimit(this.#prismaClient, project.organizationId, project.id);
const [currentPlan, plans] = await Promise.all([
getCurrentPlan(project.organizationId),
getPlans(),
]);
const canPurchaseBranches =
currentPlan?.v3Subscription?.plan?.limits.branches.canExceed === true;
const extraBranches = currentPlan?.v3Subscription?.addOns?.branches?.purchased ?? 0;
const maxBranchQuota = currentPlan?.v3Subscription?.addOns?.branches?.quota ?? 0;
const planBranchLimit = currentPlan?.v3Subscription?.plan?.limits.branches.number ?? 0;
const branchPricing = plans?.addOnPricing.branches ?? null;
const branches = await this.#prismaClient.runtimeEnvironment.findMany({
select: {
id: true,
slug: true,
branchName: true,
type: true,
archivedAt: true,
createdAt: true,
git: true,
},
where: {
projectId: project.id,
branchName: search
? {
contains: search,
mode: "insensitive",
}
: {
not: null,
},
...(showArchived ? {} : { archivedAt: null }),
},
orderBy: {
branchName: "asc",
},
skip: (page - 1) * BRANCHES_PER_PAGE,
take: BRANCHES_PER_PAGE,
});
const totalBranches = await this.#prismaClient.runtimeEnvironment.count({
where: {
projectId: project.id,
branchName: {
not: null,
},
},
});
return {
branchableEnvironment,
currentPage: page,
totalPages: Math.ceil(visibleCount / BRANCHES_PER_PAGE),
hasBranches: totalBranches > 0,
branches: branches.flatMap((branch) => {
if (branch.branchName === null) {
return [];
}
const git = processGitMetadata(branch.git);
return [
{
...branch,
branchName: branch.branchName,
git,
} as const,
];
}),
hasFilters,
limits,
canPurchaseBranches,
extraBranches,
branchPricing,
maxBranchQuota,
planBranchLimit,
};
}
}
export function processGitMetadata(data: Prisma.JsonValue): GitMetaLinks | null {
if (!data) return null;
const parsed = GitMeta.safeParse(data);
if (!parsed.success) {
return null;
}
if (!parsed.data.remoteUrl) {
return null;
}
// Clean the remote URL by removing any username/password and ensuring it's a proper GitHub URL
const cleanRemoteUrl = (() => {
try {
const url = new URL(parsed.data.remoteUrl);
// Remove any username/password from the URL
url.username = "";
url.password = "";
// Ensure we're using https
url.protocol = "https:";
// Remove any trailing .git
return url.toString().replace(/\.git$/, "");
} catch (e) {
// If URL parsing fails, try to clean it manually
return parsed.data.remoteUrl
.replace(/^git@github\.com:/, "https://github.com/")
.replace(/^https?:\/\/[^@]+@/, "https://")
.replace(/\.git$/, "");
}
})();
if (!parsed.data.commitRef || !parsed.data.commitSha) return null;
const shortSha = parsed.data.commitSha.slice(0, 7);
return {
repositoryUrl: cleanRemoteUrl,
branchName: parsed.data.commitRef,
branchUrl: `${cleanRemoteUrl}/tree/${parsed.data.commitRef}`,
commitUrl: `${cleanRemoteUrl}/commit/${parsed.data.commitSha}`,
pullRequestUrl: parsed.data.pullRequestNumber
? `${cleanRemoteUrl}/pull/${parsed.data.pullRequestNumber}`
: undefined,
pullRequestNumber: parsed.data.pullRequestNumber,
pullRequestTitle: parsed.data.pullRequestTitle,
compareUrl: `${cleanRemoteUrl}/compare/main...${parsed.data.commitRef}`,
shortSha,
isDirty: parsed.data.dirty ?? false,
commitMessage: parsed.data.commitMessage ?? "",
commitAuthor: parsed.data.commitAuthorName ?? "",
provider: parsed.data.provider,
source: parsed.data.source,
ghUsername: parsed.data.ghUsername,
ghUserAvatarUrl: parsed.data.ghUserAvatarUrl,
};
}