Skip to content

mkdocs

MkDocs module.

MkDocs

Bases: ProjectMetadataWriter

Project documentation with Markdown (MkDocs) parser and saver.

Source code in src/somesy/mkdocs/writer.py
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
class MkDocs(ProjectMetadataWriter):
    """Project documentation with Markdown (MkDocs) parser and saver."""

    def __init__(
        self,
        path: Path,
        create_if_not_exists: bool = False,
        pass_validation: bool | None = False,
    ):
        """Project documentation with Markdown (MkDocs) parser.

        See [somesy.core.writer.ProjectMetadataWriter.__init__][].
        """
        self._yaml = YAML()
        self._yaml.preserve_quotes = True

        mappings: FieldKeyMapping = {
            "name": ["site_name"],
            "description": ["site_description"],
            "homepage": ["site_url"],
            "repository": ["repo_url"],
            "authors": ["site_author"],
            "documentation": IgnoreKey(),
            "version": IgnoreKey(),
            "maintainers": IgnoreKey(),
            "license": IgnoreKey(),
            "keywords": IgnoreKey(),
        }
        super().__init__(
            path,
            create_if_not_exists=create_if_not_exists,
            direct_mappings=mappings,
            pass_validation=pass_validation,
        )

    def _load(self):
        """Load the MkDocs file."""
        with open(self.path, encoding="utf-8") as f:
            self._data = self._yaml.load(f)

    def _config_dict(self) -> dict:
        """Return the file content as dict, raising a clear error if it is empty."""
        content = self._get_property([])
        if not content:
            raise ValueError(f"{self.path} is empty, expected a MkDocs configuration.")
        return dict(content)

    def _validate(self) -> None:
        """Validate the MkDocs file."""
        config = self._config_dict()
        logger.debug(
            f"Validating config using {MkDocsConfig.__name__}: {pretty_repr(config)}"
        )
        MkDocsConfig(**config)

    def save(self, path: Path | None = None) -> None:
        """Save the MkDocs object to a file."""
        path = path or self.path

        # if description have new line characters, it should be saved as multiline string
        if self._data is not None and "site_description" in self._data:
            if isinstance(self._data["site_description"], str) and (
                "\n" in self._data["site_description"]
            ):
                self._data["site_description"] = LiteralScalarString(
                    self._data["site_description"]
                )
            elif self._data["site_description"] is not None:
                self._data["site_description"] = str(self.description)

        stream = StringIO()
        self._yaml.dump(self._data, stream)
        atomic_write(path, stream.getvalue())

    @property
    def authors(self):
        """Return the only author from the source file as list."""
        authors = self._get_property(self._get_key("authors"))
        if authors is None or self._to_person(authors) is None:
            return []
        else:
            return [authors]

    @authors.setter
    def authors(self, authors: list[Entity | Person]) -> None:
        """Set the authors of the project."""
        author = self._from_person(authors[0])
        self._set_property(self._get_key("authors"), author)

    @staticmethod
    def _from_person(person: Entity | Person):
        """MkDocs Person is a string with full name."""
        return person.to_name_email_string()

    @staticmethod
    def _to_person(person_obj: str) -> Entity | Person | None:
        """MkDocs Person is a string with full name."""
        return parse_name_email(person_obj)

    def sync(self, metadata: ProjectMetadata) -> None:
        """Sync the MkDocs object with the ProjectMetadata object."""
        if metadata.name is not None:
            self.name = metadata.name
        if metadata.description is not None:
            self.description = metadata.description
        # no author merge since it is a free text field
        if metadata.authors():
            self.authors = metadata.authors()
        if metadata.homepage:
            self.homepage = str(metadata.homepage)
        if metadata.repository:
            self.repository = str(metadata.repository)
            # display name like "org/repo", only if the user did not set one
            if not self._get_property("repo_name"):
                repo_name = metadata.repository.path or ""
                self._set_property(
                    "repo_name", repo_name.strip("/").removesuffix(".git")
                )

authors property writable

authors

Return the only author from the source file as list.

__init__

__init__(
    path: Path,
    create_if_not_exists: bool = False,
    pass_validation: bool | None = False,
)

Project documentation with Markdown (MkDocs) parser.

See somesy.core.writer.ProjectMetadataWriter.init.

Source code in src/somesy/mkdocs/writer.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
def __init__(
    self,
    path: Path,
    create_if_not_exists: bool = False,
    pass_validation: bool | None = False,
):
    """Project documentation with Markdown (MkDocs) parser.

    See [somesy.core.writer.ProjectMetadataWriter.__init__][].
    """
    self._yaml = YAML()
    self._yaml.preserve_quotes = True

    mappings: FieldKeyMapping = {
        "name": ["site_name"],
        "description": ["site_description"],
        "homepage": ["site_url"],
        "repository": ["repo_url"],
        "authors": ["site_author"],
        "documentation": IgnoreKey(),
        "version": IgnoreKey(),
        "maintainers": IgnoreKey(),
        "license": IgnoreKey(),
        "keywords": IgnoreKey(),
    }
    super().__init__(
        path,
        create_if_not_exists=create_if_not_exists,
        direct_mappings=mappings,
        pass_validation=pass_validation,
    )

save

save(path: Path | None = None) -> None

Save the MkDocs object to a file.

Source code in src/somesy/mkdocs/writer.py
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
def save(self, path: Path | None = None) -> None:
    """Save the MkDocs object to a file."""
    path = path or self.path

    # if description have new line characters, it should be saved as multiline string
    if self._data is not None and "site_description" in self._data:
        if isinstance(self._data["site_description"], str) and (
            "\n" in self._data["site_description"]
        ):
            self._data["site_description"] = LiteralScalarString(
                self._data["site_description"]
            )
        elif self._data["site_description"] is not None:
            self._data["site_description"] = str(self.description)

    stream = StringIO()
    self._yaml.dump(self._data, stream)
    atomic_write(path, stream.getvalue())

sync

sync(metadata: ProjectMetadata) -> None

Sync the MkDocs object with the ProjectMetadata object.

Source code in src/somesy/mkdocs/writer.py
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
def sync(self, metadata: ProjectMetadata) -> None:
    """Sync the MkDocs object with the ProjectMetadata object."""
    if metadata.name is not None:
        self.name = metadata.name
    if metadata.description is not None:
        self.description = metadata.description
    # no author merge since it is a free text field
    if metadata.authors():
        self.authors = metadata.authors()
    if metadata.homepage:
        self.homepage = str(metadata.homepage)
    if metadata.repository:
        self.repository = str(metadata.repository)
        # display name like "org/repo", only if the user did not set one
        if not self._get_property("repo_name"):
            repo_name = metadata.repository.path or ""
            self._set_property(
                "repo_name", repo_name.strip("/").removesuffix(".git")
            )