set-more-info-link.py 7.1 KB

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