All files / src/plugin exec.js

24.32% Statements 9/37
0% Branches 0/10
0% Functions 0/8
26.47% Lines 9/34
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80    1x     1x 1x   1x   1x   1x   1x                 1x 1x                                                                                                              
import 'colors'
import { join } from 'path'
import {
  isInitialized,
  onlyPackage,
  exec as execCmd,
  separator,
  log,
  filter
} from '../util'
 
export const plugin = function exec (program, config, directory) {
  program.command(command).description(description)
    .option('-o, --only <packageName>', 'Only execute in a single package directory')
    .option('-e, --exclude [packageNames...]', 'Exclude directories')
    .action((...args) => action(config, directory, ...args))
}

const command = 'exec [command...]'
const description = 'Execute a command in all packages'
 
function filterExclusions (packages, exclusions) {
  return filter(packages, x => exclusions.indexOf(x) === -1)
}
 
// exported for testing
export function action (config, workingDir, args, options) {
  isInitialized(config, 'exec')
 
  const packages = filterExclusions(options.only
    ? onlyPackage(options.only, config.packages)
    : config.packages
    , options.exclude || []
  )

  if (packages.length === 0) {
    if (options.only) {
      return log('Cannot find package ' + options.parent.only)
    }
    return log('Cannot find any packages to execute your command :(')
  }
 
  const cmd = args.shift()

  const outputs = []

  function runCommand (packageName, next) {
    const packageDir = join(workingDir, packageName)
    const name = require(join(packageDir, 'package.json')).name

    // create ENV variable for scripts to use
    process.env.NORTHBROOK_EXEC_DIR = packageDir
    const output = execCmd(cmd, args, {
      cwd: packageDir,
      stdio: 'inherit',
      detached: true,
      env: Object.create(process.env),
      start: separator(name) + '\n' + '$ ' + (cmd + ' ' + args.join(' ')).white + '\n\n',
      stop: separator()
    })
 
    outputs.push(output)

    output.then(() => {
      next()
    })
  }
 
  function next () {
    if (packages.length > 0) {
      const packageName = packages.shift()
      runCommand(packageName, next)
    }
  }
 
  next()

  return Promise.all(outputs)
}