env-sentinel
Version:
Zero-dependency tool that auto-validates .env files against schema.env, with optional fallback and secure warnings.
37 lines (36 loc) • 1.43 kB
JavaScript
export function parseArguments(argv, expectedArgsWithDefaults) {
const parsedArgumentsMap = new Map();
const args = argv.slice(2);
const expectedKeys = expectedArgsWithDefaults ? Object.keys(expectedArgsWithDefaults) : [];
const command = args[0]?.startsWith('--') ? undefined : args[0];
parsedArgumentsMap.set('command', command ?? expectedArgsWithDefaults?.command);
args.forEach((arg, index) => {
if (!arg.startsWith('-')) {
return;
}
let argumentName;
let argumentValue;
if (arg.includes('=')) {
const [argNameRaw, argValueRaw] = arg.split('=');
argumentName = argNameRaw.replace(/^--?/, '');
argumentValue = argValueRaw;
}
else {
argumentName = arg.replace(/^--?/, '');
const positionalArgument = args[index + 1];
if ((positionalArgument ?? '').startsWith('-')) {
argumentValue = true;
}
else {
argumentValue = positionalArgument;
}
}
if (expectedKeys.includes(argumentName) && argumentValue !== undefined) {
parsedArgumentsMap.set(argumentName, argumentValue);
}
});
return Object.fromEntries(expectedKeys.map((key) => [
key,
parsedArgumentsMap.has(key) ? parsedArgumentsMap.get(key) : expectedArgsWithDefaults?.[key],
]));
}