# All files / src parse.ts

95.47% Statements 190/199
79.31% Branches 46/58
87.5% Functions 7/8
95.47% Lines 190/199

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
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    2001x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    24x
    24x
    24x
    24x
    24x
    24x
    24x
    24x
    24x
    24x
    24x
    24x
    24x
    24x
    24x
    1x
    1x
    1x
    1x
    1x
    1x
    24x
    24x
    24x
    24x
    24x
    12x
    12x
    12x
    12x
    12x
    12x
    12x
    12x
    12x
    12x
    12x
    12x
    12x
    12x
    12x
    12x
    12x
    24x
    24x
    24x
    24x
    2x
    2x
    2x
    1x
    1x
    24x
    5x

    5x
    5x
    5x
    5x
    5x
    5x
    5x
    5x
    23x
    23x
    23x
    23x
    23x
    23x
    24x
    4x
    24x
    19x

    19x
    19x
    19x
    24x
    1x
    5x
    5x
    5x
    5x
    5x
    5x
    5x
    5x

    5x
    2x
    5x
    3x
    5x
    5x
    1x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x
    81x
    81x
    39x
    81x
    42x
    81x
    2x
    2x
    2x
    2x
    2x
    2x
    1x
    10x
    10x
    10x
    1x
    5x
    5x
    5x
    10x
    10x
    10x
    10x
    10x
    10x
    5x
    5x
    1x
    5x
    5x
    2x
    2x
    2x
    2x
    2x
    5x
    1x
    24x
    24x
    24x
    24x
    21x
    9x
    9x
    9x
    21x
    21x
    24x
    24x
     import {
        ArgumentConfig,
        ParseOptions,
        UnknownProperties,
        CommandLineOption,
        UsageGuideOptions,
        Content,
        CommandLineResults,
        ExitReason,
    } from './contracts';
    import commandLineArgs from 'command-line-args';
    import commandLineUsage from 'command-line-usage';
    import {
        createCommandLineConfig,
        getBooleanValues,
        mergeConfig,
        normaliseConfig,
        removeBooleanValues,
        visit,
    } from './helpers';
    import { addOptions, getOptionFooterSection, getOptionSections } from './helpers/options.helper';
    import { removeAdditionalFormatting } from './helpers/string.helper';
    import { readFileSync } from 'fs';
    import { resolve } from 'path';

    /**
     * parses command line arguments and returns an object with all the arguments in IF all required options passed
     * @param config the argument config. Required, used to determine what arguments are expected
     * @param options
     * @param exitProcess defaults to true. The process will exit if any required arguments are omitted
     * @param addCommandLineResults defaults to false. If passed an additional _commandLineResults object will be returned in the result
     * @returns
     */
    export function parse<T, P extends ParseOptions<T> = ParseOptions<T>, R extends boolean = false>(
        config: ArgumentConfig<T>,
        options: P = {} as any,
        exitProcess = true,
        addCommandLineResults?: R,
    ): T & UnknownProperties<P> & CommandLineResults<R> {
        options = options || {};
        const argsWithBooleanValues = options.argv || process.argv.slice(2);
        const logger = options.logger || console;
        const normalisedConfig = normaliseConfig(config);
        options.argv = removeBooleanValues(argsWithBooleanValues, normalisedConfig);
        const optionList = createCommandLineConfig(normalisedConfig);
        let parsedArgs = commandLineArgs(optionList, options) as any;

        if (parsedArgs['_all'] != null) {
            const unknown = parsedArgs['_unknown'];
            parsedArgs = parsedArgs['_all'];
            if (unknown) {
                parsedArgs['_unknown'] = unknown;
            }
        }

        const booleanValues = getBooleanValues(argsWithBooleanValues, normalisedConfig);
        parsedArgs = { ...parsedArgs, ...booleanValues };

        if (options.loadFromFileArg != null && parsedArgs[options.loadFromFileArg] != null) {
            const configFromFile: Partial<Record<keyof T, any>> = JSON.parse(
                readFileSync(resolve(parsedArgs[options.loadFromFileArg])).toString(),
            );
            const parsedArgsWithoutDefaults = commandLineArgs(
                // eslint-disable-next-line @typescript-eslint/no-unused-vars
                optionList.map(({ defaultValue, ...option }) => ({ ...option })),
                options,
            ) as any;

            parsedArgs = mergeConfig<T>(
                parsedArgs,
                { ...parsedArgsWithoutDefaults, ...booleanValues },
                configFromFile,
                normalisedConfig,
                options.loadFromFileJsonPathArg as keyof T | undefined,
            );
        }

        const missingArgs = listMissingArgs(optionList, parsedArgs);

        if (options.helpArg != null && (parsedArgs as any)[options.helpArg]) {
            printHelpGuide(options, optionList, logger);

            if (exitProcess) {
                return process.exit(resolveExitCode(options, 'usageGuide', parsedArgs, missingArgs));
            }
        } else if (missingArgs.length > 0) {
            if (options.showHelpWhenArgsMissing) {
                const missingArgsHeader =
                    typeof options.helpWhenArgMissingHeader === 'function'
                        ? options.helpWhenArgMissingHeader(missingArgs)
                        : options.helpWhenArgMissingHeader;
                const additionalHeaderSections: Content[] = missingArgsHeader != null ? [missingArgsHeader] : [];
                printHelpGuide(options, optionList, logger, additionalHeaderSections);
            } else if (options.hideMissingArgMessages !== true) {
                printMissingArgErrors(missingArgs, logger, options.baseCommand);
                printUsageGuideMessage(
                    { ...options, logger },
                    options.helpArg != null ? optionList.filter((option) => option.name === options.helpArg)[0] : undefined,
                );
            }
        }

        const _commandLineResults = {
            missingArgs: missingArgs,
            printHelp: () => printHelpGuide(options, optionList, logger),
        };

        if (missingArgs.length > 0 && exitProcess) {
            process.exit(resolveExitCode(options, 'missingArgs', parsedArgs, missingArgs));
        } else {
            if (addCommandLineResults) {
                parsedArgs = { ...parsedArgs, _commandLineResults };
            }

            return parsedArgs as T & UnknownProperties<P> & CommandLineResults<R>;
        }
    }

    function resolveExitCode<T>(
        options: ParseOptions<T>,
        reason: ExitReason,
        passedArgs: Partial<T>,
        missingArgs: CommandLineOption<T>[],
    ): number {
        switch (typeof options.processExitCode) {
            case 'number':
                return options.processExitCode;
            case 'function':
                return options.processExitCode(reason, passedArgs, missingArgs as any);
            default:
                return 0;
        }
    }

    function printHelpGuide<T>(
        options: ParseOptions<T>,
        optionList: CommandLineOption<T>[],
        logger: Console,
        additionalHeaderSections: Content[] = [],
    ) {
        const sections = [
            ...additionalHeaderSections,
            ...(options.headerContentSections?.filter(filterCliSections) || []),
            ...getOptionSections(options).map((option) => addOptions(option, optionList, options)),
            ...getOptionFooterSection(optionList, options),
            ...(options.footerContentSections?.filter(filterCliSections) || []),
        ];

        visit(sections, (value) => {
            switch (typeof value) {
                case 'string':
                    return removeAdditionalFormatting(value);
                default:
                    return value;
            }
        });

        const usageGuide = commandLineUsage(sections);

        logger.log(usageGuide);
    }

    function filterCliSections(section: Content): boolean {
        return section.includeIn == null || section.includeIn === 'both' || section.includeIn === 'cli';
    }

    function printMissingArgErrors(missingArgs: CommandLineOption[], logger: Console, baseCommand?: string) {
        baseCommand = baseCommand ? `${baseCommand} ` : ``;
        missingArgs.forEach((config) => {
            const aliasMessage = config.alias != null ? ` or '${baseCommand}-${config.alias} passedValue'` : ``;
            const runCommand =
                baseCommand !== ''
                    ? `running '${baseCommand}--${config.name}=passedValue'${aliasMessage}`
                    : `passing '--${config.name}=passedValue'${aliasMessage} in command line arguments`;
            logger.error(`Required parameter '${config.name}' was not passed. Please provide a value by ${runCommand}`);
        });
    }

    function printUsageGuideMessage(options: UsageGuideOptions & { logger: Console }, helpParam?: CommandLineOption) {
        if (helpParam != null) {
            const helpArg = helpParam.alias != null ? `-${helpParam.alias}` : `--${helpParam.name}`;
            const command = options.baseCommand != null ? `run '${options.baseCommand} ${helpArg}'` : `pass '${helpArg}'`;

            options.logger.log(`To view the help guide ${command}`);
        }
    }

    function listMissingArgs(commandLineConfig: CommandLineOption[], parsedArgs: commandLineArgs.CommandLineOptions) {
        return commandLineConfig
            .filter((config) => config.optional == null && parsedArgs[config.name] == null)
            .filter((config) => {
                if (config.type.name === 'Boolean') {
                    parsedArgs[config.name] = false;
                    return false;
                }

                return true;
            });
    }