google / keep-sorted

keep-sorted is a language-agnostic formatter that sorts lines between two markers in a larger file.
Apache License 2.0
132 stars 15 forks source link

FR: Sort simple YAML, à la block=yes #36

Closed thiagowfx closed 5 months ago

thiagowfx commented 5 months ago

Similarly to the basic block=yes construct for JSON, it would be nice if we could express the following intent with keep-sorted:

  # keep-sorted start block=yes
  - name: argo
    type: helm
    url: https://argoproj.github.io/argo-helm
  - name: foo
    type: helm
    url: https://argoproj.github.io/argo-foo
  # keep-sorted end block=yes

...in this example the list is already sorted (by name).

Perhaps block is too overloaded, it could be called yaml if so:

 # keep-sorted start yaml=yes
  - name: argo
    type: helm
    url: https://argoproj.github.io/argo-helm
  - name: foo
    type: helm
    url: https://argoproj.github.io/argo-foo
  # keep-sorted end yaml=yes

...the expectation would be to sort by the first key/property (in this case, name).

This would only make sense for simple (flattened) YAML lists like the above. For nested or overly complex ones, keep-sorted would be overkill and probably not the right tool for the job.

I do realize this may be totally out of scope of keep-sorted though; if so, feel free to close it as won't fix. I included lots of details to make it easier for others to find this FR in case they have the same idea.

JeffFaer commented 5 months ago

This should already work, and I don't think you even need block=yes. The default behavior with line continuations (group=yes) should work here for yaml: https://github.com/google/keep-sorted#line-continuations

$ cat foo
  # keep-sorted start block=yes
  - name: foo
    type: helm
    url: https://argoproj.github.io/argo-foo
  - name: argo
    type: helm
    url: https://argoproj.github.io/argo-helm
  # keep-sorted end
$ keep-sorted --mode=fix -vvv - < foo
  # keep-sorted start block=yes
  - name: argo
    type: helm
    url: https://argoproj.github.io/argo-helm
  - name: foo
    type: helm
    url: https://argoproj.github.io/argo-foo
  # keep-sorted end

removing block=yes:

$ cat foo
  # keep-sorted start
  - name: foo
    type: helm
    url: https://argoproj.github.io/argo-foo
  - name: argo
    type: helm
    url: https://argoproj.github.io/argo-helm
  # keep-sorted end
$ keep-sorted --mode=fix -vvv - < foo
  # keep-sorted start
  - name: argo
    type: helm
    url: https://argoproj.github.io/argo-helm
  - name: foo
    type: helm
    url: https://argoproj.github.io/argo-foo
  # keep-sorted end
thiagowfx commented 5 months ago

You are totally right, this is an unexpected (surprising!) behavior to have out-of-the-box, so it didn't even occur to me to test it, but it's a very benign one! Thanks!

Closing as WAI.