什么是使用 JSON 表示命令行参数的好方法

What is a good way to represent command-line arguments with JSON?

本文关键字:参数 方法 命令行 表示 JSON 什么      更新时间:2023-09-26

我正在尝试改进 grunt-closure-linter npm 项目(这样我实际上可以以富有成效的方式使用它(,这就是我现在坚持的地方:

我想指定一种将选项传递到命令行的方法,gjslint命令行是闭包 Linter 的驱动程序。

USAGE: /usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/bin/gjslint [flags]
flags:
closure_linter.checker:
  --closurized_namespaces: Namespace prefixes, used for testing ofgoog.provide/require
    (default: '')
    (a comma separated list)
  --ignored_extra_namespaces: Fully qualified namespaces that should be not be reported as extra
    by the linter.
    (default: '')
    (a comma separated list)
closure_linter.common.simplefileflags:
  -e,--exclude_directories: Exclude the specified directories (only applicable along with -r or
    --presubmit)
    (default: '_demos')
    (a comma separated list)
  -x,--exclude_files: Exclude the specified files
    (default: 'deps.js')
    (a comma separated list)
  -r,--recurse: Recurse in to the subdirectories of the given path;
    repeat this option to specify a list of values
closure_linter.ecmalintrules:
  --custom_jsdoc_tags: Extra jsdoc tags to allow
    (default: '')
    (a comma separated list)
closure_linter.error_check:
  --jslint_error: List of specific lint errors to check. Here is a list of accepted values:
    - all: enables all following errors.
    - blank_lines_at_top_level: validatesnum
...

如您所见,这东西有很多选择!

繁重的任务非常简洁,所以我很快就能够找到将其注入命令行以完成此操作的位置,但是我想知道如何最好地转换一个理智的 JSON 表示形式,例如

{
    "max_line_length": '120',
    "summary": true
}

到命令行选项字符串中:

--max_line_length 120 --summary

甚至不清楚是否有任何标准方法可以用 JSON 表示它。我确实想到,其他人可能认为使用值true指定一个普通的无参数参数是不理智的。

我想我想我可以回到一个更明确但更不结构化的

[ "--max_line_length", "120", "--summary" ]

或诸如此类,尽管考虑到我会多么想避免逗号和引号并将其保留为普通字符串,这几乎不切实际。

这应该如何定义?

我已经调整了我的模块 dargs,它将选项对象转换为命令行参数数组,用于您的用例。

只需将带有骆驼键的对象传递给它,它将完成其余的工作。

function toArgs(options) {
    var args = [];
    Object.keys(options).forEach(function (key) {
        var flag;
        var val = options[key];
        flag = key.replace(/[A-Z]/g, '_$&').toLowerCase();
        if (val === true) {
            args.push('--' + flag);
        }
        if (typeof val === 'string') {
            args.push('--' + flag, val);
        }
        if (typeof val === 'number' && isNaN(val) === false) {
            args.push('--' + flag, '' + val);
        }
        if (Array.isArray(val)) {
            val.forEach(function (arrVal) {
                args.push('--' + flag, arrVal);
            });
        }
    });
    return args;
};

例:

toArgs({ maxLineLength: 120 });

输出:

['--max_line_length', '120']