All files / check-installed/lib getOptions.js

100% Statements 17/17
100% Branches 15/15
100% Functions 2/2
100% Lines 16/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 433x               30x   30x 33x 29x 29x 29x     29x         24x 18x 6x 4x       24x 16x           30x     3x      
const { OPTIONS } = require('./constants')
 
/**
 * Get check-installed options from CLI arguments
 * @param {string[]} args - CLI arguments
 * @returns {Partial<typeof OPTIONS>} - Options for the CLI with defaults
 */
function getOptions (args = []) {
  const options = {}
 
  for (const arg of args) {
    if (arg.startsWith('--')) {
      const [key, value] = arg.slice(2).split('=')
      const keyCamelCase = key.replace(/-([a-z])/g, (_, c) => c.toUpperCase())
      const option = OPTIONS[keyCamelCase]
 
      // Only set if the option is defined in `OPTIONS`
      if (option !== undefined) {
        let newValue
 
        // If boolean, `true` only if no value or value is "true"
        // Otherwise, only if value provided
        if (typeof option === 'boolean') {
          newValue = value == null ? true : value === 'true'
        } else if (value != null) {
          newValue = value
        }
 
        // Set only if valid and not already default
        if (newValue !== undefined && newValue !== option) {
          options[keyCamelCase] = newValue
        }
      }
    }
  }
 
  return options
}
 
module.exports = {
  getOptions
}