如何在jq

时间:2019-06-05 21:01:45

标签: module jq dependency-management

从1.5版开始,jq data processing language具有library module system。一个模块由可选的元数据和一组功能组成。例如

module { name: "util", version: "1.0.0" };
def digitsum: tostring|split("")|map(tonumber)|add;
存储为文件util.jq

可以这样使用:

$ echo '789' | jq -L. 'include "util"; digitsum'
24

模块可以使用其他模块,并且modulemeta指令可以跟踪依赖关系,但是如何表达和检查模块编号的最低版本?例如:

module {
  name: "math",
  version: "0.1.0",
};

include "util"; # TODO: require at least version 1.0.0!

def digitroot:
  (.|digitsum) as $sum |
  if $sum<10 then $sum else $sum|digitroot end;

1 个答案:

答案 0 :(得分:2)

目前(2019年6月)对jq中的模块的支持仍然很少,尽管在github上有jq的模块管理系统:https://github.com/joelpurra/jqnpm

不使用这样的外部模块管理系统,jq本身可以做什么?扩展给定的示例,以下说明了一种支持版本要求的方法。请注意dependencies模块的元数据中名为math的附加键。 (当前,由于jq覆盖,因此无法将其命名为deps。)

文件

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) '