1
0

set-more-info-link.py 6.8 KB

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