generated from actions/typescript-action
-
Notifications
You must be signed in to change notification settings - Fork 11
/
api.ts
282 lines (250 loc) · 8 KB
/
api.ts
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
import * as core from "@actions/core";
import * as github from "@actions/github";
import { type ActionConfig, getConfig } from "./action.ts";
import type { Result } from "./types.ts";
import { sleep, type BranchNameResult } from "./utils.ts";
type Octokit = ReturnType<typeof github.getOctokit>;
let config: ActionConfig;
let octokit: Octokit;
export function init(cfg?: ActionConfig): void {
config = cfg ?? getConfig();
octokit = github.getOctokit(config.token);
}
export async function dispatchWorkflow(distinctId: string): Promise<void> {
try {
// https://docs.github.com/en/rest/actions/workflows#create-a-workflow-dispatch-event
const response = await octokit.rest.actions.createWorkflowDispatch({
owner: config.owner,
repo: config.repo,
workflow_id: config.workflow,
ref: config.ref,
inputs: {
...(config.workflowInputs ? config.workflowInputs : undefined),
distinct_id: distinctId,
},
});
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (response.status !== 204) {
throw new Error(
`Failed to dispatch action, expected 204 but received ${response.status}`,
);
}
core.info(
"Successfully dispatched workflow:\n" +
` Repository: ${config.owner}/${config.repo}\n` +
` Branch: ${config.ref}\n` +
` Workflow: ${config.workflow}\n` +
(config.workflowInputs
? ` Workflow Inputs: ${JSON.stringify(config.workflowInputs)}\n`
: ``) +
` Distinct ID: ${distinctId}`,
);
} catch (error) {
if (error instanceof Error) {
core.error(
`dispatchWorkflow: An unexpected error has occurred: ${error.message}`,
);
core.debug(error.stack ?? "");
}
throw error;
}
}
export async function fetchWorkflowId(
workflowFilename: string,
): Promise<number> {
try {
const sanitisedFilename = workflowFilename
.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
.trim();
const filenameRegex = new RegExp(`/${sanitisedFilename}`);
// https://docs.github.com/en/rest/actions/workflows#list-repository-workflows
const workflowIterator = octokit.paginate.iterator(
octokit.rest.actions.listRepoWorkflows,
{
owner: config.owner,
repo: config.repo,
},
);
let workflowId: number | undefined;
let workflowIdUrl: string | undefined;
for await (const response of workflowIterator) {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (response.status !== 200) {
throw new Error(
`Failed to fetch workflows, expected 200 but received ${response.status}`,
);
}
const workflowData = response.data.find((workflow) =>
filenameRegex.test(workflow.path),
);
workflowId = workflowData?.id;
if (workflowId !== undefined) {
workflowIdUrl = workflowData?.html_url;
break;
}
}
if (workflowId === undefined) {
throw new Error(`Unable to find ID for Workflow: ${workflowFilename}`);
}
core.info(
`Fetched Workflow ID:\n` +
` Repository: ${config.owner}/${config.repo}\n` +
` Workflow ID: '${workflowId}'\n` +
` Input Filename: '${workflowFilename}'\n` +
` Sanitised Filename: '${sanitisedFilename}'\n` +
` URL: ${workflowIdUrl}`,
);
return workflowId;
} catch (error) {
if (error instanceof Error) {
core.error(
`fetchWorkflowId: An unexpected error has occurred: ${error.message}`,
);
core.debug(error.stack ?? "");
}
throw error;
}
}
export async function fetchWorkflowRunUrl(runId: number): Promise<string> {
try {
// https://docs.github.com/en/rest/reference/actions#get-a-workflow-run
const response = await octokit.rest.actions.getWorkflowRun({
owner: config.owner,
repo: config.repo,
run_id: runId,
});
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (response.status !== 200) {
throw new Error(
`Failed to fetch Workflow Run state, expected 200 but received ${response.status}`,
);
}
core.debug(
`Fetched Run:\n` +
` Repository: ${config.owner}/${config.repo}\n` +
` Run ID: ${runId}\n` +
` URL: ${response.data.html_url}`,
);
return response.data.html_url;
} catch (error) {
if (error instanceof Error) {
core.error(
`fetchWorkflowRunUrl: An unexpected error has occurred: ${error.message}`,
);
core.debug(error.stack ?? "");
}
throw error;
}
}
export async function fetchWorkflowRunIds(
workflowId: number,
branch: BranchNameResult,
): Promise<number[]> {
try {
const useBranchFilter =
!branch.isTag &&
branch.branchName !== undefined &&
branch.branchName !== "";
// https://docs.github.com/en/rest/actions/workflow-runs#list-workflow-runs-for-a-repository
const response = await octokit.rest.actions.listWorkflowRuns({
owner: config.owner,
repo: config.repo,
workflow_id: workflowId,
...(useBranchFilter
? {
branch: branch.branchName,
per_page: 10,
}
: {
per_page: 20,
}),
});
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (response.status !== 200) {
throw new Error(
`Failed to fetch Workflow runs, expected 200 but received ${response.status}`,
);
}
const runIds = response.data.workflow_runs.map(
(workflowRun) => workflowRun.id,
);
const branchMsg = useBranchFilter
? `true (${branch.branchName})`
: `false (${branch.ref})`;
core.debug(
"Fetched Workflow Runs:\n" +
` Repository: ${config.owner}/${config.repo}\n` +
` Branch Filter: ${branchMsg}\n` +
` Workflow ID: ${workflowId}\n` +
` Runs Fetched: [${runIds.join(", ")}]`,
);
return runIds;
} catch (error) {
if (error instanceof Error) {
core.error(
`fetchWorkflowRunIds: An unexpected error has occurred: ${error.message}`,
);
core.debug(error.stack ?? "");
}
throw error;
}
}
export async function fetchWorkflowRunJobSteps(
runId: number,
): Promise<string[]> {
try {
// https://docs.github.com/en/rest/actions/workflow-jobs#list-jobs-for-a-workflow-run
const response = await octokit.rest.actions.listJobsForWorkflowRun({
owner: config.owner,
repo: config.repo,
run_id: runId,
filter: "latest",
});
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (response.status !== 200) {
throw new Error(
`Failed to fetch Workflow Run Jobs, expected 200 but received ${response.status}`,
);
}
const jobs = response.data.jobs.map((job) => ({
id: job.id,
steps: job.steps?.map((step) => step.name) ?? [],
}));
const steps = Array.from(new Set(jobs.flatMap((job) => job.steps)));
core.debug(
"Fetched Workflow Run Job Steps:\n" +
` Repository: ${config.owner}/${config.repo}\n` +
` Workflow Run ID: ${runId}\n` +
` Jobs Fetched: [${jobs.map((job) => job.id).join(", ")}]\n` +
` Steps Fetched: [${steps.map((step) => `"${step}"`).join(", ")}]`,
);
return steps;
} catch (error) {
if (error instanceof Error) {
core.error(
`fetchWorkflowRunJobSteps: An unexpected error has occurred: ${error.message}`,
);
core.debug(error.stack ?? "");
}
throw error;
}
}
/**
* Attempt to get a non-empty array from the API.
*/
export async function retryOrTimeout<T>(
retryFunc: () => Promise<T[]>,
timeoutMs: number,
): Promise<Result<T[]>> {
const startTime = Date.now();
let elapsedTime = 0;
while (elapsedTime < timeoutMs) {
const response = await retryFunc();
if (response.length > 0) {
return { success: true, value: response };
}
await sleep(1000);
elapsedTime = Date.now() - startTime;
}
return { success: false, reason: "timeout" };
}