api.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. # -*- coding: utf-8 -*-
  2. #
  3. # This script parses the README.md and generates a machine-readable
  4. # data structure from it, for publication as an API.
  5. #
  6. # https://springload.github.io/awesome-wagtail/api/v1/readme.json
  7. #
  8. # It is automatically ran as part of Travis builds, also validating the README
  9. # formatting, and the API endpoint is deployed on successful builds on master.
  10. #
  11. # See also:
  12. # - https://djangopackages.org/api/v3/grids/wagtail-cms/
  13. # - https://github.com/awesomerank/rank
  14. from __future__ import absolute_import, unicode_literals
  15. import json
  16. import codecs
  17. import datetime
  18. API_PATH = '/api/v1/readme.json'
  19. def parse_line(line, category):
  20. print(line)
  21. name = line.split('](')[0][3:]
  22. url = line.split('](')[1].split(')')[0]
  23. description = '' if line[-1] == ')' else line.split(') ')[1][2:]
  24. return {
  25. 'name': name,
  26. 'description': description,
  27. 'url': url,
  28. 'category': category,
  29. }
  30. def parse_section(section, category=''):
  31. return [parse_line(l, category) for l in section.split('\n')]
  32. def parse_subsections(section):
  33. subsections = section.split('### ')[1:]
  34. items = []
  35. for subsection in subsections:
  36. split_section = subsection.split('\n\n')
  37. section_title = split_section[0]
  38. items += parse_section(split_section[1], section_title)
  39. return items
  40. def cut_section(start):
  41. return readme.split('## %s\n\n' % start)[1].split('\n\n## ')[0]
  42. def parse_readme(readme):
  43. return {
  44. 'apps': parse_subsections(cut_section('Apps')),
  45. 'tools': parse_subsections(cut_section('Tools')),
  46. 'resources': parse_subsections(cut_section('Resources')),
  47. 'sites': parse_section(cut_section('Open-source sites')),
  48. 'metadata': {
  49. 'updated': '%sZ' % datetime.datetime.utcnow().isoformat(),
  50. },
  51. }
  52. if __name__ == '__main__':
  53. readme = open('README.md', 'r').read()
  54. try:
  55. parsed_readme = parse_readme(readme)
  56. json_path = './dist%s' % API_PATH
  57. with codecs.open(json_path, mode='w+', encoding='utf8') as f:
  58. readme_payload = json.dumps(parsed_readme, indent=True, ensure_ascii=False)
  59. print(readme_payload)
  60. f.write(readme_payload)
  61. except:
  62. print('Is the README well formatted?')
  63. raise