继承jsonnet库

时间:2019-09-04 08:35:16

标签: inheritance import jsonnet

我对JSONNet的import功能有疑问。我希望要导入的是一个主libsonnet文件,该文件本身由多个导入组成,并且能够访问该导入中的所有内容。

我具有以下示例结构:

.
├── library_one
│   └── init.libsonnet
├── library_two
│   └── init.libsonnet
├── init.libsonnet
└── test.jsonnet

每个文件具有以下内容:

library_one / init.libsonnet

{
  local LibraryOne = self,

  some_function(some_argument='default'):: [
    'echo "The argument was %s"' % some_argument,
  ],
}

library_two / init.libsonnet

{
  local LibraryTwo = self,

  some_other_function(some_other_argument='another_default'):: [
    'echo "The other argument was %s"' % some_other_argument,
  ],
}

最后,在根目录下的“主​​”文件 init.libsonnet

local library_one = import 'library_one/init.libsonnet';
local library_two = import 'library_two/init.libsonnet';

{}

但是,当我运行具有以下内容的文件 test.jsonnnet 时:

local master = import 'init.libsonnet';

{
  some_key: master.library_one.some_function,
  some_other_key: master.library_two.some_other_function,
}

我得到了错误:

RUNTIME ERROR: field does not exist: library_one
    test.jsonnet:4:13-31    object <anonymous>
    During manifestation

这种继承不可能吗?

2 个答案:

答案 0 :(得分:2)

local符号不会导出,因为本质上不是“全局”作用域,而是{...}主要对象的字段:

  

已修改的源以使用主要对象字段:

::::::::::::::
library_one/init.libsonnet
::::::::::::::
{
  local LibraryOne = self,

  some_function(some_argument='default'):: [
    'echo "The argument was %s"' % some_argument,
  ],
}
::::::::::::::
library_two/init.libsonnet
::::::::::::::
{
  local LibraryTwo = self,

  some_other_function(some_other_argument='another_default'):: [
    'echo "The other argument was %s"' % some_other_argument,
  ],
}
::::::::::::::
init.libsonnet
::::::::::::::
{
  library_one:: import 'library_one/init.libsonnet',
  library_two:: import 'library_two/init.libsonnet',
}
::::::::::::::
test.jsonnet
::::::::::::::
local master = import 'init.libsonnet';

{
  some_key:: master.library_one.some_function,
  some_other_key:: master.library_two.some_other_function,

  foo: $.some_key("bar")
}
  

示例输出:

{
   "foo": [
      "echo \"The argument was bar\""
   ]
}

答案 1 :(得分:2)

请先看看@jjo的答案。

我只是想补充一下,构造您的库是可行且合理的,这样您就可以使用一个对象来进行本地“声明”,然后对其进行“导出”,我认为这与您所描述的类似。 / p>

library.libsonnet

local sqr(x) = x * x;

local cube(x): x * x * x;

{
    sqr: sqr,
    cube: cube,
}

然后您可以像这样使用

local lib = import 'library.libsonnet';

[
    lib.sqr(2),
    lib.cube(3) + lib.sqr(4),
]

这种风格也可以很好地表现出来。您可以在此处查看一个真实的示例:https://github.com/sbarzowski/jsonnet-modifiers/blob/master/modifiers.libsonnet

对于“主库”,您实际上可以将这些部分一起添加到您的 init.libsonnet 中:

local library_one = import 'library_one/init.libsonnet';
local library_two = import 'library_two/init.libsonnet';

library_one + library_two

如果library_one和library_two包含相同的字段,则library_two将优先。您可以在官方网站https://jsonnet.org/learning/tutorial.html#oo上的Jsonnet中了解有关继承规则的更多信息。