Home Assistant Unofficial Reference 2024.12.1
ensure_config.py
Go to the documentation of this file.
1 """Script to ensure a configuration file exists."""
2 
3 import argparse
4 import asyncio
5 import os
6 
7 import homeassistant.config as config_util
8 from homeassistant.core import HomeAssistant
9 
10 # mypy: allow-untyped-calls, allow-untyped-defs
11 
12 
13 def run(args):
14  """Handle ensure config commandline script."""
15  parser = argparse.ArgumentParser(
16  description="Ensure a Home Assistant config exists, creates one if necessary."
17  )
18  parser.add_argument(
19  "-c",
20  "--config",
21  metavar="path_to_config_dir",
22  default=config_util.get_default_config_dir(),
23  help="Directory that contains the Home Assistant configuration",
24  )
25  parser.add_argument("--script", choices=["ensure_config"])
26 
27  args = parser.parse_args()
28 
29  config_dir = os.path.join(os.getcwd(), args.config)
30 
31  # Test if configuration directory exists
32  if not os.path.isdir(config_dir):
33  print("Creating directory", config_dir)
34  os.makedirs(config_dir, exist_ok=True)
35 
36  config_path = asyncio.run(async_run(config_dir))
37  print("Configuration file:", config_path)
38  return 0
39 
40 
41 async def async_run(config_dir):
42  """Make sure config exists."""
43  hass = HomeAssistant(config_dir)
44  path = await config_util.async_ensure_config_exists(hass)
45  await hass.async_stop(force=True)
46  return path