0

import对 JSONNet 的功能有疑问。我想要是能够导入一个主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

这种继承是不可能的吗?

4

2 回答 2

3

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\""
   ]
}
于 2019-09-04T11:46:14.813 回答
3

请先看看@jjo 的回答。

我只是想补充一点,构建您的库是可能且合理的,以便您拥有本地“声明”,然后使用对象将其“导出”,我相信这与您所描述的相似。

图书馆.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 将优先。您可以在官网阅读更多关于 Jsonnet 中的继承规则:https ://jsonnet.org/learning/tutorial.html#oo 。

于 2019-09-05T10:48:30.210 回答