Skip to content

Commit

Permalink
new: Add initial implementation. (#1)
Browse files Browse the repository at this point in the history
* Initial spike.

* Add opt level.

* Polish.
  • Loading branch information
milesj committed Nov 5, 2023
1 parent 715e207 commit 704af85
Show file tree
Hide file tree
Showing 5 changed files with 228 additions and 27 deletions.
27 changes: 12 additions & 15 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -1,21 +1,18 @@
MIT License

Copyright (c) 2023 moonrepo
Copyright (c) 2023 moonrepo, Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
18 changes: 9 additions & 9 deletions action.yml
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
name: 'Build proto plugin'
author: 'Miles Johnson'
description: 'Build, optimize, and prepare a proto WASM plugin for release.'
inputs:
auto-install:
default: false
description: 'Auto-install tools on setup.'
outputs:
cache-key:
description: 'The cache key used for the toolchain folder (~/.proto).'
# inputs:
# auto-install:
# default: false
# description: 'Auto-install tools on setup.'
# outputs:
# cache-key:
# description: 'The cache key used for the toolchain folder (~/.proto).'
runs:
using: 'node20'
main: 'dist/index.js'
branding:
icon: 'battery-charging'
color: 'purple'
icon: 'layers'
color: 'red'
170 changes: 170 additions & 0 deletions index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,178 @@
import crypto from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import * as core from '@actions/core';
import * as exec from '@actions/exec';
import * as tc from '@actions/tool-cache';

interface BuildInfo {
packageName: string;
targetName: string;
optLevel: string;
}

// https://github.com/WebAssembly/binaryen
async function installBinaryen() {
core.info('Installing WebAssembly binaryen');

let platform = 'linux';

if (process.platform === 'darwin') {
platform = 'macos';
} else if (process.platform === 'win32') {
platform = 'windows';
}

const downloadFile = await tc.downloadTool(
`https://github.com/WebAssembly/binaryen/releases/download/version_116/binaryen-version_116-x86_64-${platform}.tar.gz`,
);
const extractedDir = await tc.extractTar(downloadFile, path.join(os.homedir(), 'binaryen'));

core.addPath(path.join(extractedDir, 'bin'));
}

// https://github.com/WebAssembly/wabt
async function installWabt() {
core.info('Installing Web Assembly Binary Toolkit (WABT)');

let platform = 'ubuntu';

if (process.platform === 'darwin') {
platform = 'macos';
} else if (process.platform === 'win32') {
platform = 'windows';
}

const downloadFile = await tc.downloadTool(
`https://github.com/WebAssembly/wabt/releases/download/1.0.34/wabt-1.0.34-${platform}.tar.gz`,
);
const extractedDir = await tc.extractTar(downloadFile, path.join(os.homedir(), 'wabt'));

core.addPath(path.join(extractedDir, 'bin'));
}

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 builds: BuildInfo[] = [];
let output = '';

await exec.exec('cargo', ['metadata', '--format-version', '1', '--no-deps'], {
listeners: {
stdout: (data: Buffer) => {
output += data.toString();
},
},
});

const metadata = JSON.parse(output) as Metadata;

await Promise.all(
metadata.packages.map(async (pkg) => {
if (!metadata.workspace_members.includes(pkg.id)) {
return;
}

const manifest = JSON.parse(
await fs.promises.readFile(pkg.manifest_path, 'utf8'),
) as Manifest;

pkg.targets.forEach((target) => {
if (target.crate_types.includes('cdylib')) {
builds.push({
optLevel: manifest.profile?.release?.['opt-level'] ?? 's',
packageName: pkg.name,
targetName: target.name,
});
}
});
}),
);

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 root = process.env.GITHUB_WORKSPACE!;
const buildDir = path.join(root, 'builds');

await fs.promises.mkdir(buildDir);

await Promise.all(
builds.map(async (build) => {
core.debug(`Building ${build.packageName} (mode=release, target=wasm32-wasi)`);

await exec.exec('cargo', [
'build',
'--release',
'--package',
build.packageName,
'--target',
'wasm32-wasi',
]);

core.debug(`Optimizing ${build.packageName} (level=${build.optLevel})`);

const fileName = `${build.targetName}.wasm`;
const inputFile = path.join(root, 'target/wasm32-wasi/release', fileName);
const outputFile = path.join(buildDir, fileName);

await exec.exec('wasm-opt', [`-O${build.optLevel}`, inputFile, '--output', outputFile]);

core.debug(`Stripping ${build.packageName}`);

await exec.exec('wasm-strip', [outputFile]);

core.debug(`Hashing ${build.packageName} (checksum=sha256)`);

const checksumFile = `${outputFile}.sha256`;
const checksumHash = await hashFile(outputFile);

await fs.promises.writeFile(checksumFile, checksumHash);

core.info(build.packageName);
core.info(`--> ${outputFile}`);
core.info(`--> ${checksumFile}`);
core.info(`--> ${checksumHash}`);
}),
);
}

async function run() {
try {
await Promise.all([installWabt(), installBinaryen()]);

await buildPackages(await findBuildablePackages());
} catch (error: unknown) {
core.setFailed(error as Error);
}
Expand Down
6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"description": "A GitHub action to build, optimize, and prepare a proto WASM plugin for release.",
"main": "dist/index.js",
"scripts": {
"build": "ncc build ./index.ts && ncc build ./post.ts --out ./dist/post",
"build": "ncc build ./index.ts",
"check": "pnpm run lint && pnpm run test && pnpm run typecheck",
"deps": "pnpm update --latest --interactive",
"lint": "eslint --ext .ts,.js --fix .",
Expand All @@ -19,7 +19,9 @@
"author": "Miles Johnson",
"license": "MIT",
"dependencies": {
"@actions/core": "^1.10.1"
"@actions/core": "^1.10.1",
"@actions/exec": "^1.1.1",
"@actions/tool-cache": "^2.0.1"
},
"devDependencies": {
"@types/node": "^20.7.1",
Expand Down
34 changes: 33 additions & 1 deletion pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 704af85

Please sign in to comment.