Christian Müller
Christian Müller

Reputation: 25

How to get all subdirectories in jsonnet?

I'm creating a gitlab-ci.yml file dynamically with jsonnet. Now I want to create a job for each directory in my customers-directory. For that I want to read all directory names into an array.

How do I do that?

Pseudo code would look like this: customers:: [c for c in getAllDirectories("path/to/customers-directory")]

Thank you very much!

Upvotes: 0

Views: 1146

Answers (1)

jjo
jjo

Reputation: 3020

By design jsonnet doesn't have any means to read "environmental data" (broadly speaking: files/dirs/devices, env vars, etc). It does, however, provide ways for "injecting" this data via CLI args, please do read https://jsonnet.org/learning/tutorial.html#parameterize-entire-config for details.

In your case, this could be achieved by the below example code:

Test dirs

$ mkdir -p /tmp/customers.d/{foo,bar,baz}
$ ls -F /tmp/customers.d/
bar/  baz/  foo/

Code (dirs.jsonnet)

// Expect ext-var containing new-line separated list of dirs
local customers = std.split(std.extVar('customers'), '\n');

customers

CLI run and output

$ jsonnet --ext-str customers="$(find /tmp/customers.d/ -mindepth 1 -maxdepth 1 -type d -printf '%f\n')" dirs.jsonnet
[
   "bar",
   "foo",
   "baz"
]

Upvotes: 1

Related Questions