Coverage for src/somesy/merge.py: 93%

98 statements  

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

1"""Merge harvested metadata into the canonical Somesy project model.""" 

2 

3from __future__ import annotations 

4 

5import logging 

6import re 

7from collections.abc import Iterable 

8from typing import Any 

9 

10from somesy.core.models import ( 

11 Entity, 

12 PartialProjectMetadata, 

13 Person, 

14 ProjectMetadata, 

15 find_matching_person, 

16) 

17from somesy.git.models import GitAuthor, GitMetadata 

18 

19logger = logging.getLogger("somesy") 

20 

21_SCALAR_FIELDS = ( 

22 "name", 

23 "version", 

24 "description", 

25 "license", 

26 "homepage", 

27 "repository", 

28 "documentation", 

29) 

30 

31 

32def _value(value: Any) -> Any: 

33 """Convert common endpoint wrapper values to project-model values.""" 

34 if hasattr(value, "text"): 

35 return value.text 

36 if isinstance(value, (set, tuple)): 

37 return list(value) 

38 if isinstance(value, list): 

39 return [_value(item) for item in value] 

40 return getattr(value, "value", value) 

41 

42 

43def _repository(value: Any) -> str | None: 

44 """Return a repository URL acceptable to ProjectMetadata when possible.""" 

45 value = _value(value) 

46 if not isinstance(value, str): 

47 return None 

48 if match := re.fullmatch(r"git@([^:]+):(.+)", value): 

49 return f"https://{match[1]}/{match[2]}" 

50 # ssh://[user@]host[:port]/path or scp-like ssh://[user@]host:path 

51 if match := re.fullmatch(r"ssh://(?:[^@/]+@)?([^:/]+)(?::\d+)?[:/](.+)", value): 

52 return f"https://{match[1]}/{match[2]}" 

53 return value 

54 

55 

56def _merge_person(existing: Person | Entity, incoming: Person | Entity): 

57 """Fill missing fields and combine roles for one matching person.""" 

58 updates: dict[str, Any] = {} 

59 for field in type(existing).model_fields: 

60 old = getattr(existing, field) 

61 new = getattr(incoming, field) 

62 if field == "contribution_types": 

63 values = list(dict.fromkeys((old or []) + (new or []))) 

64 if values != (old or []): 

65 updates[field] = values 

66 elif field in {"author", "maintainer"}: 

67 if new and not old: 

68 updates[field] = True 

69 elif field == "publication_author": 

70 if new is True and old is not True: 

71 updates[field] = True 

72 elif old is None and new is not None: 

73 updates[field] = new 

74 elif old in (None, "") and new not in (None, ""): 

75 updates[field] = new 

76 return existing.model_copy(update=updates) if updates else existing 

77 

78 

79def _merge_people( 

80 existing: list[Person | Entity], incoming: Iterable[Person | Entity] 

81) -> list[Person | Entity]: 

82 """Merge people using the model's existing identity heuristics.""" 

83 result = list(existing) 

84 for candidate in incoming: 

85 # same_person is False for a Person/Entity mix 

86 index = find_matching_person(candidate, result) 

87 if index is None: 

88 result.append(candidate) 

89 else: 

90 result[index] = _merge_person(result[index], candidate) 

91 return result 

92 

93 

94def _git_person(author: GitAuthor) -> Person | None: 

95 """Convert a Git author into a Somesy Person.""" 

96 if author.name.endswith("[bot]"): 

97 return None 

98 identity = author.name 

99 if author.email: 

100 identity = f"{identity} <{author.email}>" 

101 if len(author.name.split()) < 2: 

102 logger.warning( 

103 "Skipping Git author '%s': a person needs given and family names. " 

104 "Add them to the somesy input manually.", 

105 identity, 

106 ) 

107 return None 

108 try: 

109 return Person.from_name_email_string(identity).model_copy( 

110 update={ 

111 "author": author.author, 

112 "publication_author": author.author or None, 

113 "contribution_types": author.contribution_types, 

114 } 

115 ) 

116 except (IndexError, ValueError): 

117 logger.warning("Cannot convert Git author '%s' to Somesy metadata.", identity) 

118 return None 

119 

120 

121def merge_metadata( 

122 sources: Iterable[dict[str, Any]], 

123 git: GitMetadata | None = None, 

124 *, 

125 allow_incomplete: bool = False, 

126) -> ProjectMetadata: 

127 """Merge harvested endpoint and Git data, optionally allowing missing fields. 

128 

129 Precedence of scalar values (name, version, ...): the first source that 

130 provides a non-empty value wins, in the order of ``sources``; Git data is 

131 appended last and therefore only fills what no other source provides. 

132 """ 

133 data: dict[str, Any] = {"people": [], "entities": []} 

134 keywords: list[str] = [] 

135 

136 candidates = list(sources) 

137 if git is not None: 

138 candidates.append(git.model_dump(exclude_none=True)) 

139 

140 for source in candidates: 

141 for field in _SCALAR_FIELDS: 

142 value = source.get(field) 

143 if field == "repository": 

144 value = _repository(value) 

145 else: 

146 value = _value(value) 

147 if value not in (None, "") and field not in data: 

148 data[field] = value 

149 

150 for keyword in _value(source.get("keywords", [])) or []: 

151 if keyword not in keywords: 

152 keywords.append(keyword) 

153 

154 people = source.get("people", []) or [] 

155 entities = source.get("entities", []) or [] 

156 data["people"] = _merge_people(data["people"], people) 

157 data["entities"] = _merge_people(data["entities"], entities) 

158 

159 for author in source.get("authors", []) or []: 

160 if isinstance(author, dict): 

161 author = GitAuthor(**author) 

162 if person := _git_person(author): 

163 data["people"] = _merge_people(data["people"], [person]) 

164 

165 if keywords: 

166 data["keywords"] = keywords 

167 model = PartialProjectMetadata if allow_incomplete else ProjectMetadata 

168 return model(**data)