From 90279917a9c44bc90f3c5e795c4b2d8a4c440af0 Mon Sep 17 00:00:00 2001 From: Vincent Fazio Date: Tue, 19 Nov 2024 06:16:08 -0600 Subject: [PATCH] Fix sorting "first" keys for inline tables 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 9900c719e0e7 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: 9900c719e0e7 ("Modernize tests, fix test errors") Closes: https://github.com/pappasam/toml-sort/issues/76 Signed-off-by: Vincent Fazio --- toml_sort/tomlsort.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/toml_sort/tomlsort.py b/toml_sort/tomlsort.py index 3c66927..25a0339 100644 --- a/toml_sort/tomlsort.py +++ b/toml_sort/tomlsort.py @@ -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)