|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const _ = require('lodash'); |
| 4 | +const configParser = require('gemini-configparser'); |
| 5 | +const defaults = require('./defaults'); |
| 6 | + |
| 7 | +const thr = (str) => { |
| 8 | + throw new TypeError(str); |
| 9 | +}; |
| 10 | + |
| 11 | +const {root, map, section, option} = configParser; |
| 12 | + |
| 13 | +const ENV_PREFIX = 'hermione_safari_commands_'; |
| 14 | +const CLI_PREFIX = '--hermione-safari-commands-'; |
| 15 | + |
| 16 | +const assertType = (name, validationFn, type) => { |
| 17 | + return (v) => !validationFn(v) && thr(`"${name}" option must be ${type}, but got ${typeof v}`); |
| 18 | +}; |
| 19 | + |
| 20 | +const assertBoolean = (name) => assertType(name, _.isBoolean, 'boolean'); |
| 21 | +const assertArrayOfStrings = (value, name) => { |
| 22 | + if (!(_.isArray(value) && value.every(_.isString))) { |
| 23 | + throw new Error(`"${name}" must be an array of strings but got ${JSON.stringify(value)}`); |
| 24 | + } |
| 25 | +}; |
| 26 | + |
| 27 | +const getParser = () => { |
| 28 | + return root(section({ |
| 29 | + enabled: option({ |
| 30 | + defaultValue: defaults.enabled, |
| 31 | + parseEnv: JSON.parse, |
| 32 | + parseCli: JSON.parse, |
| 33 | + validate: assertBoolean('enabled') |
| 34 | + }), |
| 35 | + browsers: map(section({ |
| 36 | + commands: option({ |
| 37 | + defaultValue: defaults.commands, |
| 38 | + parseEnv: JSON.parse, |
| 39 | + parseCli: JSON.parse, |
| 40 | + validate: (value) => { |
| 41 | + _.isNull(value) |
| 42 | + ? thr('Each browser must have "commands" option') |
| 43 | + : assertArrayOfStrings(value, 'commands'); |
| 44 | + } |
| 45 | + }) |
| 46 | + })) |
| 47 | + }), {envPrefix: ENV_PREFIX, cliPrefix: CLI_PREFIX}); |
| 48 | +}; |
| 49 | + |
| 50 | +module.exports = (options) => { |
| 51 | + const {env, argv} = process; |
| 52 | + |
| 53 | + return getParser()({options, env, argv}); |
| 54 | +}; |
0 commit comments