Skip to content

Commit 4b17176

Browse files
authored
ruff format codebase
1 parent d55299f commit 4b17176

File tree

10 files changed

+170
-101
lines changed

10 files changed

+170
-101
lines changed

.pre-commit-config.yaml

+1-17
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,4 @@
11
repos:
2-
- repo: local
3-
hooks:
4-
- id: black
5-
name: black
6-
entry: black
7-
language: python
8-
types: [python]
9-
language_version: python3.8
10-
args: [--line-length=120]
112
- repo: local
123
hooks:
134
- id: mypy
@@ -16,14 +7,7 @@ repos:
167
language: system
178
types: [python]
189
args: [--ignore-missing-imports, --namespace-packages, --show-error-codes, --pretty]
19-
- repo: local
20-
hooks:
21-
- id: flake8
22-
name: flake8
23-
entry: flake8
24-
language: system
25-
types: [python]
26-
args: [--max-line-length=120, --docstring-convention=google, "--ignore=D100,D104,D212,D200,E203,W293,D412,W503,W605,E722"]
10+
2711
# D100 requires all Python files (modules) to have a "public" docstring even if all functions within have a docstring.
2812
# D104 requires __init__ files to have a docstring
2913
# D212

docs/contributing.md

+6-11
Original file line numberDiff line numberDiff line change
@@ -9,31 +9,26 @@ Thanks for considering to contribute to this project! Some guidelines:
99

1010
## Unit Tests
1111

12-
Make sure to install an editable version before running tests:
12+
We use [uv](https://docs.astral.sh/uv/getting-started/installation/) to manage python:
1313

1414
```bash
15-
pip install -r tests/test_requirements.txt
16-
pip install -e .
17-
pytest --cov=mkdocs_print_site_plugin --cov-report term-missing tests/
15+
uv run pytest --cov=mkdocs_print_site_plugin --cov-report term-missing tests/
1816
```
1917

2018
If it makes sense, writing tests for your PRs is always appreciated and will help get them merged.
2119

22-
In addition, this project uses [pyflakes](https://pypi.org/project/pyflakes/) for static code checking:
20+
You can also apply formatting using:
2321

2422
```bash
25-
pip install pyflakes
26-
pyflakes tests/ mkdocs_print_site_plugin/
23+
uv run --with ruff ruff format src/
2724
```
2825

2926
## Manual testing
3027

3128
To quickly serve a website with your latest changes to the plugin use the sites in our tests suite. For example:
3229

3330
```bash
34-
pip install -r tests/test_requirements.txt
35-
pip install -e .
36-
mkdocs serve -f tests/fixutures/basic/mkdocs.yml
31+
uv run mkdocs serve -f tests/fixutures/basic/mkdocs.yml
3732
```
3833

3934
Tip: If you use google chrome, you can also view the print version of a page inside the browser [by setting the renderer](https://www.smashingmagazine.com/2018/05/print-stylesheets-in-2018/).
@@ -49,7 +44,7 @@ We use google-style docstrings.
4944
Is in `docs/`. To [deploy the docs](https://www.mkdocs.org/user-guide/deploying-your-docs/), run:
5045

5146
```bash
52-
mkdocs gh-deploy
47+
uv run mkdocs gh-deploy
5348
```
5449

5550
Note: there is no automated github action for this currently.

pyproject.toml

+1
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,7 @@ dev = [
119119
"mkdocs-img2fig-plugin>=0.9.3",
120120
"mkdocs-material>=9.6.7",
121121
"mkdocs-windmill>=1.0.5",
122+
"mypy>=1.14.1",
122123
"pytest>=8.3.5",
123124
"pytest-cov>=5.0.0",
124125
"ruff>=0.9.10",
+1-1
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
__version__ = "2.7.0"
1+
__version__ = "2.7.0"

src/mkdocs_print_site_plugin/exclude.py

+1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
44
Inspired by https://github.com/apenwarr/mkdocs-exclude
55
"""
6+
67
import os
78
import fnmatch
89
from typing import List

src/mkdocs_print_site_plugin/plugin.py

+25-52
Original file line numberDiff line numberDiff line change
@@ -71,27 +71,23 @@ def on_config(self, config, **kwargs):
7171
# Check if 'hooks' is defined in the 'plugins' section
7272
if isinstance(config.get("hooks"), dict):
7373
position_offset += len(config.get("hooks"))
74-
74+
7575
if print_site_position != len(plugins) - position_offset:
7676
msg = "[mkdocs-print-site] 'print-site' should be defined as the *last* plugin,"
7777
msg += "to ensure the print page has any changes other plugins make."
7878
msg += "Please update the 'plugins:' section in your mkdocs.yml"
7979
logger.warning(msg)
8080

8181
if "--dirtyreload" in sys.argv:
82-
msg = (
83-
"[mkdocs-print-site] Note the 'print-site' page does render all pages "
84-
)
82+
msg = "[mkdocs-print-site] Note the 'print-site' page does render all pages "
8583
msg += "when using the --dirtyreload option."
8684
logger.warning(msg)
8785

8886
# Get abs path to cover_page_template
8987
self.cover_page_template_path = ""
9088
if self.config.get("add_cover_page"):
9189
if self.config.get("cover_page_template") == "":
92-
self.cover_page_template_path = os.path.join(
93-
HERE, "templates", "cover_page.tpl"
94-
)
90+
self.cover_page_template_path = os.path.join(HERE, "templates", "cover_page.tpl")
9591
else:
9692
self.cover_page_template_path = os.path.join(
9793
os.path.dirname(config.get("config_file_path")),
@@ -101,17 +97,13 @@ def on_config(self, config, **kwargs):
10197
msg = "[print-site-plugin]: Path specified in 'cover_page_template' not found."
10298
msg += "\nMake sure to use the URL relative to your mkdocs.yml file."
10399
logger.warning(msg)
104-
raise FileNotFoundError(
105-
"File not found: %s" % self.cover_page_template_path
106-
)
100+
raise FileNotFoundError("File not found: %s" % self.cover_page_template_path)
107101

108102
# Get abs path to print_site_banner_template
109103
self.banner_template_path = ""
110104
if self.config.get("add_print_site_banner"):
111105
if self.config.get("print_site_banner_template") == "":
112-
self.banner_template_path = os.path.join(
113-
HERE, "templates", "print_site_banner.tpl"
114-
)
106+
self.banner_template_path = os.path.join(HERE, "templates", "print_site_banner.tpl")
115107
else:
116108
self.banner_template_path = os.path.join(
117109
os.path.dirname(config.get("config_file_path")),
@@ -121,9 +113,7 @@ def on_config(self, config, **kwargs):
121113
msg = "[print-site-plugin]: Path specified in 'print_site_banner_template' not found."
122114
msg += "\nMake sure to use the URL relative to your mkdocs.yml file."
123115
logger.warning(msg)
124-
raise FileNotFoundError(
125-
"File not found: %s" % self.banner_template_path
126-
)
116+
raise FileNotFoundError("File not found: %s" % self.banner_template_path)
127117

128118
# Add pointer to print-site javascript
129119
config["extra_javascript"] = ["js/print-site.js"] + config["extra_javascript"]
@@ -146,7 +136,6 @@ def on_config(self, config, **kwargs):
146136

147137
config["extra_css"] = self.enum_css_files + config["extra_css"]
148138

149-
150139
# Create MkDocs Page and File instances
151140
self.print_file = File(
152141
path=self.config.get("print_page_basename") + ".md",
@@ -217,9 +206,7 @@ def on_page_content(self, html, page, config, files, **kwargs):
217206
if is_external(pdf_url):
218207
page.url_to_pdf = pdf_url
219208
else:
220-
page.url_to_pdf = get_relative_url(
221-
pdf_url, page.file.url
222-
)
209+
page.url_to_pdf = get_relative_url(pdf_url, page.file.url)
223210

224211
return html
225212

@@ -262,11 +249,14 @@ def on_template_context(self, context, template_name, config, **kwargs):
262249
if template_name == "404.html":
263250
self.context = context
264251
# Make sure paths are OK
265-
if config.get('extra_css'):
266-
self.context['extra_css'] = [get_relative_url(f, self.print_page.file.url) for f in config.get('extra_css')]
267-
if config.get('extra_javascript'):
268-
self.context['extra_javascript'] = [get_relative_url(str(f), self.print_page.file.url) for f in config.get('extra_javascript')]
269-
252+
if config.get("extra_css"):
253+
self.context["extra_css"] = [
254+
get_relative_url(f, self.print_page.file.url) for f in config.get("extra_css")
255+
]
256+
if config.get("extra_javascript"):
257+
self.context["extra_javascript"] = [
258+
get_relative_url(str(f), self.print_page.file.url) for f in config.get("extra_javascript")
259+
]
270260

271261
def on_post_build(self, config, **kwargs):
272262
"""
@@ -292,25 +282,19 @@ def on_post_build(self, config, **kwargs):
292282
# Add print-site.css
293283
css_output_base_path = os.path.join(config["site_dir"], "css")
294284
css_file_path = os.path.join(css_output_base_path, "print-site.css")
295-
copy_file(
296-
os.path.join(os.path.join(HERE, "css"), "print-site.css"), css_file_path
297-
)
285+
copy_file(os.path.join(os.path.join(HERE, "css"), "print-site.css"), css_file_path)
298286

299287
# Add enumeration css
300288
for f in self.enum_css_files:
301289
f = f.replace("/", os.sep)
302290
css_file_path = os.path.join(config["site_dir"], f)
303-
copy_file(
304-
os.path.join(HERE, f), css_file_path
305-
)
291+
copy_file(os.path.join(HERE, f), css_file_path)
306292

307293
# Add theme CSS file
308294
css_file = "print-site-%s.css" % get_theme_name(config)
309295
if css_file in os.listdir(os.path.join(HERE, "css")):
310296
css_file_path = os.path.join(css_output_base_path, css_file)
311-
copy_file(
312-
os.path.join(os.path.join(HERE, "css"), css_file), css_file_path
313-
)
297+
copy_file(os.path.join(os.path.join(HERE, "css"), css_file), css_file_path)
314298

315299
# Combine the HTML of all pages present in the navigation
316300
self.print_page.content, self.print_page.toc = self.renderer.write_combined()
@@ -325,38 +309,30 @@ def on_post_build(self, config, **kwargs):
325309

326310
# Remove lazy loading attributes from images
327311
# https://regex101.com/r/HVpKPs/1
328-
html = re.sub(r"(\<img.+)(loading=\"lazy\")", r"\1", html)
312+
html = re.sub(r"(\<img.+)(loading=\"lazy\")", r"\1", html)
329313

330314
# Compatiblity with mkdocs-chart-plugin
331315
# As this plugin adds some javascript to every page
332316
# It should be included in the print site also
333317
if config.get("plugins", {}).get("charts"):
334-
html = (
335-
config.get("plugins", {})
336-
.get("charts")
337-
.add_javascript_variables(html, self.print_page, config)
338-
)
318+
html = config.get("plugins", {}).get("charts").add_javascript_variables(html, self.print_page, config)
339319

340320
# Compatibility with mkdocs-drawio
341321
# As this plugin adds renderer html for every drawio diagram
342322
# referenced in your markdown files. This rendering happens
343323
# in the on_post_page event, which is skipped by this plugin
344-
# therefore we need to manual execute the drawio plugin renderer here.
324+
# therefore we need to manual execute the drawio plugin renderer here.
345325
if config.get("plugins", {}).get("drawio"):
346-
html = (
347-
config.get("plugins", {})
348-
.get("drawio")
349-
.render_drawio_diagrams(html, self.print_page)
350-
)
326+
html = config.get("plugins", {}).get("drawio").render_drawio_diagrams(html, self.print_page)
351327

352328
# Compatibility with https://github.com/g-provost/lightgallery-markdown
353329
# This plugin insert link hrefs with double dashes, f.e.
354330
# <link href="//assets/css/somecss.css">
355331
# Details https://github.com/timvink/mkdocs-print-site-plugin/issues/68
356332
htmls = html.split("</head>")
357333
base_url = "../" if config.get("use_directory_urls") else ""
358-
htmls[0] = htmls[0].replace("href=\"//", f"href=\"{base_url}")
359-
htmls[0] = htmls[0].replace("src=\"//", f"src=\"{base_url}")
334+
htmls[0] = htmls[0].replace('href="//', f'href="{base_url}')
335+
htmls[0] = htmls[0].replace('src="//', f'src="{base_url}')
360336
html = "</head>".join(htmls)
361337

362338
# Determine calls to required javascript functions
@@ -379,7 +355,4 @@ def on_post_build(self, config, **kwargs):
379355
html = html.replace("</head>", print_site_js + "</head>")
380356

381357
# Write the print_page file to the output folder
382-
write_file(
383-
html.encode("utf-8", errors="xmlcharrefreplace"),
384-
self.print_page.file.abs_dest_path
385-
)
358+
write_file(html.encode("utf-8", errors="xmlcharrefreplace"), self.print_page.file.abs_dest_path)

src/mkdocs_print_site_plugin/renderer.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ def get_html_and_anchor_links_from_items(
8282
heading_styles: List[str] = [],
8383
) -> Tuple[str, List[AnchorLink]]:
8484
"""
85-
Get all the HTML and anchor links from the pages.
85+
Get all the HTML and anchor links from the pages.
8686
"""
8787
items_html = ""
8888
anchor_links = []
@@ -163,7 +163,7 @@ def get_html_and_anchor_links_from_items(
163163

164164
return items_html, anchor_links
165165

166-
heading_styles = []
166+
heading_styles: List[str] = []
167167
items_html, anchor_links = get_html_and_anchor_links_from_items(
168168
self._get_items(),
169169
dir_urls=self.mkdocs_config.get("use_directory_urls"),

src/mkdocs_print_site_plugin/urls.py

+11-17
Original file line numberDiff line numberDiff line change
@@ -41,11 +41,12 @@ def is_external(url):
4141
prefixes = ("http", "www", "mailto:", "tel:", "skype:", "ftp:")
4242
return url.startswith(prefixes)
4343

44+
4445
def is_base64_image(url):
4546
"""
4647
Test if a url is a base64 data image.
4748
"""
48-
prefixes = ("data:image")
49+
prefixes = "data:image"
4950
return url.startswith(prefixes)
5051

5152

@@ -76,14 +77,7 @@ def get_page_key(page_url):
7677
Args:
7778
page_url (str): The MkDocs url of the page
7879
"""
79-
page_key = (
80-
page_url.lower()
81-
.strip()
82-
.rstrip("/")
83-
.replace(".html", "")
84-
.replace("/", "-")
85-
.lstrip("-")
86-
)
80+
page_key = page_url.lower().strip().rstrip("/").replace(".html", "").replace("/", "-").lstrip("-")
8781
if len(page_key) > 0:
8882
return page_key
8983
else:
@@ -190,13 +184,13 @@ def fix_tabbed_content(page_html, page_key):
190184
<label for="{page_key}__tabbed_1_1">C</label>
191185
"""
192186
regex = re.compile(r"(\<input.*?name=\")([^\"]*?)(\".*?\>)", re.I)
193-
page_html = re.sub(regex, fr"\g<1>{page_key}-\g<2>\g<3>", page_html)
187+
page_html = re.sub(regex, rf"\g<1>{page_key}-\g<2>\g<3>", page_html)
194188

195189
regex = re.compile(r"(\<input.*?id=\")([^\"]*?)(\".*?\>)", re.I)
196-
page_html = re.sub(regex, fr"\g<1>{page_key}-\g<2>\g<3>", page_html)
190+
page_html = re.sub(regex, rf"\g<1>{page_key}-\g<2>\g<3>", page_html)
197191

198192
regex = re.compile(r"(\<label.*?for=\")([^\"]*?)(\".*?\>)", re.I)
199-
page_html = re.sub(regex, fr"\g<1>{page_key}-\g<2>\g<3>", page_html)
193+
page_html = re.sub(regex, rf"\g<1>{page_key}-\g<2>\g<3>", page_html)
200194

201195
return page_html
202196

@@ -209,9 +203,7 @@ def fix_image_src(page_html, page_url, directory_urls):
209203
"""
210204
# Loop over all images src attributes
211205
# Example regex https://regex101.com/r/PLUmZ7/2
212-
img_regex = re.compile(
213-
r"<img[^>]+src=\"([^\">]+)\"", flags=re.IGNORECASE
214-
)
206+
img_regex = re.compile(r"<img[^>]+src=\"([^\">]+)\"", flags=re.IGNORECASE)
215207
matches = re.finditer(img_regex, page_html)
216208

217209
for m in matches:
@@ -220,7 +212,7 @@ def fix_image_src(page_html, page_url, directory_urls):
220212
continue
221213
elif is_base64_image(img_src):
222214
continue
223-
215+
224216
img_text = m.group()
225217

226218
new_url = get_url_from_root(img_src, page_url)
@@ -283,7 +275,9 @@ def fix_internal_links(page_html, page_url, directory_urls, heading_number):
283275

284276
# Finally, wrap the entire page in a section with an anchor ID
285277
page_html = (
286-
('<section class="print-page" id="%s" heading-number="%s">' % (page_key, heading_number)) + page_html + "</section>"
278+
('<section class="print-page" id="%s" heading-number="%s">' % (page_key, heading_number))
279+
+ page_html
280+
+ "</section>"
287281
)
288282

289283
return page_html

src/mkdocs_print_site_plugin/utils.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -27,4 +27,4 @@ def get_theme_name(config) -> str:
2727

2828

2929
def get_section_id(section_number: str) -> str:
30-
return f"section-{section_number.replace('.', '-')}"
30+
return f"section-{section_number.replace('.', '-')}"

0 commit comments

Comments
 (0)