Skip to content

Commit

Permalink
Fix sorting "first" keys for inline tables
Browse files Browse the repository at this point in the history
Previously, sorting inline tables would throw a ValueError if the key in
the table had trailing spaces.

For example:

  [a]
  b = {c=1, d = 3}

Sorting a.b with "d" first would fail.

Removing the space would "pass":

  [a]
  b = {c=1, d=3}

However, when the table was written back out, rerunning toml-sort would
fail because the keys are written with surrounding spaces:

  [a]
  b = {c = 1, d = 3}

When commit 9900c71 was introduced, the value used for the index
lookup in the list of "first" keys changed to be `Key.as_string()`.

The intent was probably to pass type checks as the list of keys are
strings and mypy complains when doing an index lookup that doesn't match
the typing of the list elements (str vs Key).

However, `as_string()` uses the "original" value of the key which
includes spaces and is subtlely different than the check performed
on the previous line that checked if the value was in the list.

Both the `in` keyword and the `list.index` method use the equality
operation to evaluate if a value is in a list.

The `Key` object defines the `__eq__` method that compares the internal
key value (which is stripped) to the other value. This is why the `in`
lookup succeeds but the `index` lookup fails.

Now, the lookup logic is simplified.

Instead of potentially searching the list of "first" keys twice, once
via `in` and once via `list.index`, iterate the list via `enumerate` to
keep track of the index and perform an explicit equality check against
`Key.key` which appeases mypy.

Fixes: 9900c71 ("Modernize tests, fix test errors")
Closes: #76
Signed-off-by: Vincent Fazio <[email protected]>
  • Loading branch information
vfazio committed Nov 19, 2024
1 parent 4ba1cbd commit 9027991
Showing 1 changed file with 3 additions and 2 deletions.
5 changes: 3 additions & 2 deletions toml_sort/tomlsort.py
Original file line number Diff line number Diff line change
Expand Up @@ -430,8 +430,9 @@ def sort_keys(
"""

def sort_first(item: TomlSortItem) -> int:
if item.keys.base in sort_config.first:
return sort_config.first.index(item.keys.base.as_string())
for index, value in enumerate(sort_config.first):
if value == item.keys.base.key:
return index
return len(sort_config.first)

items = sorted(items, key=self.key_sort_func)
Expand Down

0 comments on commit 9027991

Please sign in to comment.