aboutsummaryrefslogtreecommitdiff
path: root/spec2md.py
blob: fde79bb4941e83aec227796eaf0f86c5f1b7d204 (plain)
  1. #!/usr/bin/env python3
  2. import re
  3. import sys
  4. stage = 0
  5. example = 0
  6. section = ""
  7. mdlines = []
  8. refs = []
  9. if len(sys.argv) > 1:
  10. specfile = sys.argv[1]
  11. else:
  12. specfile = 'spec.txt'
  13. with open(specfile, 'r', encoding='utf-8') as spec:
  14. for ln in spec:
  15. if re.match(r'^\.$', ln):
  16. if stage == 0:
  17. example += 1
  18. mdlines.append("\n<div class=\"example\" id=\"example-{0}\" data-section=\"{1}\">\n".format(example, section))
  19. mdlines.append("<div class=\"examplenum\"><a href=\"#example-{0}\">Example {0}</a>&nbsp;&nbsp;<a class=\"dingus\" title=\"open in interactive dingus\">(interact)</a></div>\n\n".format(example))
  20. mdlines.append("````````````````````````````````````````````````````````` markdown\n")
  21. stage = 1
  22. elif stage == 1:
  23. mdlines.append("`````````````````````````````````````````````````````````\n\n")
  24. mdlines.append("````````````````````````````````````````````````````````` html\n")
  25. stage = 2
  26. elif stage == 2:
  27. mdlines.append("`````````````````````````````````````````````````````````\n\n")
  28. mdlines.append("</div>\n")
  29. stage = 0
  30. else:
  31. sys.stderr.out("Encountered unknown stage {0}\n".format(stage))
  32. sys.exit(1)
  33. else:
  34. if stage == 0:
  35. match = re.match(r'^#{1,6} *(.*)', ln)
  36. if match:
  37. section = match.group(1)
  38. else:
  39. for match in re.finditer(r'\[([^]]*)\]\(@([^)]*)\)', ln):
  40. refs.append("[{0}]: #{1}".format(match.group(1), match.group(2)))
  41. else:
  42. ln = re.sub(r' ', '␣', ln)
  43. mdlines.append(ln)
  44. mdtext = ''.join(mdlines) + '\n\n' + '\n'.join(refs) + '\n'
  45. sys.stdout.write(mdtext)