tweag / nickel

Better configuration for less
https://nickel-lang.org/
MIT License
2.23k stars 85 forks source link

Output query results as JSON #1976

Open GuillaumeDesforges opened 1 week ago

GuillaumeDesforges commented 1 week ago

Is your feature request related to a problem? Please describe. I need to programmatically list top-level fields of a nickel program.

$ nickel query cbuild.ncl
warning: empty query path
 = You queried a value without requesting a specific field path. This operation can't find any metadata, beside listing the fields of a record.
 = Try to query the root configuration and provide a query path instead.
 = For example, instead of querying the expression `(import "config.ncl").module.input` with an empty path, query `config.ncl` with the `module.input` path: 
   `nickel query config.ncl --field module.input

Available fields
• hello
No metadata found for this field.

It is too hard to parse in my script.

Describe the solution you'd like

$ nickel query --json cbuild.ncl
{"fields":["hello"]}

Additional context I'm calling nickel as a subprocess.

suimong commented 1 week ago

As a workaround, you could write another nickel program extract_toplevel_fields.ncl like this:

let record = import "cbuild.ncl" in {
  fields = record |> std.record.fields   # or std.record.fields_with_opts
}

Then nickel export extract_toplevel_fields.ncl.

In case you'd like to specify the file being imported at runtime, which is not directly supported by nickel, just template the whole program, making the filename part a template variable, use whatever string templating mechanism available in your PL to render the program and pipe into nickel export.

Heck you could even do all that with Nickel alone:

# extract_toplevel_fields.ncl
{
    filename,
    program | force = "let record = import \"%{filename}\" in {fields = record |> std.record.fields}"
}

Then invoke the following:

nickel export toplevel_fields.ncl --field=program --format=raw -- filename="cbuild.ncl" | nickel export
GuillaumeDesforges commented 1 week ago

Thanks for the workaround.

I do want to emphasize that facilitating the interoperability of tools like Nickel with scripting would be a good plus.

Since there is a --error-format on most commands and --format for the export command, I think it also makes sense to provide --format for query command.

suimong commented 1 week ago

I second your proposal. It would be very helpful if outputs of nickel query can be easily machine readable. Though this might require a little bit of designing with regard to the "schema" of the output, among other things. What do you think @yannham ?