Debian Codegraph @

cloud_sptheme/ext/auto_redirect.py

raw symbols SCIP
1 """
2 ==================================================================
3 :mod:`cloud_sptheme.ext.auto_redirect` -- Redirect Deprecated URLs
4 ==================================================================
5
6 .. versionadded:: 1.9
7
8 Overview
9 ========
10 This extension is helpful for when html documentation has been relocated
11 to a new host; e.g. moving from ``pythonhosted.org`` to ``readthedocs.io``.
12 Once enabled, it adds a helpful "Documentation has moved" message to the top
13 of every page, and automatically redirects the user as well.
14
15 Configuration
16 =============
17 This extension looks for the following config options:
18
19 ``auto_redirect_subject``
20
21 subject to insert into message.
22 defaults to ``The {project name} documentation``.
23
24 ``auto_redirect_domain_url``
25
26 url to redirect user to.
27 no message or redirect will happen if this isn't set.
28
29 ``auto_redirect_domain_footer``
30
31 optional footer text to append to message
32
33 Internals
34 =========
35 This should work with other sphinx themes, the js & css is (mostly) generic.
36
37 .. todo::
38
39 the "redirect to exact page" part of JS code currently only works
40 with this theme; would like to fix that.
41
42 .. todo::
43
44 support configuring redirects to other pages within same documentation.
45
46 .. todo::
47
48 if user has dismissed "auto redirect", remember via cookie?
49 """
50 #=============================================================================
51 # imports
52 #=============================================================================
53 # core
54 import os
55 # site
56 from docutils.nodes import raw
57 from sphinx.builders.html import StandaloneHTMLBuilder
58 from sphinx.util.pycompat import htmlescape
59 # pkg
60 from cloud_sptheme import __version__, _root_dir, is_cloud_theme
61 from cloud_sptheme.utils import add_static_file
62 # local
63 __all__ = [
64 "setup",
65 ]
66
67 #=============================================================================
68 # patch builder to copy css file (if needed)
69 #=============================================================================
70
71 ext_static_dir = os.path.join(_root_dir, "ext", "static")
72
73 cloud_base_js_path = os.path.join(_root_dir, "themes", "cloud", "static", "cloud_base.js")
74
75 class RedirectHelper(object):
76
77 template_path = os.path.join(ext_static_dir, "auto_redirect.html_t")
78 css_path = os.path.join(ext_static_dir, "auto_redirect.css")
79
80 def __init__(self, app):
81 self.app = app
82
83 @property
84 def for_html(self):
85 return isinstance(self.app.builder, StandaloneHTMLBuilder)
86
87 @property
88 def domain_subject(self):
89 config = self.app.config
90 return config.auto_redirect_domain_subject or \
91 "The %s documentation" % (config.project,)
92 @property
93 def domain_url(self):
94 return self.app.config.auto_redirect_domain_url
95
96 @property
97 def domain_root(self):
98 root = self.app.config.auto_redirect_domain_root
99 # XXX: use urljoin here?
100 if not root:
101 return self.domain_url
102 if root[:1] == "/" and root[:2] != "//":
103 return self.domain_url + root
104 return root
105
106 @property
107 def domain_footer(self):
108 return self.app.config.auto_redirect_domain_footer
109
110 @property
111 def timeout(self):
112 return self.app.config.auto_redirect_timeout or 10
113
114
115 def install_static_assets(app):
116 # skip unless html builder & redirect configured
117 helper = RedirectHelper(app)
118 if not helper.for_html or not helper.domain_url:
119 return
120
121 # make sure JS is added
122 if not is_cloud_theme(app.config.html_theme):
123 add_static_file(app.builder, cloud_base_js_path, javascript=True)
124
125 # make sure needed css styling gets included when building html
126 add_static_file(app.builder, helper.css_path, stylesheet=True)
127
128
129 # FIXME: This doesn't get called for auto-generated pages, e.g. search page & genindex.
130 # Need to modify this code to get run as part of builder.handle_page() call,
131 # such as via event that insert_canonical_link() is using below.
132 def prepend_redirect(app, doctree):
133
134 """
135 called after doctree has been read;
136 inserted "Raw" node with our content.
137 """
138 # skip unless configured, and using html builder
139 helper = RedirectHelper(app)
140 if not helper.for_html or not helper.domain_url:
141 return
142
143 # render fragment into insert
144 builder = app.builder
145 renderer = builder.templates
146 ctx = dict(app=app, redirector=helper)
147 with open(helper.template_path) as fh:
148 content = renderer.render_string(fh.read(), ctx)
149
150 # insert raw node w/ content
151 node = raw(content, content, format="html")
152 doctree.insert(0, node)
153
154
155 def insert_canonical_link(app, pagename, templatename, context, doctree):
156 # skip unless html builder & redirect configured
157 helper = RedirectHelper(app)
158 root_url = helper.domain_root
159 if not helper.for_html or not root_url:
160 return
161
162 # XXX: any gotchas w/ generating url from pagename this way?
163 url = "%s/%s.html" % (root_url.rstrip("/"), pagename)
164
165 # insert "canonical" link to help search engines
166 # XXX: skipping this if another ext sets this?
167 # XXX: split this out under separate name / extension?
168 meta = context.get("metatags", "")
169 context['metatags'] = meta + '<link rel="canonical" href="%s" />\n' % htmlescape(url, True)
170
171 #=============================================================================
172 # register extension
173 #=============================================================================
174 def setup(app):
175 #
176 # register config vars
177 #
178
179 # title to use when referring to project.
180 # defaults to "The {project} documentation"
181 app.add_config_value("auto_redirect_domain_subject", None, "html")
182
183 # base url to redirect to -- if not set, extension does nothing.
184 app.add_config_value("auto_redirect_domain_url", None, "html")
185
186 # optional url suffix to add before adding per-page redirects.
187 app.add_config_value("auto_redirect_domain_root", None, "html")
188
189 # optional html to append to message
190 app.add_config_value("auto_redirect_domain_footer", None, "html")
191
192 # seconds before redirecting via JS
193 app.add_config_value("auto_redirect_timeout", 10, "html")
194
195 #
196 # connect events
197 # XXX: can we connect events on the fly? could do single check when builder init'd,
198 # and attach events there as needed. could then make everything a method
199 # of the redirect helper.
200 #
201 app.connect("builder-inited", install_static_assets)
202 app.connect("doctree-read", prepend_redirect)
203 app.connect("html-page-context", insert_canonical_link)
204
205 #
206 # identifies the version of our extension
207 #
208 return {'version': __version__}
209
210 #=============================================================================
211 # eof
212 #=============================================================================