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
 17
 18
 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
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) as f:
            self._data = self._yaml.load(f)

    def _validate(self) -> None:
        """Validate the MkDocs file."""
        if self.pass_validation:
            return
        config = dict(self._get_property([]))
        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 "\n" in self._data["site_description"]:
                self._data["site_description"] = LiteralScalarString(
                    self._data["site_description"]
                )
            else:
                self._data["site_description"] = str(self.description)

        self._yaml.dump(self._data, path)

    @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."""
        try:
            return Person.from_name_email_string(person_obj)
        except (ValueError, AttributeError):
            logger.info(f"Cannot convert {person_obj} to Person object, trying Entity.")

        try:
            return Entity.from_name_email_string(person_obj)
        except (ValueError, AttributeError):
            logger.warning(f"Cannot convert {person_obj} to Entity.")
            return None

    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)
            self.repo_name = metadata.repository.path

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
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
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
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 "\n" in self._data["site_description"]:
            self._data["site_description"] = LiteralScalarString(
                self._data["site_description"]
            )
        else:
            self._data["site_description"] = str(self.description)

    self._yaml.dump(self._data, path)

sync

sync(metadata: ProjectMetadata) -> None

Sync the MkDocs object with the ProjectMetadata object.

Source code in src/somesy/mkdocs/writer.py
116
117
118
119
120
121
122
123
124
125
126
127
128
129
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)
        self.repo_name = metadata.repository.path