2021-03-11 01:20:53 +01:00
|
|
|
import * as log from 'loglevel';
|
|
|
|
|
|
|
|
import { isWindows } from '../helpers/helpers';
|
|
|
|
|
|
|
|
export function parseBoolean(
|
2021-06-16 04:20:49 +02:00
|
|
|
val: boolean | string | number | undefined,
|
2021-03-11 01:20:53 +01:00
|
|
|
_default: boolean,
|
|
|
|
): boolean {
|
2021-06-16 04:20:49 +02:00
|
|
|
if (val === undefined) {
|
|
|
|
return _default;
|
|
|
|
}
|
2021-03-11 01:20:53 +01:00
|
|
|
try {
|
|
|
|
if (typeof val === 'boolean') {
|
|
|
|
return val;
|
|
|
|
}
|
|
|
|
val = String(val);
|
|
|
|
switch (val.toLocaleLowerCase()) {
|
|
|
|
case 'true':
|
|
|
|
case '1':
|
|
|
|
case 'yes':
|
|
|
|
return true;
|
|
|
|
case 'false':
|
|
|
|
case '0':
|
|
|
|
case 'no':
|
|
|
|
return false;
|
|
|
|
default:
|
|
|
|
return _default;
|
|
|
|
}
|
2021-06-16 04:20:49 +02:00
|
|
|
} catch {
|
2021-03-11 01:20:53 +01:00
|
|
|
return _default;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export function parseBooleanOrString(val: string): boolean | string {
|
|
|
|
switch (val) {
|
|
|
|
case 'true':
|
|
|
|
return true;
|
|
|
|
case 'false':
|
|
|
|
return false;
|
|
|
|
default:
|
|
|
|
return val;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-06-16 04:20:49 +02:00
|
|
|
export function parseJson<Type>(val: string): Type | undefined {
|
|
|
|
if (!val) return undefined;
|
2021-03-11 01:20:53 +01:00
|
|
|
try {
|
2021-06-16 04:20:49 +02:00
|
|
|
return JSON.parse(val) as Type;
|
|
|
|
} catch (err: unknown) {
|
2021-03-11 01:20:53 +01:00
|
|
|
const windowsShellHint = isWindows()
|
|
|
|
? `\n In particular, Windows cmd doesn't have single quotes, so you have to use only double-quotes plus escaping: "{\\"someKey\\": \\"someValue\\"}"`
|
|
|
|
: '';
|
|
|
|
|
|
|
|
log.error(
|
|
|
|
`Unable to parse JSON value: ${val}\n` +
|
|
|
|
`JSON should look like {"someString": "someValue", "someBoolean": true, "someArray": [1,2,3]}.\n` +
|
|
|
|
` - Only double quotes are allowed, single quotes are not.\n` +
|
|
|
|
` - Learn how your shell behaves and escapes characters.${windowsShellHint}\n` +
|
|
|
|
` - If unsure, validate your JSON using an online service.`,
|
|
|
|
);
|
|
|
|
throw err;
|
|
|
|
}
|
|
|
|
}
|