rst.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. # Jérôme Carretero, 2013 (zougloub)
  4. """
  5. reStructuredText support (experimental)
  6. Example::
  7. def configure(conf):
  8. conf.load('rst')
  9. if not conf.env.RST2HTML:
  10. conf.fatal('The program rst2html is required')
  11. def build(bld):
  12. bld(
  13. features = 'rst',
  14. type = 'rst2html', # rst2html, rst2pdf, ...
  15. source = 'index.rst', # mandatory, the source
  16. deps = 'image.png', # to give additional non-trivial dependencies
  17. )
  18. By default the tool looks for a set of programs in PATH.
  19. The tools are defined in `rst_progs`.
  20. To configure with a special program use::
  21. $ RST2HTML=/path/to/rst2html waf configure
  22. This tool is experimental; don't hesitate to contribute to it.
  23. """
  24. import re
  25. from waflib import Node, Utils, Task, Errors, Logs
  26. from waflib.TaskGen import feature, before_method
  27. rst_progs = "rst2html rst2xetex rst2latex rst2xml rst2pdf rst2s5 rst2man rst2odt rst2rtf".split()
  28. def parse_rst_node(task, node, nodes, names, seen, dirs=None):
  29. # TODO add extensibility, to handle custom rst include tags...
  30. if dirs is None:
  31. dirs = (node.parent,node.get_bld().parent)
  32. if node in seen:
  33. return
  34. seen.append(node)
  35. code = node.read()
  36. re_rst = re.compile(r'^\s*.. ((?P<subst>\|\S+\|) )?(?P<type>include|image|figure):: (?P<file>.*)$', re.M)
  37. for match in re_rst.finditer(code):
  38. ipath = match.group('file')
  39. itype = match.group('type')
  40. Logs.debug('rst: visiting %s: %s', itype, ipath)
  41. found = False
  42. for d in dirs:
  43. Logs.debug('rst: looking for %s in %s', ipath, d.abspath())
  44. found = d.find_node(ipath)
  45. if found:
  46. Logs.debug('rst: found %s as %s', ipath, found.abspath())
  47. nodes.append((itype, found))
  48. if itype == 'include':
  49. parse_rst_node(task, found, nodes, names, seen)
  50. break
  51. if not found:
  52. names.append((itype, ipath))
  53. class docutils(Task.Task):
  54. """
  55. Compile a rst file.
  56. """
  57. def scan(self):
  58. """
  59. A recursive regex-based scanner that finds rst dependencies.
  60. """
  61. nodes = []
  62. names = []
  63. seen = []
  64. node = self.inputs[0]
  65. if not node:
  66. return (nodes, names)
  67. parse_rst_node(self, node, nodes, names, seen)
  68. Logs.debug('rst: %r: found the following file deps: %r', self, nodes)
  69. if names:
  70. Logs.warn('rst: %r: could not find the following file deps: %r', self, names)
  71. return ([v for (t,v) in nodes], [v for (t,v) in names])
  72. def check_status(self, msg, retcode):
  73. """
  74. Check an exit status and raise an error with a particular message
  75. :param msg: message to display if the code is non-zero
  76. :type msg: string
  77. :param retcode: condition
  78. :type retcode: boolean
  79. """
  80. if retcode != 0:
  81. raise Errors.WafError('%r command exit status %r' % (msg, retcode))
  82. def run(self):
  83. """
  84. Runs the rst compilation using docutils
  85. """
  86. raise NotImplementedError()
  87. class rst2html(docutils):
  88. color = 'BLUE'
  89. def __init__(self, *args, **kw):
  90. docutils.__init__(self, *args, **kw)
  91. self.command = self.generator.env.RST2HTML
  92. self.attributes = ['stylesheet']
  93. def scan(self):
  94. nodes, names = docutils.scan(self)
  95. for attribute in self.attributes:
  96. stylesheet = getattr(self.generator, attribute, None)
  97. if stylesheet is not None:
  98. ssnode = self.generator.to_nodes(stylesheet)[0]
  99. nodes.append(ssnode)
  100. Logs.debug('rst: adding dep to %s %s', attribute, stylesheet)
  101. return nodes, names
  102. def run(self):
  103. cwdn = self.outputs[0].parent
  104. src = self.inputs[0].path_from(cwdn)
  105. dst = self.outputs[0].path_from(cwdn)
  106. cmd = self.command + [src, dst]
  107. cmd += Utils.to_list(getattr(self.generator, 'options', []))
  108. for attribute in self.attributes:
  109. stylesheet = getattr(self.generator, attribute, None)
  110. if stylesheet is not None:
  111. stylesheet = self.generator.to_nodes(stylesheet)[0]
  112. cmd += ['--%s' % attribute, stylesheet.path_from(cwdn)]
  113. return self.exec_command(cmd, cwd=cwdn.abspath())
  114. class rst2s5(rst2html):
  115. def __init__(self, *args, **kw):
  116. rst2html.__init__(self, *args, **kw)
  117. self.command = self.generator.env.RST2S5
  118. self.attributes = ['stylesheet']
  119. class rst2latex(rst2html):
  120. def __init__(self, *args, **kw):
  121. rst2html.__init__(self, *args, **kw)
  122. self.command = self.generator.env.RST2LATEX
  123. self.attributes = ['stylesheet']
  124. class rst2xetex(rst2html):
  125. def __init__(self, *args, **kw):
  126. rst2html.__init__(self, *args, **kw)
  127. self.command = self.generator.env.RST2XETEX
  128. self.attributes = ['stylesheet']
  129. class rst2pdf(docutils):
  130. color = 'BLUE'
  131. def run(self):
  132. cwdn = self.outputs[0].parent
  133. src = self.inputs[0].path_from(cwdn)
  134. dst = self.outputs[0].path_from(cwdn)
  135. cmd = self.generator.env.RST2PDF + [src, '-o', dst]
  136. cmd += Utils.to_list(getattr(self.generator, 'options', []))
  137. return self.exec_command(cmd, cwd=cwdn.abspath())
  138. @feature('rst')
  139. @before_method('process_source')
  140. def apply_rst(self):
  141. """
  142. Create :py:class:`rst` or other rst-related task objects
  143. """
  144. if self.target:
  145. if isinstance(self.target, Node.Node):
  146. tgt = self.target
  147. elif isinstance(self.target, str):
  148. tgt = self.path.get_bld().make_node(self.target)
  149. else:
  150. self.bld.fatal("rst: Don't know how to build target name %s which is not a string or Node for %s" % (self.target, self))
  151. else:
  152. tgt = None
  153. tsk_type = getattr(self, 'type', None)
  154. src = self.to_nodes(self.source)
  155. assert len(src) == 1
  156. src = src[0]
  157. if tsk_type is not None and tgt is None:
  158. if tsk_type.startswith('rst2'):
  159. ext = tsk_type[4:]
  160. else:
  161. self.bld.fatal("rst: Could not detect the output file extension for %s" % self)
  162. tgt = src.change_ext('.%s' % ext)
  163. elif tsk_type is None and tgt is not None:
  164. out = tgt.name
  165. ext = out[out.rfind('.')+1:]
  166. self.type = 'rst2' + ext
  167. elif tsk_type is not None and tgt is not None:
  168. # the user knows what he wants
  169. pass
  170. else:
  171. self.bld.fatal("rst: Need to indicate task type or target name for %s" % self)
  172. deps_lst = []
  173. if getattr(self, 'deps', None):
  174. deps = self.to_list(self.deps)
  175. for filename in deps:
  176. n = self.path.find_resource(filename)
  177. if not n:
  178. self.bld.fatal('Could not find %r for %r' % (filename, self))
  179. if not n in deps_lst:
  180. deps_lst.append(n)
  181. try:
  182. task = self.create_task(self.type, src, tgt)
  183. except KeyError:
  184. self.bld.fatal("rst: Task of type %s not implemented (created by %s)" % (self.type, self))
  185. task.env = self.env
  186. # add the manual dependencies
  187. if deps_lst:
  188. try:
  189. lst = self.bld.node_deps[task.uid()]
  190. for n in deps_lst:
  191. if not n in lst:
  192. lst.append(n)
  193. except KeyError:
  194. self.bld.node_deps[task.uid()] = deps_lst
  195. inst_to = getattr(self, 'install_path', None)
  196. if inst_to:
  197. self.install_task = self.add_install_files(install_to=inst_to, install_from=task.outputs[:])
  198. self.source = []
  199. def configure(self):
  200. """
  201. Try to find the rst programs.
  202. Do not raise any error if they are not found.
  203. You'll have to use additional code in configure() to die
  204. if programs were not found.
  205. """
  206. for p in rst_progs:
  207. self.find_program(p, mandatory=False)