Guest User

Untitled

a guest
Apr 19th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. # Convert Sphinx formatted files to regular RST (e.g. for PyPI README's)
  2. from __future__ import with_statement
  3. import re
  4. import sys
  5.  
  6. RE_CODE_BLOCK = re.compile(r'.. code-block:: (.+?)\s*$')
  7. RE_REFERENCE = re.compile(r':(.+?):`(.+?)`')
  8.  
  9.  
  10. def replace_code_block(lines, pos):
  11. lines[pos] = ""
  12. curpos = pos - 1
  13. # Find the first previous line with text to append "::" to it.
  14. while True:
  15. prev_line = lines[curpos]
  16. if not prev_line.isspace():
  17. prev_line_with_text = curpos
  18. break
  19. curpos -= 1
  20.  
  21. if lines[prev_line_with_text].endswith(":"):
  22. lines[prev_line_with_text] += ":"
  23. else:
  24. lines[prev_line_with_text] += "::"
  25.  
  26. TO_RST_MAP = {RE_CODE_BLOCK: replace_code_block,
  27. RE_REFERENCE: r'``\2``'}
  28.  
  29.  
  30. def _process(lines):
  31. lines = list(lines) # non-destructive
  32. for i, line in enumerate(lines):
  33. for regex, alt in TO_RST_MAP.items():
  34. if callable(alt):
  35. if regex.match(line):
  36. alt(lines, i)
  37. line = lines[i]
  38. else:
  39. lines[i] = regex.sub(alt, line)
  40. return lines
  41.  
  42.  
  43. def sphinx_to_rst(fh):
  44. return "".join(_process(fh))
  45.  
  46.  
  47. if __name__ == "__main__":
  48. with open(sys.argv[1]) as fh:
  49. print(sphinx_to_rst(fh))
Add Comment
Please, Sign In to add comment