bazel-contrib / rules_jsonnet

Jsonnet rules for Bazel
https://bazelbuild.github.io/rules_jsonnet/
Apache License 2.0
68 stars 73 forks source link

Include example on jsonnet library with absolute path #88

Closed borg286 closed 5 years ago

borg286 commented 5 years ago

Currently importing libraries that are not under the current folder seems to require references that walk up and down the directory tree (../../../). If paths from the workspace root is available please document how to do this.

borg286 commented 5 years ago

After some playing I've found that it is possible to have jsonnet files used as libraries. In this repo they seem to call them libsonnet, but there doesn't seem to be much difference. A libsonnet seems to be a jsonnet file that outputs a top level json object. Inside this object there are functions that can be called. This json file is then imported into a variable. Thus after the import you can reference the variable then use . to get at the inner functions.

The key to making a jsonnet file a library that is in one folder in the bazel workspace and use it in another and not use relative paths is to wrap the jsonnet file in jsonnet_library, passing the jsonnet file in as the srcs. In the place where you want to use it, like a jsonnet_to_json is to pass this library target into the deps field. Then in the jsonnet where you import it you can either specify a local file OR the path to the file from the workspace root. For external libraries like https://github.com/bitnami-labs/kube-libsonnet that have no BUILD file I had to create one myself.

new_http_archive( name = "kube_jsonnet", url = "https://github.com/bitnami-labs/kube-libsonnet/archive/d30a2d7fd5c6686b5a2aeda914533530e26019e0.tar.gz", strip_prefix = "kube-libsonnet-d30a2d7fd5c6686b5a2aeda914533530e26019e0", build_file_content = """ package(default_visibility = ["//visibility:public"]) load("@io_bazel_rules_jsonnet//jsonnet:jsonnet.bzl", "jsonnet_library") jsonnet_library( name = "kube_lib", srcs = ["kube.libsonnet"], ) """, )

This resulted in a build target I could access like jsonnet_to_json( name = "kube-job", src = "job.jsonnet", deps = ["@kube_jsonnet//:kube_lib"], ... )

And then I could import it like this in my jsonnet

local kube = import 'external/kube_jsonnet/kube.libsonnet'; { "my-depl.json": kube.Deployment("bla"){...}, }

Another issue put here is that someone didn't want to use the external reference, but that seems acceptable so that I can distinguish between internal libraries and external ones.