Created
April 10, 2018 08:35
-
-
Save tatat/bfc0ceb95e647a5bea6a1544a73d0650 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const path = require('path') | |
const { spawn } = require('child_process') | |
const fs = require('fs') | |
const spawnPromise = (command, args = [], options = {}) => { | |
return new Promise((resolve, reject) => { | |
const cp = spawn(command, args, { stdio: 'inherit', ...options }) | |
cp.on('error', error => reject(error)) | |
cp.on('close', (code, signal) => code === 0 ? resolve() : reject(new Error(`Exited with code ${ code }`))) | |
}) | |
} | |
const build = async (name, tasks = [], cwd) => { | |
cwd = cwd || path.join('node_modules', name) | |
const manager = fs.existsSync(path.join(cwd, 'yarn.lock')) ? 'yarn' : 'npm' | |
await spawnPromise(manager, ['install'], { cwd }) | |
tasks.forEach(async (task) => { | |
if (Array.isArray(task)) { | |
let [command, args, options] = task | |
args = args || [] | |
options = options || {} | |
await spawnPromise(command, args, { cwd, ...options }) | |
} else { | |
await spawnPromise(manager, ['run', task], { cwd }) | |
} | |
}) | |
} | |
const run = async (params) => { | |
try { | |
await Promise.all(params.map(async (p) => await build(p.name, p.tasks, p.cwd))) | |
} catch(e) { | |
console.error(e) | |
} | |
} | |
if (require.main === module) { | |
// e.g. `node scripts/build-module.js module-1 module-2=pre-build,build` | |
run(process.argv.slice(2).map(arg => { | |
let [name, tasks] = arg.split('=') | |
if (!tasks) { | |
tasks = [] | |
} else { | |
tasks = tasks.split(',').map(t => t.trim()) | |
} | |
if (tasks.length === 0) | |
tasks.push('build') | |
return { name, tasks } | |
})) | |
} else { | |
module.exports = { build, run } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment