Coverage for src/somesy/commands/init_config.py: 98%
42 statements
« prev ^ index » next coverage.py v7.16.0, created at 2026-11-09 13:08 +0000
« prev ^ index » next coverage.py v7.16.0, created at 2026-11-09 13:08 +0000
1"""CLI command to initialize somesy configuration file."""
3import logging
4from pathlib import Path
6import tomlkit
7from pydantic import BaseModel
9from somesy.core.core import atomic_write
10from somesy.core.log import VERBOSE
11from somesy.core.models import ProjectMetadata, SomesyConfig, SomesyInput
13logger = logging.getLogger("somesy")
16def write_somesy_file(
17 metadata: ProjectMetadata,
18 path: Path = Path("somesy.toml"),
19 *,
20 config: SomesyConfig | None = None,
21 overwrite: bool = False,
22) -> None:
23 """Write project metadata to a standalone ``somesy.toml`` file."""
24 if path.exists() and not overwrite:
25 raise FileExistsError(f"Output file already exists: {path}")
27 content = {
28 "project": BaseModel.model_dump(
29 metadata,
30 mode="json",
31 by_alias=True,
32 exclude_defaults=True,
33 exclude_none=True,
34 )
35 }
36 if config is not None:
37 content["config"] = config.model_dump(mode="json", by_alias=True)
38 atomic_write(path, tomlkit.dumps(content), exclusive=not overwrite)
41def init_config(input_path: Path, options: dict) -> None:
42 """Initialize somesy configuration file.
44 Args:
45 input_path (Path): Path to somesy file (will be created/overwritten).
46 options (dict): CLI options.
48 """
49 logger.info(f"Updating input file ({input_path}) with CLI configurations...")
51 is_somesy = SomesyInput.is_somesy_file_path(input_path)
52 if input_path.exists():
53 # read directly: get_input_content refuses files without a somesy section
54 with open(input_path, encoding="utf-8") as f:
55 content = tomlkit.load(f)
56 elif is_somesy:
57 content = tomlkit.document()
58 else:
59 raise FileNotFoundError(f"Input file not found: {input_path}")
61 input_file_type = "somesy" if is_somesy else "pyproject"
62 msg = f"Found input file with {input_file_type} format."
63 logger.log(VERBOSE, msg)
65 logger.debug(f"Input file content: {options}")
67 options.pop("input_file", None)
68 if is_somesy:
69 table = content
70 else:
71 if "tool" not in content:
72 content["tool"] = tomlkit.table(is_super_table=True)
73 if "somesy" not in content["tool"]:
74 content["tool"]["somesy"] = tomlkit.table()
75 table = content["tool"]["somesy"]
76 # merge into the existing table, keeping keys that were not prompted for
77 if "config" not in table:
78 table["config"] = tomlkit.table()
79 table["config"].update(options)
81 atomic_write(input_path, tomlkit.dumps(content))
83 logger.info(f"Input file ({input_path}) updated.")
84 logger.debug(f"Input file content: {content}")