• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright © 2020-2021 Collabora Ltd
2#
3# Permission is hereby granted, free of charge, to any person obtaining a copy
4# of this software and associated documentation files (the "Software"), to deal
5# in the Software without restriction, including without limitation the rights
6# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7# copies of the Software, and to permit persons to whom the Software is
8# furnished to do so, subject to the following conditions:
9#
10# The above copyright notice and this permission notice shall be included in
11# all copies or substantial portions of the Software.
12#
13# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19# SOFTWARE.
20
21import os
22import pathlib
23from urllib.parse import urlparse
24
25def create_redirect(dst):
26    tpl = '<html><head><meta http-equiv="refresh" content="0; url={0}"><script>window.location.replace("{0}")</script></head></html>'
27    return tpl.format(dst)
28
29def create_redirects(app, exception):
30    if exception is not None or not app.builder.name == 'html':
31        return
32    for src, dst in app.config.html_redirects:
33        path = os.path.join(app.outdir, '{0}.html'.format(src))
34
35        os.makedirs(os.path.dirname(path), exist_ok=True)
36
37        if urlparse(dst).scheme == "":
38            dst = pathlib.posixpath.relpath(dst, start=os.path.dirname(src))
39            if not os.path.isfile(os.path.join(os.path.dirname(path), dst)):
40                raise Exception('{0} does not exitst'.format(dst))
41
42        with open(path, 'w') as f:
43            f.write(create_redirect(dst))
44
45def setup(app):
46    app.add_config_value('html_redirects', [], '')
47    app.connect('build-finished', create_redirects)
48