diff --git a/commitizen/config/toml_config.py b/commitizen/config/toml_config.py index 1950cb11d..284e8d41b 100644 --- a/commitizen/config/toml_config.py +++ b/commitizen/config/toml_config.py @@ -1,7 +1,8 @@ +import os from pathlib import Path from typing import Union -from tomlkit import exceptions, parse +from tomlkit import exceptions, parse, table from .base_config import BaseConfig @@ -14,8 +15,17 @@ def __init__(self, *, data: Union[bytes, str], path: Union[Path, str]): self.add_path(path) def init_empty_config_content(self): - with open(self.path, "a") as toml_file: - toml_file.write("[tool.commitizen]") + if os.path.isfile(self.path): + with open(self.path, "rb") as input_toml_file: + parser = parse(input_toml_file.read()) + else: + parser = parse("") + + with open(self.path, "wb") as output_toml_file: + if parser.get("tool") is None: + parser["tool"] = table() + parser["tool"]["commitizen"] = table() + output_toml_file.write(parser.as_string().encode("utf-8")) def set_key(self, key, value): """Set or update a key in the conf. diff --git a/tests/commands/test_init_command.py b/tests/commands/test_init_command.py index 729950fc8..e7f2c00ed 100644 --- a/tests/commands/test_init_command.py +++ b/tests/commands/test_init_command.py @@ -25,6 +25,7 @@ def ask(self): } expected_config = ( + "[tool]\n" "[tool.commitizen]\n" 'name = "cz_conventional_commits"\n' 'version = "0.0.1"\n' diff --git a/tests/test_conf.py b/tests/test_conf.py index ea7b3a3c9..f05603cfe 100644 --- a/tests/test_conf.py +++ b/tests/test_conf.py @@ -132,7 +132,7 @@ def test_init_empty_config_content(self, tmpdir): toml_config.init_empty_config_content() with open(path, "r") as toml_file: - assert toml_file.read() == "[tool.commitizen]" + assert toml_file.read() == "[tool]\n[tool.commitizen]\n" def test_init_empty_config_content_with_existing_content(self, tmpdir): existing_content = "[tool.black]\n" "line-length = 88\n" @@ -143,7 +143,7 @@ def test_init_empty_config_content_with_existing_content(self, tmpdir): toml_config.init_empty_config_content() with open(path, "r") as toml_file: - assert toml_file.read() == existing_content + "[tool.commitizen]" + assert toml_file.read() == existing_content + "\n[tool.commitizen]\n" class TestJsonConfig: