set-alias-page.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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-more-info-link.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. lines = f.readlines()
  80. for line in lines:
  81. if re.search(r"^`tldr ", line):
  82. return re.search("`tldr (.+)`", line).group(1)
  83. return ""
  84. def set_alias_page(file, command):
  85. """
  86. Write an alias page to disk.
  87. Parameters:
  88. file (string): Path to an alias page
  89. command (string): The command that the alias stands for.
  90. Returns:
  91. str: Execution status
  92. "" if the alias page standing for the same command already exists.
  93. "\x1b[36mpage added" if it's a new alias page.
  94. "\x1b[34mpage updated" if the command updates.
  95. """
  96. # compute locale
  97. pages_dir = os.path.basename(os.path.dirname(os.path.dirname(file)))
  98. if "." in pages_dir:
  99. _, locale = pages_dir.split(".")
  100. else:
  101. locale = "en"
  102. if locale not in templates:
  103. return ""
  104. # Test if the alias page already exists
  105. orig_command = get_alias_page(file)
  106. if orig_command == command:
  107. return ""
  108. elif orig_command == "":
  109. status = "\x1b[36mpage added"
  110. else:
  111. status = "\x1b[34mpage updated"
  112. alias_name = os.path.basename(file[:-3])
  113. text = (
  114. templates[locale].replace("example", alias_name, 1).replace("example", command)
  115. )
  116. os.makedirs(os.path.dirname(file), exist_ok=True)
  117. with open(file, "w") as f:
  118. f.write(text)
  119. return status
  120. def sync(root, pages_dirs, alias_name, orig_command):
  121. """
  122. Synchronize an alias page into all translations:
  123. Parameters:
  124. root (str): TLDR_ROOT
  125. pages_dirs (list of str): Strings of page entry and platform, e.g. "page.fr/common".
  126. alias_name (str): An alias command with .md extension like "vi.md".
  127. orig_command (string): An Original command like "vim".
  128. Returns:
  129. str: a list of paths to be staged into git, using by --stage option.
  130. """
  131. rel_paths = []
  132. for page_dir in pages_dirs:
  133. path = os.path.join(root, page_dir, alias_name)
  134. status = set_alias_page(path, orig_command)
  135. if status != "":
  136. rel_path = path.replace(f"{root}/", "")
  137. rel_paths.append(rel_path)
  138. print(f"\x1b[32m{rel_path} {status}\x1b[0m")
  139. return rel_paths
  140. def main():
  141. parser = argparse.ArgumentParser(
  142. description="Sets the alias page for all translations of a page"
  143. )
  144. parser.add_argument(
  145. "-p",
  146. "--page",
  147. type=str,
  148. required=False,
  149. default="",
  150. help='page name in the format "platform/alias_command.md"',
  151. )
  152. parser.add_argument(
  153. "-s",
  154. "--stage",
  155. action="store_true",
  156. default=False,
  157. help="stage modified pages (requires `git` to be on $PATH and TLDR_ROOT to be a Git repository)",
  158. )
  159. parser.add_argument(
  160. "-S",
  161. "--sync",
  162. action="store_true",
  163. default=False,
  164. help="synchronize each translation's alias page (if exists) with that of English page",
  165. )
  166. parser.add_argument("command", type=str, nargs="?", default="")
  167. args = parser.parse_args()
  168. root = get_tldr_root()
  169. # A dictionary of all alias page translations
  170. global templates
  171. templates = get_templates(root)
  172. pages_dirs = [d for d in os.listdir(root) if d.startswith("pages")]
  173. rel_paths = []
  174. # Use '--page' option
  175. if args.page != "":
  176. if not args.page.lower().endswith(".md"):
  177. args.page = f"{args.page}.md"
  178. target_paths = [os.path.join(root, p, args.page) for p in pages_dirs]
  179. target_paths.sort()
  180. for path in target_paths:
  181. rel_path = path.replace(f"{root}/", "")
  182. rel_paths.append(rel_path)
  183. status = set_alias_page(path, args.command)
  184. if status != "":
  185. print(f"\x1b[32m{rel_path} {status}\x1b[0m")
  186. # Use '--sync' option
  187. elif args.sync:
  188. pages_dirs.remove("pages")
  189. en_page = os.path.join(root, "pages")
  190. platforms = [i for i in os.listdir(en_page) if i not in IGNORE_FILES]
  191. for platform in platforms:
  192. platform_path = os.path.join(en_page, platform)
  193. commands = [
  194. f"{platform}/{p}"
  195. for p in os.listdir(platform_path)
  196. if p not in IGNORE_FILES
  197. ]
  198. for command in commands:
  199. orig_command = get_alias_page(os.path.join(root, "pages", command))
  200. if orig_command != "":
  201. rel_paths += sync(root, pages_dirs, command, orig_command)
  202. if args.stage:
  203. subprocess.call(["git", "add", *rel_paths], cwd=root)
  204. if __name__ == "__main__":
  205. main()