google / yamlfmt

An extensible command line tool or library to format yaml files.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Last list item if commented will be indented two spaces after formatting

djgoku opened this issue · comments

Originally posted here: #74 (comment)

input yaml:

repos:
  - repo: https://github.com/antonbabenko/pre-commit-terraform
    rev: v1.77.2
    hooks:
      # - id: infracost_breakdown
      - id: terraform_fmt
      # - id: terraform_providers_lock
      - id: terraform_validate
      # - id: terrascan

output yaml:

repos:
  - repo: https://github.com/antonbabenko/pre-commit-terraform
    rev: v1.77.2
    hooks:
      # - id: infracost_breakdown
      - id: terraform_fmt
      # - id: terraform_providers_lock
      - id: terraform_validate
        # - id: terrascan <-- two leading spaces

Hi @djgoku I apologize for the delay in addressing the issue. I haven't had time to look at this project for the last month, but I finally had some time to check today.

This is a really funky edge case with the go-yaml libraries way of parsing comments. I know what the bug is, but I don't have a fix for it right now.

What's happening here is that when the comment is at the end of the array (in YAML syntax grammar called a "mapping block") it does not get rendered properly. I don't know if this is as a hack or for some genuine grammar reason, but when the parser encounters a foot comment for a mapping block like this, it forces it to be the foot comment of the key of the last item in the mapping block, so in this case the id in the last non-comment item. That's why it gets aligned like this. Under some scenarios, it might get mistakenly scanned as the foot comment for hooks and get moved back a tab too.

I couldn't figure out how to fix it while working yesterday but I will try to fix it soon.