Skip to content

Commit 931d30b

Browse files
chore: formating src by ruff
1 parent f6086a9 commit 931d30b

8 files changed

Lines changed: 166 additions & 151 deletions

File tree

src/mkdocs_note/cli.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313

1414
def get_version():
1515
"""Get the version of mkdocs-note package.
16-
16+
1717
Returns:
1818
str: Version string from package metadata
1919
"""
@@ -92,7 +92,7 @@ def format_commands(self, ctx, formatter):
9292
@click.pass_context
9393
def cli(ctx):
9494
"""MkDocs Note CLI - Manage notes and their assets structure.
95-
95+
9696
A command-line interface for managing MkDocs notes with co-located assets.
9797
"""
9898
ctx.ensure_object(dict)
@@ -103,12 +103,12 @@ def cli(ctx):
103103
@click.pass_context
104104
def new_command(ctx, file_path):
105105
"""Create a new note file with proper asset structure.
106-
106+
107107
\b
108108
Examples:
109109
mkdocs-note new docs/notes/my-note.md
110110
mkdocs-note new docs/notes/python/intro.md
111-
111+
112112
FILE_PATH: Path where the new note file should be created
113113
"""
114114
click.echo("⚠️ 'new' command is not yet implemented")
@@ -121,15 +121,15 @@ def new_command(ctx, file_path):
121121
@click.pass_context
122122
def remove_command(ctx, file_path):
123123
"""Remove a note file and its corresponding asset directory.
124-
124+
125125
\b
126126
Aliases: rm
127-
127+
128128
\b
129129
Examples:
130130
mkdocs-note remove docs/notes/test.md
131131
mkdocs-note rm docs/notes/test.md --yes
132-
132+
133133
FILE_PATH: Path to the note file to remove
134134
"""
135135
click.echo("⚠️ 'remove' command is not yet implemented")
@@ -151,15 +151,15 @@ def rm_command(ctx, file_path):
151151
@click.pass_context
152152
def move_command(ctx, source, destination):
153153
"""Move or rename a note file/directory and its asset directory.
154-
154+
155155
\b
156156
Aliases: mv
157-
157+
158158
\b
159159
Examples:
160160
mkdocs-note move docs/notes/old.md docs/notes/new.md
161161
mkdocs-note mv docs/notes/test.md docs/notes/archive
162-
162+
163163
\b
164164
Arguments:
165165
SOURCE: Current path of the note file or directory
@@ -183,7 +183,7 @@ def mv_command(ctx, source, destination):
183183
@click.pass_context
184184
def clean_command(ctx):
185185
"""Clean up orphaned asset directories without corresponding notes.
186-
186+
187187
\b
188188
Examples:
189189
mkdocs-note clean --dry-run
@@ -198,10 +198,10 @@ def clean_command(ctx):
198198
@click.pass_context
199199
def template_command(ctx):
200200
"""Manage the note template file.
201-
201+
202202
This command helps you check and create the template file
203203
configured in your mkdocs.yml.
204-
204+
205205
\b
206206
Examples:
207207
mkdocs-note template

src/mkdocs_note/config.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ class MkdocsNoteConfig(Config):
1515
"""
1616

1717
recent_notes_config = config_opt.Type(
18-
dict,
18+
dict,
1919
default={
2020
"enabled": False,
2121
"insert_marker": "<!-- recent_notes -->",

src/mkdocs_note/graph.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616

1717
logger = get_plugin_logger(__name__)
1818

19+
1920
class Graph:
2021
"""Represents the connection graph between files."""
2122

@@ -121,6 +122,7 @@ def to_dict(self):
121122
"""Return the graph as a dictionary."""
122123
return {"nodes": self.nodes, "edges": self.edges}
123124

125+
124126
def add_static_resouces(config: MkDocsConfig) -> None:
125127
"""Add static resources into mkdocs config for network graph.
126128
@@ -134,9 +136,10 @@ def add_static_resouces(config: MkDocsConfig) -> None:
134136
if "css/graph.css" not in config["extra_css"]:
135137
config["extra_css"].append("css/graph.css")
136138

139+
137140
def inject_graph_script(output: str, config: MkDocsConfig, debug: bool = False) -> str:
138141
"""Inject the graph script into the HTML page.
139-
142+
140143
Args:
141144
output (str): The HTML output.
142145
config (MkDocsConfig): The MkDocs configuration.
@@ -166,9 +169,10 @@ def inject_graph_script(output: str, config: MkDocsConfig, debug: bool = False)
166169
return output.replace("</body>", f"{options_script}</body>")
167170
return output
168171

172+
169173
def copy_static_assets(static_dir: str, config: MkDocsConfig) -> None:
170174
"""Copy static assets into the site directory.
171-
175+
172176
Args:
173177
config (MkDocsConfig): The MkDocs configuration.
174178
"""

src/mkdocs_note/plugin.py

Lines changed: 38 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -12,16 +12,21 @@
1212
from mkdocs_note.config import MkdocsNoteConfig
1313
from mkdocs_note.utils import scanner
1414
from mkdocs_note.utils.meta import extract_title, extract_date
15-
from mkdocs_note.graph import Graph, add_static_resouces, inject_graph_script, copy_static_assets
15+
from mkdocs_note.graph import (
16+
Graph,
17+
add_static_resouces,
18+
inject_graph_script,
19+
copy_static_assets,
20+
)
1621

1722

1823
log = get_plugin_logger(__name__)
1924

25+
2026
class MkdocsNotePlugin(BasePlugin[MkdocsNoteConfig]):
2127
"""Mkdocs Note Plugin entry point."""
2228

2329
notes_list: list[File] = []
24-
2530

2631
@event_priority(100)
2732
def on_files(self, files: Files, config: MkDocsConfig) -> Files:
@@ -46,12 +51,7 @@ def on_config(self, config: MkDocsConfig) -> MkDocsConfig:
4651

4752
return config
4853

49-
def on_pre_build(
50-
self,
51-
*,
52-
config: dict,
53-
**kwagrs
54-
) -> None:
54+
def on_pre_build(self, *, config: dict, **kwagrs) -> None:
5555
"""Handle pre-build."""
5656
if self.config.graph_config["enabled"]:
5757
self._graph = Graph(self.config.graph_config)
@@ -121,7 +121,7 @@ def on_post_build(
121121
config (MkDocsConfig): The MkDocs configuration.
122122
"""
123123
# Build graph if enabled
124-
if hasattr(self, '_graph') and hasattr(self, '_files'):
124+
if hasattr(self, "_graph") and hasattr(self, "_files"):
125125
self._graph(self._files)
126126
self._write_graph_file(config=config)
127127

@@ -150,7 +150,9 @@ def on_page_markdown(
150150
str: The markdown content.
151151
"""
152152
# Only process recent notes on the note index page
153-
if self.config.recent_notes_config["enabled"] and self.is_note_index_page(page.file):
153+
if self.config.recent_notes_config["enabled"] and self.is_note_index_page(
154+
page.file
155+
):
154156
markdown = insert_recent_note_links(
155157
markdown=markdown,
156158
notes_list=self.notes_list,
@@ -161,7 +163,6 @@ def on_page_markdown(
161163

162164
return markdown
163165

164-
165166
def is_note_index_page(self, f: File) -> bool:
166167
"""Check if the page is a note index page.
167168
@@ -177,30 +178,30 @@ def is_note_index_page(self, f: File) -> bool:
177178

178179

179180
def insert_recent_note_links(
180-
markdown: str,
181-
notes_list: list[File],
182-
insert_num: int,
183-
replace_marker: str,
181+
markdown: str,
182+
notes_list: list[File],
183+
insert_num: int,
184+
replace_marker: str,
184185
) -> str:
185-
"""Insert recent note links into the markdown.
186-
187-
Args:
188-
markdown (str): The markdown content.
189-
notes_list (list[File]): The list of valid notes.
190-
insert_num (int): The number of recent notes to insert.
191-
replace_marker (str): The marker to replace.
192-
193-
Returns:
194-
str: The markdown content with recent note links inserted.
195-
"""
196-
197-
content = "<ul>\n"
198-
for f in notes_list[:insert_num]:
199-
title = extract_title(f)
200-
date = extract_date(f).strftime("%Y-%m-%d %H:%M:%S")
201-
# Use f.url (relative URL) or f.page.url if page is available
202-
url = f.page.url if hasattr(f, 'page') and f.page else f.url
203-
# No indentation to avoid Markdown treating it as code block
204-
content += f'<li><div style="display:flex; justify-content:space-between; align-items:center;"><a href="{url}">{title}</a><span style="font-size:0.8em; color:#888;">{date}</span></div></li>\n'
205-
content += "</ul>\n"
206-
return markdown.replace(replace_marker, content)
186+
"""Insert recent note links into the markdown.
187+
188+
Args:
189+
markdown (str): The markdown content.
190+
notes_list (list[File]): The list of valid notes.
191+
insert_num (int): The number of recent notes to insert.
192+
replace_marker (str): The marker to replace.
193+
194+
Returns:
195+
str: The markdown content with recent note links inserted.
196+
"""
197+
198+
content = "<ul>\n"
199+
for f in notes_list[:insert_num]:
200+
title = extract_title(f)
201+
date = extract_date(f).strftime("%Y-%m-%d %H:%M:%S")
202+
# Use f.url (relative URL) or f.page.url if page is available
203+
url = f.page.url if hasattr(f, "page") and f.page else f.url
204+
# No indentation to avoid Markdown treating it as code block
205+
content += f'<li><div style="display:flex; justify-content:space-between; align-items:center;"><a href="{url}">{title}</a><span style="font-size:0.8em; color:#888;">{date}</span></div></li>\n'
206+
content += "</ul>\n"
207+
return markdown.replace(replace_marker, content)

src/mkdocs_note/utils/meta.py

Lines changed: 59 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -8,73 +8,79 @@
88

99
logger = get_plugin_logger(__name__)
1010

11+
1112
def validate_frontmatter(f: File) -> bool:
12-
"""Validate the frontmatter of the file
13+
"""Validate the frontmatter of the file
14+
15+
Args:
16+
file (File): The file to validate
1317
14-
Args:
15-
file (File): The file to validate
18+
Returns:
19+
bool: True if the frontmatter is valid, False otherwise
20+
"""
21+
try:
22+
_, frontmatter = meta.get_data(f.content_string)
1623

17-
Returns:
18-
bool: True if the frontmatter is valid, False otherwise
19-
"""
20-
try:
21-
_, frontmatter = meta.get_data(f.content_string)
24+
if not frontmatter.get("publish", False):
25+
logger.debug(f"Skipping {f.src_uri} because it is not published")
26+
return False
2227

23-
if not frontmatter.get("publish", False):
24-
logger.debug(f"Skipping {f.src_uri} because it is not published")
25-
return False
28+
if "date" not in frontmatter:
29+
logger.error(f"Invalid frontmatter for {f.src_uri}: 'date' is required")
30+
return False
2631

27-
if "date" not in frontmatter:
28-
logger.error(f"Invalid frontmatter for {f.src_uri}: 'date' is required")
29-
return False
32+
date = frontmatter["date"]
33+
if not isinstance(date, datetime):
34+
logger.error(
35+
f"Invalid frontmatter for {f.src_uri}: 'date' must be a datetime object"
36+
)
37+
return False
3038

31-
date = frontmatter["date"]
32-
if not isinstance(date, datetime):
33-
logger.error(f"Invalid frontmatter for {f.src_uri}: 'date' must be a datetime object")
34-
return False
39+
setattr(f, "note_date", date)
3540

36-
setattr(f, "note_date", date)
41+
if "title" not in frontmatter:
42+
logger.error(f"Invalid frontmatter for {f.src_uri}: 'title' is required")
43+
return False
3744

38-
if "title" not in frontmatter:
39-
logger.error(f"Invalid frontmatter for {f.src_uri}: 'title' is required")
40-
return False
45+
title = frontmatter["title"]
46+
if not isinstance(title, str):
47+
logger.error(
48+
f"Invalid frontmatter for {f.src_uri}: 'title' must be a string"
49+
)
50+
return False
4151

42-
title = frontmatter["title"]
43-
if not isinstance(title, str):
44-
logger.error(f"Invalid frontmatter for {f.src_uri}: 'title' must be a string")
45-
return False
52+
setattr(f, "note_title", title)
53+
return True
4654

47-
setattr(f, "note_title", title)
48-
return True
55+
except Exception as e:
56+
logger.error(f"Error validating frontmatter for {f.src_uri}: {e}")
57+
raise e
4958

50-
except Exception as e:
51-
logger.error(f"Error validating frontmatter for {f.src_uri}: {e}")
52-
raise e
5359

5460
def extract_date(f: File) -> Optional[datetime]:
55-
"""Extract date from docs file
56-
Args:
57-
f (File): The file to extract date from
61+
"""Extract date from docs file
62+
Args:
63+
f (File): The file to extract date from
5864
59-
Returns:
60-
Optional[datetime]: The date if successful, None otherwise
61-
"""
62-
try:
63-
return f.note_date
64-
except Exception:
65-
return None
65+
Returns:
66+
Optional[datetime]: The date if successful, None otherwise
67+
"""
68+
try:
69+
return f.note_date
70+
except Exception:
71+
return None
6672

6773

6874
def extract_title(f: File) -> Optional[str]:
69-
"""Extract title from docs file
70-
71-
Args:
72-
f (File): The file to extract title from
73-
74-
Returns:
75-
Optional[str]: The title if successful, None otherwise
76-
"""
77-
try:
78-
return f.note_title
79-
except Exception:
80-
return None
75+
"""Extract title from docs file
76+
77+
Args:
78+
f (File): The file to extract title from
79+
80+
Returns:
81+
Optional[str]: The title if successful, None otherwise
82+
"""
83+
try:
84+
return f.note_title
85+
except Exception:
86+
return None

0 commit comments

Comments
 (0)