Skip to content

Commit

Permalink
Refactor around dict key access
Browse files Browse the repository at this point in the history
  • Loading branch information
oprypin committed Jun 23, 2023
1 parent b162c5e commit 7b1bc92
Show file tree
Hide file tree
Showing 8 changed files with 49 additions and 43 deletions.
2 changes: 1 addition & 1 deletion docs/about/release-notes.md
Original file line number Diff line number Diff line change
Expand Up @@ -888,7 +888,7 @@ corresponding configuration values (`config.extra_javascript` and
`config.extra_css` respectively) should be used with the filter instead.

```django
{% for path in config['extra_css'] %}
{% for path in config.extra_css %}
<link href="{{ path|url }}" rel="stylesheet">
{% endfor %}
```
Expand Down
5 changes: 1 addition & 4 deletions mkdocs/commands/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,10 +212,7 @@ def _build_page(
context = get_context(nav, doc_files, config, page)

# Allow 'template:' override in md source files.
if 'template' in page.meta:
template = env.get_template(page.meta['template'])
else:
template = env.get_template('main.html')
template = env.get_template(page.meta.get('template', 'main.html'))

# Run `page_context` plugin events.
context = config.plugins.on_page_context(context, page=page, config=config, nav=nav)
Expand Down
13 changes: 7 additions & 6 deletions mkdocs/contrib/search/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

if TYPE_CHECKING:
from mkdocs.config.defaults import MkDocsConfig
from mkdocs.structure.pages import Page
from mkdocs.util.templates import TemplateContext

log = logging.getLogger(__name__)
Expand Down Expand Up @@ -62,17 +63,17 @@ class SearchPlugin(BasePlugin[_PluginConfig]):

def on_config(self, config: MkDocsConfig, **kwargs) -> MkDocsConfig:
"Add plugin templates and scripts to config."
if 'include_search_page' in config.theme and config.theme['include_search_page']:
if config.theme.get('include_search_page'):
config.theme.static_templates.add('search.html')
if not ('search_index_only' in config.theme and config.theme['search_index_only']):
if not config.theme.get('search_index_only'):
path = os.path.join(base_path, 'templates')
config.theme.dirs.append(path)
if 'search/main.js' not in config.extra_javascript:
config.extra_javascript.append('search/main.js') # type: ignore
if self.config.lang is None:
# lang setting undefined. Set default based on theme locale
validate = _PluginConfig.lang.run_validation
self.config.lang = validate(config.theme['locale'].language)
self.config.lang = validate(config.theme.locale.language)
# The `python` method of `prebuild_index` is pending deprecation as of version 1.2.
# TODO: Raise a deprecation warning in a future release (1.3?).
if self.config.prebuild_index == 'python':
Expand All @@ -86,9 +87,9 @@ def on_pre_build(self, config: MkDocsConfig, **kwargs) -> None:
"Create search index instance for later use."
self.search_index = SearchIndex(**self.config)

def on_page_context(self, context: TemplateContext, **kwargs) -> None:
def on_page_context(self, context: TemplateContext, page: Page, **kwargs) -> None:
"Add page to search index."
self.search_index.add_entry_from_context(context['page'])
self.search_index.add_entry_from_context(page)

def on_post_build(self, config: MkDocsConfig, **kwargs) -> None:
"Build search index."
Expand All @@ -98,7 +99,7 @@ def on_post_build(self, config: MkDocsConfig, **kwargs) -> None:
utils.write_file(search_index.encode('utf-8'), json_output_path)

assert self.config.lang is not None
if not ('search_index_only' in config.theme and config.theme['search_index_only']):
if not config.theme.get('search_index_only'):
# Include language support files in output. Copy them directly
# so that only the needed files are included.
files = []
Expand Down
2 changes: 1 addition & 1 deletion mkdocs/structure/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,5 +32,5 @@ def ancestors(self) -> Iterable[StructureItem]:
return []
return [self.parent, *self.parent.ancestors]

def _indent_print(self, depth=0):
def _indent_print(self, depth: int = 0) -> str:
return (' ' * depth) + repr(self)
2 changes: 1 addition & 1 deletion mkdocs/structure/nav.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ def active(self, value: bool):
is_link: bool = False
"""Indicates that the navigation object is a "link" object. Always `False` for section objects."""

def _indent_print(self, depth: int = 0):
def _indent_print(self, depth: int = 0) -> str:
ret = [super()._indent_print(depth)]
for item in self.children:
ret.append(item._indent_print(depth + 1))
Expand Down
59 changes: 36 additions & 23 deletions mkdocs/structure/toc.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,35 +7,30 @@
"""
from __future__ import annotations

from typing import Any
import sys
from typing import Iterable, Iterator

if sys.version_info >= (3, 8):
from typing import TypedDict
else:
from typing_extensions import TypedDict

def get_toc(toc_tokens: list) -> TableOfContents:

class _TocToken(TypedDict):
level: int
id: str
name: str
children: list[_TocToken]


def get_toc(toc_tokens: list[_TocToken]) -> TableOfContents:
toc = [_parse_toc_token(i) for i in toc_tokens]
# For the table of contents, always mark the first element as active
if len(toc):
toc[0].active = True # type: ignore[attr-defined]
return TableOfContents(toc)


class TableOfContents:
"""
Represents the table of contents for a given page.
"""

def __init__(self, items: list) -> None:
self.items = items

def __iter__(self):
return iter(self.items)

def __len__(self) -> int:
return len(self.items)

def __str__(self) -> str:
return ''.join(str(item) for item in self)


class AnchorLink:
"""
A single entry in the table of contents.
Expand All @@ -59,18 +54,36 @@ def url(self) -> str:
children: list[AnchorLink]
"""An iterable of any child items."""

def __str__(self):
def __str__(self) -> str:
return self.indent_print()

def indent_print(self, depth=0):
def indent_print(self, depth: int = 0) -> str:
indent = ' ' * depth
ret = f'{indent}{self.title} - {self.url}\n'
for item in self.children:
ret += item.indent_print(depth + 1)
return ret


def _parse_toc_token(token: dict[str, Any]) -> AnchorLink:
class TableOfContents(Iterable[AnchorLink]):
"""
Represents the table of contents for a given page.
"""

def __init__(self, items: list[AnchorLink]) -> None:
self.items = items

def __iter__(self) -> Iterator[AnchorLink]:
return iter(self.items)

def __len__(self) -> int:
return len(self.items)

def __str__(self) -> str:
return ''.join(str(item) for item in self)


def _parse_toc_token(token: _TocToken) -> AnchorLink:
anchor = AnchorLink(token['name'], token['id'], token['level'])
for i in token['children']:
anchor.children.append(_parse_toc_token(i))
Expand Down
2 changes: 1 addition & 1 deletion mkdocs/tests/config/config_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ def test_theme(self, mytheme, custom):
self.assertEqual(warnings, [])
self.assertEqual(conf['theme'].dirs, result['dirs'])
self.assertEqual(conf['theme'].static_templates, set(result['static_templates']))
self.assertEqual({k: conf['theme'][k] for k in iter(conf['theme'])}, result['vars'])
self.assertEqual(dict(conf['theme']), result['vars'])

def test_empty_nav(self):
conf = defaults.MkDocsConfig(
Expand Down
7 changes: 1 addition & 6 deletions mkdocs/tests/theme_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,6 @@
theme_dir = os.path.abspath(os.path.join(mkdocs_dir, 'themes'))


def get_vars(theme):
"""Return dict of theme vars."""
return {k: theme[k] for k in iter(theme)}


class ThemeTests(unittest.TestCase):
def test_simple_theme(self):
theme = Theme(name='mkdocs')
Expand All @@ -27,7 +22,7 @@ def test_simple_theme(self):
)
self.assertEqual(theme.static_templates, {'404.html', 'sitemap.xml'})
self.assertEqual(
get_vars(theme),
dict(theme),
{
'name': 'mkdocs',
'locale': parse_locale('en'),
Expand Down

0 comments on commit 7b1bc92

Please sign in to comment.