sphinx-to-rst.py 1.2 KB

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