set-more-info-link.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  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. new_line = f'> {labels[locale]} <{link}>.\n'
  70. if lines[desc_end] == new_line:
  71. # return empty status to indicate that no changes were made
  72. return ''
  73. if re.search(r'^>.*<.+>', lines[desc_end]):
  74. # overwrite last line
  75. lines[desc_end] = new_line
  76. status = '\x1b[34mlink updated'
  77. else:
  78. # add new line
  79. lines.insert(desc_end + 1, new_line)
  80. status = '\x1b[36mlink added'
  81. with open(file, 'w') as f:
  82. f.writelines(lines)
  83. return status
  84. def main():
  85. parser = argparse.ArgumentParser(
  86. description='Sets the "More information" link for all translations of a page')
  87. parser.add_argument('-p', '--page', type=str, required=True,
  88. help='page name in the format "platform/command.md"')
  89. parser.add_argument('-s', '--stage', action='store_true', default=False,
  90. help='stage modified pages (requires `git` to be on $PATH and TLDR_ROOT to be a Git repository)')
  91. parser.add_argument('link', type=str)
  92. args = parser.parse_args()
  93. root = get_tldr_root()
  94. pages_dirs = [d for d in os.listdir(root) if d.startswith('pages')]
  95. target_paths = []
  96. rel_paths = []
  97. if not args.page.lower().endswith('.md'):
  98. args.page = f'{args.page}.md'
  99. for pages_dir in pages_dirs:
  100. pages_dir_path = os.path.join(root, pages_dir)
  101. platforms = [i for i in os.listdir(
  102. pages_dir_path) if i not in IGNORE_FILES]
  103. for platform in platforms:
  104. platform_path = os.path.join(pages_dir_path, platform)
  105. pages = os.listdir(platform_path)
  106. commands = [
  107. f'{platform}/{p}' for p in pages if p not in IGNORE_FILES]
  108. if args.page in commands:
  109. path = os.path.join(pages_dir_path, args.page)
  110. target_paths.append(path)
  111. target_paths.sort()
  112. for path in target_paths:
  113. rel_path = path.replace(f'{root}/', '')
  114. rel_paths.append(rel_path)
  115. status = set_link(path, args.link)
  116. if status != '':
  117. print(f'\x1b[32m{rel_path} {status}\x1b[0m')
  118. if args.stage:
  119. subprocess.call(['git', 'add', *rel_paths], cwd=root)
  120. if __name__ == '__main__':
  121. main()