Skip to content

Commit b3ee5ff

Browse files
committed
Minor cleanup
1 parent 9c1fe10 commit b3ee5ff

File tree

5 files changed

+83
-81
lines changed

5 files changed

+83
-81
lines changed

mkdocs_markmap/__meta__.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
PACKAGE_NAME: str = 'mkdocs_markmap'
2-
PROJECT_NAME: str = PACKAGE_NAME.replace('_', '-')
3-
PROJECT_VERSION: str = '2.4.0'
1+
PACKAGE_NAME: str = "mkdocs_markmap"
2+
PROJECT_NAME: str = PACKAGE_NAME.replace("_", "-")
3+
PROJECT_VERSION: str = "2.4.0"
44

5-
OWNER: str = 'neatc0der'
6-
ORGANISATION: str = 'markmap'
7-
REPOSITORY_NAME: str = f'{ORGANISATION}/{PROJECT_NAME}'
8-
REPOSITORY_URL: str = f'https://github.com/{REPOSITORY_NAME}'
5+
OWNER: str = "neatc0der"
6+
ORGANISATION: str = "markmap"
7+
REPOSITORY_NAME: str = f"{ORGANISATION}/{PROJECT_NAME}"
8+
REPOSITORY_URL: str = f"https://github.com/{REPOSITORY_NAME}"

mkdocs_markmap/defaults.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,23 +9,23 @@ class JsModuleConfig(object):
99
uri: str = attr.attrib()
1010

1111
D3_LIB: JsModuleConfig = JsModuleConfig(
12-
version='7',
13-
uri='https://unpkg.com/d3@{}',
12+
version="7",
13+
uri="https://unpkg.com/d3@{}",
1414
)
1515

1616
MARKMAP_LIB: JsModuleConfig = JsModuleConfig(
17-
version='0.15.4',
18-
uri='https://unpkg.com/markmap-lib@{}',
17+
version="0.15.4",
18+
uri="https://unpkg.com/markmap-lib@{}",
1919
)
2020

2121
MARKMAP_VIEW: JsModuleConfig = JsModuleConfig(
22-
version='0.15.4',
23-
uri='https://unpkg.com/markmap-view@{}',
22+
version="0.15.4",
23+
uri="https://unpkg.com/markmap-view@{}",
2424
)
2525

2626

2727
MARKMAP: Dict[str, JsModuleConfig] = {
28-
'd3': D3_LIB,
29-
'lib': MARKMAP_LIB,
30-
'view': MARKMAP_VIEW,
28+
"d3": D3_LIB,
29+
"lib": MARKMAP_LIB,
30+
"view": MARKMAP_VIEW,
3131
}

mkdocs_markmap/extension.py

Lines changed: 24 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,10 @@
99
from markdown.preprocessors import Preprocessor
1010

1111

12-
log = logging.getLogger('mkdocs.markmap')
12+
log = logging.getLogger("mkdocs.markmap")
1313

1414

15-
INCLUDE_SYNTAX = re.compile(r'\{!\s*(?P<path>.+?)\s*!\}')
15+
INCLUDE_SYNTAX = re.compile(r"\{!\s*(?P<path>.+?)\s*!\}")
1616

1717

1818
class MarkmapPreprocessor(Preprocessor):
@@ -22,9 +22,9 @@ class MarkmapPreprocessor(Preprocessor):
2222

2323
def __init__(self, md: Markdown, config: Dict[str, str]):
2424
super(MarkmapPreprocessor, self).__init__(md)
25-
self.base_path: str = config['base_path']
26-
self.encoding: str = config['encoding']
27-
self.file_extension: str = config['file_extension']
25+
self.base_path: str = config["base_path"]
26+
self.encoding: str = config["encoding"]
27+
self.file_extension: str = config["file_extension"]
2828

2929
def run(self, lines: List[str]) -> List[str]:
3030
done: bool = False
@@ -35,7 +35,7 @@ def run(self, lines: List[str]) -> List[str]:
3535
if match is None:
3636
continue
3737

38-
path: Path = Path(match.group('path'))
38+
path: Path = Path(match.group("path"))
3939
if not path.name.lower().endswith(self.file_extension):
4040
continue
4141

@@ -48,25 +48,25 @@ def run(self, lines: List[str]) -> List[str]:
4848

4949
included_paths.append(path)
5050
try:
51-
with open(path, 'r', encoding=self.encoding) as r:
51+
with open(path, "r", encoding=self.encoding) as r:
5252
markmap: List[str] = r.readlines()
5353

5454
except Exception as e:
55-
log.error('unable to include file {}. Ignoring statement. Error: {}'.format(path, e))
56-
lines[loc] = INCLUDE_SYNTAX.sub('',line)
55+
log.error("unable to include file {}. Ignoring statement. Error: {}".format(path, e))
56+
lines[loc] = INCLUDE_SYNTAX.sub("",line)
5757
break
5858

5959
line_split: List[str] = INCLUDE_SYNTAX.split(line)
6060
if len(markmap) == 0:
61-
markmap.append('')
61+
markmap.append("")
6262
else:
63-
markmap.insert(0, '```markmap')
64-
markmap.append('```')
63+
markmap.insert(0, "```markmap")
64+
markmap.append("```")
6565

66-
if line_split[0].strip() != '':
66+
if line_split[0].strip() != "":
6767
markmap.insert(0, line_split[0])
6868

69-
if line_split[2].strip() != '':
69+
if line_split[2].strip() != "":
7070
markmap.append(line_split[2])
7171

7272
lines = lines[:loc] + markmap + lines[loc+1:]
@@ -80,9 +80,9 @@ def run(self, lines: List[str]) -> List[str]:
8080

8181
class MarkmapExtension(Extension):
8282
config_defaults: Dict[str, str] = {
83-
'base_path': ['docs', 'Default location from which to evaluate relative paths for the include statement.'],
84-
'encoding': ['utf-8', 'Encoding of the files used by the include statement.'],
85-
'file_extension': ['.mm.md', 'File extension of mindmap files'],
83+
"base_path": ["docs", "Default location from which to evaluate relative paths for the include statement."],
84+
"encoding": ["utf-8", "Encoding of the files used by the include statement."],
85+
"file_extension": [".mm.md", "File extension of mindmap files"],
8686
}
8787

8888
def __init__(self, **configs: Dict[str, str]):
@@ -91,21 +91,21 @@ def __init__(self, **configs: Dict[str, str]):
9191
self.setConfig(key, value)
9292

9393
def extendMarkdown(self, md: Markdown) -> None:
94-
md.preprocessors.register(MarkmapPreprocessor(md, self.getConfigs()), 'include_markmap', 102)
94+
md.preprocessors.register(MarkmapPreprocessor(md, self.getConfigs()), "include_markmap", 102)
9595
for extension in md.registeredExtensions:
96-
if extension.__class__.__name__ == 'SuperFencesCodeExtension':
97-
log.info(f'superfences detected by markmap')
96+
if extension.__class__.__name__ == "SuperFencesCodeExtension":
97+
log.info(f"superfences detected by markmap")
9898
try:
9999
from pymdownx.superfences import default_validator, fence_code_format, _formatter, _validator
100100
extension.extend_super_fences(
101-
'markmap',
102-
partial(_formatter, class_name='language-markmap', _fmt=fence_code_format),
101+
"markmap",
102+
partial(_formatter, class_name="language-markmap", _fmt=fence_code_format),
103103
partial(_validator, validator=default_validator)
104104
)
105105
break
106106

107107
except ImportError as e:
108-
log.warning(f'markmap detected pymdownx.superfences, but import is not working: {e}')
108+
log.warning(f"markmap detected pymdownx.superfences, but import is not working: {e}")
109109

110110
except Exception as e:
111-
log.error(f'unexpected error: {e}')
111+
log.error(f"unexpected error: {e}")

mkdocs_markmap/plugin.py

Lines changed: 36 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,14 @@
1515
from .utils import download
1616

1717

18-
log = logging.getLogger('mkdocs.markmap')
18+
log = logging.getLogger("mkdocs.markmap")
1919

2020

21-
STATICS_PATH: Path = Path(__file__).parent / 'static_files'
22-
STYLE_PATH: Path = STATICS_PATH / 'mkdocs-markmap.css'
23-
SCRIPT_PATH: Path = STATICS_PATH / 'mkdocs-markmap.js'
21+
STATICS_PATH: Path = Path(__file__).parent / "static_files"
22+
STYLE_PATH: Path = STATICS_PATH / "mkdocs-markmap.css"
23+
SCRIPT_PATH: Path = STATICS_PATH / "mkdocs-markmap.js"
24+
25+
VERSION_KEY = "{name}_version"
2426

2527

2628
class MarkmapPlugin(BasePlugin):
@@ -29,12 +31,12 @@ class MarkmapPlugin(BasePlugin):
2931
"""
3032
config_scheme: Tuple[Tuple[str, PluginType]] = (
3133
*(
32-
(f'{name}_version', PluginType(str, default=module.version))
34+
(VERSION_KEY.format(name=name), PluginType(str, default=module.version))
3335
for name, module in MARKMAP.items()
3436
),
35-
('base_path', PluginType(str, default='docs')),
36-
('encoding', PluginType(str, default='utf-8')),
37-
('file_extension', PluginType(str, default='.mm.md')),
37+
("base_path", PluginType(str, default="docs")),
38+
("encoding", PluginType(str, default="utf-8")),
39+
("file_extension", PluginType(str, default=".mm.md")),
3840
)
3941

4042
def __init__(self):
@@ -48,83 +50,83 @@ def markmap(self) -> Dict[str, str]:
4850
if self._markmap is None:
4951
self._markmap: Dict[str, str] = {}
5052
for name, module in MARKMAP.items():
51-
if self.config[f'{name}_version']:
52-
self._markmap[name] = module.uri.format(self.config[f'{name}_version'])
53+
if self.config[VERSION_KEY.format(name=name)]:
54+
self._markmap[name] = module.uri.format(self.config[VERSION_KEY.format(name=name)])
5355

5456
return self._markmap
5557

5658
def _load_scripts(self, soup: BeautifulSoup, script_base_url: str, js_path: Path) -> None:
5759
for script_url in self.markmap.values():
5860
if script_url.lower().startswith("http"):
5961
try:
60-
src: str = script_base_url + download(js_path, script_url, extname='.js')
62+
src: str = script_base_url + download(js_path, script_url, extname=".js")
6163
except Exception as e:
62-
log.error(f'unable to download script: {script_url}')
64+
log.error(f"unable to download script: {script_url}")
6365
src = script_url
6466

6567
else:
6668
log.info(f"static script detected: {script_url}")
6769
src = script_url
6870

69-
script: Tag = soup.new_tag('script', src=src, type='text/javascript')
71+
script: Tag = soup.new_tag("script", src=src, type="text/javascript")
7072
soup.head.append(script)
7173

7274
@staticmethod
7375
def _add_statics(soup: BeautifulSoup):
7476
statics = (
75-
(STYLE_PATH, 'style', 'text/css', 'head'),
76-
(SCRIPT_PATH, 'script', 'text/javascript', 'body'),
77+
(STYLE_PATH, "style", "text/css", "head"),
78+
(SCRIPT_PATH, "script", "text/javascript", "body"),
7779
)
7880

7981
for path, tag_name, text_type, attribute in statics:
8082
tag: Tag = soup.new_tag(tag_name, type=text_type)
81-
with open(path, 'r') as fp:
83+
with open(path, "r") as fp:
8284
tag.string = fp.read()
8385
getattr(soup, attribute).append(tag)
8486

8587
def on_config(self, config: Config) -> Config:
86-
config['markdown_extensions'].append('markmap')
87-
config['mdx_configs']['markmap'] = {
88+
config["markdown_extensions"].append("markmap")
89+
config["mdx_configs"]["markmap"] = {
8890
key: value
89-
for key, value in config['plugins'].get('markmap').config.items()
91+
for key, value in config["plugins"].get("markmap").config.items()
9092
if key in MarkmapExtension.config_defaults
9193
}
92-
self.config['extra_javascript'] = config.get('extra_javascript', [])
94+
self.config["extra_javascript"] = config.get("extra_javascript", [])
9395

9496
return config
9597

9698
def on_post_page(self, html: str, page: Page, config: Config, **kwargs) -> str:
97-
if not getattr(page, '_found_markmap', False):
99+
if not getattr(page, "_found_markmap", False):
98100
log.info(f"no markmap found: {page.file.name}")
99101
return html
100102

101-
soup: BeautifulSoup = BeautifulSoup(html, 'html.parser')
102-
script_base_url: str = re.sub(r'[^/]+?/', '../', re.sub(r'/+?', '/', page.url)) + 'js/'
103-
js_path: Path = Path(config['site_dir']) / 'js'
103+
soup: BeautifulSoup = BeautifulSoup(html, "html.parser")
104+
script_base_url: str = re.sub(r"[^/]+?/", "../", re.sub(r"/+?", "/", page.url)) + "js/"
105+
js_path: Path = Path(config["site_dir"]) / "js"
104106
self._load_scripts(soup, script_base_url, js_path)
105107
self._add_statics(soup)
106108

107109
return str(soup)
108110

109111
def on_page_content(self, html: str, page: Page, **kwargs) -> str:
110-
soup: BeautifulSoup = BeautifulSoup(html, 'html.parser')
111-
markmaps: ResultSet = soup.find_all(class_='language-markmap')
112-
setattr(page, '_found_markmap', any(markmaps))
112+
soup: BeautifulSoup = BeautifulSoup(html, "html.parser")
113+
markmaps: ResultSet = soup.find_all(class_="language-markmap")
114+
setattr(page, "_found_markmap", any(markmaps))
113115

114116
for index, markmap in enumerate(markmaps):
115117
markmap: Tag
116-
tag_id: str = f'markmap-{index}'
118+
tag_id: str = f"markmap-{index}"
117119
pre: Tag
118120
code: Tag
119-
if markmap.name == 'pre':
121+
if markmap.name == "pre":
120122
pre = markmap
121-
code = markmap.findChild('code')
123+
code = markmap.findChild("code")
122124
else:
123125
pre = markmap.parent
124126
code = markmap
125-
pre.name = 'div'
126-
pre['class'] = pre.get('class', []) + ['mkdocs-markmap']
127-
code.name = 'script'
128-
code['type'] = 'text/template'
127+
pre.name = "div"
128+
pre["class"] = pre.get("class", []) + ["mkdocs-markmap"]
129+
code.name = "script"
130+
code["type"] = "text/template"
129131

130132
return str(soup)

mkdocs_markmap/utils.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,14 @@
1010
from requests.sessions import Session
1111

1212

13-
log = logging.getLogger('mkdocs.markmap')
13+
log = logging.getLogger("mkdocs.markmap")
1414

1515

16-
def download(base_path: Path, url: str, flat: bool = False, force_reload: bool = False, extname: str = '') -> str:
16+
def download(base_path: Path, url: str, flat: bool = False, force_reload: bool = False, extname: str = "") -> str:
1717
parsed_url: Url = parse_url(url)
18-
path: str = unquote(parsed_url.request_uri.split('?')[0])
19-
sub_path: str = os.path.basename(path) if flat else f'{parsed_url.hostname}{path}'
20-
if extname != '' and not sub_path.endswith(extname):
18+
path: str = unquote(parsed_url.request_uri.split("?")[0])
19+
sub_path: str = os.path.basename(path) if flat else f"{parsed_url.hostname}{path}"
20+
if extname and not sub_path.endswith(extname):
2121
sub_path += extname
2222
file_path: Path = base_path / sub_path
2323

@@ -31,11 +31,11 @@ def download(base_path: Path, url: str, flat: bool = False, force_reload: bool =
3131
http.mount("http://", adapter)
3232

3333
response: Response = http.get(url, allow_redirects=True, timeout=3.0)
34-
with open(file_path, 'wb') as fp:
34+
with open(file_path, "wb") as fp:
3535
for chunk in response.iter_content(chunk_size=1024):
3636
if chunk:
3737
fp.write(chunk)
3838

39-
log.info(f'script downloaded: {url}')
39+
log.info(f"script downloaded: {url}")
4040

4141
return str(sub_path)

0 commit comments

Comments
 (0)