Coverage for src/somesy/commands/init_config.py: 47%

36 statements  

« prev     ^ index     » next       coverage.py v7.16.0, created at 2026-09-04 11:35 +0000

1"""CLI command to initialize somesy configuration file.""" 

2 

3import logging 

4from pathlib import Path 

5 

6import tomlkit 

7from pydantic import BaseModel 

8 

9from somesy.core.core import get_input_content 

10from somesy.core.log import VERBOSE 

11from somesy.core.models import ProjectMetadata, SomesyConfig, SomesyInput 

12 

13logger = logging.getLogger("somesy") 

14 

15 

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}") 

26 

27 content = { 

28 "project": BaseModel.model_dump( 

29 metadata, mode="json", by_alias=True, exclude_none=True 

30 ) 

31 } 

32 if config is not None: 

33 content["config"] = config.model_dump(mode="json", by_alias=True) 

34 with open(path, "w" if overwrite else "x") as file: 

35 tomlkit.dump(content, file) 

36 

37 

38def init_config(input_path: Path, options: dict) -> None: 

39 """Initialize somesy configuration file. 

40 

41 Args: 

42 input_path (Path): Path to somesy file (will be created/overwritten). 

43 options (dict): CLI options. 

44 

45 """ 

46 logger.info(f"Updating input file ({input_path}) with CLI configurations...") 

47 

48 content = get_input_content(input_path, no_unwrap=True) 

49 

50 is_somesy = SomesyInput.is_somesy_file_path(input_path) 

51 input_file_type = "somesy" if is_somesy else "pyproject" 

52 msg = f"Found input file with {input_file_type} format." 

53 logger.log(VERBOSE, msg) 

54 

55 logger.debug(f"Input file content: {options}") 

56 

57 options.pop("input_file", None) 

58 if is_somesy: 

59 content["config"] = options 

60 else: 

61 if "tool" not in content: 

62 content["tool"] = {} 

63 if "somesy" not in content["tool"]: 

64 content["tool"]["somesy"] = {} 

65 content["tool"]["somesy"]["config"] = options 

66 

67 with open(input_path, "w") as f: 

68 tomlkit.dump(content, f) 

69 

70 logger.info(f"Input file ({input_path}) updated.") 

71 logger.debug(f"Input file content: {content}")