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.

242 lines
7.3 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. errors = []
  18. title_links = []
  19. anchor_re = re.compile(anchor + '\s(.+)')
  20. section_title_re = re.compile('\*\s\[(.*)\]')
  21. link_re = re.compile('\[(.+)\]\((http.*)\)')
  22. # Type aliases
  23. APIList = List[str]
  24. Categories = Dict[str, APIList]
  25. CategoriesLineNumber = Dict[str, int]
  26. def error_message(line_number: int, message: str) -> str:
  27. line = line_number + 1
  28. return f'(L{line:03d}) {message}'
  29. def get_categories_content(contents: List[str]) -> Tuple[Categories, CategoriesLineNumber]:
  30. categories = {}
  31. category_line_num = {}
  32. for line_num, line_content in enumerate(contents):
  33. if line_content.startswith(anchor):
  34. category = line_content.split(anchor)[1].strip()
  35. categories[category] = []
  36. category_line_num[category] = line_num
  37. continue
  38. if not line_content.startswith('|') or line_content.startswith('|---'):
  39. continue
  40. raw_title = [
  41. raw_content.strip() for raw_content in line_content.split('|')[1:-1]
  42. ][0]
  43. title_match = link_re.match(raw_title)
  44. if title_match:
  45. title = title_match.group(1).upper()
  46. categories[category].append(title)
  47. return (categories, category_line_num)
  48. def check_alphabetical_order(lines: List[str]) -> None:
  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. message = error_message(
  53. category_line_num[category],
  54. f'{category} category is not alphabetical order'
  55. )
  56. errors.append(message)
  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) -> None:
  128. with open(filename, mode='r', encoding='utf-8') as file:
  129. lines = list(line.rstrip() for line in file)
  130. check_alphabetical_order(lines)
  131. num_in_category = min_entries_per_section + 1
  132. category = ''
  133. category_line = 0
  134. for line_num, line in enumerate(lines):
  135. section_title_match = section_title_re.match(line)
  136. if section_title_match:
  137. title_links.append(section_title_match.group(1))
  138. # check each section for the minimum number of entries
  139. if line.startswith(anchor):
  140. category_match = anchor_re.match(line)
  141. if category_match:
  142. if category_match.group(1) not in title_links:
  143. message = error_message(line_num, f'section header ({category_match.group(1)}) not added as a title link')
  144. errors.append(message)
  145. else:
  146. message = error_message(line_num, 'section header is not formatted correctly')
  147. errors.append(message)
  148. if num_in_category < min_entries_per_section:
  149. message = error_message(category_line, f'{category} section does not have the minimum {min_entries_per_section} entries (only has {num_in_category})')
  150. errors.append(message)
  151. category = line.split(' ')[1]
  152. category_line = line_num
  153. num_in_category = 0
  154. continue
  155. # skips lines that we do not care about
  156. if not line.startswith('|') or line.startswith('|---'):
  157. continue
  158. num_in_category += 1
  159. segments = line.split('|')[1:-1]
  160. if len(segments) < num_segments:
  161. message = error_message(line_num, f'entry does not have all the required sections (have {len(segments)}, need {num_segments})')
  162. errors.append(message)
  163. continue
  164. for segment in segments:
  165. # every line segment should start and end with exactly 1 space
  166. if len(segment) - len(segment.lstrip()) != 1 or len(segment) - len(segment.rstrip()) != 1:
  167. message = error_message(line_num, 'each segment must start and end with exactly 1 space')
  168. errors.append(message)
  169. segments = [segment.strip() for segment in segments]
  170. entry_err_msgs = check_entry(line_num, segments)
  171. errors.extend(entry_err_msgs)