From 1eecc33ef67d346556c060975d530820fb12e996 Mon Sep 17 00:00:00 2001 From: Ole Herman Schumacher Elgesem Date: Wed, 18 Jun 2025 13:09:12 +0200 Subject: [PATCH] pretty_file: Added detection whether reformatting is necessary Signed-off-by: Ole Herman Schumacher Elgesem --- cfbs/pretty.py | 11 +++++++---- tests/test_pretty.py | 13 +++++++++++-- 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/cfbs/pretty.py b/cfbs/pretty.py index e83fe45e..0c415c19 100644 --- a/cfbs/pretty.py +++ b/cfbs/pretty.py @@ -201,10 +201,13 @@ def pretty_check_string(s, sorting_rules=None): def pretty_file(filename, sorting_rules=None): with open(filename) as f: - data = pretty_string(f.read(), sorting_rules) - with open(filename, "w") as f: - f.write(data) - f.write("\n") + old_data = f.read() + new_data = pretty_string(old_data, sorting_rules) + "\n" + if old_data != new_data: + with open(filename, "w") as f: + f.write(new_data) + return True + return False def pretty_string(s, sorting_rules=None): diff --git a/tests/test_pretty.py b/tests/test_pretty.py index fc774f6e..712c1a77 100644 --- a/tests/test_pretty.py +++ b/tests/test_pretty.py @@ -1,6 +1,6 @@ from collections import OrderedDict -from cfbs.pretty import pretty, pretty_check_string, pretty_string -from cfbs.utils import item_index +from cfbs.pretty import pretty, pretty_check_string, pretty_string, pretty_file +from cfbs.utils import item_index, mkdir, read_file def test_pretty(): @@ -205,6 +205,15 @@ def test_pretty_string(): assert pretty_string(test) == expected +def test_pretty_file(): + mkdir("tests/tmp/", exist_ok=True) + with open("tests/tmp/test_pretty_file.json", "w") as f: + f.write(" {} \n") + assert pretty_file("tests/tmp/test_pretty_file.json") == True + assert read_file("tests/tmp/test_pretty_file.json") == "{}\n" + assert pretty_file("tests/tmp/test_pretty_file.json") == False + + def test_pretty_check_string(): assert pretty_check_string(' "Hello" ') == False assert pretty_check_string('"Hello"') == True