4 # Author: David Goodger <goodger@python.org>
5 # Copyright: This module has been placed in the public domain.
8 Generates .html from all the .txt files in a directory.
10 Ordinary .txt files are understood to be standalone reStructuredText.
11 Files named ``pep-*.txt`` are interpreted as reStructuredText PEPs.
13 # Once PySource is here, build .html from .py as well.
15 __docformat__
= 'reStructuredText'
20 locale
.setlocale(locale
.LC_ALL
, '')
28 from fnmatch
import fnmatch
30 from docutils
import ApplicationError
31 from docutils
import core
, frontend
, utils
32 from docutils
.parsers
import rst
33 from docutils
.readers
import standalone
, pep
34 from docutils
.writers
import html4css1
, pep_html
37 usage
= '%prog [options] [<directory> ...]'
38 description
= ('Generates .html from all the reStructuredText .txt files '
39 '(including PEPs) in each <directory> '
40 '(default is the current directory).')
43 class SettingsSpec(docutils
.SettingsSpec
):
46 Runtime settings & command-line options for the front end.
49 # Can't be included in OptionParser below because we don't want to
50 # override the base class.
54 (('Recursively scan subdirectories for files to process. This is '
57 {'action': 'store_true', 'default': 1,
58 'validator': frontend
.validate_boolean
}),
59 ('Do not scan subdirectories for files to process.',
60 ['--local'], {'dest': 'recurse', 'action': 'store_false'}),
61 ('BROKEN Do not process files in <directory>. This option may be used '
62 'more than once to specify multiple directories.',
64 {'metavar': '<directory>', 'action': 'append',
65 'validator': frontend
.validate_colon_separated_string_list
}),
66 ('BROKEN Recursively ignore files or directories matching any of the given '
67 'wildcard (shell globbing) patterns (separated by colons). '
68 'Default: ".svn:CVS"',
70 {'metavar': '<patterns>', 'action': 'append',
71 'default': ['.svn', 'CVS'],
72 'validator': frontend
.validate_colon_separated_string_list
}),
73 ('Work silently (no progress messages). Independent of "--quiet".',
75 {'action': 'store_true', 'validator': frontend
.validate_boolean
}),
76 ('Do not process files, show files that would be processed.',
78 {'action': 'store_true', 'validator': frontend
.validate_boolean
}),))
80 relative_path_settings
= ('prune',)
81 config_section
= 'buildhtml application'
82 config_section_dependencies
= ('applications',)
85 class OptionParser(frontend
.OptionParser
):
88 Command-line option processing for the ``buildhtml.py`` front end.
91 def check_values(self
, values
, args
):
92 frontend
.OptionParser
.check_values(self
, values
, args
)
96 def check_args(self
, args
):
97 source
= destination
= None
99 self
.values
._directories
= args
101 self
.values
._directories
= [os
.getcwd()]
102 return source
, destination
107 """Stores data attributes for dotted-attribute access."""
109 def __init__(self
, **keywordargs
):
110 self
.__dict
__.update(keywordargs
)
117 '': Struct(components
=(pep
.Reader
, rst
.Parser
, pep_html
.Writer
,
119 '.txt': Struct(components
=(rst
.Parser
, standalone
.Reader
,
120 html4css1
.Writer
, SettingsSpec
),
121 reader_name
='standalone',
123 'PEPs': Struct(components
=(rst
.Parser
, pep
.Reader
,
124 pep_html
.Writer
, SettingsSpec
),
126 writer_name
='pep_html')}
127 """Publisher-specific settings. Key '' is for the front-end script
128 itself. ``self.publishers[''].components`` must contain a superset of
129 all components used by individual publishers."""
131 self
.setup_publishers()
133 def setup_publishers(self
):
135 Manage configurations for individual publishers.
137 Each publisher (combination of parser, reader, and writer) may have
138 its own configuration defaults, which must be kept separate from those
139 of the other publishers. Setting defaults are combined with the
140 config file settings and command-line options by
141 `self.get_settings()`.
143 for name
, publisher
in self
.publishers
.items():
144 option_parser
= OptionParser(
145 components
=publisher
.components
, read_config_files
=1,
146 usage
=usage
, description
=description
)
147 publisher
.option_parser
= option_parser
148 publisher
.setting_defaults
= option_parser
.get_default_values()
149 frontend
.make_paths_absolute(publisher
.setting_defaults
.__dict
__,
150 option_parser
.relative_path_settings
)
151 publisher
.config_settings
= (
152 option_parser
.get_standard_config_settings())
153 self
.settings_spec
= self
.publishers
[''].option_parser
.parse_args(
154 values
=frontend
.Values()) # no defaults; just the cmdline opts
155 self
.initial_settings
= self
.get_settings('')
157 def get_settings(self
, publisher_name
, directory
=None):
159 Return a settings object, from multiple sources.
161 Copy the setting defaults, overlay the startup config file settings,
162 then the local config file settings, then the command-line options.
163 Assumes the current directory has been set.
165 publisher
= self
.publishers
[publisher_name
]
166 settings
= frontend
.Values(publisher
.setting_defaults
.__dict
__)
167 settings
.update(publisher
.config_settings
, publisher
.option_parser
)
169 local_config
= publisher
.option_parser
.get_config_file_settings(
170 os
.path
.join(directory
, 'docutils.conf'))
171 frontend
.make_paths_absolute(
172 local_config
, publisher
.option_parser
.relative_path_settings
,
174 settings
.update(local_config
, publisher
.option_parser
)
175 settings
.update(self
.settings_spec
.__dict
__, publisher
.option_parser
)
178 def run(self
, directory
=None, recurse
=1):
179 recurse
= recurse
and self
.initial_settings
.recurse
181 self
.directories
= [directory
]
182 elif self
.settings_spec
._directories
:
183 self
.directories
= self
.settings_spec
._directories
185 self
.directories
= [os
.getcwd()]
186 for directory
in self
.directories
:
187 for root
, dirs
, files
in os
.walk(directory
):
188 # os.walk by default this recurses down the tree,
189 # influence by modifying dirs.
192 self
.visit(root
, files
)
194 def visit(self
, directory
, names
):
195 # BUG prune and ignore do not work
196 settings
= self
.get_settings('', directory
)
197 if settings
.prune
and (os
.path
.abspath(directory
) in settings
.prune
):
198 print >>sys
.stderr
, '/// ...Skipping directory (pruned):', directory
202 if not self
.initial_settings
.silent
:
203 print >>sys
.stderr
, '/// Processing directory:', directory
205 # settings.ignore grows many duplicate entries as we recurse
206 # if we add patterns in config files or on the command line.
207 for pattern
in utils
.uniq(settings
.ignore
):
208 for i
in range(len(names
) - 1, -1, -1):
209 if fnmatch(names
[i
], pattern
):
214 if name
.endswith('.txt'):
215 prune
= self
.process_txt(directory
, name
)
219 def process_txt(self
, directory
, name
):
220 if name
.startswith('pep-'):
224 settings
= self
.get_settings(publisher
, directory
)
225 pub_struct
= self
.publishers
[publisher
]
226 if settings
.prune
and (directory
in settings
.prune
):
228 settings
._source
= os
.path
.normpath(os
.path
.join(directory
, name
))
229 settings
._destination
= settings
._source
[:-4]+'.html'
230 if not self
.initial_settings
.silent
:
231 print >>sys
.stderr
, ' ::: Processing:', name
234 if not settings
.dry_run
:
235 core
.publish_file(source_path
=settings
._source
,
236 destination_path
=settings
._destination
,
237 reader_name
=pub_struct
.reader_name
,
238 parser_name
='restructuredtext',
239 writer_name
=pub_struct
.writer_name
,
241 except ApplicationError
, error
:
242 print >>sys
.stderr
, (' Error (%s): %s'
243 % (error
.__class
__.__name
__, error
))
246 if __name__
== "__main__":