Skip to content

Commit

Permalink
Fixed run on Python 3.5.
Browse files Browse the repository at this point in the history
  • Loading branch information
orzih committed Jan 11, 2021
1 parent 1c935b6 commit d307c46
Show file tree
Hide file tree
Showing 17 changed files with 241 additions and 203 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
mkdocs-with-pdf 0.8.3 (2021-01-11)

* Fixed run on Python 3.5.

mkdocs-with-pdf 0.8.2 (2021-01-08)

* Added a rendering hook module handler.
Expand Down
3 changes: 1 addition & 2 deletions Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ autopep8 = "*"
mdx-gh-links = "*"
mkdocs-redirects = "*"
mkdocs-minify-plugin = "*"
python-barcode = "*"
qrcode = "*"

[packages]
Expand All @@ -30,5 +29,5 @@ weasyprint = "*"

[scripts]
lint = "flake8 --show-source mkdocs_with_pdf"
format = "autopep8 -ivr mkdocs_with_pdf"
format = "autopep8 -ivaar mkdocs_with_pdf"
test = "python -m unittest discover -v -s tests"
286 changes: 154 additions & 132 deletions Pipfile.lock

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions mkdocs_with_pdf/cover.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def _make_cover(soup: PageElement, options: Options):
keywords = options.template.keywords
template = options.template.select(['cover', 'default_cover'])

options.logger.info(f'Generate a cover page with "{template.name}".')
options.logger.info('Generate a cover page with "%s".', template.name)
soup_template = BeautifulSoup(template.render(keywords), 'html.parser')

soup.body.insert(0, soup_template)
Expand All @@ -38,7 +38,7 @@ def _make_back_cover(soup: PageElement, options: Options):
['back_cover', 'default_back_cover'])

options.logger.info(
f'Generate a back cover page with "{template.name}".')
'Generate a back cover page with "%s".', template.name)
soup_template = BeautifulSoup(template.render(keywords), 'html.parser')

soup.body.append(soup_template)
Expand Down
6 changes: 3 additions & 3 deletions mkdocs_with_pdf/drivers/event_hook.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ class EventHookHandler(object):

@classmethod
def on_serve(cls, server, builder, logger: logging):
path = f'./{cls._module_name}.py'
path = './' + cls._module_name + '.py'
if os.path.isfile(path):
logger.warn(f'watch {path}')
logger.warn('watch %s', path)
server.watch(path, builder)

def __init__(self, options: object, config: Config, logger: logging):
Expand All @@ -37,7 +37,7 @@ def _load_module(self):
module = __import__(self.__class__._module_name)
importlib.reload(module)
self._logger.info('Found PDF rendering event hook module.')
except ModuleNotFoundError:
except ImportError:
module = None

return module
Expand Down
4 changes: 2 additions & 2 deletions mkdocs_with_pdf/drivers/headless_chrome.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ def setup(self, program_path: str, logger: Logger):
if not which(program_path):
raise RuntimeError(
'No such `Headless Chrome` program or not executable'
+ f': "{program_path}".')
+ ': ' + program_path + '.')
return self(program_path, logger)

def __init__(self, program_path: str, logger: Logger):
Expand Down Expand Up @@ -41,7 +41,7 @@ def render(self, html: str) -> str:
return chrome.stdout.read().decode('utf-8')

except Exception as e:
self._logger.error(f'Failed to render by JS: {e}')
self._logger.error('Failed to render by JS: %s', e)
finally:
os.unlink(temp.name)

Expand Down
52 changes: 28 additions & 24 deletions mkdocs_with_pdf/generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def on_nav(self, nav):
""" on_nav """
self._nav = nav
if nav:
self._options.logger.debug(f'theme: {self._theme}')
self._options.logger.debug('theme: %s', self._theme)

def on_post_page(self, output_content: str, page, pdf_path: str) -> str:
""" on_post_page """
Expand All @@ -47,18 +47,18 @@ def is_excluded(url: str) -> bool:
return url in self._options.exclude_pages

if is_excluded(page.url):
self.logger.info(f'Page skipped: [{page.title}]({page.url})')
return f"<!-- skipped '{page}' -->"
self.logger.info('Page skipped: [%s](%s)', page.title, page.url)
return "<!-- skipped '{}' -->".format(page)
else:
self.logger.debug(f' (post: [{page.title}]({page.url})')
self.logger.debug(' (post: [%s](%s)', page.title, page.url)

soup = self._soup_from_content(output_content, page)

self._remove_empty_tags(soup)

if not self._head:
self._head = soup.find('head')
# self.logger.debug(f'{self._head}')
# self.logger.debug('%s', self._head)

# for 'material'
article = soup.find('article')
Expand All @@ -83,7 +83,8 @@ def is_excluded(url: str) -> bool:
setattr(page, 'pdf-article', article)
self._scrap_scripts(soup)
else:
self.logger.warning(f'Missing article: [{page.title}]({page.url})')
self.logger.warning(
'Missing article: [%s](%s)', page.title, page.url)

return self._options.hook.inject_link(
output_content, pdf_path, page, self._theme)
Expand Down Expand Up @@ -128,7 +129,7 @@ def add_stylesheet(stylesheet: str):
html_string = self._options.hook.pre_pdf_render(html_string)

if self._options.debug_html:
print(f'{html_string}')
print(html_string)

self.logger.info("Rendering for PDF.")
html = HTML(string=html_string)
Expand All @@ -137,7 +138,7 @@ def add_stylesheet(stylesheet: str):
abs_pdf_path = os.path.join(config['site_dir'], output_path)
os.makedirs(os.path.dirname(abs_pdf_path), exist_ok=True)

self.logger.info(f'Output a PDF to "{abs_pdf_path}".')
self.logger.info('Output a PDF to "%s".', abs_pdf_path)
render.write_pdf(abs_pdf_path)

# ------------------------
Expand All @@ -156,7 +157,7 @@ def is_blank(el):
hit = False
for x in soup.find_all():
if x.name in includes and is_blank(x):
# self.logger.debug(f'Strip: {x}')
# self.logger.debug('Strip: %s'%(x))
x.extract()
hit = True
if not hit:
Expand Down Expand Up @@ -199,13 +200,13 @@ def _get_content(self, soup: PageElement, page):
def shift_heading(elem, page):
for i in range(7, 0, -1):
while True:
h = elem.find(f'h{i}')
h = elem.find('h%d' % (i))
if not h:
break
h.name = f'h{i + 1}'
h.name = 'h%d' % (i + 1)

page_path = self._page_path_for_id(page)
h1 = soup.new_tag('h1', id=f'{page_path}')
h1 = soup.new_tag('h1', id=str(page_path))
h1.append(page.title)
elem.insert(0, h1)
return elem
Expand All @@ -220,8 +221,8 @@ def cleanup_class(classes: []):
if article:

page_path = self._page_path_for_id(page)
article['id'] = f'{page_path}:' # anchor for each page.
article['data-url'] = f'/{page_path}'
article['id'] = '{}:'.format(page_path) # anchor for each page.
article['data-url'] = '/{}'.format(page_path)
return article

elif page.children:
Expand All @@ -246,8 +247,9 @@ def cleanup_class(classes: []):
child_article['class'] = cleanup_class(classes)

page_path = self._page_path_for_id(page)
new_article['id'] = f'{page_path}:' # anchor for each page.
new_article['data-url'] = f'/{page_path}'
# anchor for each page.
new_article['id'] = '{}:'.format(page_path)
new_article['data-url'] = '/{}'.format(page_path)
if child_classes:
new_article['class'] = child_classes

Expand Down Expand Up @@ -282,14 +284,15 @@ def _load_theme_handler(self):
return mod
except FileNotFoundError as e:
self.logger.error(
f'Could not load theme handler {theme}'
f' from custom directory "{custom_handler_path}": {e}')
'Could not load theme handler %s'
' from custom directory "%s": %s',
theme, custom_handler_path, e)
pass

try:
return import_module(module_name, 'mkdocs_with_pdf.themes')
except ImportError as e:
self.logger.error(f'Could not load theme handler {theme}: {e}')
self.logger.error('Could not load theme handler %s: %s', theme, e)
return generic_theme

# -------------------------------------------------------------
Expand Down Expand Up @@ -319,7 +322,7 @@ def normalize_anchor_chars(anchor: str):
if not (self._options.strict or self._options.debug_html):
self.logger.info('Anchor points provided:')
for anchor in sorted(anchors):
self.logger.info(f'| {anchor}')
self.logger.info('| %s', anchor)
return

missing = set()
Expand All @@ -335,15 +338,15 @@ def normalize_anchor_chars(anchor: str):
missing.add(href)

if len(missing):
self.logger.error(f'Missing {len(missing)} link(s):')
self.logger.error('Missing %d link(s):', len(missing))
for link in sorted(missing):
self.logger.warning(f' | {link}')
self.logger.warning(' | %s', link)
if (self._options.show_anchors or
self._options.verbose or
self._options.debug_html):
self.logger.info(' | --- found anchors:')
for anchor in sorted(anchors):
self.logger.info(f' | {anchor}')
self.logger.info(' | %s', anchor)

# -------------------------------------------------------------

Expand All @@ -365,7 +368,8 @@ def _render_js(self, soup):
tag.text = self._mixed_script
body.append(tag)
for src in scripts:
body.append(soup.new_tag('script', src=f'file://{src}'))
body.append(soup.new_tag(
'script', src='file://%s' % (src)))

return self._options.js_renderer.render(str(soup))

Expand Down
9 changes: 5 additions & 4 deletions mkdocs_with_pdf/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,8 @@ def on_config(self, config):
if not self.enabled:
self._logger.warning(
'without generate PDF'
f'(set environment variable {env_name} to 1 to enable)'
'(set environment variable %s to 1 to enable)',
env_name
)
return
else:
Expand Down Expand Up @@ -135,15 +136,15 @@ def on_post_build(self, config):
end = timer()
self._total_time += (end - start)
self._logger.info(
f'Converting {self._num_pages} articles to PDF'
f' took {self._total_time:.1f}s'
'Converting {} articles to PDF'
' took {:.1f}s'.format(self._num_pages, self._total_time)
)

if self._error_counter:
errors, warns = self._error_counter.counts()
if errors > 0 or warns > 0:
raise RuntimeError(
f'{errors} error(s) and/or {warns} warning(s)'
'{} error(s) and/or {} warning(s)'.format(errors, warns)
+ ' occurred while generating PDF.')

def _get_path_to_pdf_from(self, start):
Expand Down
8 changes: 4 additions & 4 deletions mkdocs_with_pdf/preprocessor/links/transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def transform():
target = urljoin(rel_url, target_url.path)

if target in ['/', '.', 'index.html']:
return f'#.:{hash}'
return '#.:{}'.format(hash)

if target.endswith('.png'):
return href
Expand All @@ -39,7 +39,7 @@ def transform():
if not target.endswith('/'):
target += '/'

return f'#{quote(target)}:{hash}'
return '#{}:{}'.format(quote(target), hash)

x_href = transform()

Expand All @@ -63,7 +63,7 @@ def transform_id(id: str, rel_url: str):
"""normalize id to foo/bar/section:id"""

if rel_url in ['.', 'index.html']:
return f'.:{id}'
return '.:{}'.format(id)

head, tail = os.path.split(rel_url)
section, _ = os.path.splitext(tail)
Expand All @@ -77,4 +77,4 @@ def normalize(path):
head = normalize(head)
section = normalize(section)

return f'{head}{section}:{id}'
return '{}{}:{}'.format(head, section, id)
22 changes: 13 additions & 9 deletions mkdocs_with_pdf/styles/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,20 @@ def _css_escape(text: str) -> str:


def style_for_print(options: Options) -> str:
scss = f"""
:root {{
string-set: author '{_css_escape(options.author)}',
copyright '{_css_escape(options.copyright)}',
title '{_css_escape(options.cover_title)}';
}}
h1, h2, h3 {{
scss = """
:root {
string-set: author '%s',
copyright '%s',
title '%s';
}
h1, h2, h3 {
string-set: chapter content();
}}
"""
}
""" % (
_css_escape(options.author),
_css_escape(options.copyright),
_css_escape(options.cover_title)
)
css = sass.compile(string=scss)

base_path = os.path.abspath(os.path.dirname(__file__))
Expand Down
3 changes: 2 additions & 1 deletion mkdocs_with_pdf/templates/filters/qrcode.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,4 +78,5 @@ def __call__(self, content: str, format='SVG',
with io.BytesIO() as stream:
img.save(stream, kind=_save_kind(fmt))
data = base64.b64encode(stream.getvalue())
return f'data:{_content_type(fmt)};base64,' + data.decode("ascii")
return 'data:{};base64,'.format(
_content_type(fmt)) + data.decode("ascii")
4 changes: 2 additions & 2 deletions mkdocs_with_pdf/templates/template.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@

try:
from .filters.barcode import Barcode
except ModuleNotFoundError:
except ImportError:
Barcode = None
try:
from .filters.qrcode import QRCode
except ModuleNotFoundError:
except ImportError:
QRCode = None


Expand Down
Loading

0 comments on commit d307c46

Please sign in to comment.