set-more-info-link.py 6.6 KB

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