Search code examples
yamlyq

yq - Print a string conditionally


I'm trying to generate a file CHANGELOG.md from a YAML file with mikefarah/yq.

From the following YAML file:

releases:
  - name: v0.0.2
    changes:
      added:
        - Second feature (#3)
  - name: v0.0.1
    changes:
  - name: v0.0.0
    changes:
      added:
        - Bootstrap the project (#1)
        - First feature (#2)

I would like to generate the following:

## v0.0.2
### Added
- Second feature (#3)

## v0.0.1

## v0.0.0
### Added
- Bootstrap the project (#1)
- First feature (#2)

I got a close result with the following recipe:

.releases[] as $release | (
  "## " + $release.name,
  "### Added",
  "- " + $release.changes.added[],
  ""
)

However there is an extra ### Added below ## v1.0.1:

## v0.0.2
### Added
- Second feature (#3)

## v0.0.1
### Added

## v0.0.0
### Added
- Bootstrap the project (#1)
- First feature (#2)

I've tried to make the ### Added conditional by using select and with but didn't succeed (cf. Logic without if/elif/else).
Is there a way to conditionally print the string ### Added?


Solution

  • Try first building the result array, and just then iterate over it:

    .releases[] as $release | (
      "## " + $release.name, (
        $release.changes.added | (
          select(.) | ["### Added"]
        ) + map("- " + .) | .[]
      ),
      ""
    )
    
    ## v0.0.2
    ### Added
    - Second feature (#3)
    
    ## v0.0.1
    
    ## v0.0.0
    ### Added
    - Bootstrap the project (#1)
    - First feature (#2)