Coverage for src/somesy/mkdocs/writer.py: 97%

69 statements  

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

1"""Project documentation with Markdown (MkDocs) parser and saver.""" 

2 

3import logging 

4from io import StringIO 

5from pathlib import Path 

6 

7from rich.pretty import pretty_repr 

8from ruamel.yaml import YAML 

9from ruamel.yaml.scalarstring import LiteralScalarString 

10 

11from somesy.core.core import atomic_write 

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

13from somesy.core.writer import FieldKeyMapping, IgnoreKey, ProjectMetadataWriter 

14from somesy.mkdocs.models import MkDocsConfig 

15 

16logger = logging.getLogger("somesy") 

17 

18 

19class MkDocs(ProjectMetadataWriter): 

20 """Project documentation with Markdown (MkDocs) parser and saver.""" 

21 

22 def __init__( 

23 self, 

24 path: Path, 

25 create_if_not_exists: bool = False, 

26 pass_validation: bool | None = False, 

27 ): 

28 """Project documentation with Markdown (MkDocs) parser. 

29 

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

31 """ 

32 self._yaml = YAML() 

33 self._yaml.preserve_quotes = True 

34 

35 mappings: FieldKeyMapping = { 

36 "name": ["site_name"], 

37 "description": ["site_description"], 

38 "homepage": ["site_url"], 

39 "repository": ["repo_url"], 

40 "authors": ["site_author"], 

41 "documentation": IgnoreKey(), 

42 "version": IgnoreKey(), 

43 "maintainers": IgnoreKey(), 

44 "license": IgnoreKey(), 

45 "keywords": IgnoreKey(), 

46 } 

47 super().__init__( 

48 path, 

49 create_if_not_exists=create_if_not_exists, 

50 direct_mappings=mappings, 

51 pass_validation=pass_validation, 

52 ) 

53 

54 def _load(self): 

55 """Load the MkDocs file.""" 

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

57 self._data = self._yaml.load(f) 

58 

59 def _config_dict(self) -> dict: 

60 """Return the file content as dict, raising a clear error if it is empty.""" 

61 content = self._get_property([]) 

62 if not content: 

63 raise ValueError(f"{self.path} is empty, expected a MkDocs configuration.") 

64 return dict(content) 

65 

66 def _validate(self) -> None: 

67 """Validate the MkDocs file.""" 

68 config = self._config_dict() 

69 logger.debug( 

70 f"Validating config using {MkDocsConfig.__name__}: {pretty_repr(config)}" 

71 ) 

72 MkDocsConfig(**config) 

73 

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

75 """Save the MkDocs object to a file.""" 

76 path = path or self.path 

77 

78 # if description have new line characters, it should be saved as multiline string 

79 if self._data is not None and "site_description" in self._data: 

80 if isinstance(self._data["site_description"], str) and ( 

81 "\n" in self._data["site_description"] 

82 ): 

83 self._data["site_description"] = LiteralScalarString( 

84 self._data["site_description"] 

85 ) 

86 elif self._data["site_description"] is not None: 

87 self._data["site_description"] = str(self.description) 

88 

89 stream = StringIO() 

90 self._yaml.dump(self._data, stream) 

91 atomic_write(path, stream.getvalue()) 

92 

93 @property 

94 def authors(self): 

95 """Return the only author from the source file as list.""" 

96 authors = self._get_property(self._get_key("authors")) 

97 if authors is None or self._to_person(authors) is None: 

98 return [] 

99 else: 

100 return [authors] 

101 

102 @authors.setter 

103 def authors(self, authors: list[Entity | Person]) -> None: 

104 """Set the authors of the project.""" 

105 author = self._from_person(authors[0]) 

106 self._set_property(self._get_key("authors"), author) 

107 

108 @staticmethod 

109 def _from_person(person: Entity | Person): 

110 """MkDocs Person is a string with full name.""" 

111 return person.to_name_email_string() 

112 

113 @staticmethod 

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

115 """MkDocs Person is a string with full name.""" 

116 return parse_name_email(person_obj) 

117 

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

119 """Sync the MkDocs object with the ProjectMetadata object.""" 

120 if metadata.name is not None: 

121 self.name = metadata.name 

122 if metadata.description is not None: 

123 self.description = metadata.description 

124 # no author merge since it is a free text field 

125 if metadata.authors(): 

126 self.authors = metadata.authors() 

127 if metadata.homepage: 

128 self.homepage = str(metadata.homepage) 

129 if metadata.repository: 

130 self.repository = str(metadata.repository) 

131 # display name like "org/repo", only if the user did not set one 

132 if not self._get_property("repo_name"): 

133 repo_name = metadata.repository.path or "" 

134 self._set_property( 

135 "repo_name", repo_name.strip("/").removesuffix(".git") 

136 )