set-alias-page.py 7.1 KB

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