html_redirects.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. # the file 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. # attaching to this event is a hack, but it's a convenient stage in the build
  39. # to create HTML redirects
  40. app.connect('html-collect-pages', create_redirect_pages)
  41. return {'parallel_read_safe': True, 'parallel_write_safe': True, 'version': '0.1'}
  42. def create_redirect_pages(app):
  43. if not isinstance(app.builder, StandaloneHTMLBuilder):
  44. return # only relevant for standalone HTML output
  45. for (old_url, new_url) in app.config.html_redirect_pages:
  46. print('Creating redirect %s to %s...' % (old_url, new_url))
  47. if old_url.startswith('/'):
  48. print('Stripping leading / from URL in config file...')
  49. old_url = old_url[1:]
  50. new_url = app.builder.get_relative_uri(old_url, new_url)
  51. out_file = app.builder.get_outfilename(old_url)
  52. print('HTML file %s redirects to relative URL %s' % (out_file, new_url))
  53. out_dir = os.path.dirname(out_file)
  54. if not os.path.exists(out_dir):
  55. os.makedirs(out_dir)
  56. content = REDIRECT_TEMPLATE.replace('$NEWURL', new_url)
  57. with open(out_file, 'w') as rp:
  58. rp.write(content)
  59. return []