All files / src/plugin exec.js

34.62% Statements 9/26
0% Branches 0/6
0% Functions 0/4
37.5% Lines 9/24
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    1x     1x 1x   1x   1x   1x   1x                 1x 1x                                                        
import 'colors'
import { join } from 'path'
import {
  isInitialized,
  map,
  onlyPackage,
  exec as execCmd,
  separator,
  log
} 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')
    .action((...args) => action(config, directory, ...args))
}

const command = 'exec [command...]'
const description = 'Execute a command in all packages'

// exported for testing
export function action (config, workingDir, args, options) {
  isInitialized(config, 'exec')
 
  const packages = options.parent.only
    ? onlyPackage(options.parent.only, config.packages)
    : config.packages

  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()

  // return promise for testing
  return Promise.all(map(packages, function (packageName) {
    const packageDir = join(workingDir, packageName)
    const name = require(join(packageDir, 'package.json')).name
 
    return 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()
    })
  }))
}