目前(2019年6月),jq对模块的支持仍然非常有限,但是在github上有一个用于管理jq模块的模块管理系统:
https://github.com/joelpurra/jqnpm
如果不使用这样的外部模块管理系统,jq本身能做些什么?通过扩展给定的示例,以下是支持版本要求的一种方法。请注意,在
math
模块的元数据中有一个名为
dependencies
的附加键。(目前,此键不能命名为
deps
,因为jq会覆盖它。)
文件
dependencies.jq
# Recursively check specified version constraints
module { name: "dependencies", version: "0.0.2" };
# parents of a module as defined by its .deps
def parents:
. as $in
| if type == "array" then map(parents) | add
else modulemeta | .deps | map(.relpath)
end ;
# ancestors of a single module or an array of modules.
# The array of "ancestors" of a module includes itself.
def ancestors:
# input and $visited should be arrays of strings
def ancestors($visited):
. as $in
| ($in - $visited) as $new
| if $new == [] then $visited
else $new | parents | ancestors($visited + $new | unique)
end;
if type == "array" then . else [.] end
| ancestors([]) ;
def versionsort:
def parse:
sub("(?<a>(alpha|beta|gamma))"; "\(.a).")
| [splits("[-.]")]
| map(tonumber?
sort_by(parse);
# Input: a module name
# Emit empty if the constraints for the given module are satisfied, otherwise raise an error
def dependencies($version):
def le($y): (. == $y) or ([.,$y] | . == versionsort);
modulemeta
| .version as $mv
| if (($mv == null) or ($version | le($mv))) then empty
else ("module \(.name) dependencies version \($version) vs \($mv)" | error)
end ;
# Input: a module name or array of module names
# Check the module-version dependencies in .dependencies, proceeding up the chain as defined by .deps
def dependencies:
def check:
modulemeta
| select(has("dependencies"))
| all( .dependencies | to_entries[];
.key as $m | .value as $v | ($m | dependencies($v) ))
| empty;
ancestors[] | check;
util.jq
module { name: "util", version: "1.0.0" };
def digitsum: tostring|split("")|map(tonumber)|add;
math.jq
module {
name: "math",
version: "0.1.0",
dependencies: {"util": "1.0.0"} };
include "util" ;
def digitroot:
digitsum as $sum
| if $sum<10 then $sum
else $sum|digitroot
end;
调用
jq -n -L . '
include "dependencies";
include "math";
"math" | dependencies,
(123|digitroot) '
deps
代替require.jq
和check
)和结构(元数据字段require
应该是一个对象而不是一个数组,check
函数也应该接受一个数组)。 - Jakobdependencies
,因为这样更容易记住,而且该字段在 npm 的package.json
中也是这样使用的。 - Jakob