-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
302 lines (229 loc) · 7.63 KB
/
index.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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
/* eslint-disable no-await-in-loop */
import crypto from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import parseChangelog from 'changelog-parser';
import * as core from '@actions/core';
import * as exec from '@actions/exec';
import * as tc from '@actions/tool-cache';
import TOML from '@ltd/j-toml';
interface BuildInfo {
packageName: string;
targetName: string;
optLevel: string;
}
const BINARYEN_VERSION = '118';
const WABT_VERSION = '1.0.36';
function getRoot(): string {
return process.env.GITHUB_WORKSPACE!;
}
let TAG: string | null = null;
let PLUGIN: string | null = null;
let PLUGIN_VERSION: string | null = null;
let PLUGIN_ROOT: string | null = null;
function detectVersionAndProject() {
const ref = process.env.GITHUB_REF;
if (ref && ref.startsWith('refs/tags/')) {
const tag = ref.replace('refs/tags/', '');
let project = '';
let version = '';
let prerelease = false;
core.info(`Detected tag ${tag}`);
TAG = tag;
const regex = /^(?:(?<project>[\w-]+)[@-])?(?<version>v?\d+\.\d+\.\d+(?<suffix>[\w+.-]+)?)$/i;
const match = tag.match(regex);
if (match?.groups) {
({ project = '', version = '' } = match.groups);
prerelease = !!match.groups?.suffix;
} else {
version = tag;
}
if (version.startsWith('v') || version.startsWith('V')) {
version = version.slice(1);
}
core.info(`Detected tagged version ${version}`);
core.setOutput('tagged-version', version);
core.setOutput('prerelease', prerelease);
PLUGIN_VERSION = version;
if (project) {
core.info(`Detected tagged project ${project}`);
core.setOutput('tagged-project', project);
PLUGIN = project;
}
}
}
// https://github.com/WebAssembly/binaryen
async function installBinaryen() {
core.info('Installing WebAssembly binaryen');
let platform = 'linux';
let arch = process.arch === 'arm64' ? 'aarch64' : 'x86_64';
if (process.platform === 'darwin') {
platform = 'macos';
if (process.arch === 'arm64') {
arch = 'arm64';
}
} else if (process.platform === 'win32') {
platform = 'windows';
}
const downloadFile = await tc.downloadTool(
`https://github.com/WebAssembly/binaryen/releases/download/version_${BINARYEN_VERSION}/binaryen-version_${BINARYEN_VERSION}-${arch}-${platform}.tar.gz`,
);
const extractedDir = await tc.extractTar(downloadFile, path.join(os.homedir(), 'binaryen'));
core.addPath(path.join(extractedDir, `binaryen-version_${BINARYEN_VERSION}/bin`));
}
// https://github.com/WebAssembly/wabt
async function installWabt() {
core.info('Installing WebAssembly wabt');
let platform = 'ubuntu-20.04';
if (process.platform === 'darwin') {
platform = process.arch === 'arm64' ? 'macos-14' : 'macos-12';
} else if (process.platform === 'win32') {
platform = 'windows';
}
const downloadFile = await tc.downloadTool(
`https://github.com/WebAssembly/wabt/releases/download/${WABT_VERSION}/wabt-${WABT_VERSION}-${platform}.tar.gz`,
);
const extractedDir = await tc.extractTar(downloadFile, path.join(os.homedir(), 'wabt'));
core.addPath(path.join(extractedDir, `wabt-${WABT_VERSION}/bin`));
}
async function addRustupTarget() {
core.info('Adding wasm32-wasi target');
await exec.exec('rustup', ['target', 'add', 'wasm32-wasi']);
}
async function findBuildablePackages() {
core.info('Finding buildable packages in Cargo workspace');
interface Package {
id: string;
name: string;
manifest_path: string;
targets: {
crate_types: string[];
name: string;
}[];
}
interface Metadata {
packages: Package[];
workspace_members: string[];
}
interface Manifest {
profile?: Record<string, { 'opt-level'?: string }>;
}
const output = (
await exec.getExecOutput('cargo', ['metadata', '--format-version', '1', '--no-deps'])
).stdout;
const builds: BuildInfo[] = [];
const metadata = JSON.parse(output) as Metadata;
const rootManifest = TOML.parse(
await fs.promises.readFile(path.join(getRoot(), 'Cargo.toml'), 'utf8'),
) as Manifest;
metadata.packages.forEach((pkg) => {
if (!metadata.workspace_members.includes(pkg.id)) {
core.info(`Skipping ${pkg.name}, not a workspace member`);
return;
}
if (PLUGIN && pkg.name !== PLUGIN) {
core.info(`Skipping ${pkg.name}, not associated to tag ${TAG}`);
return;
}
core.info(`Found ${pkg.name}, loading manifest ${pkg.manifest_path}, checking targets`);
const manifest = TOML.parse(fs.readFileSync(pkg.manifest_path, 'utf8')) as Manifest;
pkg.targets.forEach((target) => {
if (target.crate_types.includes('cdylib')) {
core.info(`Has cdylib lib target, adding build`);
builds.push({
optLevel:
manifest.profile?.release?.['opt-level'] ??
rootManifest.profile?.release?.['opt-level'] ??
's',
packageName: pkg.name,
targetName: target.name,
});
}
});
if (PLUGIN) {
PLUGIN_ROOT = path.dirname(pkg.manifest_path);
}
});
core.info(`Found ${builds.length} builds`);
return builds;
}
async function hashFile(filePath: string): Promise<string> {
const hasher = crypto.createHash('sha256');
hasher.update(await fs.promises.readFile(filePath));
return hasher.digest('hex');
}
async function buildPackages(builds: BuildInfo[]) {
core.info(`Building packages: ${builds.map((build) => build.packageName).join(', ')}`);
const buildDir = path.join(getRoot(), 'builds');
await fs.promises.mkdir(buildDir);
core.info(`Building all (mode=release, target=wasm32-wasi)`);
await exec.exec('cargo', [
'build',
'--release',
'--target=wasm32-wasi',
...builds.map((build) => `--package=${build.packageName}`),
]);
for (const build of builds) {
core.info(`Optimizing ${build.packageName} (level=${build.optLevel})`);
const fileName = `${build.targetName}.wasm`;
const inputFile = path.join(getRoot(), 'target/wasm32-wasi/release', fileName);
const outputFile = path.join(buildDir, fileName);
core.debug(`Input: ${inputFile}`);
core.debug(`Output: ${outputFile}`);
await exec.exec('wasm-opt', [`-O${build.optLevel}`, inputFile, '--output', outputFile]);
await exec.exec('wasm-strip', [outputFile]);
core.info(`Hashing ${build.packageName} (checksum=sha256)`);
const checksumFile = `${outputFile}.sha256`;
const checksumHash = await hashFile(outputFile);
await fs.promises.writeFile(checksumFile, checksumHash);
core.info(`Built ${build.packageName}`);
core.info(`\tPlugin file: ${outputFile}`);
core.info(`\tChecksum file: ${checksumFile}`);
core.info(`\tChecksum: ${checksumHash}`);
}
core.setOutput('built', 'true');
}
async function extractChangelog() {
let changelogPath = null;
for (const lookup of ['CHANGELOG.md', 'CHANGELOG', 'HISTORY.md', 'HISTORY']) {
const lookupPath = path.join(PLUGIN_ROOT ?? getRoot(), lookup);
if (fs.existsSync(lookupPath)) {
changelogPath = lookupPath;
break;
}
}
if (!changelogPath || !PLUGIN_VERSION) {
return;
}
const changelog = await parseChangelog({
filePath: changelogPath,
removeMarkdown: false,
});
for (const entry of changelog.versions) {
if (entry.version === PLUGIN_VERSION && entry.body) {
core.setOutput('changelog-entry', entry.body.trim());
break;
}
}
}
async function run() {
core.setOutput('built', 'false');
core.setOutput('changelog-entry', '');
core.setOutput('tagged-project', '');
core.setOutput('tagged-version', '');
core.setOutput('prerelease', 'false');
try {
detectVersionAndProject();
const builds = await findBuildablePackages();
if (builds.length > 0) {
await Promise.all([installWabt(), installBinaryen(), addRustupTarget()]);
await buildPackages(builds);
}
await extractChangelog();
} catch (error: unknown) {
core.setFailed(error as Error);
}
}
// eslint-disable-next-line unicorn/prefer-top-level-await
void run();