|
| 1 | +#!/usr/bin/env node |
| 2 | + |
| 3 | +// Usage: e.g. node build-addons.mjs <path to node-gyp> <directory> |
| 4 | + |
| 5 | +import child_process from 'node:child_process'; |
| 6 | +import path from 'node:path'; |
| 7 | +import fs from 'node:fs/promises'; |
| 8 | +import util from 'node:util'; |
| 9 | +import process from 'node:process'; |
| 10 | +import os from 'node:os'; |
| 11 | + |
| 12 | +const execFile = util.promisify(child_process.execFile); |
| 13 | + |
| 14 | +const parallelization = +process.env.JOBS || os.cpus().length; |
| 15 | +const nodeGyp = process.argv[2]; |
| 16 | +const directory = process.argv[3]; |
| 17 | + |
| 18 | +async function buildAddon(dir) { |
| 19 | + try { |
| 20 | + // Only run for directories that have a `binding.gyp`. |
| 21 | + // (https://github.com/nodejs/node/issues/14843) |
| 22 | + await fs.stat(path.join(dir, 'binding.gyp')); |
| 23 | + } catch (err) { |
| 24 | + if (err.code === 'ENOENT' || err.code === 'ENOTDIR') |
| 25 | + return; |
| 26 | + throw err; |
| 27 | + } |
| 28 | + |
| 29 | + console.log(`Building addon in ${dir}`); |
| 30 | + const { stdout, stderr } = |
| 31 | + await execFile(process.execPath, [nodeGyp, 'rebuild', `--directory=${dir}`], |
| 32 | + { |
| 33 | + stdio: 'inherit', |
| 34 | + env: { ...process.env, MAKEFLAGS: '-j1' } |
| 35 | + }); |
| 36 | + |
| 37 | + // We buffer the output and print it out once the process is done in order |
| 38 | + // to avoid interleaved output from multiple builds running at once. |
| 39 | + process.stdout.write(stdout); |
| 40 | + process.stderr.write(stderr); |
| 41 | +} |
| 42 | + |
| 43 | +async function parallel(jobQueue, limit) { |
| 44 | + const next = async () => { |
| 45 | + if (jobQueue.length === 0) { |
| 46 | + return; |
| 47 | + } |
| 48 | + const job = jobQueue.shift(); |
| 49 | + await job(); |
| 50 | + await next(); |
| 51 | + }; |
| 52 | + |
| 53 | + const workerCnt = Math.min(limit, jobQueue.length); |
| 54 | + await Promise.all(Array.from({ length: workerCnt }, next)); |
| 55 | +} |
| 56 | + |
| 57 | +const jobs = []; |
| 58 | +for await (const dirent of await fs.opendir(directory)) { |
| 59 | + if (dirent.isDirectory()) { |
| 60 | + jobs.push(() => buildAddon(path.join(directory, dirent.name))); |
| 61 | + } |
| 62 | +} |
| 63 | +await parallel(jobs, parallelization); |
0 commit comments