set-more-info-link.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. #!/usr/bin/env python3
  2. # SPDX-License-Identifier: MIT
  3. """
  4. This script sets the "More information" link for all translations of a page.
  5. It can be used to add or update the links in translations.
  6. Note: Before running this script, ensure that TLDR_ROOT is set to the location
  7. of a clone of https://github.com/tldr-pages/tldr, and 'git' is available.
  8. 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: python3 scripts/set-more-info-link.py [-p PAGE] [-s] [-S] [-n] [LINK]
  11. Supported Arguments:
  12. -p, --page Specify the page name in the format "platform/command.md".
  13. This option allows setting the link for a specific page.
  14. -s, --stage Stage modified pages for commit. This option requires 'git'
  15. to be on the $PATH and TLDR_ROOT to be a Git repository.
  16. -S, --sync Synchronize each translation's more information link (if
  17. exists) with that of the English page. This is useful to
  18. ensure consistency across translations.
  19. -n, --dry-run Show what changes would be made without actually modifying the page.
  20. Positional Argument:
  21. LINK The link to be set as the "More information" link.
  22. Examples:
  23. 1. Set the link for a specific page:
  24. python3 scripts/set-more-info-link.py -p common/tar.md https://example.com
  25. 2. Synchronize more information links across translations:
  26. python3 scripts/set-more-info-link.py -S
  27. 3. Synchronize more information links across translations and stage modified pages for commit:
  28. python3 scripts/set-more-info-link.py -Ss
  29. python3 scripts/set-more-info-link.py --sync --stage
  30. 4. Show what changes would be made across translations:
  31. python3 scripts/set-more-info-link.py -Sn
  32. python3 scripts/set-more-info-link.py --sync --dry-run
  33. """
  34. import argparse
  35. import os
  36. import re
  37. import subprocess
  38. import sys
  39. labels = {
  40. "en": "More information:",
  41. "ar": "لمزيد من التفاصيل:",
  42. "bn": "আরও তথ্য পাবেন:",
  43. "bs": "Više informacija:",
  44. "cs": "Více informací:",
  45. "ca": "Més informació:",
  46. "da": "Mere information:",
  47. "de": "Weitere Informationen:",
  48. "es": "Más información:",
  49. "fa": "اطلاعات بیشتر:",
  50. "fi": "Lisätietoja:",
  51. "fr": "Plus d'informations :",
  52. "sh": "Više informacija:",
  53. "hi": "अधिक जानकारी:",
  54. "id": "Informasi lebih lanjut:",
  55. "it": "Maggiori informazioni:",
  56. "ja": "詳しくはこちら:",
  57. "ko": "더 많은 정보:",
  58. "lo": "ຂໍ້ມູນເພີ່ມເຕີມ:",
  59. "ml": "കൂടുതൽ വിവരങ്ങൾ:",
  60. "ne": "थप जानकारी:",
  61. "nl": "Meer informatie:",
  62. "no": "Mer informasjon:",
  63. "pl": "Więcej informacji:",
  64. "pt_BR": "Mais informações:",
  65. "pt_PT": "Mais informações:",
  66. "ro": "Mai multe informații:",
  67. "ru": "Больше информации:",
  68. "sr": "Više informacija na:",
  69. "sv": "Mer information:",
  70. "ta": "மேலும் விவரத்திற்கு:",
  71. "th": "ข้อมูลเพิ่มเติม:",
  72. "tr": "Daha fazla bilgi için:",
  73. "uk": "Більше інформації:",
  74. "uz": "Ko'proq malumot:",
  75. "zh_TW": "更多資訊:",
  76. "zh": "更多信息:",
  77. }
  78. IGNORE_FILES = (".DS_Store",)
  79. def get_tldr_root():
  80. # if this script is running from tldr/scripts, the parent's parent is the root
  81. f = os.path.normpath(__file__)
  82. if f.endswith("tldr/scripts/set-more-info-link.py"):
  83. return os.path.dirname(os.path.dirname(f))
  84. if "TLDR_ROOT" in os.environ:
  85. return os.environ["TLDR_ROOT"]
  86. print(
  87. "\x1b[31mPlease set TLDR_ROOT to the location of a clone of https://github.com/tldr-pages/tldr."
  88. )
  89. sys.exit(1)
  90. def set_link(file, link, dry_run=False):
  91. with open(file, encoding="utf-8") as f:
  92. lines = f.readlines()
  93. desc_start = 0
  94. desc_end = 0
  95. # find start and end of description
  96. for i, line in enumerate(lines):
  97. if line.startswith(">") and desc_start == 0:
  98. desc_start = i
  99. if not lines[i + 1].startswith(">") and desc_start != 0:
  100. desc_end = i
  101. break
  102. # compute locale
  103. pages_dir = os.path.basename(os.path.dirname(os.path.dirname(file)))
  104. if "." in pages_dir:
  105. _, locale = pages_dir.split(".")
  106. else:
  107. locale = "en"
  108. # build new line
  109. if locale in ["bn", "hi", "ne"]:
  110. new_line = f"> {labels[locale]} <{link}>।\n"
  111. elif locale in ["ja", "th"]:
  112. new_line = f"> {labels[locale]} <{link}>\n"
  113. elif locale in ["zh", "zh_TW"]:
  114. new_line = f"> {labels[locale]}<{link}>.\n"
  115. else:
  116. new_line = f"> {labels[locale]} <{link}>.\n"
  117. if lines[desc_end] == new_line:
  118. # return empty status to indicate that no changes were made
  119. return ""
  120. status_prefix = "\x1b[36m" # Color code for pages
  121. if re.search(r"^>.*<.+>", lines[desc_end]):
  122. # overwrite last line
  123. lines[desc_end] = new_line
  124. status_prefix = "\x1b[34m"
  125. action = "updated"
  126. else:
  127. # add new line
  128. lines.insert(desc_end + 1, new_line)
  129. status_prefix = "\x1b[36m"
  130. action = "added"
  131. if dry_run:
  132. status = f"link will be {action}"
  133. else:
  134. status = f"link {action}"
  135. status = f"{status_prefix}{status}\x1b[0m"
  136. if not dry_run:
  137. with open(file, "w", encoding="utf-8") as f:
  138. f.writelines(lines)
  139. return status
  140. def get_link(file):
  141. with open(file, encoding="utf-8") as f:
  142. lines = f.readlines()
  143. desc_start = 0
  144. desc_end = 0
  145. # find start and end of description
  146. for i, line in enumerate(lines):
  147. if line.startswith(">") and desc_start == 0:
  148. desc_start = i
  149. if not lines[i + 1].startswith(">") and desc_start != 0:
  150. desc_end = i
  151. break
  152. # match link
  153. if re.search(r"^>.*<.+>", lines[desc_end]):
  154. return re.search("<(.+)>", lines[desc_end]).group(1)
  155. else:
  156. return ""
  157. def sync(root, pages_dirs, command, link, dry_run=False):
  158. rel_paths = []
  159. for page_dir in pages_dirs:
  160. path = os.path.join(root, page_dir, command)
  161. if os.path.exists(path):
  162. rel_path = path.replace(f"{root}/", "")
  163. rel_paths.append(rel_path)
  164. status = set_link(path, link, dry_run)
  165. if status != "":
  166. print(f"\x1b[32m{rel_path} {status}\x1b[0m")
  167. return rel_paths
  168. def main():
  169. parser = argparse.ArgumentParser(
  170. description='Sets the "More information" link for all translations of a page'
  171. )
  172. parser.add_argument(
  173. "-p",
  174. "--page",
  175. type=str,
  176. required=False,
  177. default="",
  178. help='page name in the format "platform/command.md"',
  179. )
  180. parser.add_argument(
  181. "-s",
  182. "--stage",
  183. action="store_true",
  184. default=False,
  185. help="stage modified pages (requires `git` to be on $PATH and TLDR_ROOT to be a Git repository)",
  186. )
  187. parser.add_argument(
  188. "-S",
  189. "--sync",
  190. action="store_true",
  191. default=False,
  192. help="synchronize each translation's more information link (if exists) with that of English page",
  193. )
  194. parser.add_argument(
  195. "-n",
  196. "--dry-run",
  197. action="store_true",
  198. default=False,
  199. help="show what changes would be made without actually modifying the pages",
  200. )
  201. parser.add_argument("link", type=str, nargs="?", default="")
  202. args = parser.parse_args()
  203. root = get_tldr_root()
  204. pages_dirs = [d for d in os.listdir(root) if d.startswith("pages")]
  205. rel_paths = []
  206. # Use '--page' option
  207. if args.page != "":
  208. target_paths = []
  209. if not args.page.lower().endswith(".md"):
  210. args.page = f"{args.page}.md"
  211. for pages_dir in pages_dirs:
  212. pages_dir_path = os.path.join(root, pages_dir)
  213. platforms = [i for i in os.listdir(pages_dir_path) if i not in IGNORE_FILES]
  214. for platform in platforms:
  215. platform_path = os.path.join(pages_dir_path, platform)
  216. commands = [
  217. f"{platform}/{p}"
  218. for p in os.listdir(platform_path)
  219. if p not in IGNORE_FILES
  220. ]
  221. if args.page in commands:
  222. path = os.path.join(pages_dir_path, args.page)
  223. target_paths.append(path)
  224. target_paths.sort()
  225. for path in target_paths:
  226. rel_path = path.replace(f"{root}/", "")
  227. rel_paths.append(rel_path)
  228. status = set_link(path, args.link)
  229. if status != "":
  230. print(f"\x1b[32m{rel_path} {status}\x1b[0m")
  231. # Use '--sync' option
  232. elif args.sync:
  233. pages_dirs.remove("pages")
  234. en_page = os.path.join(root, "pages")
  235. platforms = [i for i in os.listdir(en_page) if i not in IGNORE_FILES]
  236. for platform in platforms:
  237. platform_path = os.path.join(en_page, platform)
  238. commands = [
  239. f"{platform}/{p}"
  240. for p in os.listdir(platform_path)
  241. if p not in IGNORE_FILES
  242. ]
  243. for command in commands:
  244. link = get_link(os.path.join(root, "pages", command))
  245. if link != "":
  246. rel_paths += sync(root, pages_dirs, command, link, args.dry_run)
  247. if args.stage and not args.dry_run:
  248. subprocess.call(["git", "add", *rel_paths], cwd=root)
  249. if __name__ == "__main__":
  250. main()