set-more-info-link.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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. else:
  72. new_line = f"> {labels[locale]} <{link}>.\n"
  73. if lines[desc_end] == new_line:
  74. # return empty status to indicate that no changes were made
  75. return ""
  76. if re.search(r"^>.*<.+>", lines[desc_end]):
  77. # overwrite last line
  78. lines[desc_end] = new_line
  79. status = "\x1b[34mlink updated"
  80. else:
  81. # add new line
  82. lines.insert(desc_end + 1, new_line)
  83. status = "\x1b[36mlink added"
  84. with open(file, "w") as f:
  85. f.writelines(lines)
  86. return status
  87. def get_link(file):
  88. with open(file) as f:
  89. lines = f.readlines()
  90. desc_start = 0
  91. desc_end = 0
  92. # find start and end of description
  93. for i, line in enumerate(lines):
  94. if line.startswith(">") and desc_start == 0:
  95. desc_start = i
  96. if not lines[i + 1].startswith(">") and desc_start != 0:
  97. desc_end = i
  98. break
  99. # match link
  100. if re.search(r"^>.*<.+>", lines[desc_end]):
  101. return re.search("<(.+)>", lines[desc_end]).group(1)
  102. else:
  103. return ""
  104. def sync(root, pages_dirs, command, link):
  105. rel_paths = []
  106. for page_dir in pages_dirs:
  107. path = os.path.join(root, page_dir, command)
  108. if os.path.exists(path):
  109. rel_path = path.replace(f"{root}/", "")
  110. rel_paths.append(rel_path)
  111. status = set_link(path, link)
  112. if status != "":
  113. print(f"\x1b[32m{rel_path} {status}\x1b[0m")
  114. return rel_paths
  115. def main():
  116. parser = argparse.ArgumentParser(
  117. description='Sets the "More information" link for all translations of a page'
  118. )
  119. parser.add_argument(
  120. "-p",
  121. "--page",
  122. type=str,
  123. required=False,
  124. default="",
  125. help='page name in the format "platform/command.md"',
  126. )
  127. parser.add_argument(
  128. "-s",
  129. "--stage",
  130. action="store_true",
  131. default=False,
  132. help="stage modified pages (requires `git` to be on $PATH and TLDR_ROOT to be a Git repository)",
  133. )
  134. parser.add_argument(
  135. "-S",
  136. "--sync",
  137. action="store_true",
  138. default=False,
  139. help="synchronize each translation's more information link (if exists) with that of English page",
  140. )
  141. parser.add_argument("link", type=str, nargs="?", default="")
  142. args = parser.parse_args()
  143. root = get_tldr_root()
  144. pages_dirs = [d for d in os.listdir(root) if d.startswith("pages")]
  145. rel_paths = []
  146. # Use '--page' option
  147. if args.page != "":
  148. target_paths = []
  149. if not args.page.lower().endswith(".md"):
  150. args.page = f"{args.page}.md"
  151. for pages_dir in pages_dirs:
  152. pages_dir_path = os.path.join(root, pages_dir)
  153. platforms = [i for i in os.listdir(pages_dir_path) if i not in IGNORE_FILES]
  154. for platform in platforms:
  155. platform_path = os.path.join(pages_dir_path, platform)
  156. commands = [
  157. f"{platform}/{p}"
  158. for p in os.listdir(platform_path)
  159. if p not in IGNORE_FILES
  160. ]
  161. if args.page in commands:
  162. path = os.path.join(pages_dir_path, args.page)
  163. target_paths.append(path)
  164. target_paths.sort()
  165. for path in target_paths:
  166. rel_path = path.replace(f"{root}/", "")
  167. rel_paths.append(rel_path)
  168. status = set_link(path, args.link)
  169. if status != "":
  170. print(f"\x1b[32m{rel_path} {status}\x1b[0m")
  171. # Use '--sync' option
  172. elif args.sync:
  173. pages_dirs.remove("pages")
  174. en_page = os.path.join(root, "pages")
  175. platforms = [i for i in os.listdir(en_page) if i not in IGNORE_FILES]
  176. for platform in platforms:
  177. platform_path = os.path.join(en_page, platform)
  178. commands = [
  179. f"{platform}/{p}"
  180. for p in os.listdir(platform_path)
  181. if p not in IGNORE_FILES
  182. ]
  183. for command in commands:
  184. link = get_link(os.path.join(root, "pages", command))
  185. if link != "":
  186. rel_paths += sync(root, pages_dirs, command, link)
  187. if args.stage:
  188. subprocess.call(["git", "add", *rel_paths], cwd=root)
  189. if __name__ == "__main__":
  190. main()