All files / src/bin-utils get-script-by-prefix.js

100% Statements 30/30
100% Branches 20/20
100% Functions 3/3
100% Lines 30/30
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                        22x 9x           13x 12x 4x   8x 8x 8x             1x       23x 9x 14x 13x 4x   9x   1x         22x     22x 22x 19x 19x 19x 19x 16x   4x           12x             22x 15x 15x   7x    
import prefixMatches from 'prefix-matches'
import {keys, isPlainObject, isString, has} from 'lodash'
 
/*
  Converts a string or object with a "script" key into an object with
   {
    name,
    script,
    description
   }
*/
export function scriptToObject(name, scriptArg) {
  if (isString(scriptArg)) {
    return {
      name,
      script: scriptArg,
      description: '',
    }
  }
  if (isPlainObject(scriptArg)) {
    if (has(scriptArg, 'default')) {
      return scriptToObject(`${name}.default`, scriptArg.default)
    } else {
      const description = scriptArg.description || ''
      const script = scriptArg.script
      return {
        name,
        description,
        script,
      }
    }
  }
  return null
}
 
function isValidScript(script) {
  if (isString(script)) {
    return true
  } else if (isPlainObject(script)) {
    if (has(script, 'default')) {
      return isValidScript(script.default)
    }
    return has(script, 'script')
  } else {
    return false
  }
}
 
export default function getScriptByPrefix({scripts}, prefix) {
  const matches = prefixMatches(prefix, scripts)
  // This array holds all the valid scripts in
  // the order of priority (default scripts have lowest priority)
  const matchedScriptsSortedByPriority = []
  for (const match of matches) {
    const matchedKeys = keys(match)
    const name = matchedKeys[0]
    const script = match[name]
    if (isValidScript(script)) {
      if (has(script, 'default')) {
        // if it's a default script, push to the last of the array
        matchedScriptsSortedByPriority.push({
          name,
          script,
        })
      } else {
        // if it's not a default script, push to the first of the array
        matchedScriptsSortedByPriority.unshift({
          name,
          script,
        })
      }
    }
  }
  if (matchedScriptsSortedByPriority.length) {
    const {name, script} = matchedScriptsSortedByPriority[0]
    return scriptToObject(name, script)
  }
  return null
}