1. #!/usr/bin/env node
    
  2. 
    
  3. 'use strict';
    
  4. 
    
  5. const {exec} = require('child-process-promise');
    
  6. const {existsSync} = require('fs');
    
  7. const {join} = require('path');
    
  8. const {execRead, logPromise} = require('../utils');
    
  9. const theme = require('../theme');
    
  10. 
    
  11. const run = async ({cwd, local, packages, version}) => {
    
  12.   if (local) {
    
  13.     // Sanity test
    
  14.     if (!existsSync(join(cwd, 'build', 'node_modules', 'react'))) {
    
  15.       console.error(theme.error`No local build exists.`);
    
  16.       process.exit(1);
    
  17.     }
    
  18.     return;
    
  19.   }
    
  20. 
    
  21.   if (!existsSync(join(cwd, 'build'))) {
    
  22.     await exec(`mkdir ./build`, {cwd});
    
  23.   }
    
  24. 
    
  25.   // Cleanup from previous builds
    
  26.   await exec(`rm -rf ./build/node_modules*`, {cwd});
    
  27.   await exec(`mkdir ./build/node_modules`, {cwd});
    
  28. 
    
  29.   const nodeModulesPath = join(cwd, 'build/node_modules');
    
  30. 
    
  31.   // Checkout "next" release from NPM for all local packages
    
  32.   for (let i = 0; i < packages.length; i++) {
    
  33.     const packageName = packages[i];
    
  34. 
    
  35.     // We previously used `npm install` for this,
    
  36.     // but in addition to checking out a lot of transient dependencies that we don't care about–
    
  37.     // the NPM client also added a lot of registry metadata to the package JSONs,
    
  38.     // which we had to remove as a separate step before re-publishing.
    
  39.     // It's easier for us to just download and extract the tarball.
    
  40.     const url = await execRead(
    
  41.       `npm view ${packageName}@${version} dist.tarball`
    
  42.     );
    
  43.     const filePath = join(nodeModulesPath, `${packageName}.tgz`);
    
  44.     const packagePath = join(nodeModulesPath, `${packageName}`);
    
  45.     const tempPackagePath = join(nodeModulesPath, 'package');
    
  46. 
    
  47.     // Download packages from NPM and extract them to the expected build locations.
    
  48.     await exec(`curl -L ${url} > ${filePath}`, {cwd});
    
  49.     await exec(`tar -xvzf ${filePath} -C ${nodeModulesPath}`, {cwd});
    
  50.     await exec(`mv ${tempPackagePath} ${packagePath}`, {cwd});
    
  51.     await exec(`rm ${filePath}`, {cwd});
    
  52.   }
    
  53. };
    
  54. 
    
  55. module.exports = async params => {
    
  56.   return logPromise(
    
  57.     run(params),
    
  58.     theme`Checking out "next" from NPM {version ${params.version}}`
    
  59.   );
    
  60. };