set-more-info-link.py 7.1 KB

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