post-checkout-npm-install
Version:
npm install when package.json dependencies have changed post-checkout
3 lines (2 loc) • 1.53 kB
JavaScript
var child_process=require("child_process"),fs=require("fs");function postNpmInstall(e,s=!1){3!==e.length&&(console.error("Invalid post-checkout args."),process.exit(1)),"0"===e[2]&&(console.log("Skipping non-branch checkout."),process.exit(0)),checkChanges(e[0],e[1]).then(e=>{if(e)return canUseCi(s);process.exit(0)}).then(e=>{child_process.execSync(e?"npm ci":"npm install",{stdio:["pipe","pipe",process.stderr]}),console.log("Please restart the server.")}).then(()=>process.exit(0),e=>{console.error(e),process.exit(1)})}const checkChanges=(e,s)=>Promise.all([exec(`git show ${e}:package.json`),exec(`git show ${s}:package.json`)]).then(e=>{const s=JSON.parse(e[0]),c=JSON.parse(e[1]);return haveObjectValuesChanged(s.dependencies,c.dependencies)||haveObjectValuesChanged(s.devDependencies,c.devDependencies)},e=>{const s=/^fatal: Invalid object name/;if(!s.test(e))throw new Error(s)}),canUseCi=e=>Promise.all([checkNpmCiExist(),doesPackageLockJsonExist()]).then(([s,c])=>(!c&&e&&console.warn("Please ensure you have a lockfile before attempting to use npm ci.\nFalling back to npm install."),s&&c&&e)),exec=(e,s)=>new Promise((c,n)=>{child_process.exec(e,Object(s),(e,s,o)=>{e?n(o):c(s)})}),checkNpmCiExist=()=>exec("npm ci --help").then(e=>"npm ci"===e.toString()),doesPackageLockJsonExist=()=>new Promise(e=>{fs.access("package-lock.json",fs.constants.R_OK,s=>{e(!s)})}),haveObjectValuesChanged=(e,s)=>Object.keys(Object(e)).concat(Object.keys(Object(s))).some(c=>e[c]!==s[c]);module.exports=postNpmInstall;