api.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # -*- coding: utf-8 -*-
  2. from __future__ import absolute_import, unicode_literals
  3. import json
  4. import datetime
  5. API_PATH = '/api/v1/readme.json'
  6. def parse_line(line, category):
  7. print(line)
  8. name = line.split('](')[0][3:]
  9. url = line.split('](')[1].split(')')[0]
  10. description = '' if line[-1] == ')' else line.split(') ')[1][2:]
  11. return {
  12. 'name': name,
  13. 'description': description,
  14. 'url': url,
  15. 'category': category,
  16. }
  17. def parse_section(section, category=''):
  18. return [parse_line(l, category) for l in section.split('\n')]
  19. def parse_subsections(section):
  20. subsections = section.split('### ')[1:]
  21. items = []
  22. for subsection in subsections:
  23. split_section = subsection.split('\n\n')
  24. section_title = split_section[0]
  25. items += parse_section(split_section[1], section_title)
  26. return items
  27. def cut_section(start):
  28. return readme.split('## %s\n\n' % start)[1].split('\n\n## ')[0]
  29. def parse_readme(readme):
  30. return {
  31. 'apps': parse_subsections(cut_section('Apps')),
  32. 'tools': parse_section(cut_section('Tools')),
  33. 'resources': parse_subsections(cut_section('Resources')),
  34. 'sites': parse_section(cut_section('Open-source sites')),
  35. 'metadata': {
  36. 'updated': '%sZ' % datetime.datetime.utcnow().isoformat(),
  37. },
  38. }
  39. if __name__ == '__main__':
  40. readme = open('README.md', 'r').read()
  41. try:
  42. parsed_readme = parse_readme(readme)
  43. with open('./dist%s' % API_PATH, mode='w+', encoding='utf-8') as f:
  44. readme_payload = json.dumps(parsed_readme, indent=True)
  45. print(readme_payload)
  46. f.write(readme_payload)
  47. except:
  48. print('Is the README well formatted?')
  49. raise