set-alias-page.py 8.8 KB

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