set-more-info-link.py 7.0 KB

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