Coverage for src/somesy/core/core.py: 78%

45 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-08-10 14:33 +0000

1"""Core somesy functions.""" 

2import json 

3import logging 

4from pathlib import Path 

5from typing import Any, Dict, Optional 

6 

7import tomlkit 

8 

9logger = logging.getLogger("somesy") 

10 

11INPUT_FILES_ORDERED = [".somesy.toml", "somesy.toml", "pyproject.toml", "package.json"] 

12"""Input files ordered by priority for discovery.""" 

13 

14 

15def discover_input(input_file: Optional[Path] = None) -> Path: 

16 """Check given input file path. If not given, find somesy configuration file path from default list. 

17 

18 Args: 

19 input_file: somesy configuration file path. Defaults to None. 

20 

21 Raises: 

22 FileNotFoundError: Raised if no somesy input file found from cli input or the defaults. 

23 

24 Returns: 

25 somesy configuration file path. 

26 """ 

27 if input_file: 

28 if input_file.is_file(): 

29 logger.info(f"Using provided file '{input_file}' as somesy input file.") 

30 return input_file 

31 else: 

32 msg = f"Passed file '{input_file}' does not exist. Searching for usable somesy input file..." 

33 logger.verbose(msg) 

34 

35 for filename in INPUT_FILES_ORDERED: 

36 input_file = Path(filename) 

37 if input_file.is_file(): 

38 try: 

39 get_input_content(input_file) 

40 except RuntimeError: 

41 continue 

42 

43 msg = f"Using '{input_file}' as somesy input file." 

44 logger.verbose(msg) 

45 return input_file 

46 

47 raise FileNotFoundError("No somesy input file found.") 

48 

49 

50def get_input_content(path: Path, *, no_unwrap: bool = False) -> Dict[str, Any]: 

51 """Read contents of a supported somesy input file. 

52 

53 Given a path to a TOML file, this function reads the file and returns its content as a TOMLDocument object. 

54 The function checks if the file is a valid somesy input file by checking its name and content. 

55 

56 Args: 

57 path (Path): path to the input file 

58 

59 Returns: 

60 the content of the input file as a TOMLDocument object 

61 

62 Raises: 

63 ValueError: if the input file is not a valid somesy input file or if the file is not a TOML file. 

64 RuntimeError: if the input file does not contain a somesy input section at expected key 

65 """ 

66 logger.debug(f"Path {path}") 

67 # somesy.toml / .somesy.toml 

68 if path.suffix == ".toml" and "somesy" in path.name: 

69 with open(path, "r") as f: 

70 ret = tomlkit.load(f) 

71 return ret if no_unwrap else ret.unwrap() 

72 

73 # pyproject.toml 

74 if path.suffix == ".toml" and "pyproject" in path.name: 

75 with open(path, "r") as f: 

76 input_content = tomlkit.load(f) 

77 if "tool" in input_content and "somesy" in input_content["tool"]: 

78 return input_content["tool"]["somesy"].unwrap() 

79 else: 

80 raise RuntimeError( 

81 "No tool.somesy section found in pyproject.toml file!" 

82 ) 

83 

84 if path.suffix == ".json" and "package" in path.name: 

85 with open(path, "r") as f: 

86 input_content = json.load(f) 

87 if "somesy" in input_content: 

88 return input_content["somesy"] 

89 else: 

90 raise RuntimeError("No somesy section found in package.json file!") 

91 

92 # no match: 

93 raise ValueError("Unsupported input file.")