All files / src/bin-utils autocomplete-get-scripts.js

100% Statements 23/23
100% Branches 19/19
100% Functions 4/4
100% Lines 23/23
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                2x         33x 33x   98x 98x 98x 98x 98x 98x 98x 56x   42x       42x   42x 20x 8x   20x 18x   20x 22x 21x   42x         42x    
import {
  includes,
  kebabCase,
  camelCase,
  isPlainObject,
  startsWith,
} from 'lodash'
 
const excludedKeys = ['default', 'script', 'description', 'hiddenFromHelp']
 
export default getScripts
 
function getScripts(objWithScripts, prefix = '') {
  const [prefixToMatch, ...remainingToMatch] = prefix.split('.')
  return Object.keys(objWithScripts).reduce((acc, key) => {
    /* eslint complexity:0 */
    const kebabKey = kebabCase(key)
    const camelKey = camelCase(key)
    const startsWithKey = startsWith(key, prefixToMatch)
    const startsWithKebab = startsWith(kebabKey, prefixToMatch)
    const startsWithCamel = startsWith(camelKey, prefixToMatch)
    const startMatches = startsWithKey || startsWithKebab || startsWithCamel
    if (!startMatches || includes(excludedKeys, key)) {
      return acc
    }
    const value = objWithScripts[key]
 
    // default to kebab-case
    // eslint-disable-next-line
    const keyToPush = !isKebab(prefixToMatch) ? camelKey : kebabKey;
 
    if (isPlainObject(value)) {
      if ((value.default || value.script) && !remainingToMatch.length) {
        acc.push(keyToPush)
      }
      const subscripts = getScripts(value, remainingToMatch.join('.')).map(
        scriptName => `${keyToPush}.${scriptName}`,
      )
      acc = [...acc, ...subscripts]
    } else if (!remainingToMatch.length) {
      acc.push(keyToPush)
    }
    return acc
  }, [])
}
 
function isKebab(str) {
  return includes(str, '-')
}