UNPKG

gtw

Version:

git

103 lines (83 loc) 2.18 kB
const cp = require("child_process"); const fs = require("fs"); const path = require("path"); const { spawnSync, execSync } = cp; const cwd = process.cwd(); const userPkg = getUserPkg(); function getUserPkg() { return fs.existsSync(path.resolve(cwd, "package.json")) ? require(path.resolve(cwd, "package.json")) : {}; } function run(options, args) { if (!Object.keys(options).length && !args.length) return; execCmd(args); } function execCmd(args) { try { execHook(getHookName("pre", args[0]), args); spawnSync("git", args, { stdio: "inherit", encoding: "utf-8", }); execHook(getHookName("post", args[0]), args); } catch (error) { error && console.log(error.message); process.exit(1); } } function execHook(hook, args) { if (!hasCustomsScripts()) { const externalPath = path.resolve(cwd, `.gtw/${hook}.js`); let hookPath = externalPath; if (!fs.existsSync(externalPath)) { hookPath = path.resolve(__dirname, `../src/hooks/${hook}.js`); } if (fs.existsSync(hookPath)) { handleOutput( spawnSync("node", [hookPath, ...args], { stdio: "pipe", }) ); } } else { execScript(hook); } } function execScript(hook) { if (!hasCustomsScripts()) return; const { gtw } = userPkg; if (gtw.hooks) { Object.entries(gtw.hooks).forEach((value) => { if (hook === value[0]) { if (value[1]) { handleOutput(execSync(value[1], { stdio: "inherit" })); } } }); } } function hasCustomsScripts() { const { gtw } = userPkg; return typeof gtw !== "undefined" ? typeof gtw.hooks !== "undefined" && !!Object.keys(gtw.hooks).length : false; } /** * @param {'pre' | 'post'} prefix * @param {string} cmd */ function getHookName(prefix, cmd) { return `${prefix}-${cmd}`; } function handleOutput(output) { const { stdout, stderr, status } = output; const errorText = stderr.toString().trim(); const stdoutText = stdout.toString(); if (stdoutText) console.log(stdoutText); if (errorText) { throw new Error(errorText); } if (status) process.exit(status); } module.exports = run;