默认导入器使用相对于导入它们的文件的路径。如果evaluate_snippet
您需要手动传递路径。这样 jsonnet 就知道在哪里查找导入的文件。
如果您打算处理文件,您可以使用自定义导入器。(题外话:jsonnet 试图避免对源文件进行预处理,所以可能有更好的方法或者 jsonnet 中缺少的特性。)
下面是关于如何在 Python 中使用自定义导入器的完整工作示例(根据提供的目录结构进行了调整):
import os
import unittest
import _jsonnet
# Returns content if worked, None if file not found, or throws an exception
def try_path(dir, rel):
if not rel:
raise RuntimeError('Got invalid filename (empty string).')
if rel[0] == '/':
full_path = rel
else:
full_path = dir + rel
if full_path[-1] == '/':
raise RuntimeError('Attempted to import a directory')
if not os.path.isfile(full_path):
return full_path, None
with open(full_path) as f:
return full_path, f.read()
def import_callback(dir, rel):
full_path, content = try_path(dir, rel)
if content:
return full_path, content
raise RuntimeError('File not found')
class JsonnetTests(unittest.TestCase):
def setUp(self):
self.input_filename = os.path.join(
"jsonnet",
"bar.jsonnet",
)
self.expected_str = '{\n "num": 42,\n "str": "The answer to life ..."\n}\n'
with open(self.input_filename, "r") as infile:
self.input_snippet = infile.read()
def test_evaluate_file(self):
json_str = _jsonnet.evaluate_file(
self.input_filename,
import_callback=import_callback,
)
self.assertEqual(json_str, self.expected_str)
def test_evaluate_snippet(self):
json_str = _jsonnet.evaluate_snippet(
"jsonnet/bar.jsonnet",
self.input_snippet,
import_callback=import_callback,
)
self.assertEqual(json_str, self.expected_str)
if __name__ == '__main__':
unittest.main()
注意:这是jsonnet repo 中示例的修改版本。