html_redirects.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # Copyright 2018-2019 Espressif Systems (Shanghai) PTE LTD
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. #
  15. # Mechanism to generate static HTML redirect pages in the output
  16. #
  17. # Uses redirect_template.html and the list of pages given in
  18. # conf.html_redirect_pages
  19. #
  20. # Adapted from ideas in https://tech.signavio.com/2017/managing-sphinx-redirects
  21. import os.path
  22. from sphinx.builders.html import StandaloneHTMLBuilder
  23. REDIRECT_TEMPLATE = """
  24. <html>
  25. <head>
  26. <meta http-equiv="refresh" content="0; url=$NEWURL" />
  27. <script>
  28. window.location.href = "$NEWURL"
  29. </script>
  30. </head>
  31. <body>
  32. <p>Page has moved <a href="$NEWURL">here</a>.</p>
  33. </body>
  34. </html>
  35. """
  36. def setup(app):
  37. app.add_config_value('html_redirect_pages', [], 'html')
  38. app.connect('build-finished', create_redirect_pages)
  39. def create_redirect_pages(app, docname):
  40. if not isinstance(app.builder, StandaloneHTMLBuilder):
  41. return # only relevant for standalone HTML output
  42. for (old_url, new_url) in app.config.html_redirect_pages:
  43. print("Creating redirect %s to %s..." % (old_url, new_url))
  44. if old_url.startswith('/'):
  45. print("Stripping leading / from URL in config file...")
  46. old_url = old_url[1:]
  47. new_url = app.builder.get_relative_uri(old_url, new_url)
  48. out_file = app.builder.get_outfilename(old_url)
  49. print("HTML file %s redirects to relative URL %s" % (out_file, new_url))
  50. out_dir = os.path.dirname(out_file)
  51. if not os.path.exists(out_dir):
  52. os.makedirs(out_dir)
  53. content = REDIRECT_TEMPLATE.replace("$NEWURL", new_url)
  54. with open(out_file, "w") as rp:
  55. rp.write(content)