set-alias-page.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. #!/usr/bin/env python3
  2. # SPDX-License-Identifier: MIT
  3. """
  4. A Python script to generate or update alias pages.
  5. Disclaimer: This script generates a lot of false positives so it
  6. isn't suggested to use the sync option. If used, only stage changes
  7. and commit verified changes for your language.
  8. Note: If there is a symlink error when using the stage flag remove the `pages.en`
  9. directory temporarily and try executing it again.
  10. Usage:
  11. python3 scripts/set-alias-page.py [-p PAGE] [-s] [-S] [COMMAND]
  12. Options:
  13. -p, --page PAGE
  14. Specify the alias page in the format "platform/alias_command.md".
  15. -s, --stage
  16. Stage modified pages (requires 'git' on $PATH and TLDR_ROOT to be a Git repository).
  17. -S, --sync
  18. Synchronize each translation's alias page (if exists) with that of the English page.
  19. Examples:
  20. 1. Add 'vi' as an alias page of 'vim':
  21. python3 scripts/set-alias-page.py -p common/vi vim
  22. 2. Read English alias pages and synchronize them into all translations:
  23. python3 scripts/set-alias-page.py -S
  24. """
  25. import argparse
  26. import os
  27. import re
  28. import subprocess
  29. IGNORE_FILES = (".DS_Store", "tldr.md", "aria2.md")
  30. def get_tldr_root():
  31. """
  32. Get the path of local tldr repository for environment variable TLDR_ROOT.
  33. """
  34. # If this script is running from tldr/scripts, the parent's parent is the root
  35. f = os.path.normpath(__file__)
  36. if f.endswith("tldr/scripts/set-alias-page.py"):
  37. return os.path.dirname(os.path.dirname(f))
  38. if "TLDR_ROOT" in os.environ:
  39. return os.environ["TLDR_ROOT"]
  40. else:
  41. raise SystemExit(
  42. "\x1b[31mPlease set TLDR_ROOT to the location of a clone of https://github.com/tldr-pages/tldr.\x1b[0m"
  43. )
  44. def get_templates(root):
  45. """
  46. Get all alias page translation templates from
  47. TLDR_ROOT/contributing-guides/translation-templates/alias-pages.md.
  48. Parameters:
  49. root (string): The path of local tldr repository, i.e., TLDR_ROOT.
  50. Returns:
  51. dict of (str, str): Language labels map to alias page templates.
  52. """
  53. template_file = os.path.join(
  54. root, "contributing-guides/translation-templates/alias-pages.md"
  55. )
  56. with open(template_file) as f:
  57. lines = f.readlines()
  58. # Parse alias-pages.md
  59. templates = {}
  60. i = 0
  61. while i < len(lines):
  62. if lines[i].startswith("###"):
  63. lang = lines[i][4:].strip("\n").strip(" ")
  64. while True:
  65. i = i + 1
  66. if lines[i].startswith("Not translated yet."):
  67. is_translated = False
  68. break
  69. elif lines[i].startswith("```markdown"):
  70. i = i + 1
  71. is_translated = True
  72. break
  73. if is_translated:
  74. text = ""
  75. while not lines[i].startswith("```"):
  76. text += lines[i]
  77. i = i + 1
  78. templates[lang] = text
  79. i = i + 1
  80. return templates
  81. def get_alias_page(file):
  82. """
  83. Determine whether the given file is an alias page.
  84. Parameters:
  85. file (string): Path to a page
  86. Returns:
  87. str: "" If the file doesn't exit or is not an alias page,
  88. otherwise return what command the alias stands for.
  89. """
  90. if not os.path.isfile(file):
  91. return ""
  92. with open(file) as f:
  93. for line in f:
  94. if match := re.search(r"^`tldr (.+)`", line):
  95. return match[1]
  96. return ""
  97. def set_alias_page(file, command):
  98. """
  99. Write an alias page to disk.
  100. Parameters:
  101. file (string): Path to an alias page
  102. command (string): The command that the alias stands for.
  103. Returns:
  104. str: Execution status
  105. "" if the alias page standing for the same command already exists.
  106. "\x1b[36mpage added" if it's a new alias page.
  107. "\x1b[34mpage updated" if the command updates.
  108. """
  109. # compute locale
  110. pages_dir = os.path.basename(os.path.dirname(os.path.dirname(file)))
  111. if "." in pages_dir:
  112. _, locale = pages_dir.split(".")
  113. else:
  114. locale = "en"
  115. if locale not in templates:
  116. return ""
  117. # Test if the alias page already exists
  118. orig_command = get_alias_page(file)
  119. if orig_command == command:
  120. return ""
  121. elif orig_command == "":
  122. status = "\x1b[36mpage added"
  123. else:
  124. status = "\x1b[34mpage updated"
  125. alias_name = os.path.basename(file[:-3])
  126. text = (
  127. templates[locale].replace("example", alias_name, 1).replace("example", command)
  128. )
  129. os.makedirs(os.path.dirname(file), exist_ok=True)
  130. with open(file, "w") as f:
  131. f.write(text)
  132. return status
  133. def sync(root, pages_dirs, alias_name, orig_command):
  134. """
  135. Synchronize an alias page into all translations:
  136. Parameters:
  137. root (str): TLDR_ROOT
  138. pages_dirs (list of str): Strings of page entry and platform, e.g. "page.fr/common".
  139. alias_name (str): An alias command with .md extension like "vi.md".
  140. orig_command (string): An Original command like "vim".
  141. Returns:
  142. str: a list of paths to be staged into git, using by --stage option.
  143. """
  144. rel_paths = []
  145. for page_dir in pages_dirs:
  146. path = os.path.join(root, page_dir, alias_name)
  147. status = set_alias_page(path, orig_command)
  148. if status != "":
  149. rel_path = path.replace(f"{root}/", "")
  150. rel_paths.append(rel_path)
  151. print(f"\x1b[32m{rel_path} {status}\x1b[0m")
  152. return rel_paths
  153. def main():
  154. parser = argparse.ArgumentParser(
  155. description="Sets the alias page for all translations of a page"
  156. )
  157. parser.add_argument(
  158. "-p",
  159. "--page",
  160. type=str,
  161. required=False,
  162. default="",
  163. help='page name in the format "platform/alias_command.md"',
  164. )
  165. parser.add_argument(
  166. "-s",
  167. "--stage",
  168. action="store_true",
  169. default=False,
  170. help="stage modified pages (requires `git` to be on $PATH and TLDR_ROOT to be a Git repository)",
  171. )
  172. parser.add_argument(
  173. "-S",
  174. "--sync",
  175. action="store_true",
  176. default=False,
  177. help="synchronize each translation's alias page (if exists) with that of English page",
  178. )
  179. parser.add_argument("command", type=str, nargs="?", default="")
  180. args = parser.parse_args()
  181. root = get_tldr_root()
  182. # A dictionary of all alias page translations
  183. global templates
  184. templates = get_templates(root)
  185. pages_dirs = [d for d in os.listdir(root) if d.startswith("pages")]
  186. rel_paths = []
  187. # Use '--page' option
  188. if args.page != "":
  189. if not args.page.lower().endswith(".md"):
  190. args.page = f"{args.page}.md"
  191. target_paths = [os.path.join(root, p, args.page) for p in pages_dirs]
  192. target_paths.sort()
  193. for path in target_paths:
  194. rel_path = path.replace(f"{root}/", "")
  195. rel_paths.append(rel_path)
  196. status = set_alias_page(path, args.command)
  197. if status != "":
  198. print(f"\x1b[32m{rel_path} {status}\x1b[0m")
  199. # Use '--sync' option
  200. elif args.sync:
  201. pages_dirs.remove("pages")
  202. en_page = os.path.join(root, "pages")
  203. platforms = [i for i in os.listdir(en_page) if i not in IGNORE_FILES]
  204. for platform in platforms:
  205. platform_path = os.path.join(en_page, platform)
  206. commands = [
  207. f"{platform}/{p}"
  208. for p in os.listdir(platform_path)
  209. if p not in IGNORE_FILES
  210. ]
  211. for command in commands:
  212. orig_command = get_alias_page(os.path.join(root, "pages", command))
  213. if orig_command != "":
  214. rel_paths += sync(root, pages_dirs, command, orig_command)
  215. if args.stage:
  216. subprocess.call(["git", "add", *rel_paths], cwd=root)
  217. if __name__ == "__main__":
  218. main()