1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
|
# -*- encoding: utf-8 -*-
#
# Versioning for the 404 page.
# When you want to build an archive version update the versions.json file beforehand.
#
import os
import re
import json
from sphinx.util import logging
def html_page_context(app, pagename, templatename, context, doctree):
"""Adds a version tag variable to the context which can be accessed by the template."""
if templatename == "404.html":
gen_htaccess(app, context['language'], context['version'])
def gen_htaccess(app, lang, version):
text = read_htaccess()
if text:
text = text.format(lang=lang, version=version)
try:
build_dir = app.outdir
except AttributeError as err:
logger = logging.getLogger(__name__)
logger.warning("404.py: Sphinx API change: {1}".format(err))
else:
write_htaccess(build_dir, text)
def read_htaccess():
current_dir = os.path.abspath(os.path.dirname(__file__))
ht_fn = os.path.normpath(os.path.join(current_dir, "..", ".htaccess"))
try:
with open(ht_fn, "r", encoding="utf-8") as f:
text = f.read()
except (IOError, OSError) as err:
logger = logging.getLogger(__name__)
logger.warning("{0}: cannot read: {1}".format(ht_fn, err))
return None
else:
return text
def write_htaccess(build_dir, text):
current_dir = os.path.abspath(os.path.dirname(__file__))
ht_fn = os.path.normpath(os.path.join(current_dir, "..", build_dir, ".htaccess"))
try:
with open(ht_fn, "w", encoding="utf-8") as f:
f.write(text)
except (IOError, OSError) as err:
logger = logging.getLogger(__name__)
logger.warning("{0}: cannot write: {1}".format(ht_fn, err))
return None
def setup(app):
app.connect('html-page-context', html_page_context)
return {
'parallel_read_safe': True,
'parallel_write_safe': True,
}
|