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

36 statements  

« prev     ^ index     » next       coverage.py v7.16.0, created at 2026-09-08 11:27 +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, 

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 with open(path, "w" if overwrite else "x") as file: 

39 tomlkit.dump(content, file) 

40 

41 

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

43 """Initialize somesy configuration file. 

44 

45 Args: 

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

47 options (dict): CLI options. 

48 

49 """ 

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

51 

52 content = get_input_content(input_path, no_unwrap=True) 

53 

54 is_somesy = SomesyInput.is_somesy_file_path(input_path) 

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

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

57 logger.log(VERBOSE, msg) 

58 

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

60 

61 options.pop("input_file", None) 

62 if is_somesy: 

63 content["config"] = options 

64 else: 

65 if "tool" not in content: 

66 content["tool"] = {} 

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

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

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

70 

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

72 tomlkit.dump(content, f) 

73 

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

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