set-more-info-link.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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. "uz": "Ko'proq malumot:",
  40. "zh_TW": "更多資訊:",
  41. "zh": "更多信息:",
  42. }
  43. IGNORE_FILES = (".DS_Store",)
  44. def get_tldr_root():
  45. # if this script is running from tldr/scripts, the parent's parent is the root
  46. f = os.path.normpath(__file__)
  47. if f.endswith("tldr/scripts/set-more-info-link.py"):
  48. return os.path.dirname(os.path.dirname(f))
  49. if "TLDR_ROOT" in os.environ:
  50. return os.environ["TLDR_ROOT"]
  51. else:
  52. print(
  53. "\x1b[31mPlease set TLDR_ROOT to the location of a clone of https://github.com/tldr-pages/tldr."
  54. )
  55. sys.exit(1)
  56. def set_link(file, link):
  57. with open(file) as f:
  58. lines = f.readlines()
  59. desc_start = 0
  60. desc_end = 0
  61. # find start and end of description
  62. for i, line in enumerate(lines):
  63. if line.startswith(">") and desc_start == 0:
  64. desc_start = i
  65. if not lines[i + 1].startswith(">") and desc_start != 0:
  66. desc_end = i
  67. break
  68. # compute locale
  69. pages_dir = os.path.basename(os.path.dirname(os.path.dirname(file)))
  70. if "." in pages_dir:
  71. _, locale = pages_dir.split(".")
  72. else:
  73. locale = "en"
  74. # build new line
  75. if locale == "hi":
  76. new_line = f"> {labels[locale]} <{link}>।\n"
  77. elif locale == "ja":
  78. new_line = f"> {labels[locale]} <{link}>\n"
  79. elif locale == "zh" or locale == "zh_TW":
  80. new_line = f"> {labels[locale]}<{link}>.\n"
  81. else:
  82. new_line = f"> {labels[locale]} <{link}>.\n"
  83. if lines[desc_end] == new_line:
  84. # return empty status to indicate that no changes were made
  85. return ""
  86. if re.search(r"^>.*<.+>", lines[desc_end]):
  87. # overwrite last line
  88. lines[desc_end] = new_line
  89. status = "\x1b[34mlink updated"
  90. else:
  91. # add new line
  92. lines.insert(desc_end + 1, new_line)
  93. status = "\x1b[36mlink added"
  94. with open(file, "w") as f:
  95. f.writelines(lines)
  96. return status
  97. def get_link(file):
  98. with open(file) as f:
  99. lines = f.readlines()
  100. desc_start = 0
  101. desc_end = 0
  102. # find start and end of description
  103. for i, line in enumerate(lines):
  104. if line.startswith(">") and desc_start == 0:
  105. desc_start = i
  106. if not lines[i + 1].startswith(">") and desc_start != 0:
  107. desc_end = i
  108. break
  109. # match link
  110. if re.search(r"^>.*<.+>", lines[desc_end]):
  111. return re.search("<(.+)>", lines[desc_end]).group(1)
  112. else:
  113. return ""
  114. def sync(root, pages_dirs, command, link):
  115. rel_paths = []
  116. for page_dir in pages_dirs:
  117. path = os.path.join(root, page_dir, command)
  118. if os.path.exists(path):
  119. rel_path = path.replace(f"{root}/", "")
  120. rel_paths.append(rel_path)
  121. status = set_link(path, link)
  122. if status != "":
  123. print(f"\x1b[32m{rel_path} {status}\x1b[0m")
  124. return rel_paths
  125. def main():
  126. parser = argparse.ArgumentParser(
  127. description='Sets the "More information" link for all translations of a page'
  128. )
  129. parser.add_argument(
  130. "-p",
  131. "--page",
  132. type=str,
  133. required=False,
  134. default="",
  135. help='page name in the format "platform/command.md"',
  136. )
  137. parser.add_argument(
  138. "-s",
  139. "--stage",
  140. action="store_true",
  141. default=False,
  142. help="stage modified pages (requires `git` to be on $PATH and TLDR_ROOT to be a Git repository)",
  143. )
  144. parser.add_argument(
  145. "-S",
  146. "--sync",
  147. action="store_true",
  148. default=False,
  149. help="synchronize each translation's more information link (if exists) with that of English page",
  150. )
  151. parser.add_argument("link", type=str, nargs="?", default="")
  152. args = parser.parse_args()
  153. root = get_tldr_root()
  154. pages_dirs = [d for d in os.listdir(root) if d.startswith("pages")]
  155. rel_paths = []
  156. # Use '--page' option
  157. if args.page != "":
  158. target_paths = []
  159. if not args.page.lower().endswith(".md"):
  160. args.page = f"{args.page}.md"
  161. for pages_dir in pages_dirs:
  162. pages_dir_path = os.path.join(root, pages_dir)
  163. platforms = [i for i in os.listdir(pages_dir_path) if i not in IGNORE_FILES]
  164. for platform in platforms:
  165. platform_path = os.path.join(pages_dir_path, platform)
  166. commands = [
  167. f"{platform}/{p}"
  168. for p in os.listdir(platform_path)
  169. if p not in IGNORE_FILES
  170. ]
  171. if args.page in commands:
  172. path = os.path.join(pages_dir_path, args.page)
  173. target_paths.append(path)
  174. target_paths.sort()
  175. for path in target_paths:
  176. rel_path = path.replace(f"{root}/", "")
  177. rel_paths.append(rel_path)
  178. status = set_link(path, args.link)
  179. if status != "":
  180. print(f"\x1b[32m{rel_path} {status}\x1b[0m")
  181. # Use '--sync' option
  182. elif args.sync:
  183. pages_dirs.remove("pages")
  184. en_page = os.path.join(root, "pages")
  185. platforms = [i for i in os.listdir(en_page) if i not in IGNORE_FILES]
  186. for platform in platforms:
  187. platform_path = os.path.join(en_page, platform)
  188. commands = [
  189. f"{platform}/{p}"
  190. for p in os.listdir(platform_path)
  191. if p not in IGNORE_FILES
  192. ]
  193. for command in commands:
  194. link = get_link(os.path.join(root, "pages", command))
  195. if link != "":
  196. rel_paths += sync(root, pages_dirs, command, link)
  197. if args.stage:
  198. subprocess.call(["git", "add", *rel_paths], cwd=root)
  199. if __name__ == "__main__":
  200. main()