sphinx-to-rst.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #!/usr/bin/even/python
  2. from __future__ import with_statement
  3. import os
  4. import re
  5. import sys
  6. dirname = ""
  7. RE_CODE_BLOCK = re.compile(r'.. code-block:: (.+?)\s*$')
  8. RE_INCLUDE = re.compile(r'.. include:: (.+?)\s*$')
  9. RE_REFERENCE = re.compile(r':(.+?):`(.+?)`')
  10. def include_file(lines, pos, match):
  11. filename = os.path.join(dirname, match.groups()[0])
  12. with file(filename) as fh:
  13. lines[pos] = "".join(fh.readlines())
  14. def replace_code_block(lines, pos, match):
  15. lines[pos] = ""
  16. curpos = pos - 1
  17. # Find the first previous line with text to append "::" to it.
  18. while True:
  19. prev_line = lines[curpos]
  20. if not prev_line.isspace():
  21. prev_line_with_text = curpos
  22. break
  23. curpos -= 1
  24. if lines[prev_line_with_text].endswith(":"):
  25. lines[prev_line_with_text] += ":"
  26. else:
  27. lines[prev_line_with_text] += "::"
  28. TO_RST_MAP = {RE_CODE_BLOCK: replace_code_block,
  29. RE_REFERENCE: r'``\2``',
  30. RE_INCLUDE: include_file}
  31. def _process(lines):
  32. lines = list(lines) # non-destructive
  33. for i, line in enumerate(lines):
  34. for regex, alt in TO_RST_MAP.items():
  35. if callable(alt):
  36. match = regex.match(line)
  37. if match:
  38. alt(lines, i, match)
  39. line = lines[i]
  40. else:
  41. lines[i] = regex.sub(alt, line)
  42. return lines
  43. def sphinx_to_rst(fh):
  44. return "".join(_process(fh))
  45. if __name__ == "__main__":
  46. global dirname
  47. dirname = os.path.dirname(sys.argv[1])
  48. with open(sys.argv[1]) as fh:
  49. print(sphinx_to_rst(fh))