google / jsonnet

Jsonnet - The data templating language
http://jsonnet.org
Apache License 2.0
6.98k stars 440 forks source link

Is it possible to interpolate nested object? #983

Open pombadev opened 2 years ago

pombadev commented 2 years ago

My jsonnet file looks like this.

local constants = {
  sys: {
    os: 'linux',
    arch: ['amd64', 'x86_64'],
  },
};

{
  prefix: '~/.local',
  packages: [
    {
      local version = '1.18',

      name: 'golang',
      version: version,
      file: 'go%(version)s.%(sys.os)s-%(sys.arch[0])s.tar.gz' % { version: version } + constants,
      description: 'The Go programming language.',
      url: 'https://dl.google.com/go/' + self.file,
      prebuild: "curl -LO '%(url)s'" % self,

      build: |||
        rm -rf %(prefix)s/go
        tar -C %(prefix)s -xzf %(file)s
      ||| % { prefix: $.prefix, url: $.packages[0].file },
    },
  ],
}

I'm trying to access nested field but get an error:

...
file: 'go%(version)s.%(sys.os)s-%(sys.arch[0])s.tar.gz' % { version: version } + constants,
...

Error:

RUNTIME ERROR: No such field: sys.os

Expected:

file: "go1.18.linux-amd64.tar.gz"
johnbartholomew commented 8 months ago

Unfortunately, no. The format operator % / format function std.format do not perform full expression interpolation, they only look up the specified key in a flat object. This is the same as the Python 2 string-formatting % operator (https://docs.python.org/2/library/stdtypes.html#string-formatting-operations).

There was a related feature request from several years ago, #45, asking to add support for ES6 backtick strings (aka template literals).

(I'm aware this question was from a while ago, but perhaps having an answer will be useful for someone in the future)

CertainLach commented 8 months ago

std.format supports nested objects: https://github.com/google/jsonnet/pull/1011 But syntax is limited to only objects, no array access.

johnbartholomew commented 8 months ago

std.format supports nested objects: #1011

Oh, huh... that's interesting. I did not realize that. Thanks for the correction!

johnbartholomew commented 8 months ago

Hmm... it looks like that feature was reverted: https://github.com/google/jsonnet/pull/1099