Skip to content

Commit 262942a

Browse files
committed
Fixes
1 parent 2b9ce7a commit 262942a

File tree

6 files changed

+84
-26
lines changed

6 files changed

+84
-26
lines changed

mkdocs/docs/assets/extra.css

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
.md-typeset h1 code,
2+
.md-typeset h2 code,
3+
.md-typeset h3 code,
4+
.md-typeset h4 code,
5+
.md-typeset h5 code,
6+
.md-typeset h6 code
7+
{
8+
background-color: unset;
9+
}

mkdocs/mkdocs.yaml

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ site_dir: dist/mkdocs_site
44

55
# gives a link on each documentation page directly to edit that page in Github!
66
repo_url: https://github.com/couling/MkdocstringsPythonGenerator
7-
edit_uri: edit/main/docs/
7+
edit_uri: edit/main/mkdocs/docs/
88

99

1010
# Enable the theme "Material"
@@ -17,6 +17,9 @@ theme:
1717
- navigation.sections
1818
- navigation.indexes
1919

20+
extra_css:
21+
- assets/extra.css
22+
2023
markdown_extensions:
2124
- pymdownx.highlight:
2225
anchor_linenums: true
@@ -45,8 +48,10 @@ plugins:
4548
docstring_style: sphinx
4649
- mkdocstrings-python-generator:
4750
nav_heading:
48-
- Reference
51+
- Code Reference
4952
base: ../source
53+
edit_uri: edit/main/source/
54+
init_section_index: true
5055
search:
5156
- ../source/mkdocstrings_python_generator
5257

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1 @@
1-
"""
2-
# This is a page
3-
No really it's a page
4-
"""
1+
"""hello world"""

source/mkdocstrings_python_generator/files_generator.py

Lines changed: 27 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
import logging
22
from fnmatch import fnmatch
33
from pathlib import Path
4-
from typing import Dict, Iterable, List, NamedTuple, Optional, Tuple
54
from tempfile import TemporaryDirectory
5+
from typing import Dict, Iterable, List, NamedTuple, Tuple
6+
67
from mkdocs.structure.files import File
78

89
log = logging.getLogger(__name__)
@@ -34,7 +35,7 @@ class FilesGenerator:
3435
base_path: Path
3536
_temp_dir: TemporaryDirectory
3637

37-
def __init__(self, dest_dir: str, use_directory_urls: bool):
38+
def __init__(self, dest_dir: str, use_directory_urls: bool, init_section_index: bool):
3839
"""
3940
:param dest_dir: Configured mkdocs destination directory
4041
:param use_directory_urls: Configured mkdocs use_directory_urls
@@ -43,6 +44,7 @@ def __init__(self, dest_dir: str, use_directory_urls: bool):
4344
self._temp_dir = TemporaryDirectory()
4445
self.base_path = Path(self._temp_dir.name)
4546

47+
self._init_section_index = init_section_index
4648
self._dest_dir = dest_dir
4749
self._use_directory_urls = use_directory_urls
4850

@@ -73,9 +75,9 @@ def generate_page(self, source_base_path: Path, source_path: Path, page_template
7375
with open(target_path, "xt", encoding="utf8") as page:
7476
page.write(
7577
page_template.format(
76-
module_name=module_id[-1],
77-
printable_module_id=module_name(module_id),
78-
module_id=module_name(module_id),
78+
module_name=self.module_name(module_id, full_name=False, printable=True),
79+
printable_module_id=self.module_name(module_id, full_name=True, printable=True),
80+
module_id=self.module_name(module_id, full_name=True, printable=False),
7981
)
8082
)
8183

@@ -114,10 +116,29 @@ def generate_pages_recursive(self, source: Source, template: str) -> List[FileEn
114116
return entries
115117

116118
def file_path_for_module_id(self, module_id: ModuleId) -> Path:
117-
if module_id[-1] == "__init__":
119+
"""
120+
Format a .md file path for a file
121+
:param module_id: The module id
122+
:return: An absolute path
123+
"""
124+
if self._init_section_index and module_id[-1] == "__init__":
118125
module_id = module_id[:-1] + ("README.md",)
119126
return Path(self.base_path, "_ref", *module_id).with_suffix(".md")
120127

128+
def module_name(self, module_id: ModuleId, full_name: bool, printable: bool) -> str:
129+
"""
130+
Get the module name for a given module_id
131+
132+
:param module_id: Module ID generated by the function ``module_id()``
133+
:param full_name: If true, the full module name "foo.bar.baz" will be returned. Otherwise, just the last section
134+
"baz" will be returned.
135+
:param printable: Make adjustments for rendering this name. If false, the name must match something python
136+
can import. If True it will be modified to be more pleasing on the eye.
137+
"""
138+
if module_id[-1] == "__init__" and (not printable or self._init_section_index):
139+
module_id = module_id[:-1]
140+
return ".".join(module_id) if full_name else module_id[-1]
141+
121142

122143
def get_module_id(module_path: Path, base_path: Path) -> ModuleId:
123144
"""
@@ -129,16 +150,6 @@ def get_module_id(module_path: Path, base_path: Path) -> ModuleId:
129150
return module_path.relative_to(base_path).with_suffix("").parts
130151

131152

132-
def module_name(module_id: ModuleId) -> str:
133-
"""
134-
Get the module name for a given module_id
135-
136-
:param module_id: Module ID generated by the function ``module_id()``
137-
"""
138-
if module_id[-1] == "__init__":
139-
module_id = module_id[:-1]
140-
return ".".join(module_id)
141-
142153

143154
def discover_python_files(source_dir: Path, ignore: List[str]) -> Iterable[Path]:
144155
"""

source/mkdocstrings_python_generator/nav_util.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,9 @@ def add_page_to_nav(nav_parent: list[NavItem], page: NavItem, module_id: ModuleI
9191
The page will be added to the nav as <nav_parent> -> "foo" -> "bar".
9292
:return: The added page.
9393
"""
94-
if module_id[-1] == "__init__":
94+
if page.file.src_uri.endswith("README.md"):
95+
# README.md is optionally used elsewhere for __init__ files to make them a section index page on the nav.
96+
# Setting the nav title to None indicates this page is the index of the section.
9597
page.title = None
9698
else:
9799
page.title = module_id[-1]

source/mkdocstrings_python_generator/plugin.py

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from mkdocs.config import Config, base, config_options as c
66
from mkdocs.config.defaults import MkDocsConfig
77
from mkdocs.plugins import BasePlugin
8-
from mkdocs.structure.files import Files
8+
from mkdocs.structure.files import File, Files
99
from mkdocs.structure.nav import Navigation, Page
1010

1111
from . import files_generator, nav_util
@@ -22,8 +22,11 @@
2222
class GeneratePythonDocsConfig(base.Config):
2323
nav_heading: list[str] = c.ListOfItems(c.Type(str), default=["Reference"])
2424
base: str = c.Optional(c.Dir(exists=True))
25+
edit_uri: str = c.Optional(c.Type(str))
26+
edit_uri_template: str = c.Optional(c.Type(str))
2527
search: list[str] = c.ListOfItems(c.Dir(exists=True))
2628
ignore: list[str] = c.ListOfItems(c.Type(str), default=["test", "tests", "__main__.py"])
29+
init_section_index: bool = c.Type(bool, default=False)
2730
flatten_nav_package: str = c.Type(str, default="")
2831

2932

@@ -35,6 +38,7 @@ def on_files(self, files: Files, config: Config, **kwargs):
3538
self._files_generator = files_generator.FilesGenerator(
3639
dest_dir=config["site_dir"],
3740
use_directory_urls=config["use_directory_urls"],
41+
init_section_index=self.config.init_section_index,
3842
)
3943
for search_path in self.config.search:
4044
self._files_generator.generate_pages_recursive(
@@ -65,8 +69,10 @@ def patch_config_nav(self, config: Config) -> None:
6569
]
6670
config["nav"].append({"_ref": dummy_nav_list})
6771

68-
def on_page_content(self, html: str, *, page: Page, config: MkDocsConfig, files: Files) -> Optional[str]:
69-
...
72+
def on_pre_page(self, page: Page, *, config: MkDocsConfig, files: Files) -> Optional[Page]:
73+
if (generated_file := self._files_generator.generated_pages.get(Path(page.file.abs_src_path))) is None:
74+
return
75+
page.edit_url = self.make_edit_url(config, generated_file)
7076

7177
def on_nav(self, nav: Navigation, *, config: MkDocsConfig, files: Files) -> None:
7278
nav_util.build_reference_nav(nav, self._files_generator.generated_pages, self.config.nav_heading, config)
@@ -81,3 +87,31 @@ def _cleanup(self):
8187
if self._files_generator is not None:
8288
self._files_generator.cleanup()
8389
self._files_generator = None
90+
91+
def make_edit_url(self, config: Config, file: files_generator.FileEntry) -> str:
92+
93+
# Frustratingly, the mkdocs function to format the edit URL is wrapped up in the constructor of Page
94+
# It takes config and the File.src_uri as inputs
95+
# To work around this...
96+
97+
# Make a dummy config with edit_uri and edit_uri_template replaced with this plugin's config.
98+
if self.config.edit_uri is not None or self.config.edit_uri_template is not None:
99+
dummy_config = config.copy()
100+
dummy_config["edit_uri"] = self.config.edit_uri
101+
dummy_config["edit_uri_template"] = self.config.edit_uri_template
102+
else:
103+
dummy_config = config
104+
105+
# Make a dummy file with the python source file as src_uri instead of the .md file
106+
dummy_file = File(
107+
path=str(file.source_file_path.relative_to(Path(self.config.base))),
108+
src_dir=self.config.base,
109+
dest_dir=dummy_config["site_dir"],
110+
use_directory_urls=dummy_config["use_directory_urls"],
111+
)
112+
113+
# Make a dummy_page page from the dummy_config and dummy_file
114+
dummy_page = Page("if you can see this something broke", dummy_file, dummy_config)
115+
116+
# extract the edit_url
117+
return dummy_page.edit_url

0 commit comments

Comments
 (0)