asciidocapi.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. #!/usr/bin/env python
  2. """
  3. asciidocapi - AsciiDoc API wrapper class.
  4. The AsciiDocAPI class provides an API for executing asciidoc. Minimal example
  5. compiles `mydoc.txt` to `mydoc.html`:
  6. import asciidocapi
  7. asciidoc = asciidocapi.AsciiDocAPI()
  8. asciidoc.execute('mydoc.txt')
  9. - Full documentation in asciidocapi.txt.
  10. - See the doctests below for more examples.
  11. Doctests:
  12. 1. Check execution:
  13. >>> import StringIO
  14. >>> infile = StringIO.StringIO('Hello *{author}*')
  15. >>> outfile = StringIO.StringIO()
  16. >>> asciidoc = AsciiDocAPI()
  17. >>> asciidoc.options('--no-header-footer')
  18. >>> asciidoc.attributes['author'] = 'Joe Bloggs'
  19. >>> asciidoc.execute(infile, outfile, backend='html4')
  20. >>> print outfile.getvalue()
  21. <p>Hello <strong>Joe Bloggs</strong></p>
  22. >>> asciidoc.attributes['author'] = 'Bill Smith'
  23. >>> infile = StringIO.StringIO('Hello _{author}_')
  24. >>> outfile = StringIO.StringIO()
  25. >>> asciidoc.execute(infile, outfile, backend='docbook')
  26. >>> print outfile.getvalue()
  27. <simpara>Hello <emphasis>Bill Smith</emphasis></simpara>
  28. 2. Check error handling:
  29. >>> import StringIO
  30. >>> asciidoc = AsciiDocAPI()
  31. >>> infile = StringIO.StringIO('---------')
  32. >>> outfile = StringIO.StringIO()
  33. >>> asciidoc.execute(infile, outfile)
  34. Traceback (most recent call last):
  35. File "<stdin>", line 1, in <module>
  36. File "asciidocapi.py", line 189, in execute
  37. raise AsciiDocError(self.messages[-1])
  38. AsciiDocError: ERROR: <stdin>: line 1: [blockdef-listing] missing closing delimiter
  39. Copyright (C) 2009 Stuart Rackham. Free use of this software is granted
  40. under the terms of the GNU General Public License (GPL).
  41. """
  42. import sys,os,re,imp
  43. API_VERSION = '0.1.2'
  44. MIN_ASCIIDOC_VERSION = '8.4.1' # Minimum acceptable AsciiDoc version.
  45. def find_in_path(fname, path=None):
  46. """
  47. Find file fname in paths. Return None if not found.
  48. """
  49. if path is None:
  50. path = os.environ.get('PATH', '')
  51. for dir in path.split(os.pathsep):
  52. fpath = os.path.join(dir, fname)
  53. if os.path.isfile(fpath):
  54. return fpath
  55. else:
  56. return None
  57. class AsciiDocError(Exception):
  58. pass
  59. class Options(object):
  60. """
  61. Stores asciidoc(1) command options.
  62. """
  63. def __init__(self, values=[]):
  64. self.values = values[:]
  65. def __call__(self, name, value=None):
  66. """Shortcut for append method."""
  67. self.append(name, value)
  68. def append(self, name, value=None):
  69. if type(value) in (int,float):
  70. value = str(value)
  71. self.values.append((name,value))
  72. class Version(object):
  73. """
  74. Parse and compare AsciiDoc version numbers. Instance attributes:
  75. string: String version number '<major>.<minor>[.<micro>][suffix]'.
  76. major: Integer major version number.
  77. minor: Integer minor version number.
  78. micro: Integer micro version number.
  79. suffix: Suffix (begins with non-numeric character) is ignored when
  80. comparing.
  81. Doctest examples:
  82. >>> Version('8.2.5') < Version('8.3 beta 1')
  83. True
  84. >>> Version('8.3.0') == Version('8.3. beta 1')
  85. True
  86. >>> Version('8.2.0') < Version('8.20')
  87. True
  88. >>> Version('8.20').major
  89. 8
  90. >>> Version('8.20').minor
  91. 20
  92. >>> Version('8.20').micro
  93. 0
  94. >>> Version('8.20').suffix
  95. ''
  96. >>> Version('8.20 beta 1').suffix
  97. 'beta 1'
  98. """
  99. def __init__(self, version):
  100. self.string = version
  101. reo = re.match(r'^(\d+)\.(\d+)(\.(\d+))?\s*(.*?)\s*$', self.string)
  102. if not reo:
  103. raise ValueError('invalid version number: %s' % self.string)
  104. groups = reo.groups()
  105. self.major = int(groups[0])
  106. self.minor = int(groups[1])
  107. self.micro = int(groups[3] or '0')
  108. self.suffix = groups[4] or ''
  109. def __cmp__(self, other):
  110. result = cmp(self.major, other.major)
  111. if result == 0:
  112. result = cmp(self.minor, other.minor)
  113. if result == 0:
  114. result = cmp(self.micro, other.micro)
  115. return result
  116. class AsciiDocAPI(object):
  117. """
  118. AsciiDoc API class.
  119. """
  120. def __init__(self, asciidoc_py=None):
  121. """
  122. Locate and import asciidoc.py.
  123. Initialize instance attributes.
  124. """
  125. self.options = Options()
  126. self.attributes = {}
  127. self.messages = []
  128. # Search for the asciidoc command file.
  129. # Try ASCIIDOC_PY environment variable first.
  130. cmd = os.environ.get('ASCIIDOC_PY')
  131. if cmd:
  132. if not os.path.isfile(cmd):
  133. raise AsciiDocError('missing ASCIIDOC_PY file: %s' % cmd)
  134. elif asciidoc_py:
  135. # Next try path specified by caller.
  136. cmd = asciidoc_py
  137. if not os.path.isfile(cmd):
  138. raise AsciiDocError('missing file: %s' % cmd)
  139. else:
  140. # Try shell search paths.
  141. for fname in ['asciidoc.py','asciidoc.pyc','asciidoc']:
  142. cmd = find_in_path(fname)
  143. if cmd: break
  144. else:
  145. # Finally try current working directory.
  146. for cmd in ['asciidoc.py','asciidoc.pyc','asciidoc']:
  147. if os.path.isfile(cmd): break
  148. else:
  149. raise AsciiDocError('failed to locate asciidoc')
  150. self.cmd = os.path.realpath(cmd)
  151. self.__import_asciidoc()
  152. def __import_asciidoc(self, reload=False):
  153. '''
  154. Import asciidoc module (script or compiled .pyc).
  155. See
  156. http://groups.google.com/group/asciidoc/browse_frm/thread/66e7b59d12cd2f91
  157. for an explanation of why a seemingly straight-forward job turned out
  158. quite complicated.
  159. '''
  160. if os.path.splitext(self.cmd)[1] in ['.py','.pyc']:
  161. sys.path.insert(0, os.path.dirname(self.cmd))
  162. try:
  163. try:
  164. if reload:
  165. import __builtin__ # Because reload() is shadowed.
  166. __builtin__.reload(self.asciidoc)
  167. else:
  168. import asciidoc
  169. self.asciidoc = asciidoc
  170. except ImportError:
  171. raise AsciiDocError('failed to import ' + self.cmd)
  172. finally:
  173. del sys.path[0]
  174. else:
  175. # The import statement can only handle .py or .pyc files, have to
  176. # use imp.load_source() for scripts with other names.
  177. try:
  178. imp.load_source('asciidoc', self.cmd)
  179. import asciidoc
  180. self.asciidoc = asciidoc
  181. except ImportError:
  182. raise AsciiDocError('failed to import ' + self.cmd)
  183. if Version(self.asciidoc.VERSION) < Version(MIN_ASCIIDOC_VERSION):
  184. raise AsciiDocError(
  185. 'asciidocapi %s requires asciidoc %s or better'
  186. % (API_VERSION, MIN_ASCIIDOC_VERSION))
  187. def execute(self, infile, outfile=None, backend=None):
  188. """
  189. Compile infile to outfile using backend format.
  190. infile can outfile can be file path strings or file like objects.
  191. """
  192. self.messages = []
  193. opts = Options(self.options.values)
  194. if outfile is not None:
  195. opts('--out-file', outfile)
  196. if backend is not None:
  197. opts('--backend', backend)
  198. for k,v in self.attributes.items():
  199. if v == '' or k[-1] in '!@':
  200. s = k
  201. elif v is None: # A None value undefines the attribute.
  202. s = k + '!'
  203. else:
  204. s = '%s=%s' % (k,v)
  205. opts('--attribute', s)
  206. args = [infile]
  207. # The AsciiDoc command was designed to process source text then
  208. # exit, there are globals and statics in asciidoc.py that have
  209. # to be reinitialized before each run -- hence the reload.
  210. self.__import_asciidoc(reload=True)
  211. try:
  212. try:
  213. self.asciidoc.execute(self.cmd, opts.values, args)
  214. finally:
  215. self.messages = self.asciidoc.messages[:]
  216. except SystemExit, e:
  217. if e.code:
  218. raise AsciiDocError(self.messages[-1])
  219. if __name__ == "__main__":
  220. """
  221. Run module doctests.
  222. """
  223. import doctest
  224. options = doctest.NORMALIZE_WHITESPACE + doctest.ELLIPSIS
  225. doctest.testmod(optionflags=options)