set-more-info-link.py 9.8 KB

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