con2 / emrichen

A Template engine for YAML & JSON
MIT License
107 stars 11 forks source link

Help with !If omitting value in flow style list #40

Closed TroyNeubauer closed 3 years ago

TroyNeubauer commented 3 years ago

I have recently been using emrichen to template yml concourse configuration files but I have run into a snag with !If. I want to be able to omit a value in a list based on a variable. Here is the file I'm trying to template:

resources:
  - name: gitflow-test-git
    type: git
    icon: github
    source:
      uri: <SNIP>
      branch: master
      username: concourse
      password: <SNIP>

jobs:
  - name: build
    public: true
    plan:
      - get: gitflow-test-git
        trigger: true
      - task: build
        file: gitflow-test-git/ci/build.yml
        params:
          VERSION: !Var VERSION
          VERSION_MAJOR: !Var VERSION_MAJOR
          VERSION_MINOR: !Var VERSION_MINOR
          VERSION_PATCH: !Var VERSION_PATCH
          BRANCH: !Var BRANCH

      !If
        test: !Op [master, eq, !Var BRANCH]
        then:
          - task: deploy-prod
            file: gitflow-test-git/ci/deploy-prod.yml
        else: !Void

Ignoring the concourse jargon I want to be able to omit the deploy-prod task when branch resolves to non-master. I have been able to get the !If block to work when it is the only thing in the file. Eg:

echo "!If
           test: !Op [master, eq, !Var BRANCH]
           then:
             - task: deploy-prod
               file: gitflow-test-git/ci/deploy-prod.yml
           else: !Void" | emrichen --define "BRANCH=master"

resolves correctly to

- task: deploy-prod
  file: gitflow-test-git/ci/deploy-prod.yml

or

This may or not be a bug, I am somewhat new to yml and even newer to emrichen so please let me know the correct usage to achieve my desired functionality.

japsu commented 3 years ago

Hi @TroyNeubauer!

Try this:

jobs:
  - name: build
    public: true
    plan:
      - get: gitflow-test-git
        trigger: true
      - task: build
        file: gitflow-test-git/ci/build.yml
        params:
          VERSION: !Var VERSION
          VERSION_MAJOR: !Var VERSION_MAJOR
          VERSION_MINOR: !Var VERSION_MINOR
          VERSION_PATCH: !Var VERSION_PATCH
          BRANCH: !Var BRANCH

      - !If
          test: !Op [master, eq, !Var BRANCH]
          then:
            task: deploy-prod
            file: gitflow-test-git/ci/deploy-prod.yml

!If emits a special value called !Void when the test is false. That special value is then erased from the list when it is outputted. It works similarly in dicts/object: consider eg.

foo: !Void
bar: 5

only produces bar: 5 without any foo.

Please close if this solved your problem!

TroyNeubauer commented 3 years ago

This worked like a charm. Thanks for your help!