set-more-info-link.py 7.0 KB

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