set-more-info-link.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. import argparse
  2. import os
  3. import re
  4. import subprocess
  5. import sys
  6. labels = {
  7. 'en': 'More information:',
  8. 'bs': 'Više informacija:',
  9. 'da': 'Mere information:',
  10. 'de': 'Weitere Informationen:',
  11. 'es': 'Más información:',
  12. 'fa': 'اطلاعات بیشتر:',
  13. 'fr': 'Plus d\'informations\xa0:',
  14. 'sh': 'Više informacija:',
  15. 'hi': 'अधिक जानकारी:',
  16. 'id': 'Informasi lebih lanjut:',
  17. 'it': 'Maggiori informazioni:',
  18. 'ja': '詳しくはこちら:',
  19. 'ko': '더 많은 정보:',
  20. 'ml': 'കൂടുതൽ വിവരങ്ങൾ:',
  21. 'nl': 'Meer informatie:',
  22. 'no': 'Mer informasjon:',
  23. 'pl': 'Więcej informacji:',
  24. 'pt_BR': 'Mais informações:',
  25. 'pt_PT': 'Mais informações:',
  26. 'ru': 'Больше информации:',
  27. 'sv': 'Mer information:',
  28. 'ta': 'மேலும் தகவல்:',
  29. 'th': 'ดูเพิ่มเติม:',
  30. 'tr': 'Daha fazla bilgi için:',
  31. 'zh_TW': '更多資訊:',
  32. 'zh': '更多信息:',
  33. }
  34. IGNORE_FILES = (
  35. '.DS_Store',
  36. )
  37. def get_tldr_root():
  38. # if this script is running from tldr/scripts, the parent's parent is the root
  39. f = os.path.normpath(__file__)
  40. if f.endswith('tldr/scripts/set-more-info-link.py'):
  41. return os.path.dirname(os.path.dirname(f))
  42. if 'TLDR_ROOT' in os.environ:
  43. return os.environ['TLDR_ROOT']
  44. else:
  45. print(
  46. '\x1b[31mPlease set TLDR_ROOT to the location of a clone of https://github.com/tldr-pages/tldr.')
  47. sys.exit(1)
  48. def set_link(file, link):
  49. with open(file) as f:
  50. lines = f.readlines()
  51. desc_start = 0
  52. desc_end = 0
  53. # find start and end of description
  54. for i, line in enumerate(lines):
  55. if line.startswith('>') and desc_start == 0:
  56. desc_start = i
  57. if not lines[i + 1].startswith('>') and desc_start != 0:
  58. desc_end = i
  59. break
  60. # compute locale
  61. pages_dir = os.path.basename(os.path.dirname(os.path.dirname(file)))
  62. if '.' in pages_dir:
  63. _, locale = pages_dir.split('.')
  64. else:
  65. locale = 'en'
  66. # build new line
  67. new_line = f'> {labels[locale]} <{link}>.\n'
  68. if lines[desc_end] == new_line:
  69. # return empty status to indicate that no changes were made
  70. return ''
  71. if re.search(r'^>.*<.+>', lines[desc_end]):
  72. # overwrite last line
  73. lines[desc_end] = new_line
  74. status = '\x1b[34mlink updated'
  75. else:
  76. # add new line
  77. lines.insert(desc_end + 1, new_line)
  78. status = '\x1b[36mlink added'
  79. with open(file, 'w') as f:
  80. f.writelines(lines)
  81. return status
  82. def main():
  83. parser = argparse.ArgumentParser(
  84. description='Sets the "More information" link for all translations of a page')
  85. parser.add_argument('-p', '--page', type=str, required=True,
  86. help='page name in the format "platform/command.md"')
  87. parser.add_argument('-s', '--stage', action='store_true', default=False,
  88. help='stage modified pages (requires `git` to be on $PATH and TLDR_ROOT to be a Git repository)')
  89. parser.add_argument('link', type=str)
  90. args = parser.parse_args()
  91. root = get_tldr_root()
  92. pages_dirs = [d for d in os.listdir(root) if d.startswith('pages')]
  93. target_paths = []
  94. rel_paths = []
  95. if not args.page.lower().endswith('.md'):
  96. args.page = f'{args.page}.md'
  97. for pages_dir in pages_dirs:
  98. pages_dir_path = os.path.join(root, pages_dir)
  99. platforms = [i for i in os.listdir(
  100. pages_dir_path) if i not in IGNORE_FILES]
  101. for platform in platforms:
  102. platform_path = os.path.join(pages_dir_path, platform)
  103. pages = os.listdir(platform_path)
  104. commands = [
  105. f'{platform}/{p}' for p in pages if p not in IGNORE_FILES]
  106. if args.page in commands:
  107. path = os.path.join(pages_dir_path, args.page)
  108. target_paths.append(path)
  109. target_paths.sort()
  110. for path in target_paths:
  111. rel_path = path.replace(f'{root}/', '')
  112. rel_paths.append(rel_path)
  113. status = set_link(path, args.link)
  114. if status != '':
  115. print(f'\x1b[32m{rel_path} {status}\x1b[0m')
  116. if args.stage:
  117. subprocess.call(['git', 'add', *rel_paths], cwd=root)
  118. if __name__ == '__main__':
  119. main()