smortex / yaml-sort

Sort lines in YAML files in a predictable order
MIT License
4 stars 0 forks source link

Option to ignore merge keys? #32

Open gstokkink opened 1 year ago

gstokkink commented 1 year ago

Right now, when you try to sort a YAML file that contains a merge key using, e.g., a YAML alias, you get the following error message:

test.yml:8: '<<:' references are not sortable:
  <<: *foo
  ^~~

An option to ignore such merge keys would be nice to have. Now YAML files containing merge keys cannot be sorted at all.

smortex commented 1 year ago

I guess we can do some sorting, e.g. when given:

data:
  d: d
  a: a
  <<: *foo
  c: c
  b: b

we can generate:

data:
  a: a
  d: d
  <<: *foo
  b: b
  c: c

That is sort each group of items between the beginning of a dictionary, the end of a dictionary, or a reference. << would act as a stop token when sorting.

Would that work for you? Do you see any pitfall?

gstokkink commented 1 year ago

@smortex I think I would prefer to sort the merge keys to the top of the hash, then sort the rest. So something like this:

 data:
  <<: *foo
  a: a
  b: b
  c: c
  d: d

Reason being that we do not know exactly what is being merged, plus I think it's the idiom to keep merge keys to the top.

@OtherCroissant what do you think?

smortex commented 1 year ago

In that case, that would break things like:

foo: &foo
  a: 42
data:
  d: d
  a: a
  <<: *foo
  c: c
  b: b

here, data.a = 42, but with your sorting, data.a = "a":

foo: &foo
  a: 42
data:
  <<: *foo
  a: a
  b: b
  c: c
  d: d

Also, the "correct" sorting should output data before foo, and this reordering is not possible with merges… Maybe there is no reliable sorting mechanism that can exist for this use case…

OtherCroissant commented 1 year ago

I agree that changing the position of the merge will change its meaning and outcome of the evaluation. Keeping the merge keys on top of the list could also be seen as a convention and the rest still works if the suggested group sorting is implemented.

gstokkink commented 1 year ago

@smortex ah, you are right, I did not consider the overriding of existing keys. Then yeah, your proposed solution is the best one. Keep the merge keys on top.