1
0

set-more-info-link.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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", "th"]:
  129. new_line = f"> {labels[locale]} <{link}>\n"
  130. elif locale in ["zh", "zh_TW"]:
  131. new_line = f"> {labels[locale]}<{link}>.\n"
  132. else:
  133. new_line = f"> {labels[locale]} <{link}>.\n"
  134. if lines[desc_end] == new_line:
  135. # return empty status to indicate that no changes were made
  136. return ""
  137. if re.search(r"^>.*<.+>", lines[desc_end]):
  138. # overwrite last line
  139. lines[desc_end] = new_line
  140. action = "updated"
  141. else:
  142. # add new line
  143. lines.insert(desc_end + 1, new_line)
  144. action = "added"
  145. status = get_status(action, dry_run, "link")
  146. if not dry_run: # Only write to the path during a non-dry-run
  147. with path.open("w", encoding="utf-8") as f:
  148. f.writelines(lines)
  149. return status
  150. def get_link(path: Path) -> str:
  151. """
  152. Determine whether the given path has a "More information" link.
  153. Parameters:
  154. path (Path): Path to a page
  155. Returns:
  156. str: "" If the path doesn't exit or does not have a link,
  157. otherwise return the "More information" link.
  158. """
  159. if not path.exists():
  160. return ""
  161. with path.open(encoding="utf-8") as f:
  162. lines = f.readlines()
  163. desc_start = 0
  164. desc_end = 0
  165. # find start and end of description
  166. for i, line in enumerate(lines):
  167. if line.startswith(">") and desc_start == 0:
  168. desc_start = i
  169. if not lines[i + 1].startswith(">") and desc_start != 0:
  170. desc_end = i
  171. break
  172. # match link
  173. if re.search(r"^>.*<.+>", lines[desc_end]):
  174. return re.search("<(.+)>", lines[desc_end]).group(1)
  175. else:
  176. return ""
  177. def sync(
  178. root: Path,
  179. pages_dirs: list[Path],
  180. command: str,
  181. link: str,
  182. dry_run: bool = False,
  183. language_to_update: str = "",
  184. ) -> list[Path]:
  185. """
  186. Synchronize a "More information" link into all translations.
  187. Parameters:
  188. root (Path): TLDR_ROOT
  189. pages_dirs (list of Path's): Path's of page entry and platform, e.g. "page.fr/common".
  190. command (str): A command like "tar".
  191. link (str): A link like "https://example.com".
  192. dry_run (bool): Whether to perform a dry-run, i.e. only show the changes that would be made.
  193. language_to_update (str): Optionally, the language of the translation to be updated.
  194. Returns:
  195. list (list of Path's): A list of Path's to be staged into git, using by --stage option.
  196. """
  197. paths = []
  198. for page_dir in pages_dirs:
  199. path = root / page_dir / command
  200. if path.exists():
  201. status = set_link(path, link, dry_run, language_to_update)
  202. if status != "":
  203. rel_path = "/".join(path.parts[-3:])
  204. paths.append(rel_path)
  205. print(create_colored_line(Colors.GREEN, f"{rel_path} {status}"))
  206. return paths
  207. def main():
  208. parser = create_argument_parser(
  209. 'Sets the "More information" link for all translations of a page'
  210. )
  211. parser.add_argument("link", type=str, nargs="?", default="")
  212. args = parser.parse_args()
  213. root = get_tldr_root()
  214. pages_dirs = get_pages_dir(root)
  215. target_paths = []
  216. # Use '--page' option
  217. if args.page != "":
  218. target_paths += get_target_paths(args.page, pages_dirs)
  219. for path in target_paths:
  220. rel_path = "/".join(path.parts[-3:])
  221. status = set_link(path, args.link, args.dry_run, args.language)
  222. if status != "":
  223. print(create_colored_line(Colors.GREEN, f"{rel_path} {status}"))
  224. # Use '--sync' option
  225. elif args.sync:
  226. pages_dirs.remove(root / "pages")
  227. en_path = root / "pages"
  228. platforms = [i.name for i in en_path.iterdir() if i.name not in IGNORE_FILES]
  229. for platform in platforms:
  230. platform_path = en_path / platform
  231. commands = [
  232. f"{platform}/{page.name}"
  233. for page in platform_path.iterdir()
  234. if page.name not in IGNORE_FILES
  235. ]
  236. for command in commands:
  237. link = get_link(root / "pages" / command)
  238. if link != "":
  239. target_paths += sync(
  240. root, pages_dirs, command, link, args.dry_run, args.language
  241. )
  242. # Use '--stage' option
  243. if args.stage and not args.dry_run and len(target_paths) > 0:
  244. stage(target_paths)
  245. if __name__ == "__main__":
  246. main()