New sub-module and test suite for error reporting.
[docutils.git] / docutils / parsers / rst / directives / tables.py
blob7485576204cf3f7c83be31e0ab578283b9d23bd1
1 # $Id$
2 # Authors: David Goodger <goodger@python.org>; David Priest
3 # Copyright: This module has been placed in the public domain.
5 """
6 Directives for table elements.
7 """
9 __docformat__ = 'reStructuredText'
12 import sys
13 import os.path
14 import csv
16 from docutils import io, nodes, statemachine, utils
17 from docutils.error_reporting import SafeString
18 from docutils.utils import SystemMessagePropagation
19 from docutils.parsers.rst import Directive
20 from docutils.parsers.rst import directives
23 class Table(Directive):
25 """
26 Generic table base class.
27 """
29 required_arguments = 0
30 optional_arguments = 1
31 final_argument_whitespace = True
32 option_spec = {'class': directives.class_option}
33 has_content = True
35 def make_title(self):
36 if self.arguments:
37 title_text = self.arguments[0]
38 text_nodes, messages = self.state.inline_text(title_text,
39 self.lineno)
40 title = nodes.title(title_text, '', *text_nodes)
41 else:
42 title = None
43 messages = []
44 return title, messages
46 def process_header_option(self):
47 source = self.state_machine.get_source(self.lineno - 1)
48 table_head = []
49 max_header_cols = 0
50 if 'header' in self.options: # separate table header in option
51 rows, max_header_cols = self.parse_csv_data_into_rows(
52 self.options['header'].split('\n'), self.HeaderDialect(),
53 source)
54 table_head.extend(rows)
55 return table_head, max_header_cols
57 def check_table_dimensions(self, rows, header_rows, stub_columns):
58 if len(rows) < header_rows:
59 error = self.state_machine.reporter.error(
60 '%s header row(s) specified but only %s row(s) of data '
61 'supplied ("%s" directive).'
62 % (header_rows, len(rows), self.name), nodes.literal_block(
63 self.block_text, self.block_text), line=self.lineno)
64 raise SystemMessagePropagation(error)
65 if len(rows) == header_rows > 0:
66 error = self.state_machine.reporter.error(
67 'Insufficient data supplied (%s row(s)); no data remaining '
68 'for table body, required by "%s" directive.'
69 % (len(rows), self.name), nodes.literal_block(
70 self.block_text, self.block_text), line=self.lineno)
71 raise SystemMessagePropagation(error)
72 for row in rows:
73 if len(row) < stub_columns:
74 error = self.state_machine.reporter.error(
75 '%s stub column(s) specified but only %s columns(s) of '
76 'data supplied ("%s" directive).' %
77 (stub_columns, len(row), self.name), nodes.literal_block(
78 self.block_text, self.block_text), line=self.lineno)
79 raise SystemMessagePropagation(error)
80 if len(row) == stub_columns > 0:
81 error = self.state_machine.reporter.error(
82 'Insufficient data supplied (%s columns(s)); no data remaining '
83 'for table body, required by "%s" directive.'
84 % (len(row), self.name), nodes.literal_block(
85 self.block_text, self.block_text), line=self.lineno)
86 raise SystemMessagePropagation(error)
88 def get_column_widths(self, max_cols):
89 if 'widths' in self.options:
90 col_widths = self.options['widths']
91 if len(col_widths) != max_cols:
92 error = self.state_machine.reporter.error(
93 '"%s" widths do not match the number of columns in table '
94 '(%s).' % (self.name, max_cols), nodes.literal_block(
95 self.block_text, self.block_text), line=self.lineno)
96 raise SystemMessagePropagation(error)
97 elif max_cols:
98 col_widths = [100 // max_cols] * max_cols
99 else:
100 error = self.state_machine.reporter.error(
101 'No table data detected in CSV file.', nodes.literal_block(
102 self.block_text, self.block_text), line=self.lineno)
103 raise SystemMessagePropagation(error)
104 return col_widths
106 def extend_short_rows_with_empty_cells(self, columns, parts):
107 for part in parts:
108 for row in part:
109 if len(row) < columns:
110 row.extend([(0, 0, 0, [])] * (columns - len(row)))
113 class RSTTable(Table):
115 def run(self):
116 if not self.content:
117 warning = self.state_machine.reporter.warning(
118 'Content block expected for the "%s" directive; none found.'
119 % self.name, nodes.literal_block(
120 self.block_text, self.block_text), line=self.lineno)
121 return [warning]
122 title, messages = self.make_title()
123 node = nodes.Element() # anonymous container for parsing
124 self.state.nested_parse(self.content, self.content_offset, node)
125 if len(node) != 1 or not isinstance(node[0], nodes.table):
126 error = self.state_machine.reporter.error(
127 'Error parsing content block for the "%s" directive: exactly '
128 'one table expected.' % self.name, nodes.literal_block(
129 self.block_text, self.block_text), line=self.lineno)
130 return [error]
131 table_node = node[0]
132 table_node['classes'] += self.options.get('class', [])
133 if title:
134 table_node.insert(0, title)
135 return [table_node] + messages
138 class CSVTable(Table):
140 option_spec = {'header-rows': directives.nonnegative_int,
141 'stub-columns': directives.nonnegative_int,
142 'header': directives.unchanged,
143 'widths': directives.positive_int_list,
144 'file': directives.path,
145 'url': directives.uri,
146 'encoding': directives.encoding,
147 'class': directives.class_option,
148 # field delimiter char
149 'delim': directives.single_char_or_whitespace_or_unicode,
150 # treat whitespace after delimiter as significant
151 'keepspace': directives.flag,
152 # text field quote/unquote char:
153 'quote': directives.single_char_or_unicode,
154 # char used to escape delim & quote as-needed:
155 'escape': directives.single_char_or_unicode,}
157 class DocutilsDialect(csv.Dialect):
159 """CSV dialect for `csv_table` directive."""
161 delimiter = ','
162 quotechar = '"'
163 doublequote = True
164 skipinitialspace = True
165 lineterminator = '\n'
166 quoting = csv.QUOTE_MINIMAL
168 def __init__(self, options):
169 if 'delim' in options:
170 self.delimiter = str(options['delim'])
171 if 'keepspace' in options:
172 self.skipinitialspace = False
173 if 'quote' in options:
174 self.quotechar = str(options['quote'])
175 if 'escape' in options:
176 self.doublequote = False
177 self.escapechar = str(options['escape'])
178 csv.Dialect.__init__(self)
181 class HeaderDialect(csv.Dialect):
183 """CSV dialect to use for the "header" option data."""
185 delimiter = ','
186 quotechar = '"'
187 escapechar = '\\'
188 doublequote = False
189 skipinitialspace = True
190 lineterminator = '\n'
191 quoting = csv.QUOTE_MINIMAL
193 def check_requirements(self):
194 pass
196 def run(self):
197 try:
198 if (not self.state.document.settings.file_insertion_enabled
199 and ('file' in self.options
200 or 'url' in self.options)):
201 warning = self.state_machine.reporter.warning(
202 'File and URL access deactivated; ignoring "%s" '
203 'directive.' % self.name, nodes.literal_block(
204 self.block_text, self.block_text), line=self.lineno)
205 return [warning]
206 self.check_requirements()
207 title, messages = self.make_title()
208 csv_data, source = self.get_csv_data()
209 table_head, max_header_cols = self.process_header_option()
210 rows, max_cols = self.parse_csv_data_into_rows(
211 csv_data, self.DocutilsDialect(self.options), source)
212 max_cols = max(max_cols, max_header_cols)
213 header_rows = self.options.get('header-rows', 0)
214 stub_columns = self.options.get('stub-columns', 0)
215 self.check_table_dimensions(rows, header_rows, stub_columns)
216 table_head.extend(rows[:header_rows])
217 table_body = rows[header_rows:]
218 col_widths = self.get_column_widths(max_cols)
219 self.extend_short_rows_with_empty_cells(max_cols,
220 (table_head, table_body))
221 except SystemMessagePropagation, detail:
222 return [detail.args[0]]
223 except csv.Error, detail:
224 error = self.state_machine.reporter.error(
225 'Error with CSV data in "%s" directive:\n%s'
226 % (self.name, detail), nodes.literal_block(
227 self.block_text, self.block_text), line=self.lineno)
228 return [error]
229 table = (col_widths, table_head, table_body)
230 table_node = self.state.build_table(table, self.content_offset,
231 stub_columns)
232 table_node['classes'] += self.options.get('class', [])
233 if title:
234 table_node.insert(0, title)
235 return [table_node] + messages
237 def get_csv_data(self):
239 Get CSV data from the directive content, from an external
240 file, or from a URL reference.
242 encoding = self.options.get(
243 'encoding', self.state.document.settings.input_encoding)
244 if self.content:
245 # CSV data is from directive content.
246 if 'file' in self.options or 'url' in self.options:
247 error = self.state_machine.reporter.error(
248 '"%s" directive may not both specify an external file and'
249 ' have content.' % self.name, nodes.literal_block(
250 self.block_text, self.block_text), line=self.lineno)
251 raise SystemMessagePropagation(error)
252 source = self.content.source(0)
253 csv_data = self.content
254 elif 'file' in self.options:
255 # CSV data is from an external file.
256 if 'url' in self.options:
257 error = self.state_machine.reporter.error(
258 'The "file" and "url" options may not be simultaneously'
259 ' specified for the "%s" directive.' % self.name,
260 nodes.literal_block(self.block_text, self.block_text),
261 line=self.lineno)
262 raise SystemMessagePropagation(error)
263 source_dir = os.path.dirname(
264 os.path.abspath(self.state.document.current_source))
265 source = os.path.normpath(os.path.join(source_dir,
266 self.options['file']))
267 source = utils.relative_path(None, source)
268 try:
269 self.state.document.settings.record_dependencies.add(source)
270 csv_file = io.FileInput(
271 source_path=source, encoding=encoding,
272 error_handler=(self.state.document.settings.\
273 input_encoding_error_handler),
274 handle_io_errors=None)
275 csv_data = csv_file.read().splitlines()
276 except IOError, error:
277 severe = self.state_machine.reporter.severe(
278 u'Problems with "%s" directive path:\n%s.'
279 % (self.name, SafeString(error)),
280 nodes.literal_block(self.block_text, self.block_text),
281 line=self.lineno)
282 raise SystemMessagePropagation(severe)
283 elif 'url' in self.options:
284 # CSV data is from a URL.
285 # Do not import urllib2 at the top of the module because
286 # it may fail due to broken SSL dependencies, and it takes
287 # about 0.15 seconds to load.
288 import urllib2
289 source = self.options['url']
290 try:
291 csv_text = urllib2.urlopen(source).read()
292 except (urllib2.URLError, IOError, OSError, ValueError), error:
293 severe = self.state_machine.reporter.severe(
294 'Problems with "%s" directive URL "%s":\n%s.'
295 % (self.name, self.options['url'], SafeString(error)),
296 nodes.literal_block(self.block_text, self.block_text),
297 line=self.lineno)
298 raise SystemMessagePropagation(severe)
299 csv_file = io.StringInput(
300 source=csv_text, source_path=source, encoding=encoding,
301 error_handler=(self.state.document.settings.\
302 input_encoding_error_handler))
303 csv_data = csv_file.read().splitlines()
304 else:
305 error = self.state_machine.reporter.warning(
306 'The "%s" directive requires content; none supplied.'
307 % self.name, nodes.literal_block(
308 self.block_text, self.block_text), line=self.lineno)
309 raise SystemMessagePropagation(error)
310 return csv_data, source
312 if sys.version_info < (3,):
313 # 2.x csv module doesn't do Unicode
314 def decode_from_csv(s):
315 return s.decode('utf-8')
316 def encode_for_csv(s):
317 return s.encode('utf-8')
318 else:
319 def decode_from_csv(s):
320 return s
321 def encode_for_csv(s):
322 return s
323 decode_from_csv = staticmethod(decode_from_csv)
324 encode_for_csv = staticmethod(encode_for_csv)
326 def parse_csv_data_into_rows(self, csv_data, dialect, source):
327 # csv.py doesn't do Unicode; encode temporarily as UTF-8
328 csv_reader = csv.reader([self.encode_for_csv(line + '\n')
329 for line in csv_data],
330 dialect=dialect)
331 rows = []
332 max_cols = 0
333 for row in csv_reader:
334 row_data = []
335 for cell in row:
336 # decode UTF-8 back to Unicode
337 cell_text = self.decode_from_csv(cell)
338 cell_data = (0, 0, 0, statemachine.StringList(
339 cell_text.splitlines(), source=source))
340 row_data.append(cell_data)
341 rows.append(row_data)
342 max_cols = max(max_cols, len(row))
343 return rows, max_cols
346 class ListTable(Table):
349 Implement tables whose data is encoded as a uniform two-level bullet list.
350 For further ideas, see
351 http://docutils.sf.net/docs/dev/rst/alternatives.html#list-driven-tables
352 """
354 option_spec = {'header-rows': directives.nonnegative_int,
355 'stub-columns': directives.nonnegative_int,
356 'widths': directives.positive_int_list,
357 'class': directives.class_option}
359 def run(self):
360 if not self.content:
361 error = self.state_machine.reporter.error(
362 'The "%s" directive is empty; content required.' % self.name,
363 nodes.literal_block(self.block_text, self.block_text),
364 line=self.lineno)
365 return [error]
366 title, messages = self.make_title()
367 node = nodes.Element() # anonymous container for parsing
368 self.state.nested_parse(self.content, self.content_offset, node)
369 try:
370 num_cols, col_widths = self.check_list_content(node)
371 table_data = [[item.children for item in row_list[0]]
372 for row_list in node[0]]
373 header_rows = self.options.get('header-rows', 0)
374 stub_columns = self.options.get('stub-columns', 0)
375 self.check_table_dimensions(table_data, header_rows, stub_columns)
376 except SystemMessagePropagation, detail:
377 return [detail.args[0]]
378 table_node = self.build_table_from_list(table_data, col_widths,
379 header_rows, stub_columns)
380 table_node['classes'] += self.options.get('class', [])
381 if title:
382 table_node.insert(0, title)
383 return [table_node] + messages
385 def check_list_content(self, node):
386 if len(node) != 1 or not isinstance(node[0], nodes.bullet_list):
387 error = self.state_machine.reporter.error(
388 'Error parsing content block for the "%s" directive: '
389 'exactly one bullet list expected.' % self.name,
390 nodes.literal_block(self.block_text, self.block_text),
391 line=self.lineno)
392 raise SystemMessagePropagation(error)
393 list_node = node[0]
394 # Check for a uniform two-level bullet list:
395 for item_index in range(len(list_node)):
396 item = list_node[item_index]
397 if len(item) != 1 or not isinstance(item[0], nodes.bullet_list):
398 error = self.state_machine.reporter.error(
399 'Error parsing content block for the "%s" directive: '
400 'two-level bullet list expected, but row %s does not '
401 'contain a second-level bullet list.'
402 % (self.name, item_index + 1), nodes.literal_block(
403 self.block_text, self.block_text), line=self.lineno)
404 raise SystemMessagePropagation(error)
405 elif item_index:
406 # ATTN pychecker users: num_cols is guaranteed to be set in the
407 # "else" clause below for item_index==0, before this branch is
408 # triggered.
409 if len(item[0]) != num_cols:
410 error = self.state_machine.reporter.error(
411 'Error parsing content block for the "%s" directive: '
412 'uniform two-level bullet list expected, but row %s '
413 'does not contain the same number of items as row 1 '
414 '(%s vs %s).'
415 % (self.name, item_index + 1, len(item[0]), num_cols),
416 nodes.literal_block(self.block_text, self.block_text),
417 line=self.lineno)
418 raise SystemMessagePropagation(error)
419 else:
420 num_cols = len(item[0])
421 col_widths = self.get_column_widths(num_cols)
422 return num_cols, col_widths
424 def build_table_from_list(self, table_data, col_widths, header_rows, stub_columns):
425 table = nodes.table()
426 tgroup = nodes.tgroup(cols=len(col_widths))
427 table += tgroup
428 for col_width in col_widths:
429 colspec = nodes.colspec(colwidth=col_width)
430 if stub_columns:
431 colspec.attributes['stub'] = 1
432 stub_columns -= 1
433 tgroup += colspec
434 rows = []
435 for row in table_data:
436 row_node = nodes.row()
437 for cell in row:
438 entry = nodes.entry()
439 entry += cell
440 row_node += entry
441 rows.append(row_node)
442 if header_rows:
443 thead = nodes.thead()
444 thead.extend(rows[:header_rows])
445 tgroup += thead
446 tbody = nodes.tbody()
447 tbody.extend(rows[header_rows:])
448 tgroup += tbody
449 return table