You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

redirects.py 1.7 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. from pathlib import Path
  2. from string import Template
  3. import sys
  4. THIS_FILE_DIR = Path(__file__).parent
  5. # Contains single text template $to_url
  6. HTML_PAGE_TEMPLATE_FILE = THIS_FILE_DIR / "redirect_template.html"
  7. HTML_REDIRECT_TEMPLATE = HTML_PAGE_TEMPLATE_FILE.open("r").read()
  8. REDIRECT_URLS_FILE = THIS_FILE_DIR / "redirect_urls.txt"
  9. def generate_redirect(file_to_write: str, new_url: str, base_dir: Path):
  10. # Create a new redirect page
  11. redirect_page = Template(HTML_REDIRECT_TEMPLATE).substitute(to_url=new_url)
  12. # If the url ends with /, add index.html
  13. if file_to_write.endswith("/"):
  14. file_to_write += "index.html"
  15. else:
  16. file_to_write += "/index.html"
  17. if file_to_write.startswith("/"):
  18. file_to_write = file_to_write[1:]
  19. # Create the path to the redirect page
  20. redirect_page_path = base_dir / file_to_write
  21. # Create the directory if it doesn't exist
  22. redirect_page_path.parent.mkdir(parents=True, exist_ok=True)
  23. # Write the redirect page
  24. with open(redirect_page_path, "w") as f:
  25. f.write(redirect_page)
  26. def main():
  27. if len(sys.argv) != 2:
  28. print("Usage: python redirects.py <base_dir>")
  29. sys.exit(1)
  30. base_dir = Path(sys.argv[1])
  31. # Read file
  32. with open(REDIRECT_URLS_FILE, "r") as f:
  33. lines = f.readlines()
  34. for line in lines:
  35. # Split line by comma, where old is left and new is right
  36. old_url, new_url = line.strip().split(",")
  37. # Deal with pages base path of /autogen/
  38. file_to_write = old_url.replace("/autogen/", "/")
  39. generate_redirect(file_to_write, new_url, base_dir)
  40. if __name__ == '__main__':
  41. main()