set-more-info-link.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  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. 'ru': 'Больше информации:',
  29. 'sv': 'Mer information:',
  30. 'ta': 'மேலும் தகவல்:',
  31. 'th': 'ดูเพิ่มเติม:',
  32. 'tr': 'Daha fazla bilgi için:',
  33. 'zh_TW': '更多資訊:',
  34. 'zh': '更多信息:',
  35. }
  36. IGNORE_FILES = (
  37. '.DS_Store',
  38. )
  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. 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 main():
  88. parser = argparse.ArgumentParser(
  89. description='Sets the "More information" link for all translations of a page')
  90. parser.add_argument('-p', '--page', type=str, required=True,
  91. help='page name in the format "platform/command.md"')
  92. parser.add_argument('-s', '--stage', action='store_true', default=False,
  93. help='stage modified pages (requires `git` to be on $PATH and TLDR_ROOT to be a Git repository)')
  94. parser.add_argument('link', type=str)
  95. args = parser.parse_args()
  96. root = get_tldr_root()
  97. pages_dirs = [d for d in os.listdir(root) if d.startswith('pages')]
  98. target_paths = []
  99. rel_paths = []
  100. if not args.page.lower().endswith('.md'):
  101. args.page = f'{args.page}.md'
  102. for pages_dir in pages_dirs:
  103. pages_dir_path = os.path.join(root, pages_dir)
  104. platforms = [i for i in os.listdir(
  105. pages_dir_path) if i not in IGNORE_FILES]
  106. for platform in platforms:
  107. platform_path = os.path.join(pages_dir_path, platform)
  108. pages = os.listdir(platform_path)
  109. commands = [
  110. f'{platform}/{p}' for p in pages if p not in IGNORE_FILES]
  111. if args.page in commands:
  112. path = os.path.join(pages_dir_path, args.page)
  113. target_paths.append(path)
  114. target_paths.sort()
  115. for path in target_paths:
  116. rel_path = path.replace(f'{root}/', '')
  117. rel_paths.append(rel_path)
  118. status = set_link(path, args.link)
  119. if status != '':
  120. print(f'\x1b[32m{rel_path} {status}\x1b[0m')
  121. if args.stage:
  122. subprocess.call(['git', 'add', *rel_paths], cwd=root)
  123. if __name__ == '__main__':
  124. main()