set-more-info-link.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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. from pathlib import Path
  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() -> Path:
  80. f = Path(__file__).resolve()
  81. return next(path for path in f.parents if path.name == "tldr")
  82. if "TLDR_ROOT" in os.environ:
  83. return Path(os.environ["TLDR_ROOT"])
  84. raise SystemError(
  85. "\x1b[31mPlease set TLDR_ROOT to the location of a clone of https://github.com/tldr-pages/tldr."
  86. )
  87. def set_link(path: Path, link: str, dry_run=False) -> str:
  88. with path.open(encoding="utf-8") as f:
  89. lines = f.readlines()
  90. desc_start = 0
  91. desc_end = 0
  92. # find start and end of description
  93. for i, line in enumerate(lines):
  94. if line.startswith(">") and desc_start == 0:
  95. desc_start = i
  96. if not lines[i + 1].startswith(">") and desc_start != 0:
  97. desc_end = i
  98. break
  99. # compute locale
  100. pages_dirname = path.parents[1].name
  101. if "." in pages_dirname:
  102. _, locale = pages_dirname.split(".")
  103. else:
  104. locale = "en"
  105. # build new line
  106. if locale in ["bn", "hi", "ne"]:
  107. new_line = f"> {labels[locale]} <{link}>।\n"
  108. elif locale in ["ja", "th"]:
  109. new_line = f"> {labels[locale]} <{link}>\n"
  110. elif locale in ["zh", "zh_TW"]:
  111. new_line = f"> {labels[locale]}<{link}>.\n"
  112. else:
  113. new_line = f"> {labels[locale]} <{link}>.\n"
  114. if lines[desc_end] == new_line:
  115. # return empty status to indicate that no changes were made
  116. return ""
  117. status_prefix = "\x1b[36m" # Color code for pages
  118. if re.search(r"^>.*<.+>", lines[desc_end]):
  119. # overwrite last line
  120. lines[desc_end] = new_line
  121. status_prefix = "\x1b[34m"
  122. action = "updated"
  123. else:
  124. # add new line
  125. lines.insert(desc_end + 1, new_line)
  126. status_prefix = "\x1b[36m"
  127. action = "added"
  128. if dry_run:
  129. status = f"link will be {action}"
  130. else:
  131. status = f"link {action}"
  132. status = f"{status_prefix}{status}\x1b[0m"
  133. if not dry_run:
  134. with path.open("w", encoding="utf-8") as f:
  135. f.writelines(lines)
  136. return status
  137. def get_link(path: Path) -> str:
  138. with path.open(encoding="utf-8") as f:
  139. lines = f.readlines()
  140. desc_start = 0
  141. desc_end = 0
  142. # find start and end of description
  143. for i, line in enumerate(lines):
  144. if line.startswith(">") and desc_start == 0:
  145. desc_start = i
  146. if not lines[i + 1].startswith(">") and desc_start != 0:
  147. desc_end = i
  148. break
  149. # match link
  150. if re.search(r"^>.*<.+>", lines[desc_end]):
  151. return re.search("<(.+)>", lines[desc_end]).group(1)
  152. else:
  153. return ""
  154. def sync(
  155. root: Path, pages_dirs: list[str], command: str, link: str, dry_run=False
  156. ) -> list[str]:
  157. paths = []
  158. for page_dir in pages_dirs:
  159. path = root / page_dir / command
  160. if path.exists():
  161. rel_path = "/".join(path.parts[-3:])
  162. status = set_link(path, link, dry_run)
  163. if status != "":
  164. paths.append(path)
  165. print(f"\x1b[32m{rel_path} {status}\x1b[0m")
  166. return paths
  167. def main():
  168. parser = argparse.ArgumentParser(
  169. description='Sets the "More information" link for all translations of a page'
  170. )
  171. parser.add_argument(
  172. "-p",
  173. "--page",
  174. type=str,
  175. required=False,
  176. default="",
  177. help='page name in the format "platform/command.md"',
  178. )
  179. parser.add_argument(
  180. "-s",
  181. "--stage",
  182. action="store_true",
  183. default=False,
  184. help="stage modified pages (requires `git` to be on $PATH and TLDR_ROOT to be a Git repository)",
  185. )
  186. parser.add_argument(
  187. "-S",
  188. "--sync",
  189. action="store_true",
  190. default=False,
  191. help="synchronize each translation's more information link (if exists) with that of English page",
  192. )
  193. parser.add_argument(
  194. "-n",
  195. "--dry-run",
  196. action="store_true",
  197. default=False,
  198. help="show what changes would be made without actually modifying the pages",
  199. )
  200. parser.add_argument("link", type=str, nargs="?", default="")
  201. args = parser.parse_args()
  202. root = get_tldr_root()
  203. pages_dirs = [d for d in root.iterdir() if d.name.startswith("pages")]
  204. target_paths = []
  205. # Use '--page' option
  206. if args.page != "":
  207. if not args.page.lower().endswith(".md"):
  208. args.page = f"{args.page}.md"
  209. arg_platform, arg_page = args.page.split("/")
  210. for pages_dir in pages_dirs:
  211. page_path = pages_dir / arg_platform / arg_page
  212. if not page_path.exists():
  213. continue
  214. target_paths.append(page_path)
  215. target_paths.sort()
  216. for path in target_paths:
  217. rel_path = "/".join(path.parts[-3:])
  218. status = set_link(path, args.link)
  219. if status != "":
  220. print(f"\x1b[32m{rel_path} {status}\x1b[0m")
  221. # Use '--sync' option
  222. elif args.sync:
  223. pages_dirs.remove(root / "pages")
  224. en_path = root / "pages"
  225. platforms = [i.name for i in en_path.iterdir() if i.name not in IGNORE_FILES]
  226. for platform in platforms:
  227. platform_path = en_path / platform
  228. commands = [
  229. f"{platform}/{page.name}"
  230. for page in platform_path.iterdir()
  231. if page not in IGNORE_FILES
  232. ]
  233. for command in commands:
  234. link = get_link(root / "pages" / command)
  235. if link != "":
  236. target_paths += sync(root, pages_dirs, command, link, args.dry_run)
  237. if args.stage and not args.dry_run and len(target_paths) > 0:
  238. subprocess.call(["git", "add", *target_paths], cwd=root)
  239. if __name__ == "__main__":
  240. main()