1import os 2import pathlib 3from urllib.parse import urlparse 4 5def create_redirect(dst): 6 tpl = '<html><head><meta http-equiv="refresh" content="0; url={0}"><script>window.location.replace("{0}")</script></head></html>' 7 return tpl.format(dst) 8 9def create_redirects(app, exception): 10 if exception is not None or not app.builder.name == 'html': 11 return 12 for src, dst in app.config.html_redirects: 13 path = os.path.join(app.outdir, '{0}.html'.format(src)) 14 15 os.makedirs(os.path.dirname(path), exist_ok=True) 16 17 if urlparse(dst).scheme == "": 18 dst = pathlib.posixpath.relpath(dst, start=os.path.dirname(src)) 19 if not os.path.isfile(os.path.join(os.path.dirname(path), dst)): 20 raise Exception('{0} does not exitst'.format(dst)) 21 22 with open(path, 'w') as f: 23 f.write(create_redirect(dst)) 24 25def setup(app): 26 app.add_config_value('html_redirects', [], '') 27 app.connect('build-finished', create_redirects) 28