Skip to content

Commit 5dfd1cb

Browse files
Don't modify empty files if unchanged
1 parent 3487cc1 commit 5dfd1cb

3 files changed

Lines changed: 18 additions & 2 deletions

File tree

src/usethis/_integrations/file/yaml/io_.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -474,7 +474,12 @@ def edit_yaml(
474474
except YAMLError as err:
475475
msg = f"Error reading '{yaml_path}':\n{err}"
476476
raise YAMLDecodeError(msg) from None
477+
478+
start_empty = not yaml_document.content
477479
yield yaml_document
480+
if start_empty and not yaml_document.content:
481+
# No change
482+
return
478483
yaml_document.roundtripper.dump(yaml_document.content, stream=yaml_path)
479484

480485

src/usethis/_integrations/pre_commit/io_.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ def edit_pre_commit_config_yaml() -> Generator[PreCommitConfigYAMLDocument, None
6262

6363
def _validate_config(ruamel_content: YAMLLiteral) -> JsonSchemaForPreCommitConfigYaml:
6464
if isinstance(ruamel_content, CommentedMap) and not ruamel_content:
65-
ruamel_content["repos"] = []
65+
ruamel_content = CommentedMap({"repos": []})
6666

6767
try:
6868
return JsonSchemaForPreCommitConfigYaml.model_validate(ruamel_content)

tests/usethis/_integrations/pre_commit/test_pre_commit_io_.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ def test_unchanged(self, tmp_path: Path):
3030
# Assert
3131
assert (tmp_path / ".pre-commit-config.yaml").read_text() == content_str
3232

33-
def test_empty_is_valid(self, tmp_path: Path):
33+
def test_start_with_empty_file(self, tmp_path: Path):
3434
# Arrange
3535
(tmp_path / ".pre-commit-config.yaml").write_text("")
3636

@@ -43,3 +43,14 @@ def test_empty_is_valid(self, tmp_path: Path):
4343

4444
# Assert
4545
assert (tmp_path / ".pre-commit-config.yaml").read_text() == "repos: []\n"
46+
47+
def test_empty_valid_but_unchanged(self, tmp_path: Path):
48+
# Arrange
49+
(tmp_path / ".pre-commit-config.yaml").write_text("")
50+
51+
# Act
52+
with change_cwd(tmp_path), edit_pre_commit_config_yaml():
53+
pass
54+
55+
# Assert
56+
assert (tmp_path / ".pre-commit-config.yaml").read_text() == ""

0 commit comments

Comments
 (0)