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

104 statements  

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

1"""Core somesy functions.""" 

2 

3import json 

4import logging 

5import os 

6import stat 

7import tempfile 

8from pathlib import Path 

9from typing import Any 

10 

11import tomlkit 

12 

13from .log import VERBOSE 

14 

15logger = logging.getLogger("somesy") 

16 

17INPUT_FILES_ORDERED = [ 

18 ".somesy.toml", 

19 "somesy.toml", 

20 "pyproject.toml", 

21 "package.json", 

22 "Project.toml", 

23 "fpm.toml", 

24 "Cargo.toml", 

25] 

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

27 

28 

29def atomic_write( 

30 path: Path, 

31 data: str | bytes, 

32 *, 

33 newline: str | None = None, 

34 exclusive: bool = False, 

35) -> None: 

36 """Write a file atomically: a failure never leaves a truncated or partial file. 

37 

38 The data is written to a temporary file in the same directory, which then 

39 replaces the target. The mode of an existing target is kept; text is 

40 encoded as UTF-8. 

41 

42 Args: 

43 path: Target file. 

44 data: Text or bytes to write; serialize before calling. 

45 newline: Newline translation for text, as for `open`. 

46 exclusive: Raise `FileExistsError` instead of replacing an existing file. 

47 

48 """ 

49 path = Path(path) 

50 if exclusive and path.exists(): 

51 raise FileExistsError(f"File already exists: {path}") 

52 if path.is_symlink(): 

53 path = path.resolve() 

54 if path.exists(): 

55 mode = stat.S_IMODE(path.stat().st_mode) 

56 else: 

57 umask = os.umask(0) 

58 os.umask(umask) 

59 mode = 0o666 & ~umask 

60 if not path.parent.exists(): 

61 path.parent.mkdir(parents=True, exist_ok=True) 

62 logger.info(f"Created missing folder '{path.parent}'.") 

63 fd, tmp_name = tempfile.mkstemp( 

64 dir=path.parent, prefix=f".{path.name}.", suffix=".tmp" 

65 ) 

66 try: 

67 if isinstance(data, bytes): 

68 with os.fdopen(fd, "wb") as binary: 

69 binary.write(data) 

70 else: 

71 with os.fdopen(fd, "w", encoding="utf-8", newline=newline) as text: 

72 text.write(data) 

73 os.chmod(tmp_name, mode) 

74 try: 

75 os.replace(tmp_name, path) 

76 except PermissionError as err: 

77 # e.g. on Windows when another program has the target open 

78 if not path.exists(): 

79 raise 

80 try: 

81 if isinstance(data, bytes): 

82 with open(path, "wb") as binary: 

83 binary.write(data) 

84 else: 

85 with open(path, "w", encoding="utf-8", newline=newline) as text: 

86 text.write(data) 

87 except OSError: 

88 raise err from None 

89 logger.warning( 

90 f"File '{path}' could not be replaced, wrote it directly instead." 

91 ) 

92 Path(tmp_name).unlink(missing_ok=True) 

93 except BaseException: 

94 Path(tmp_name).unlink(missing_ok=True) 

95 raise 

96 

97 

98def write_json(data: Any, path: Path) -> None: 

99 """Write data as UTF-8 JSON with 2-space indentation, unescaped non-ASCII and a trailing newline.""" 

100 text = json.dumps(data, ensure_ascii=False, indent=2) + "\n" 

101 atomic_write(path, text, newline="\n") 

102 

103 

104def discover_input(input_file: Path | None = None) -> Path: 

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

106 

107 Args: 

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

109 

110 Raises: 

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

112 

113 Returns: 

114 somesy configuration file path. 

115 

116 """ 

117 missing: Path | None = None 

118 if input_file: 

119 if input_file.is_file(): 

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

121 return input_file 

122 else: 

123 missing = input_file 

124 logger.warning( 

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

126 ) 

127 

128 for filename in INPUT_FILES_ORDERED: 

129 input_file = Path(filename) 

130 if input_file.is_file(): 

131 try: 

132 get_input_content(input_file) 

133 except RuntimeError: 

134 continue 

135 except (ValueError, TypeError, KeyError, OSError) as e: 

136 # NOTE: tomlkit and json parse errors are ValueError subclasses 

137 logger.warning(f"Skipping malformed input file '{input_file}': {e}") 

138 continue 

139 

140 if missing is not None: 

141 logger.warning( 

142 f"Input file '{missing}' does not exist, using '{input_file}' instead." 

143 ) 

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

145 logger.log(VERBOSE, msg) 

146 return input_file 

147 

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

149 

150 

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

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

153 

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

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

156 

157 Args: 

158 path (Path): path to the input file 

159 no_unwrap (bool): if True, the function returns the TOMLDocument object instead of unwrapping it 

160 

161 Returns: 

162 the content of the input file as a TOMLDocument object 

163 

164 Raises: 

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

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

167 

168 """ 

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

170 # somesy.toml / .somesy.toml 

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

172 with open(path, "r", encoding="utf-8") as f: 

173 ret = tomlkit.load(f) 

174 return ret if no_unwrap else ret.unwrap() 

175 

176 # pyproject.toml or fpm.toml 

177 if (path.suffix == ".toml" and "pyproject" in path.name) or path.name in [ 

178 "Project.toml", 

179 "fpm.toml", 

180 ]: 

181 with open(path, "r", encoding="utf-8") as f: 

182 input_content = tomlkit.load(f) 

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

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

185 else: 

186 raise RuntimeError( 

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

188 ) 

189 

190 # Cargo.toml 

191 if path.name == "Cargo.toml": 

192 with open(path, "r", encoding="utf-8") as f: 

193 input_content = tomlkit.load(f) 

194 if ( 

195 "package" in input_content 

196 and "metadata" in input_content["package"] 

197 and "somesy" in input_content["package"]["metadata"] 

198 ): 

199 return input_content["package"]["metadata"]["somesy"].unwrap() 

200 else: 

201 raise RuntimeError( 

202 "No package.somesy section found in Cargo.toml file!" 

203 ) 

204 

205 # package.json 

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

207 with open(path, "r", encoding="utf-8") as f: 

208 input_content = json.load(f) 

209 if "somesy" in input_content: 

210 return input_content["somesy"] 

211 else: 

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

213 

214 # no match: 

215 raise ValueError("Unsupported input file.")