Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feat][CLI]: add w4 opt | wasm-opt integration #261

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions cli/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,16 @@ program.command("bundle <cart>")
bundle.run(cart, opts);
});

program.command('opt <cart>')
.alias('optimize')
.description("optimize and minimize cart size using binaryen wasm-opt")
.option("-o, --output <file>", "output wasm file", "./cart-opt.wasm")
.option("-s, --silent", "do not print to stdout", false)
.action((cart, opts) => {
const opt = require("./lib/opt");
opt.optimizeCart(cart, opts);
});

program
.name("w4")
.description("WASM-4: Build retro games using WebAssembly for a fantasy console.\n\nLearn more: https://wasm4.org")
Expand Down
127 changes: 127 additions & 0 deletions cli/lib/opt.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
'use strict';
const { spawnSync } = require('child_process');
const path = require('path');
const fs = require('fs');
const binaryenPkg = require.resolve('binaryen/package.json');
const wasmOptBinPath = path.join(path.dirname(binaryenPkg), 'bin/wasm-opt');

const { EOL } = require('os');

const logError = (...args) => {
console.error(`w4 opt error: ${args.join(EOL)}`);
};

const wasmOptFlags = [
'-Oz',
'--strip-dwarf',
'--strip-producers',
'--zero-filled-memory',
];

/**
* @type {(bytes: number) => string}
*/
const formatKiB = (bytes) => {
return (bytes / 1024).toFixed(3) + 'KiB';
};

/**
* @type {(num: number, den: number) => string}
*/
const formatPercent = (num, den) => {
return `${((num / den) * 100).toFixed(2)}%`;
};

/**
* @type{(cart: string, options: { output: string, silent: boolean }) => void}
*/
function optimizeCart(cart, { output, silent }) {
const absoluteInputCartPath = path.isAbsolute(cart)
? cart
: path.resolve(process.cwd(), cart);

const absoluteOutputCartPath = path.isAbsolute(output)
? output
: path.resolve(process.cwd(), output);

/**
* @type {import('fs').Stats | null}
*/
let inCartStats = null;
/**
* @type {import('fs').Stats | null}
*/
let outCartStats = null;

try {
inCartStats = fs.statSync(absoluteInputCartPath);

if (inCartStats.isDirectory()) {
logError(`cart "${absoluteInputCartPath}" is a directory.`);
process.exitCode = 1;
return;
}
} catch (err) {
if (err?.code === 'ENOENT') {
logError(`cart "${absoluteInputCartPath}" not found.`);
} else {
logError(err);
}

process.exitCode = 1;
return;
}

// @see https://nodejs.org/api/child_process.html#child_processspawnsynccommand-args-options
const wasmOptProcess = spawnSync(wasmOptBinPath, [
absoluteInputCartPath,
'-o',
absoluteOutputCartPath,
...wasmOptFlags,
]);

// status is the `exitCode`
if (wasmOptProcess.status) {
process.exitCode = wasmOptProcess.status;

logError(
`an error has occurred while running wasm-opt. Exit code ${wasmOptProcess.status}`
);

process.stderr.write(wasmOptProcess.stderr);
return;
}

// wasmOptProcess.error Error | null: `The error object if the child process failed or timed out.`
if (wasmOptProcess.error) {
process.exitCode = 1;
logError(
`an error has occurred while running wasm-opt. Error ${wasmOptProcess.error}`
);
process.stderr.write(wasmOptProcess.stderr);

return;
}

if (!silent) {
outCartStats = fs.statSync(absoluteOutputCartPath);

process.stdout.write(
[
'w4 opt',
`- input: ${formatKiB(inCartStats.size)} ${absoluteInputCartPath}`,
`- output: ${formatKiB(outCartStats.size)} ${absoluteOutputCartPath}`,
`size reduction: ${formatPercent(
inCartStats.size - outCartStats.size,
inCartStats.size
)}`,
]
.join(EOL)
.concat(EOL)
);
}
}

module.exports = {
optimizeCart,
};
17 changes: 16 additions & 1 deletion cli/package-lock.json

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

1 change: 1 addition & 0 deletions cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"zig"
],
"dependencies": {
"binaryen": "104.0.0",
"commander": "^8.2.0",
"express": "^4.17.1",
"mustache": "^4.2.0",
Expand Down
40 changes: 40 additions & 0 deletions site/docs/reference/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,46 @@ The `--title` option changes the visible title of the game. Like in the title ba
At least one of the targets (`--html`, `--windows`, `--linux`, `--mac`) must be provided. If no target is provided, the command will fail.
:::

## `opt`

**Summary:**

Shrinks input wasm file and optimizes it.

Powered by [binaryen](https://github.com/AssemblyScript/binaryen.js).

**Usage:**

```
w4 opt <CART> [OPTIONS]
w4 optimize <CART> [OPTIONS]
```

**Description:**

`w4 opt` generates an optimized version of the input wasm module using [`wasm-opt`](https://github.com/WebAssembly/binaryen#binaryen-optimizations).

**Examples:**

```

w4 opt carts/wormhole.wasm
w4 opt target/wasm32-unknown-unknown/release/snake.wasm snake.opt.wasm
w4 opt carts/minesweeper.wasm -s
```

**Options:**

| Option | Default value | Description |
| ---------------- | ------------- | --------------------------------------- |
| -s | | Do not print to stdout |
| -silent | | Same as `-s` |
| -o FILE | cart-opt.wasm | Output file |
| --output FILE | cart-opt.wasm | Same as `-o` |

**Alias:** `optimize`


## `help`

**Summary:**
Expand Down