Coverage for src/somesy/rust/writer.py: 89%

92 statements  

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

1"""Cargo.toml writer for Rust projects.""" 

2 

3import logging 

4from collections.abc import Mapping 

5from pathlib import Path 

6from typing import Any 

7 

8from rich.pretty import pretty_repr 

9from tomlkit import dumps, load, string, table 

10 

11from somesy.core.core import atomic_write 

12from somesy.core.models import Entity, Person, ProjectMetadata, parse_name_email 

13from somesy.core.writer import ( 

14 FieldKeyMapping, 

15 IgnoreKey, 

16 ProjectMetadataWriter, 

17 toml_array, 

18) 

19 

20from .models import RustConfig, check_keyword 

21 

22logger = logging.getLogger("somesy") 

23 

24 

25class Rust(ProjectMetadataWriter): 

26 """Rust config file handler parsed from Cargo.toml.""" 

27 

28 def __init__( 

29 self, 

30 path: Path, 

31 pass_validation: bool | None = False, 

32 ): 

33 """Rust config file handler parsed from Cargo.toml. 

34 

35 See [somesy.core.writer.ProjectMetadataWriter.__init__][]. 

36 """ 

37 self._section = ["package"] 

38 mappings: FieldKeyMapping = { 

39 "maintainers": IgnoreKey(), 

40 } 

41 super().__init__( 

42 path, 

43 create_if_not_exists=False, 

44 direct_mappings=mappings, 

45 pass_validation=pass_validation, 

46 ) 

47 

48 def _load(self) -> None: 

49 """Load Cargo.toml file.""" 

50 with open(self.path, encoding="utf-8") as f: 

51 self._data = load(f) 

52 

53 def _validate(self) -> None: 

54 """Validate rust config using pydantic class. 

55 

56 In order to preserve toml comments and structure, tomlkit library is used. 

57 Pydantic class only used for validation. 

58 """ 

59 content = self._get_property([]) 

60 if content is None: 

61 raise ValueError( 

62 f"{self.path} has no [package] table (is it a workspace root?)." 

63 ) 

64 config = dict(content) 

65 logger.debug( 

66 f"Validating config using {RustConfig.__name__}: {pretty_repr(config)}" 

67 ) 

68 RustConfig(**config) 

69 

70 def save(self, path: Path | None = None) -> None: 

71 """Save the Cargo.toml file.""" 

72 path = path or self.path 

73 

74 if ( 

75 "description" in self._data["package"] 

76 and "\n" in self._data["package"]["description"] 

77 ): 

78 self._data["package"]["description"] = string( 

79 self._data["package"]["description"], multiline=True 

80 ) 

81 

82 atomic_write(path, dumps(self._data)) 

83 

84 def _get_property( 

85 self, key: str | list[str] | IgnoreKey, *, remove: bool = False, **kwargs 

86 ) -> Any: 

87 """Get a property from the Cargo.toml file.""" 

88 if isinstance(key, IgnoreKey): 

89 return None 

90 key_path = [key] if isinstance(key, str) else key 

91 full_path = self._section + key_path 

92 value = super()._get_property(full_path, remove=remove, **kwargs) 

93 if not remove and self._is_workspace_ref(value): 

94 return None # inherited from the workspace, treat as absent 

95 return value 

96 

97 @staticmethod 

98 def _is_workspace_ref(value: Any) -> bool: 

99 """Check whether value is a workspace inheritance table `{workspace = true}`.""" 

100 return isinstance(value, Mapping) and value.get("workspace") is True 

101 

102 def _set_property(self, key: str | list[str] | IgnoreKey, value: Any) -> None: 

103 """Set a property in the Cargo.toml file.""" 

104 if isinstance(key, IgnoreKey): 

105 return 

106 key_path = [key] if isinstance(key, str) else key 

107 

108 # keep workspace inheritance, e.g. `version.workspace = true` 

109 existing = super()._get_property(self._section + key_path) 

110 if self._is_workspace_ref(existing): 

111 logger.debug(f"Not setting {key_path}, inherited from workspace.") 

112 return 

113 

114 if not value: # remove value and clean up the sub-dict 

115 self._get_property(key_path, remove=True) 

116 return 

117 

118 # get the tomlkit object of the section 

119 dat = self._get_property([]) 

120 

121 # dig down, create missing nested objects on the fly 

122 curr = dat 

123 for path_key in key_path[:-1]: 

124 if path_key not in curr: 

125 curr.add(path_key, table()) 

126 curr = curr[path_key] 

127 

128 # Handle arrays with proper formatting 

129 if isinstance(value, list): 

130 arr = toml_array(value) 

131 curr[key_path[-1]] = arr 

132 else: 

133 curr[key_path[-1]] = value 

134 

135 @staticmethod 

136 def _from_person(person: Person | Entity): 

137 """Convert project metadata person object to rust string for person format "full name <email>.""" 

138 return person.to_name_email_string() 

139 

140 @staticmethod 

141 def _to_person(person_obj: str) -> Person | Entity | None: 

142 """Parse rust person string to a Person. It has format "full name <email>." but email is optional. 

143 

144 Since there is no way to know whether this entry is a person or an entity, we will directly convert to Person. 

145 """ 

146 return parse_name_email(person_obj) 

147 

148 @classmethod 

149 def _parse_people(cls, people: list[Any] | None) -> list[Person | Entity]: 

150 """Return a list of Persons parsed from list of format-specific people representations. to_person can return None, so filter out None values.""" 

151 return list(filter(None, map(cls._to_person, people or []))) 

152 

153 @property 

154 def keywords(self) -> list[str] | None: 

155 """Return the keywords of the project.""" 

156 return self._get_property(self._get_key("keywords")) 

157 

158 @keywords.setter 

159 def keywords(self, keywords: list[str]) -> None: 

160 """Set the keywords of the project.""" 

161 validated_keywords = [] 

162 for keyword in keywords: 

163 try: 

164 check_keyword(keyword) 

165 validated_keywords.append(keyword) 

166 except ValueError as e: 

167 logger.debug(f"Invalid keyword {keyword}: {e}") 

168 

169 # keyword count should max 5, so delete the rest 

170 if len(validated_keywords) > 5: 

171 validated_keywords = validated_keywords[:5] 

172 self._set_property(self._get_key("keywords"), validated_keywords) 

173 

174 def sync(self, metadata: ProjectMetadata) -> None: 

175 """Sync the rust config with the project metadata.""" 

176 super().sync(metadata) 

177 

178 # if there is a license file, remove the license field 

179 if self._get_property(self._get_key("license_file")): 

180 self.license = None