set-more-info-link.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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. "sh": "Više informacija:",
  67. "hi": "अधिक जानकारी:",
  68. "id": "Informasi lebih lanjut:",
  69. "it": "Maggiori informazioni:",
  70. "ja": "詳しくはこちら:",
  71. "ko": "더 많은 정보:",
  72. "lo": "ຂໍ້ມູນເພີ່ມເຕີມ:",
  73. "ml": "കൂടുതൽ വിവരങ്ങൾ:",
  74. "ne": "थप जानकारी:",
  75. "nl": "Meer informatie:",
  76. "no": "Mer informasjon:",
  77. "pl": "Więcej informacji:",
  78. "pt_BR": "Mais informações:",
  79. "pt_PT": "Mais informações:",
  80. "ro": "Mai multe informații:",
  81. "ru": "Больше информации:",
  82. "sh": "Više informacija:",
  83. "sr": "Više informacija na:",
  84. "sv": "Mer information:",
  85. "ta": "மேலும் விவரத்திற்கு:",
  86. "th": "ข้อมูลเพิ่มเติม:",
  87. "tr": "Daha fazla bilgi için:",
  88. "uk": "Більше інформації:",
  89. "uz": "Ko'proq malumot:",
  90. "zh_TW": "更多資訊:",
  91. "zh": "更多信息:",
  92. }
  93. def set_link(
  94. path: Path, link: str, dry_run: bool = False, language_to_update: str = ""
  95. ) -> str:
  96. """
  97. Write a "More information" link in a page to disk.
  98. Parameters:
  99. path (string): Path to a page
  100. link (string): The "More information" link to insert.
  101. dry_run (bool): Whether to perform a dry-run, i.e. only show the changes that would be made.
  102. language_to_update (string): Optionally, the language of the translation to be updated.
  103. Returns:
  104. str: Execution status
  105. "" if the page does not need an update or if the locale does not match language_to_update.
  106. "\x1b[36mlink added"
  107. "\x1b[34mlink updated"
  108. "\x1b[36mlink would be added"
  109. "\x1b[34mlink would updated"
  110. """
  111. locale = get_locale(path)
  112. if language_to_update != "" and locale != language_to_update:
  113. # return empty status to indicate that no changes were made
  114. return ""
  115. with path.open(encoding="utf-8") as f:
  116. lines = f.readlines()
  117. desc_start = 0
  118. desc_end = 0
  119. # find start and end of description
  120. for i, line in enumerate(lines):
  121. if line.startswith(">") and desc_start == 0:
  122. desc_start = i
  123. if not lines[i + 1].startswith(">") and desc_start != 0:
  124. desc_end = i
  125. break
  126. # build new line
  127. if locale in ["bn", "hi", "ne"]:
  128. new_line = f"> {labels[locale]} <{link}>।\n"
  129. elif locale in ["ja", "th"]:
  130. new_line = f"> {labels[locale]} <{link}>\n"
  131. elif locale in ["zh", "zh_TW"]:
  132. new_line = f"> {labels[locale]}<{link}>.\n"
  133. else:
  134. new_line = f"> {labels[locale]} <{link}>.\n"
  135. if lines[desc_end] == new_line:
  136. # return empty status to indicate that no changes were made
  137. return ""
  138. if re.search(r"^>.*<.+>", lines[desc_end]):
  139. # overwrite last line
  140. lines[desc_end] = new_line
  141. action = "updated"
  142. else:
  143. # add new line
  144. lines.insert(desc_end + 1, new_line)
  145. action = "added"
  146. status = get_status(action, dry_run, "link")
  147. if not dry_run: # Only write to the path during a non-dry-run
  148. with path.open("w", encoding="utf-8") as f:
  149. f.writelines(lines)
  150. return status
  151. def get_link(path: Path) -> str:
  152. """
  153. Determine whether the given path has a "More information" link.
  154. Parameters:
  155. path (Path): Path to a page
  156. Returns:
  157. str: "" If the path doesn't exit or does not have a link,
  158. otherwise return the "More information" link.
  159. """
  160. if not path.exists():
  161. return ""
  162. with path.open(encoding="utf-8") as f:
  163. lines = f.readlines()
  164. desc_start = 0
  165. desc_end = 0
  166. # find start and end of description
  167. for i, line in enumerate(lines):
  168. if line.startswith(">") and desc_start == 0:
  169. desc_start = i
  170. if not lines[i + 1].startswith(">") and desc_start != 0:
  171. desc_end = i
  172. break
  173. # match link
  174. if re.search(r"^>.*<.+>", lines[desc_end]):
  175. return re.search("<(.+)>", lines[desc_end]).group(1)
  176. else:
  177. return ""
  178. def sync(
  179. root: Path,
  180. pages_dirs: list[Path],
  181. command: str,
  182. link: str,
  183. dry_run: bool = False,
  184. language_to_update: str = "",
  185. ) -> list[Path]:
  186. """
  187. Synchronize a "More information" link into all translations.
  188. Parameters:
  189. root (Path): TLDR_ROOT
  190. pages_dirs (list of Path's): Path's of page entry and platform, e.g. "page.fr/common".
  191. command (str): A command like "tar".
  192. link (str): A link like "https://example.com".
  193. dry_run (bool): Whether to perform a dry-run, i.e. only show the changes that would be made.
  194. language_to_update (str): Optionally, the language of the translation to be updated.
  195. Returns:
  196. list (list of Path's): A list of Path's to be staged into git, using by --stage option.
  197. """
  198. paths = []
  199. for page_dir in pages_dirs:
  200. path = root / page_dir / command
  201. if path.exists():
  202. status = set_link(path, link, dry_run, language_to_update)
  203. if status != "":
  204. rel_path = "/".join(path.parts[-3:])
  205. paths.append(rel_path)
  206. print(create_colored_line(Colors.GREEN, f"{rel_path} {status}"))
  207. return paths
  208. def main():
  209. parser = create_argument_parser(
  210. 'Sets the "More information" link for all translations of a page'
  211. )
  212. parser.add_argument("link", type=str, nargs="?", default="")
  213. args = parser.parse_args()
  214. root = get_tldr_root()
  215. pages_dirs = get_pages_dir(root)
  216. target_paths = []
  217. # Use '--page' option
  218. if args.page != "":
  219. target_paths += get_target_paths(args.page, pages_dirs)
  220. for path in target_paths:
  221. rel_path = "/".join(path.parts[-3:])
  222. status = set_link(path, args.link, args.dry_run, args.language)
  223. if status != "":
  224. print(create_colored_line(Colors.GREEN, f"{rel_path} {status}"))
  225. # Use '--sync' option
  226. elif args.sync:
  227. pages_dirs.remove(root / "pages")
  228. en_path = root / "pages"
  229. platforms = [i.name for i in en_path.iterdir() if i.name not in IGNORE_FILES]
  230. for platform in platforms:
  231. platform_path = en_path / platform
  232. commands = [
  233. f"{platform}/{page.name}"
  234. for page in platform_path.iterdir()
  235. if page.name not in IGNORE_FILES
  236. ]
  237. for command in commands:
  238. link = get_link(root / "pages" / command)
  239. if link != "":
  240. target_paths += sync(
  241. root, pages_dirs, command, link, args.dry_run, args.language
  242. )
  243. # Use '--stage' option
  244. if args.stage and not args.dry_run and len(target_paths) > 0:
  245. stage(target_paths)
  246. if __name__ == "__main__":
  247. main()