Repository navigation
Expand file tree
/
Copy pathgitMeta.ts
More file actions
339 lines (293 loc) · 9.8 KB
/
Copy pathgitMeta.ts
File metadata and controls
339 lines (293 loc) · 9.8 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
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
import fs from "fs/promises";
import { join } from "path";
import ini from "ini";
import git from "git-last-commit";
import { x } from "tinyexec";
import type { GitMeta } from "@trigger.dev/core/v3";
export async function createGitMeta(directory: string): Promise<GitMeta | undefined> {
if (isGitHubApp()) {
return getGitHubAppMeta();
}
if (isGitHubActions()) {
return getGitHubActionsMeta();
}
// Fall back to git commands for local development
const remoteUrl = await getOriginUrl(join(directory, ".git/config"));
const [commitResult, dirtyResult] = await Promise.allSettled([
getLastCommit(directory),
isDirty(directory),
]);
if (commitResult.status === "rejected") {
return;
}
if (dirtyResult.status === "rejected") {
return;
}
const dirty = dirtyResult.value;
const commit = commitResult.value;
return {
source: "local",
remoteUrl: sanitizeGitRemoteUrl(remoteUrl ?? undefined),
commitAuthorName: commit.author.name,
commitMessage: commit.subject,
// Most CI providers other than GitHub Actions check out a detached HEAD
commitRef: commit.branch === "HEAD" ? (getCiBranch() ?? commit.branch) : commit.branch,
commitSha: commit.hash,
dirty,
};
}
// Branch variables for each CI provider, pull and merge request source branches first.
// Only the detected provider's variables are read, so a generic name like BRANCH_NAME set
// for another purpose isn't mistaken for the branch.
const CI_PROVIDER_BRANCH_VARS: Array<{
detect: (env: NodeJS.ProcessEnv) => boolean;
vars: string[];
}> = [
{
detect: (env) => env.GITLAB_CI === "true",
vars: ["CI_MERGE_REQUEST_SOURCE_BRANCH_NAME", "CI_COMMIT_BRANCH"],
},
{ detect: (env) => !!env.BITBUCKET_BUILD_NUMBER, vars: ["BITBUCKET_BRANCH"] },
{ detect: (env) => env.CIRCLECI === "true", vars: ["CIRCLE_BRANCH"] },
{ detect: (env) => env.BUILDKITE === "true", vars: ["BUILDKITE_BRANCH"] },
// TRAVIS_PULL_REQUEST_BRANCH is empty on push builds
{ detect: (env) => env.TRAVIS === "true", vars: ["TRAVIS_PULL_REQUEST_BRANCH", "TRAVIS_BRANCH"] },
{ detect: (env) => !!env.JENKINS_URL, vars: ["CHANGE_BRANCH", "BRANCH_NAME"] },
{
detect: (env) => env.TF_BUILD === "True",
vars: ["SYSTEM_PULLREQUEST_SOURCEBRANCH", "BUILD_SOURCEBRANCH"],
},
];
export function getCiBranch(env: NodeJS.ProcessEnv = process.env): string | undefined {
const provider = CI_PROVIDER_BRANCH_VARS.find(({ detect }) => detect(env));
for (const name of provider?.vars ?? []) {
const value = env[name]?.trim();
if (!value) {
continue;
}
// Azure uses full refs. Only branch refs name a branch, not tags or pull request merges.
if (value.startsWith("refs/")) {
if (value.startsWith("refs/heads/")) {
return value.slice("refs/heads/".length);
}
continue;
}
return value;
}
return undefined;
}
function getLastCommit(directory: string): Promise<git.Commit> {
return new Promise((resolve, reject) => {
git.getLastCommit(
(err, commit) => {
if (err) {
return reject(err);
}
resolve(commit);
},
{ dst: directory }
);
});
}
async function isDirty(directory: string): Promise<boolean> {
try {
const result = await x("git", ["--no-optional-locks", "status", "-s"], {
nodeOptions: {
cwd: directory,
},
});
// Example output (when dirty):
// M ../fs-detectors/src/index.ts
return result.stdout.trim().length > 0;
// eslint-disable-next-line no-useless-catch
} catch (error) {
throw error;
}
}
async function parseGitConfig(configPath: string) {
try {
return ini.parse(await fs.readFile(configPath, "utf8"));
} catch (_err: unknown) {
return;
}
}
function pluckOriginUrl(gitConfig: { [key: string]: any }): string | undefined {
// Assuming "origin" is the remote url that the user would want to use
return gitConfig['remote "origin"']?.url;
}
async function getOriginUrl(configPath: string): Promise<string | null> {
const gitConfig = await parseGitConfig(configPath);
if (!gitConfig) {
return null;
}
const originUrl = pluckOriginUrl(gitConfig);
if (originUrl) {
return originUrl;
}
return null;
}
export function sanitizeGitRemoteUrl(remoteUrl: string | undefined): string | undefined {
if (remoteUrl === undefined) {
return;
}
try {
const url = new URL(remoteUrl);
if (!url.username && !url.password) {
return remoteUrl;
}
url.username = "";
url.password = "";
return url.href;
} catch {
return remoteUrl.includes("://") || /^[a-z][a-z\d+.-]*:/i.test(remoteUrl.trim())
? undefined
: remoteUrl;
}
}
function errorToString(err: unknown): string {
return err instanceof Error ? err.message : String(err);
}
export function isGitHubActions() {
// GH Actions CI sets these env variables
return (
process.env.GITHUB_ACTIONS === "true" &&
process.env.GITHUB_SHA !== undefined &&
process.env.GITHUB_REF !== undefined
);
}
async function getGitHubActionsMeta(): Promise<GitMeta> {
const remoteUrl =
process.env.GITHUB_SERVER_URL && process.env.GITHUB_REPOSITORY
? `${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}.git`
: undefined;
// GITHUB_SHA and GITHUB_REF are both set in GH Actions CI
const githubSha = process.env.GITHUB_SHA ?? "";
const githubRef = process.env.GITHUB_REF ?? "";
// For push events, GITHUB_REF is fully qualified, e.g., "refs/heads/main"
let commitRef = githubRef.replace(/^refs\/(heads|tags)\//, "");
let commitMessage: string | undefined;
let commitSha = githubSha;
let pullRequestNumber: number | undefined;
let pullRequestTitle: string | undefined;
let pullRequestState: "open" | "closed" | "merged" | undefined;
if (process.env.GITHUB_EVENT_PATH) {
try {
const eventData = JSON.parse(await fs.readFile(process.env.GITHUB_EVENT_PATH, "utf8"));
if (process.env.GITHUB_EVENT_NAME === "push") {
commitMessage = eventData.head_commit?.message;
} else if (process.env.GITHUB_EVENT_NAME === "pull_request") {
// For PRs, use the head commit info
pullRequestTitle = eventData.pull_request?.title;
commitRef = eventData.pull_request?.head?.ref;
pullRequestNumber = eventData.pull_request?.number;
commitSha = eventData.pull_request?.head?.sha;
pullRequestState = eventData.pull_request?.state as "open" | "closed";
// Check if PR was merged
if (pullRequestState === "closed" && eventData.pull_request?.merged === true) {
pullRequestState = "merged";
}
await x("git", ["status"], {
nodeOptions: {
cwd: process.cwd(),
},
}).then((result) => console.debug(result.stdout));
commitMessage = await getCommitMessage(process.cwd(), commitSha, pullRequestNumber);
}
} catch (error) {
console.debug("Failed to parse GitHub event payload:", errorToString(error));
}
} else {
console.debug("No GITHUB_EVENT_PATH found");
}
return {
provider: "github",
source: "github_actions",
remoteUrl: sanitizeGitRemoteUrl(remoteUrl),
commitSha,
commitRef,
// In CI, the workspace is always clean
dirty: false,
// These fields might not be available in all GitHub Actions contexts
commitAuthorName: process.env.GITHUB_ACTOR,
commitMessage,
pullRequestNumber:
pullRequestNumber ??
(process.env.GITHUB_PULL_REQUEST_NUMBER
? parseInt(process.env.GITHUB_PULL_REQUEST_NUMBER)
: undefined),
pullRequestTitle,
pullRequestState,
};
}
function isGitHubApp() {
// we set this env variable in our build server
return process.env.TRIGGER_GITHUB_APP === "true";
}
function getGitHubAppMeta(): GitMeta {
return {
provider: "github",
source: "trigger_github_app",
remoteUrl: sanitizeGitRemoteUrl(process.env.GITHUB_REPOSITORY_URL),
commitSha: process.env.GITHUB_HEAD_COMMIT_SHA,
commitRef: process.env.GITHUB_REF?.replace(/^refs\/(heads|tags)\//, ""),
commitMessage: process.env.GITHUB_HEAD_COMMIT_MESSAGE,
commitAuthorName: process.env.GITHUB_HEAD_COMMIT_AUTHOR_NAME,
pullRequestNumber: process.env.GITHUB_PULL_REQUEST_NUMBER
? parseInt(process.env.GITHUB_PULL_REQUEST_NUMBER)
: undefined,
pullRequestTitle: process.env.GITHUB_PULL_REQUEST_TITLE,
pullRequestState: process.env.GITHUB_PULL_REQUEST_STATE as
| "open"
| "closed"
| "merged"
| undefined,
// the workspace is always clean as we clone the repo in the build server
dirty: false,
ghUsername: process.env.GITHUB_USERNAME,
ghUserAvatarUrl: process.env.GITHUB_USER_AVATAR_URL,
};
}
async function getCommitMessage(
directory: string,
sha: string,
prNumber?: number
): Promise<string | undefined> {
try {
// First try to fetch the specific commit
await x("git", ["fetch", "origin", sha], {
nodeOptions: {
cwd: directory,
},
});
// Try to get the commit message
const result = await x("git", ["log", "-1", "--format=%B", sha], {
nodeOptions: {
cwd: directory,
},
});
const message = result.stdout.trim();
if (!message && prNumber) {
// If that didn't work, try fetching the PR branch
const _branchResult = await x(
"git",
["fetch", "origin", `pull/${prNumber}/head:pr-${prNumber}`],
{
nodeOptions: {
cwd: directory,
},
}
);
// Try again with the fetched branch
const branchCommitResult = await x("git", ["log", "-1", "--format=%B", `pr-${prNumber}`], {
nodeOptions: {
cwd: directory,
},
});
return branchCommitResult.stdout.trim();
}
return message;
} catch (error) {
console.debug("Error getting commit message:", errorToString(error));
return undefined;
}
}