0

I would like to have the ability to specify different arguments to the imported variable and change the behaviour of import. For example, I would like to have something like the following:

local foo = import "foo.libsonnet";
{
  "foo1": foo["foo1"], 
  "foo2": foo["foo2"]
}

foo.libsonnet: (something like the switch case in programming that has a default value) I know the following should not work. Just maybe pseudocode for what it could be used.

{
  "foo1": "bar1", // only if foo1 is passed
  "foo2": "bar2", // only if foo2 is passed

  "bar1" : "bar1_value",//default 
  "bar2" : "bar2_value" //default 
}

output:

{
"foo1":{
  "foo1": "bar1",
  "bar1": "bar1_value",
  "bar2" : "bar2_value"
  },
"foo2":{
  "foo2": "bar2",
  "bar1": "bar1_value",
  "bar2" : "bar2_value"
  }
}
Ali
  • 1,759
  • 2
  • 32
  • 69

2 Answers2

0

NOTE: below answer tried to address original question, off-topic after it got updated (and reworded)

Just need to make foo.libsonnet a "full-fledged" object (as usually done in practice), note also that your original foo.jsonnet is not a valid construct (using braces as {} for something that resembles a list as []):

$ cat foo.jsonnet 
local foo = import "foo.libsonnet";
[ foo["foo1"], foo["foo2"] ]

$ cat foo.libsonnet 
{
  foo1: "bar1",
  foo2: "bar2",
}

$ jsonnet foo.jsonnet 
[
   "bar1",
   "bar2"
]
jjo
  • 2,595
  • 1
  • 8
  • 16
  • 1
    I think I didn't explain it properly. I have just updated the question. Would you please take a look at that? Thanks – Ali Jul 19 '19 at 00:40
  • @ali-n sure, take a look at that 2nd take, regards --jjo – jjo Jul 21 '19 at 16:10
0

A possible implementation, returning an object with a get() method that implements the "querying" logic:

$ cat foo.jsonnet 
local foo = import "foo.libsonnet";
{
  foo1: foo.get("foo1"),
  foo2: foo.get("foo2"),
  foo3: foo.get("foo3"),
}

$ cat foo.libsonnet 
local data = {
  param_q:: {
    foo1: "bar1",
    foo2: "bar2",
  },
  const:: {
    bar1: "bar1_value",
    bar2: "bar2_value",
  },
};
// Object with get() method to implement parametrized data return
{
  get(q):: (
    // const data
    data.const +
    // parametrized data (if-then-else to support q not in param_q)
    if q in data.param_q then { [q]: data.param_q[q] } else {}
  ),
}

$ jsonnet foo.jsonnet 
{
   "foo1": {
      "bar1": "bar1_value",
      "bar2": "bar2_value",
      "foo1": "bar1"
   },
   "foo2": {
      "bar1": "bar1_value",
      "bar2": "bar2_value",
      "foo2": "bar2"
   },
   "foo3": {
      "bar1": "bar1_value",
      "bar2": "bar2_value"
   }
}
jjo
  • 2,595
  • 1
  • 8
  • 16