什么是使用 JSON 表示命令行参数的好方法
What is a good way to represent command-line arguments with JSON?
我正在尝试改进 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']
相关文章:
- 如何在router.get()方法中传递url作为参数
- 我们可以用参数对象集合而不是原始数据来调用JavaScript collection.reduce()方法吗
- 如何在扩展jQuery方法时传递参数
- 使构造函数参数具有ES6类方法的特权
- 如何将javascript变量作为参数提供给asp.net方法
- 如何确保函数/方法参数为certian类型
- 克服错误的更优雅的方法是什么:需要对象说明符.当通过JXA通过Messages发送SMS时,参数没有对象说明符
- 如何使用JavaScript's”;应用“;方法,在数组之前添加一个额外的参数
- 在嵌套递归指令中将参数传递给父控制器方法
- 理解日期对象接收参数时的getDay()方法
- sinon.js验证mock方法's带回调的参数
- 在带有参数列表的表单submit上调用一个方法
- 什么's是调用具有可变参数的函数的有效方法
- 为什么参数对象没有在控制台中显示它的方法
- 将参数传递到外部 JS 脚本的最佳方法
- 我怎么能读“;.on()"jQuery中的方法参数
- 在coffeescript中链接jquery方法和参数
- 如何在从排序方法调用参数时将其传递给回调
- 使用表单和POST方法通过Javascript获取URL参数
- PageMethods调用使用1参数成功,但在2上失败(未知web方法)