api.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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 datetime
  17. API_PATH = '/api/v1/readme.json'
  18. def parse_line(line, category):
  19. print(line)
  20. name = line.split('](')[0][3:]
  21. url = line.split('](')[1].split(')')[0]
  22. description = '' if line[-1] == ')' else line.split(') ')[1][2:]
  23. return {
  24. 'name': name,
  25. 'description': description,
  26. 'url': url,
  27. 'category': category,
  28. }
  29. def parse_section(section, category=''):
  30. return [parse_line(l, category) for l in section.split('\n')]
  31. def parse_subsections(section):
  32. subsections = section.split('### ')[1:]
  33. items = []
  34. for subsection in subsections:
  35. split_section = subsection.split('\n\n')
  36. section_title = split_section[0]
  37. items += parse_section(split_section[1], section_title)
  38. return items
  39. def cut_section(start):
  40. return readme.split('## %s\n\n' % start)[1].split('\n\n## ')[0]
  41. def parse_readme(readme):
  42. return {
  43. 'apps': parse_subsections(cut_section('Apps')),
  44. 'tools': parse_section(cut_section('Tools')),
  45. 'resources': parse_subsections(cut_section('Resources')),
  46. 'sites': parse_section(cut_section('Open-source sites')),
  47. 'metadata': {
  48. 'updated': '%sZ' % datetime.datetime.utcnow().isoformat(),
  49. },
  50. }
  51. if __name__ == '__main__':
  52. readme = open('README.md', 'r').read()
  53. try:
  54. parsed_readme = parse_readme(readme)
  55. with open('./dist%s' % API_PATH, mode='w+', encoding='utf-8') as f:
  56. readme_payload = json.dumps(parsed_readme, indent=True)
  57. print(readme_payload)
  58. f.write(readme_payload)
  59. except:
  60. print('Is the README well formatted?')
  61. raise