Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

250 rader
7.6 KiB

  1. # -*- coding: utf-8 -*-
  2. import re
  3. from typing import List, Tuple, Dict
  4. anchor = '###'
  5. auth_keys = ['apiKey', 'OAuth', 'X-Mashape-Key', 'User-Agent', 'No']
  6. punctuation = ['.', '?', '!']
  7. https_keys = ['Yes', 'No']
  8. cors_keys = ['Yes', 'No', 'Unknown']
  9. index_title = 0
  10. index_desc = 1
  11. index_auth = 2
  12. index_https = 3
  13. index_cors = 4
  14. num_segments = 5
  15. min_entries_per_category = 3
  16. anchor_re = re.compile(anchor + '\s(.+)')
  17. category_title_in_index_re = re.compile('\*\s\[(.*)\]')
  18. link_re = re.compile('\[(.+)\]\((http.*)\)')
  19. # Type aliases
  20. APIList = List[str]
  21. Categories = Dict[str, APIList]
  22. CategoriesLineNumber = Dict[str, int]
  23. def error_message(line_number: int, message: str) -> str:
  24. line = line_number + 1
  25. return f'(L{line:03d}) {message}'
  26. def get_categories_content(contents: List[str]) -> Tuple[Categories, CategoriesLineNumber]:
  27. categories = {}
  28. category_line_num = {}
  29. for line_num, line_content in enumerate(contents):
  30. if line_content.startswith(anchor):
  31. category = line_content.split(anchor)[1].strip()
  32. categories[category] = []
  33. category_line_num[category] = line_num
  34. continue
  35. if not line_content.startswith('|') or line_content.startswith('|---'):
  36. continue
  37. raw_title = [
  38. raw_content.strip() for raw_content in line_content.split('|')[1:-1]
  39. ][0]
  40. title_match = link_re.match(raw_title)
  41. if title_match:
  42. title = title_match.group(1).upper()
  43. categories[category].append(title)
  44. return (categories, category_line_num)
  45. def check_alphabetical_order(lines: List[str]) -> List[str]:
  46. err_msgs = []
  47. categories, category_line_num = get_categories_content(contents=lines)
  48. for category, api_list in categories.items():
  49. if sorted(api_list) != api_list:
  50. err_msg = error_message(
  51. category_line_num[category],
  52. f'{category} category is not alphabetical order'
  53. )
  54. err_msgs.append(err_msg)
  55. return err_msgs
  56. def check_title(line_num: int, raw_title: str) -> List[str]:
  57. err_msgs = []
  58. title_match = link_re.match(raw_title)
  59. # url should be wrapped in "[TITLE](LINK)" Markdown syntax
  60. if not title_match:
  61. err_msg = error_message(line_num, 'Title syntax should be "[TITLE](LINK)"')
  62. err_msgs.append(err_msg)
  63. else:
  64. # do not allow "... API" in the entry title
  65. title = title_match.group(1)
  66. if title.upper().endswith(' API'):
  67. err_msg = error_message(line_num, 'Title should not end with "... API". Every entry is an API here!')
  68. err_msgs.append(err_msg)
  69. return err_msgs
  70. def check_description(line_num: int, description: str) -> List[str]:
  71. err_msgs = []
  72. first_char = description[0]
  73. if first_char.upper() != first_char:
  74. err_msg = error_message(line_num, 'first character of description is not capitalized')
  75. err_msgs.append(err_msg)
  76. last_char = description[-1]
  77. if last_char in punctuation:
  78. err_msg = error_message(line_num, f'description should not end with {last_char}')
  79. err_msgs.append(err_msg)
  80. desc_length = len(description)
  81. if desc_length > 100:
  82. err_msg = error_message(line_num, f'description should not exceed 100 characters (currently {desc_length})')
  83. err_msgs.append(err_msg)
  84. return err_msgs
  85. def check_auth(line_num: int, auth: str) -> List[str]:
  86. err_msgs = []
  87. backtick = '`'
  88. if auth != 'No' and (not auth.startswith(backtick) or not auth.endswith(backtick)):
  89. err_msg = error_message(line_num, 'auth value is not enclosed with `backticks`')
  90. err_msgs.append(err_msg)
  91. if auth.replace(backtick, '') not in auth_keys:
  92. err_msg = error_message(line_num, f'{auth} is not a valid Auth option')
  93. err_msgs.append(err_msg)
  94. return err_msgs
  95. def check_https(line_num: int, https: str) -> List[str]:
  96. err_msgs = []
  97. if https not in https_keys:
  98. err_msg = error_message(line_num, f'{https} is not a valid HTTPS option')
  99. err_msgs.append(err_msg)
  100. return err_msgs
  101. def check_cors(line_num: int, cors: str) -> List[str]:
  102. err_msgs = []
  103. if cors not in cors_keys:
  104. err_msg = error_message(line_num, f'{cors} is not a valid CORS option')
  105. err_msgs.append(err_msg)
  106. return err_msgs
  107. def check_entry(line_num: int, segments: List[str]) -> List[str]:
  108. raw_title = segments[index_title]
  109. description = segments[index_desc]
  110. auth = segments[index_auth]
  111. https = segments[index_https]
  112. cors = segments[index_cors]
  113. title_err_msgs = check_title(line_num, raw_title)
  114. desc_err_msgs = check_description(line_num, description)
  115. auth_err_msgs = check_auth(line_num, auth)
  116. https_err_msgs = check_https(line_num, https)
  117. cors_err_msgs = check_cors(line_num, cors)
  118. err_msgs = [
  119. *title_err_msgs,
  120. *desc_err_msgs,
  121. *auth_err_msgs,
  122. *https_err_msgs,
  123. *cors_err_msgs
  124. ]
  125. return err_msgs
  126. def check_file_format(filename: str) -> List[str]:
  127. err_msgs = []
  128. category_title_in_index = []
  129. with open(filename, mode='r', encoding='utf-8') as file:
  130. lines = list(line.rstrip() for line in file)
  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