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

Breaking TOML list syntax #10

Closed brylie-wolt closed 1 year ago

brylie-wolt commented 1 year ago

The keep-sorted pre-commit hook is breaking TOML lists, such as in pyproject.toml, by removing the trailing square brackets:

# keep-sorted start
"app.namespace1" = [
    "A",
    "B",
    "C",
-]
"app.namespace2" = [
    "A",
    "B",
    "Q"
-]
# keep-sorted end
JeffFaer commented 1 year ago

Yep! This is an unfortunate consequence of how keep-sorted is generally language agnostic. It doesn't really understand the syntax of the files it's operating on, so it tends to do things that are syntactically invalid because it's a pretty "dumb" tool. In this case, keep-sorted is removing the trailing square brackets because of its duplicate handling (I'm assuming that it's actually removing all but 1 square bracket, and it's sorting that last remaining square bracket to the top of your keep-sorted section).

I see a couple options here:

  1. You could use keep-sorted within each individual list:
"app.namespace1" = [
  # keep-sorted start
  "A",
  "B", 
  "C",
  # keep-sorted end
]
"app.namespace2" = [
  # keep-sorted start
  "A",
  "B",
  "Q"
  # keep-sorted end
]
  1. If you want to sort the "app.namespaceN bits, you might want to use block=yes instead:
# keep-sorted start block=yes
"app.namespace1" = [
   "A",
   "B",
   "C",
]
"app.namespace2" = [
   "A",
   "B",
   "Q"
]
# keep-sorted end

Note: keep-sorted doesn't yet support nested keep-sorted sections, so you won't be able to enforce both. There's an internal bug for that feature, but I wouldn't mind one here in Github as well is this is something that you'd want

brylie-wolt commented 1 year ago

Thanks for your help. Yes, I believe we're more interested in block-level sorting since the sub-lists tend to be fairly short.

JeffFaer commented 1 year ago

I'll close this out then. Feel free to open a new issue or reopen and repurpose this one as a FR for nested keep-sorted blocks if you do end up wanting that behavior.