buildhtml.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. #!/usr/bin/env python
  2. # $Id: buildhtml.py 7579 2012-12-31 10:40:14Z grubert $
  3. # Author: David Goodger <goodger@python.org>
  4. # Copyright: This module has been placed in the public domain.
  5. """
  6. Generates .html from all the .txt files in a directory.
  7. Ordinary .txt files are understood to be standalone reStructuredText.
  8. Files named ``pep-*.txt`` are interpreted as reStructuredText PEPs.
  9. """
  10. # Once PySource is here, build .html from .py as well.
  11. __docformat__ = 'reStructuredText'
  12. try:
  13. import locale
  14. locale.setlocale(locale.LC_ALL, '')
  15. except:
  16. pass
  17. import sys
  18. import os
  19. import os.path
  20. import copy
  21. from fnmatch import fnmatch
  22. import docutils
  23. from docutils import ApplicationError
  24. from docutils import core, frontend, utils
  25. from docutils.utils.error_reporting import ErrorOutput, ErrorString
  26. from docutils.parsers import rst
  27. from docutils.readers import standalone, pep
  28. from docutils.writers import html4css1, pep_html
  29. usage = '%prog [options] [<directory> ...]'
  30. description = ('Generates .html from all the reStructuredText .txt files '
  31. '(including PEPs) in each <directory> '
  32. '(default is the current directory).')
  33. class SettingsSpec(docutils.SettingsSpec):
  34. """
  35. Runtime settings & command-line options for the front end.
  36. """
  37. prune_default = ['.hg', '.bzr', '.git', '.svn', 'CVS']
  38. # Can't be included in OptionParser below because we don't want to
  39. # override the base class.
  40. settings_spec = (
  41. 'Build-HTML Options',
  42. None,
  43. (('Recursively scan subdirectories for files to process. This is '
  44. 'the default.',
  45. ['--recurse'],
  46. {'action': 'store_true', 'default': 1,
  47. 'validator': frontend.validate_boolean}),
  48. ('Do not scan subdirectories for files to process.',
  49. ['--local'], {'dest': 'recurse', 'action': 'store_false'}),
  50. ('Do not process files in <directory> (shell globbing patterns, '
  51. 'separated by colons). This option may be used '
  52. 'more than once to specify multiple directories. Default: "%s".'
  53. % ':'.join(prune_default),
  54. ['--prune'],
  55. {'metavar': '<directory>', 'action': 'append',
  56. 'validator': frontend.validate_colon_separated_string_list,
  57. 'default': prune_default,}),
  58. ('Recursively ignore files matching any of the given '
  59. 'wildcard (shell globbing) patterns (separated by colons).',
  60. ['--ignore'],
  61. {'metavar': '<patterns>', 'action': 'append',
  62. 'default': [],
  63. 'validator': frontend.validate_colon_separated_string_list}),
  64. ('Work silently (no progress messages). Independent of "--quiet".',
  65. ['--silent'],
  66. {'action': 'store_true', 'validator': frontend.validate_boolean}),
  67. ('Do not process files, show files that would be processed.',
  68. ['--dry-run'],
  69. {'action': 'store_true', 'validator': frontend.validate_boolean}),))
  70. relative_path_settings = ('prune',)
  71. config_section = 'buildhtml application'
  72. config_section_dependencies = ('applications',)
  73. class OptionParser(frontend.OptionParser):
  74. """
  75. Command-line option processing for the ``buildhtml.py`` front end.
  76. """
  77. def check_values(self, values, args):
  78. frontend.OptionParser.check_values(self, values, args)
  79. values._source = None
  80. return values
  81. def check_args(self, args):
  82. source = destination = None
  83. if args:
  84. self.values._directories = args
  85. else:
  86. self.values._directories = [os.getcwd()]
  87. return source, destination
  88. class Struct:
  89. """Stores data attributes for dotted-attribute access."""
  90. def __init__(self, **keywordargs):
  91. self.__dict__.update(keywordargs)
  92. class Builder:
  93. def __init__(self):
  94. self.publishers = {
  95. '': Struct(components=(pep.Reader, rst.Parser, pep_html.Writer,
  96. SettingsSpec)),
  97. '.txt': Struct(components=(rst.Parser, standalone.Reader,
  98. html4css1.Writer, SettingsSpec),
  99. reader_name='standalone',
  100. writer_name='html'),
  101. 'PEPs': Struct(components=(rst.Parser, pep.Reader,
  102. pep_html.Writer, SettingsSpec),
  103. reader_name='pep',
  104. writer_name='pep_html')}
  105. """Publisher-specific settings. Key '' is for the front-end script
  106. itself. ``self.publishers[''].components`` must contain a superset of
  107. all components used by individual publishers."""
  108. self.setup_publishers()
  109. def setup_publishers(self):
  110. """
  111. Manage configurations for individual publishers.
  112. Each publisher (combination of parser, reader, and writer) may have
  113. its own configuration defaults, which must be kept separate from those
  114. of the other publishers. Setting defaults are combined with the
  115. config file settings and command-line options by
  116. `self.get_settings()`.
  117. """
  118. for name, publisher in self.publishers.items():
  119. option_parser = OptionParser(
  120. components=publisher.components, read_config_files=1,
  121. usage=usage, description=description)
  122. publisher.option_parser = option_parser
  123. publisher.setting_defaults = option_parser.get_default_values()
  124. frontend.make_paths_absolute(publisher.setting_defaults.__dict__,
  125. option_parser.relative_path_settings)
  126. publisher.config_settings = (
  127. option_parser.get_standard_config_settings())
  128. self.settings_spec = self.publishers[''].option_parser.parse_args(
  129. values=frontend.Values()) # no defaults; just the cmdline opts
  130. self.initial_settings = self.get_settings('')
  131. def get_settings(self, publisher_name, directory=None):
  132. """
  133. Return a settings object, from multiple sources.
  134. Copy the setting defaults, overlay the startup config file settings,
  135. then the local config file settings, then the command-line options.
  136. Assumes the current directory has been set.
  137. """
  138. publisher = self.publishers[publisher_name]
  139. settings = frontend.Values(publisher.setting_defaults.__dict__)
  140. settings.update(publisher.config_settings, publisher.option_parser)
  141. if directory:
  142. local_config = publisher.option_parser.get_config_file_settings(
  143. os.path.join(directory, 'docutils.conf'))
  144. frontend.make_paths_absolute(
  145. local_config, publisher.option_parser.relative_path_settings,
  146. directory)
  147. settings.update(local_config, publisher.option_parser)
  148. settings.update(self.settings_spec.__dict__, publisher.option_parser)
  149. return settings
  150. def run(self, directory=None, recurse=1):
  151. recurse = recurse and self.initial_settings.recurse
  152. if directory:
  153. self.directories = [directory]
  154. elif self.settings_spec._directories:
  155. self.directories = self.settings_spec._directories
  156. else:
  157. self.directories = [os.getcwd()]
  158. for directory in self.directories:
  159. for root, dirs, files in os.walk(directory):
  160. # os.walk by default this recurses down the tree,
  161. # influence by modifying dirs.
  162. if not recurse:
  163. del dirs[:]
  164. self.visit(root, files, dirs)
  165. def visit(self, directory, names, subdirectories):
  166. settings = self.get_settings('', directory)
  167. errout = ErrorOutput(encoding=settings.error_encoding)
  168. if settings.prune and (os.path.abspath(directory) in settings.prune):
  169. errout.write('/// ...Skipping directory (pruned): %s\n' %
  170. directory)
  171. sys.stderr.flush()
  172. del subdirectories[:]
  173. return
  174. if not self.initial_settings.silent:
  175. errout.write('/// Processing directory: %s\n' % directory)
  176. sys.stderr.flush()
  177. # settings.ignore grows many duplicate entries as we recurse
  178. # if we add patterns in config files or on the command line.
  179. for pattern in utils.uniq(settings.ignore):
  180. for i in range(len(names) - 1, -1, -1):
  181. if fnmatch(names[i], pattern):
  182. # Modify in place!
  183. del names[i]
  184. for name in names:
  185. if name.endswith('.txt'):
  186. self.process_txt(directory, name)
  187. def process_txt(self, directory, name):
  188. if name.startswith('pep-'):
  189. publisher = 'PEPs'
  190. else:
  191. publisher = '.txt'
  192. settings = self.get_settings(publisher, directory)
  193. errout = ErrorOutput(encoding=settings.error_encoding)
  194. pub_struct = self.publishers[publisher]
  195. settings._source = os.path.normpath(os.path.join(directory, name))
  196. settings._destination = settings._source[:-4]+'.html'
  197. if not self.initial_settings.silent:
  198. errout.write(' ::: Processing: %s\n' % name)
  199. sys.stderr.flush()
  200. try:
  201. if not settings.dry_run:
  202. core.publish_file(source_path=settings._source,
  203. destination_path=settings._destination,
  204. reader_name=pub_struct.reader_name,
  205. parser_name='restructuredtext',
  206. writer_name=pub_struct.writer_name,
  207. settings=settings)
  208. except ApplicationError:
  209. error = sys.exc_info()[1] # get exception in Python <2.6 and 3.x
  210. errout.write(' %s\n' % ErrorString(error))
  211. if __name__ == "__main__":
  212. Builder().run()