-
Notifications
You must be signed in to change notification settings - Fork 81
Expand file tree
/
Copy pathgithub.ts
More file actions
216 lines (181 loc) · 6.58 KB
/
Copy pathgithub.ts
File metadata and controls
216 lines (181 loc) · 6.58 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
import { mkdtemp, writeFile } from "fs/promises";
import { join } from "path";
import { fetch } from "./fetch";
import { exec } from "./shell";
interface GitHubReleaseInfo {
title: string;
tag: string;
target: string;
notes:
| {
text: string;
}
| {
file: string;
};
filesToRelease?: string;
isDraft?: boolean;
repo?: string;
}
interface GitHubPRInfo {
title: string;
body: string;
head: string;
base: string;
repo?: string;
}
export class GitHub {
authSet = false;
tmpPrefix = "gh-";
async ensureAuth(): Promise<void> {
if (!this.authSet) {
if (process.env.GITHUB_TOKEN) {
// when using GITHUB_TOKEN, gh will automatically use it
} else if (process.env.GH_PAT) {
await exec(`echo "${process.env.GH_PAT}" | gh auth login --with-token`);
} else {
// No environment variables set, check if already authenticated
if (!(await this.isAuthenticated())) {
throw new Error(
"GitHub CLI is not authenticated. Please set GITHUB_TOKEN or GH_PAT environment variable, or run 'gh auth login'."
);
}
}
this.authSet = true;
}
}
private async isAuthenticated(): Promise<boolean> {
try {
// Try to run 'gh auth status' to check if authenticated
await exec("gh auth status", { stdio: "pipe" });
return true;
} catch (error) {
// If the command fails, the user is not authenticated
return false;
}
}
async createTempFile(): Promise<string> {
const dir = await mkdtemp(this.tmpPrefix);
return join(dir, "release-notes.txt");
}
async createGithubPRFrom(pr: GitHubPRInfo): Promise<void> {
await this.ensureAuth();
const repoArgument = pr.repo ? `--repo '${pr.repo}'` : "";
const command = [
`gh pr create`,
`--title '${pr.title}'`,
`--body '${pr.body}'`,
`--base '${pr.base}'`,
`--head '${pr.head}'`,
repoArgument
].join(" ");
await exec(command);
}
async createGithubReleaseFrom(params: GitHubReleaseInfo): Promise<void> {
const { notes, title, tag, filesToRelease = "", target, isDraft = false, repo } = params;
await this.ensureAuth();
const notesFilePath = "file" in notes ? notes.file : await this.createReleaseNotesFile(notes.text);
const targetHash = (await exec(`git rev-parse --verify ${target}`, { stdio: "pipe" })).stdout.trim();
const command = [
`gh release create`,
`--title '${title}'`,
`--notes-file '${notesFilePath}'`,
isDraft ? `--draft` : "",
repo ? `-R '${repo}'` : "",
`'${tag}'`,
`--target '${targetHash}'`,
filesToRelease ? `'${filesToRelease}'` : ""
]
.filter(str => str !== "")
.join(" ");
await exec(command);
}
get ghAPIHeaders(): Record<string, string> {
return {
"X-GitHub-Api-Version": "2022-11-28",
Authorization: `Bearer ${process.env.GH_PAT}`
};
}
async getReleaseIdByReleaseTag(releaseTag: string): Promise<string | undefined> {
console.log(`Searching for release from Github tag '${releaseTag}'`);
try {
const release =
(await fetch<{ id: string }>(
"GET",
`https://api.github.com/repos/mendix/web-widgets/releases/tags/${releaseTag}`,
undefined,
{ ...this.ghAPIHeaders }
)) ?? [];
if (!release) {
return undefined;
}
return release.id;
} catch (e) {
if (e instanceof Error && e.message.includes("404")) {
return undefined;
}
throw e;
}
}
async getReleaseArtifacts(releaseTag: string): Promise<Array<{ name: string; browser_download_url: string }>> {
const releaseId = await this.getReleaseIdByReleaseTag(releaseTag);
if (!releaseId) {
throw new Error(`Could not find release with tag '${releaseTag}' on GitHub`);
}
return fetch<
Array<{
name: string;
browser_download_url: string;
}>
>("GET", `https://api.github.com/repos/mendix/web-widgets/releases/${releaseId}/assets`, undefined, {
...this.ghAPIHeaders
});
}
async getMPKReleaseArtifactUrl(releaseTag: string): Promise<string> {
const artifacts = await this.getReleaseArtifacts(releaseTag);
const downloadUrl = artifacts.find(asset => asset.name.endsWith(".mpk"))?.browser_download_url;
if (!downloadUrl) {
throw new Error(`Could not retrieve MPK url from GitHub release with tag ${process.env.TAG}`);
}
return downloadUrl;
}
async createReleaseNotesFile(releaseNotesText: string): Promise<string> {
const filePath = await this.createTempFile();
await writeFile(filePath, releaseNotesText);
return filePath;
}
private async triggerGithubWorkflow(params: {
workflowId: string;
ref: string;
inputs: Record<string, string>;
owner?: string;
repo?: string;
}): Promise<void> {
await this.ensureAuth();
const { workflowId, ref, inputs, owner = "mendix", repo = "web-widgets" } = params;
// Convert inputs object to CLI parameters
const inputParams = Object.entries(inputs)
.map(([key, value]) => `-f ${key}=${value}`)
.join(" ");
const repoParam = `${owner}/${repo}`;
const command = [`gh workflow run`, `"${workflowId}"`, `--ref "${ref}"`, inputParams, `-R "${repoParam}"`]
.filter(Boolean)
.join(" ");
try {
await exec(command);
console.log(`Successfully triggered workflow '${workflowId}'`);
} catch (error) {
throw new Error(`Failed to trigger workflow '${workflowId}': ${error}`);
}
}
async triggerCreateReleaseWorkflow(packageName: string, ref = "main"): Promise<void> {
return this.triggerGithubWorkflow({
workflowId: "CreateGitHubRelease.yml",
ref,
inputs: {
package: packageName
}
});
}
}
export const gh = new GitHub();