All files / src/bin-utils/initialize index.js

100% Statements 66/66
100% Branches 30/30
100% Functions 19/19
100% Lines 65/65
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 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219                                14x                                                                                         5x         5x 5x 5x 5x   5x 1x     4x       4x       4x 4x   4x       1x       1x 1x   1x       4x 4x 4x 4x         5x     34x 34x 34x   34x 34x               34x 34x 24x         24x 4x   24x   34x 34x       5x 5x     44x 26x           15x   44x 44x 44x 10x           5x       5x 38x 4x   38x   5x       4x 4x 4x 4x 2x 2x   4x       24x 24x 24x             72x       44x           34x       76x       24x    
import {resolve, dirname} from 'path'
import {writeFileSync} from 'fs'
import {sync as findUpSync} from 'find-up'
import {
  isPlainObject,
  camelCase,
  set,
  each,
  includes,
  startsWith,
} from 'lodash'
import {safeDump} from 'js-yaml'
import stringifyObject from './stringify-object'
 
export default initialize
 
const CORE_SCRIPTS = [
  'applypatchmsg',
  'commitmsg',
  'install',
  'postapplypatch',
  'postcheckout',
  'postcommit',
  'postinstall',
  'postmerge',
  'postpublish',
  'postreceive',
  'postrestart',
  'postrewrite',
  'poststart',
  'poststop',
  'posttest',
  'postuninstall',
  'postupdate',
  'postversion',
  'preapplypatch',
  'preautogc',
  'precommit',
  'preinstall',
  'preparecommitmsg',
  'prepublish',
  'prepush',
  'prerebase',
  'prereceive',
  'prerestart',
  'prestart',
  'prestop',
  'pretest',
  'preuninstall',
  'preversion',
  'publish',
  'pushtocheckout',
  'restart',
  'stop',
  'uninstall',
  'update',
  'version',
]
 
function initialize(configType = 'js') {
  /* eslint global-require:0,import/no-dynamic-require:0 */
  const packageJsonPath = findUpSync('package.json')
  /* istanbul ignore next */
  if (packageJsonPath === null) {
    return
  }
  const packageJson = require(packageJsonPath)
  const {scripts = {}} = packageJson
  packageJson.scripts = getCoreScripts(packageJson.scripts)
  writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2))
 
  if (configType === 'yml') {
    return dumpYAMLConfig(packageJsonPath, scripts)
  }
 
  return dumpJSConfig(packageJsonPath, scripts)
}
 
function dumpJSConfig(packageJsonPath, scripts) {
  const packageScriptsPath = resolve(
    dirname(packageJsonPath),
    './package-scripts.js',
  )
  const fileContents = generatePackageScriptsFileContents(scripts)
  writeFileSync(packageScriptsPath, fileContents)
 
  return {packageJsonPath, packageScriptsPath}
}
 
function dumpYAMLConfig(packageJsonPath, scripts) {
  const packageScriptsPath = resolve(
    dirname(packageJsonPath),
    './package-scripts.yml',
  )
  const fileContents = safeDump({scripts: structureScripts(scripts)})
  writeFileSync(packageScriptsPath, fileContents)
 
  return {packageJsonPath, packageScriptsPath}
}
 
function generatePackageScriptsFileContents(scripts) {
  const indent = '    ' // start at 4 spaces because we're inside another object
  const structuredScripts = structureScripts(scripts)
  const objectString = stringifyObject(structuredScripts, indent)
  return `module.exports = {\n  scripts: {${objectString}\n  }\n};\n`
}
 
function structureScripts(scripts) {
  // start out by giving every script a `default`
  const defaultedScripts = Object.keys(scripts)
    .filter(isNotCoreScript)
    .reduce((obj, scriptKey) => {
      const keyParts = scriptKey.split(':')
      const isKeyScriptHook = isScriptHook(keyParts[0])
      const deepKey = convertToNpsScript(keyParts)
 
      const isStartScript = scriptKey.indexOf('start') === 0
      const defaultDeepKey = isStartScript ?
        convertToNpsScript([
          'default',
          ...keyParts.slice(1, keyParts.length),
          'default',
        ]) :
        `${deepKey}.default`
 
      let script = scripts[scriptKey]
      if (!isKeyScriptHook) {
        const {preHook, postHook} = getPrePostHooks(
          scripts,
          scriptKey,
          deepKey,
        )
        if (isNpmRunCommand(script)) {
          script = convertToNpsCommand(script)
        }
        script = `${preHook}${script}${postHook}`
      }
      set(obj, defaultDeepKey, script)
      return obj
    }, {})
  // traverse the object and replace all objects that
  // only have `default` with just the script itself.
  traverse(defaultedScripts, removeDefaultOnly)
  return defaultedScripts
 
  function removeDefaultOnly(key, value, object) {
    if (isOnlyDefault(value)) {
      object[key] = value.default
    }
  }
}
 
function traverse(object, fn) {
  each(object, (value, key) => {
    // we don't need to worry about a recursive structure in this case
    fn(key, value, object)
    value = object[key] // may have changed from `fn`
    if (isPlainObject(value)) {
      traverse(value, fn)
    }
  })
}
 
function getCoreScripts(scripts = {}) {
  const DEFAULT_CORE_SCRIPTS = {
    start: 'nps',
    test: scripts.test ? 'nps test' : undefined,
  }
  const coreScripts = Object.keys(scripts).reduce((result, scriptKey) => {
    if (!isNotCoreScript(scriptKey)) {
      result[scriptKey] = scripts[scriptKey]
    }
    return result
  }, {})
  return Object.assign(DEFAULT_CORE_SCRIPTS, coreScripts)
}
 
function convertToNpsCommand(npmRunCommand) {
  const [, , commandToRun, , ...args] = npmRunCommand.split(' ')
  const hasArgs = args.length > 0
  let npsScript = convertToNpsScript(commandToRun.split(':'))
  if (hasArgs) {
    const npsScriptArgs = args.join(' ')
    npsScript = `"${npsScript} ${npsScriptArgs}"`
  }
  return `nps ${npsScript}`
}
 
function getPrePostHooks(scripts, scriptKey, deepKey) {
  const preHook = scripts[`pre${scriptKey}`] ? `nps pre${deepKey} && ` : ''
  const postHook = scripts[`post${scriptKey}`] ? ` && nps post${deepKey}` : ''
  return {
    preHook,
    postHook,
  }
}
 
function convertToNpsScript(keyParts) {
  return keyParts.map(key => camelCase(key)).join('.')
}
 
function isOnlyDefault(script) {
  return (
    isPlainObject(script) && Object.keys(script).length === 1 && script.default
  )
}
 
function isScriptHook(script) {
  return script.indexOf('pre') === 0 || script.indexOf('post') === 0
}
 
function isNotCoreScript(script) {
  return !includes(CORE_SCRIPTS, script)
}
 
function isNpmRunCommand(script) {
  return startsWith(script.trim(), 'npm run')
}