You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

250 line
7.6 KiB

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