Skip to content

Commit

Permalink
Made cfbs pretty also sort module entries inside "build" array
Browse files Browse the repository at this point in the history
Signed-off-by: Ole Herman Schumacher Elgesem <ole.elgesem@northern.tech>
  • Loading branch information
olehermanse committed Nov 29, 2023
1 parent b773c1d commit b807248
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 10 deletions.
25 changes: 17 additions & 8 deletions cfbs/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,19 +97,28 @@ def pretty_command(filenames: list, check: bool, keep_order: bool) -> int:

cfbs_sorting_rules = None
if not keep_order:
# These sorting rules acchieve 3 things:
# 1. Top level keys are sorted according to a specified list
# 2. Module names in "index" and "provides" are sorted alphabetically
# 3. Fields inside module objects are sorted according to a specified list
# for "index", "provides", and "build"

module_key_sorting = (
MODULE_KEYS,
None,
)
cfbs_sorting_rules = {
None: (
TOP_LEVEL_KEYS,
{
"(index|provides)": (
"alphabetic",
{
".*": (
MODULE_KEYS,
None,
)
},
)
"alphabetic", # Module names are sorted alphabetically
{".*": module_key_sorting},
),
"build": ( # An array, not an object
None, # Don't sort elements of array
{".*": module_key_sorting},
),
},
),
}
Expand Down
21 changes: 19 additions & 2 deletions cfbs/pretty.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,24 @@ def _children_sort(child, name, sorting_rules):
Only JSON objects (dictionaries) are sorted by this function, arrays are ignored.
"""
assert type(child) == OrderedDict
if type(child) is not OrderedDict:
return

for key in child:
if type(child[key]) not in (list, tuple):
continue
if name not in sorting_rules:
continue
if key not in sorting_rules[name][1]:
continue
print("Found list: " + key)
rules = sorting_rules[name][1][key][1]
print(pretty(rules))
if key in sorting_rules:
print("sorting_rules found for " + key)
for element in child[key]:
if type(element) is OrderedDict:
_children_sort(element, key, rules)

rules = None
if name in sorting_rules.keys():
Expand Down Expand Up @@ -111,7 +128,7 @@ def _item_index(iterable, item, extra_at_end=True):
# a tuple of strings to sort by this order
if child_key_fn == "alphabetic":
child_key_fn = lambda x: x[0]
if type(child_key_fn) is tuple:
if type(child_key_fn) in (tuple, list):
values = copy(child_key_fn)
child_key_fn = lambda x: _item_index(values, x[0])

Expand Down

0 comments on commit b807248

Please sign in to comment.