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.

validate_format.py 5.7 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. #!/usr/bin/env python3
  2. import re
  3. import sys
  4. anchor = '###'
  5. min_entries_per_section = 3
  6. auth_keys = ['apiKey', 'OAuth', 'X-Mashape-Key', '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 = 6
  17. errors = []
  18. title_links = []
  19. anchor_re = re.compile(anchor + '\s(.+)')
  20. section_title_re = re.compile('\*\s\[(.*)\]')
  21. def add_error(line_num, message):
  22. """adds an error to the dynamic error list"""
  23. err = '(L{:03d}) {}'.format(line_num + 1, message)
  24. errors.append(err)
  25. def check_alphabetical(lines):
  26. """
  27. checks if all entries per section are in alphabetical order based in entry title
  28. """
  29. sections = {}
  30. section_line_num = {}
  31. for line_num, line in enumerate(lines):
  32. if line.startswith(anchor):
  33. category = line.split(anchor)[1].strip()
  34. sections[category] = []
  35. section_line_num[category] = line_num
  36. continue
  37. if not line.startswith('|') or line.startswith('|---'):
  38. continue
  39. title = [x.strip() for x in line.split('|')[1:-1]][0].upper()
  40. sections[category].append(title)
  41. for category, entries in sections.items():
  42. if sorted(entries) != entries:
  43. add_error(section_line_num[category], "{} section is not in alphabetical order".format(category))
  44. def check_entry(line_num, segments):
  45. # START Title
  46. title = segments[index_title].upper()
  47. if title.endswith(' API'):
  48. add_error(line_num, 'Title should not contain "API"')
  49. # END Title
  50. # START Description
  51. # first character should be capitalized
  52. char = segments[index_desc][0]
  53. if char.upper() != char:
  54. add_error(line_num, "first character of description is not capitalized")
  55. # last character should not punctuation
  56. char = segments[index_desc][-1]
  57. if char in punctuation:
  58. add_error(line_num, "description should not end with {}".format(char))
  59. desc_length = len(segments[index_desc])
  60. if desc_length > 100:
  61. add_error(line_num, "description should not exceed 100 characters (currently {})".format(desc_length))
  62. # END Description
  63. # START Auth
  64. # values should conform to valid options only
  65. auth = segments[index_auth]
  66. if auth != 'No' and (not auth.startswith('`') or not auth.endswith('`')):
  67. add_error(line_num, "auth value is not enclosed with `backticks`")
  68. if auth.replace('`', '') not in auth_keys:
  69. add_error(line_num, "{} is not a valid Auth option".format(auth))
  70. # END Auth
  71. # START HTTPS
  72. # values should conform to valid options only
  73. https = segments[index_https]
  74. if https not in https_keys:
  75. add_error(line_num, "{} is not a valid HTTPS option".format(https))
  76. # END HTTPS
  77. # START CORS
  78. # values should conform to valid options only
  79. cors = segments[index_cors]
  80. if cors not in cors_keys:
  81. add_error(line_num, "{} is not a valid CORS option".format(cors))
  82. # END CORS
  83. # START Link
  84. # url should be wrapped in '[Go!]()' Markdown syntax
  85. link = segments[index_link]
  86. if not link.startswith('[Go!](http') or not link.endswith(')'):
  87. add_error(line_num, 'link syntax should be "[Go!](LINK)"')
  88. # END Link
  89. def check_format(filename):
  90. """
  91. validates that each line is formatted correctly,
  92. appending to error list as needed
  93. """
  94. with open(filename) as fp:
  95. lines = list(line.rstrip() for line in fp)
  96. check_alphabetical(lines)
  97. # START Check Entries
  98. num_in_category = min_entries_per_section + 1
  99. category = ""
  100. category_line = 0
  101. for line_num, line in enumerate(lines):
  102. if section_title_re.match(line):
  103. title_links.append(section_title_re.match(line).group(1))
  104. # check each section for the minimum number of entries
  105. if line.startswith(anchor):
  106. match = anchor_re.match(line)
  107. if match:
  108. if match.group(1) not in title_links:
  109. add_error(line_num, "section header ({}) not added as a title link".format(match.group(1)))
  110. else:
  111. add_error(line_num, "section header is not formatted correctly")
  112. if num_in_category < min_entries_per_section:
  113. add_error(category_line, "{} section does not have the minimum {} entries (only has {})".format(
  114. category, min_entries_per_section, num_in_category))
  115. category = line.split(' ')[1]
  116. category_line = line_num
  117. num_in_category = 0
  118. continue
  119. # skips lines that we do not care about
  120. if not line.startswith('|') or line.startswith('|---'):
  121. continue
  122. num_in_category += 1
  123. segments = line.split('|')[1:-1]
  124. if len(segments) < num_segments:
  125. add_error(line_num, "entry does not have all the required sections (have {}, need {})".format(
  126. len(segments), num_segments))
  127. continue
  128. # START Global
  129. for segment in segments:
  130. # every line segment should start and end with exactly 1 space
  131. if len(segment) - len(segment.lstrip()) != 1 or len(segment) - len(segment.rstrip()) != 1:
  132. add_error(line_num, "each segment must start and end with exactly 1 space")
  133. # END Global
  134. segments = [seg.strip() for seg in segments]
  135. check_entry(line_num, segments)
  136. # END Check Entries
  137. def main():
  138. if len(sys.argv) < 2:
  139. print("No file passed (file should contain Markdown table syntax)")
  140. sys.exit(1)
  141. check_format(sys.argv[1])
  142. if len(errors) > 0:
  143. for err in errors:
  144. print(err)
  145. sys.exit(1)
  146. if __name__ == "__main__":
  147. main()