diff --git a/homeassistant/config.py b/homeassistant/config.py index d22df2184f6..c5f29f3c3c1 100644 --- a/homeassistant/config.py +++ b/homeassistant/config.py @@ -291,23 +291,28 @@ def _write_default_config(config_dir: str) -> bool: with open(config_path, "wt") as config_file: config_file.write(DEFAULT_CONFIG) - with open(secret_path, "wt") as secret_file: - secret_file.write(DEFAULT_SECRETS) + if not os.path.isfile(secret_path): + with open(secret_path, "wt") as secret_file: + secret_file.write(DEFAULT_SECRETS) with open(version_path, "wt") as version_file: version_file.write(__version__) - with open(group_yaml_path, "wt"): - pass + if not os.path.isfile(group_yaml_path): + with open(group_yaml_path, "wt"): + pass - with open(automation_yaml_path, "wt") as fil: - fil.write("[]") + if not os.path.isfile(automation_yaml_path): + with open(automation_yaml_path, "wt") as automation_file: + automation_file.write("[]") - with open(script_yaml_path, "wt"): - pass + if not os.path.isfile(script_yaml_path): + with open(script_yaml_path, "wt"): + pass - with open(scene_yaml_path, "wt"): - pass + if not os.path.isfile(scene_yaml_path): + with open(scene_yaml_path, "wt"): + pass return True diff --git a/tests/test_config.py b/tests/test_config.py index 7da8d8c2f67..76218ab5bf2 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -115,6 +115,19 @@ async def test_ensure_config_exists_uses_existing_config(hass): assert content == "" +async def test_ensure_existing_files_is_not_overwritten(hass): + """Test that calling async_create_default_config does not overwrite existing files.""" + create_file(SECRET_PATH) + + await config_util.async_create_default_config(hass) + + with open(SECRET_PATH) as fp: + content = fp.read() + + # File created with create_file are empty + assert content == "" + + def test_load_yaml_config_converts_empty_files_to_dict(): """Test that loading an empty file returns an empty dict.""" create_file(YAML_PATH)