25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

275 satır
8.1 KiB

  1. # -*- coding: utf-8 -*-
  2. import re
  3. import sys
  4. from string import punctuation
  5. from typing import List, Tuple, Dict
  6. anchor = '###'
  7. auth_keys = ['apiKey', 'OAuth', 'X-Mashape-Key', 'User-Agent', 'No']
  8. https_keys = ['Yes', 'No']
  9. cors_keys = ['Yes', 'No', 'Unknown']
  10. index_title = 0
  11. index_desc = 1
  12. index_auth = 2
  13. index_https = 3
  14. index_cors = 4
  15. num_segments = 5
  16. min_entries_per_category = 3
  17. max_description_length = 100
  18. anchor_re = re.compile(anchor + '\s(.+)')
  19. category_title_in_index_re = re.compile('\*\s\[(.*)\]')
  20. link_re = re.compile('\[(.+)\]\((http.*)\)')
  21. # Type aliases
  22. APIList = List[str]
  23. Categories = Dict[str, APIList]
  24. CategoriesLineNumber = Dict[str, int]
  25. def error_message(line_number: int, message: str) -> str:
  26. line = line_number + 1
  27. return f'(L{line:03d}) {message}'
  28. def get_categories_content(contents: List[str]) -> Tuple[Categories, CategoriesLineNumber]:
  29. categories = {}
  30. category_line_num = {}
  31. for line_num, line_content in enumerate(contents):
  32. if line_content.startswith(anchor):
  33. category = line_content.split(anchor)[1].strip()
  34. categories[category] = []
  35. category_line_num[category] = line_num
  36. continue
  37. if not line_content.startswith('|') or line_content.startswith('|---'):
  38. continue
  39. raw_title = [
  40. raw_content.strip() for raw_content in line_content.split('|')[1:-1]
  41. ][0]
  42. title_match = link_re.match(raw_title)
  43. if title_match:
  44. title = title_match.group(1).upper()
  45. categories[category].append(title)
  46. return (categories, category_line_num)
  47. def check_alphabetical_order(lines: List[str]) -> List[str]:
  48. err_msgs = []
  49. categories, category_line_num = get_categories_content(contents=lines)
  50. for category, api_list in categories.items():
  51. if sorted(api_list) != api_list:
  52. err_msg = error_message(
  53. category_line_num[category],
  54. f'{category} category is not alphabetical order'
  55. )
  56. err_msgs.append(err_msg)
  57. return err_msgs
  58. def check_title(line_num: int, raw_title: str) -> List[str]:
  59. err_msgs = []
  60. title_match = link_re.match(raw_title)
  61. # url should be wrapped in "[TITLE](LINK)" Markdown syntax
  62. if not title_match:
  63. err_msg = error_message(line_num, 'Title syntax should be "[TITLE](LINK)"')
  64. err_msgs.append(err_msg)
  65. else:
  66. # do not allow "... API" in the entry title
  67. title = title_match.group(1)
  68. if title.upper().endswith(' API'):
  69. err_msg = error_message(line_num, 'Title should not end with "... API". Every entry is an API here!')
  70. err_msgs.append(err_msg)
  71. return err_msgs
  72. def check_description(line_num: int, description: str) -> List[str]:
  73. err_msgs = []
  74. first_char = description[0]
  75. if first_char.upper() != first_char:
  76. err_msg = error_message(line_num, 'first character of description is not capitalized')
  77. err_msgs.append(err_msg)
  78. last_char = description[-1]
  79. if last_char in punctuation:
  80. err_msg = error_message(line_num, f'description should not end with {last_char}')
  81. err_msgs.append(err_msg)
  82. desc_length = len(description)
  83. if desc_length > max_description_length:
  84. err_msg = error_message(line_num, f'description should not exceed 100 characters (currently {desc_length})')
  85. err_msgs.append(err_msg)
  86. return err_msgs
  87. def check_auth(line_num: int, auth: str) -> List[str]:
  88. err_msgs = []
  89. backtick = '`'
  90. if auth != 'No' and (not auth.startswith(backtick) or not auth.endswith(backtick)):
  91. err_msg = error_message(line_num, 'auth value is not enclosed with `backticks`')
  92. err_msgs.append(err_msg)
  93. if auth.replace(backtick, '') not in auth_keys:
  94. err_msg = error_message(line_num, f'{auth} is not a valid Auth option')
  95. err_msgs.append(err_msg)
  96. return err_msgs
  97. def check_https(line_num: int, https: str) -> List[str]:
  98. err_msgs = []
  99. if https not in https_keys:
  100. err_msg = error_message(line_num, f'{https} is not a valid HTTPS option')
  101. err_msgs.append(err_msg)
  102. return err_msgs
  103. def check_cors(line_num: int, cors: str) -> List[str]:
  104. err_msgs = []
  105. if cors not in cors_keys:
  106. err_msg = error_message(line_num, f'{cors} is not a valid CORS option')
  107. err_msgs.append(err_msg)
  108. return err_msgs
  109. def check_entry(line_num: int, segments: List[str]) -> List[str]:
  110. raw_title = segments[index_title]
  111. description = segments[index_desc]
  112. auth = segments[index_auth]
  113. https = segments[index_https]
  114. cors = segments[index_cors]
  115. title_err_msgs = check_title(line_num, raw_title)
  116. desc_err_msgs = check_description(line_num, description)
  117. auth_err_msgs = check_auth(line_num, auth)
  118. https_err_msgs = check_https(line_num, https)
  119. cors_err_msgs = check_cors(line_num, cors)
  120. err_msgs = [
  121. *title_err_msgs,
  122. *desc_err_msgs,
  123. *auth_err_msgs,
  124. *https_err_msgs,
  125. *cors_err_msgs
  126. ]
  127. return err_msgs
  128. def check_file_format(lines: List[str]) -> List[str]:
  129. err_msgs = []
  130. category_title_in_index = []
  131. alphabetical_err_msgs = check_alphabetical_order(lines)
  132. err_msgs.extend(alphabetical_err_msgs)
  133. num_in_category = min_entries_per_category + 1
  134. category = ''
  135. category_line = 0
  136. for line_num, line_content in enumerate(lines):
  137. category_title_match = category_title_in_index_re.match(line_content)
  138. if category_title_match:
  139. category_title_in_index.append(category_title_match.group(1))
  140. # check each category for the minimum number of entries
  141. if line_content.startswith(anchor):
  142. category_match = anchor_re.match(line_content)
  143. if category_match:
  144. if category_match.group(1) not in category_title_in_index:
  145. err_msg = error_message(line_num, f'category header ({category_match.group(1)}) not added to Index section')
  146. err_msgs.append(err_msg)
  147. else:
  148. err_msg = error_message(line_num, 'category header is not formatted correctly')
  149. err_msgs.append(err_msg)
  150. if num_in_category < min_entries_per_category:
  151. err_msg = error_message(category_line, f'{category} category does not have the minimum {min_entries_per_category} entries (only has {num_in_category})')
  152. err_msgs.append(err_msg)
  153. category = line_content.split(' ')[1]
  154. category_line = line_num
  155. num_in_category = 0
  156. continue
  157. # skips lines that we do not care about
  158. if not line_content.startswith('|') or line_content.startswith('|---'):
  159. continue
  160. num_in_category += 1
  161. segments = line_content.split('|')[1:-1]
  162. if len(segments) < num_segments:
  163. err_msg = error_message(line_num, f'entry does not have all the required sections (have {len(segments)}, need {num_segments})')
  164. err_msgs.append(err_msg)
  165. continue
  166. for segment in segments:
  167. # every line segment should start and end with exactly 1 space
  168. if len(segment) - len(segment.lstrip()) != 1 or len(segment) - len(segment.rstrip()) != 1:
  169. err_msg = error_message(line_num, 'each segment must start and end with exactly 1 space')
  170. err_msgs.append(err_msg)
  171. segments = [segment.strip() for segment in segments]
  172. entry_err_msgs = check_entry(line_num, segments)
  173. err_msgs.extend(entry_err_msgs)
  174. return err_msgs
  175. def main(filename: str) -> None:
  176. with open(filename, mode='r', encoding='utf-8') as file:
  177. lines = list(line.rstrip() for line in file)
  178. file_format_err_msgs = check_file_format(lines)
  179. if file_format_err_msgs:
  180. for err_msg in file_format_err_msgs:
  181. print(err_msg)
  182. sys.exit(1)
  183. if __name__ == '__main__':
  184. num_args = len(sys.argv)
  185. if num_args < 2:
  186. print('No .md file passed (file should contain Markdown table syntax)')
  187. sys.exit(1)
  188. filename = sys.argv[1]
  189. main(filename)