PageRenderTime 70ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/External.LCA_RESTRICTED/Languages/IronPython/27/Doc/docutils/utils.py

http://github.com/IronLanguages/main
Python | 593 lines | 555 code | 13 blank | 25 comment | 4 complexity | 9473faa8af06bc7380f6bce24d67bce4 MD5 | raw file
Possible License(s): CPL-1.0, BSD-3-Clause, ISC, GPL-2.0, MPL-2.0-no-copyleft-exception
  1. # $Id: utils.py 5040 2007-04-03 17:41:59Z goodger $
  2. # Author: David Goodger <goodger@python.org>
  3. # Copyright: This module has been placed in the public domain.
  4. """
  5. Miscellaneous utilities for the documentation utilities.
  6. """
  7. __docformat__ = 'reStructuredText'
  8. import sys
  9. import os
  10. import os.path
  11. import types
  12. import warnings
  13. import unicodedata
  14. from types import StringType, UnicodeType
  15. from docutils import ApplicationError, DataError
  16. from docutils import nodes
  17. class SystemMessage(ApplicationError):
  18. def __init__(self, system_message, level):
  19. Exception.__init__(self, system_message.astext())
  20. self.level = level
  21. class SystemMessagePropagation(ApplicationError): pass
  22. class Reporter:
  23. """
  24. Info/warning/error reporter and ``system_message`` element generator.
  25. Five levels of system messages are defined, along with corresponding
  26. methods: `debug()`, `info()`, `warning()`, `error()`, and `severe()`.
  27. There is typically one Reporter object per process. A Reporter object is
  28. instantiated with thresholds for reporting (generating warnings) and
  29. halting processing (raising exceptions), a switch to turn debug output on
  30. or off, and an I/O stream for warnings. These are stored as instance
  31. attributes.
  32. When a system message is generated, its level is compared to the stored
  33. thresholds, and a warning or error is generated as appropriate. Debug
  34. messages are produced iff the stored debug switch is on, independently of
  35. other thresholds. Message output is sent to the stored warning stream if
  36. not set to ''.
  37. The Reporter class also employs a modified form of the "Observer" pattern
  38. [GoF95]_ to track system messages generated. The `attach_observer` method
  39. should be called before parsing, with a bound method or function which
  40. accepts system messages. The observer can be removed with
  41. `detach_observer`, and another added in its place.
  42. .. [GoF95] Gamma, Helm, Johnson, Vlissides. *Design Patterns: Elements of
  43. Reusable Object-Oriented Software*. Addison-Wesley, Reading, MA, USA,
  44. 1995.
  45. """
  46. levels = 'DEBUG INFO WARNING ERROR SEVERE'.split()
  47. """List of names for system message levels, indexed by level."""
  48. # system message level constants:
  49. (DEBUG_LEVEL,
  50. INFO_LEVEL,
  51. WARNING_LEVEL,
  52. ERROR_LEVEL,
  53. SEVERE_LEVEL) = range(5)
  54. def __init__(self, source, report_level, halt_level, stream=None,
  55. debug=0, encoding='ascii', error_handler='replace'):
  56. """
  57. :Parameters:
  58. - `source`: The path to or description of the source data.
  59. - `report_level`: The level at or above which warning output will
  60. be sent to `stream`.
  61. - `halt_level`: The level at or above which `SystemMessage`
  62. exceptions will be raised, halting execution.
  63. - `debug`: Show debug (level=0) system messages?
  64. - `stream`: Where warning output is sent. Can be file-like (has a
  65. ``.write`` method), a string (file name, opened for writing),
  66. '' (empty string, for discarding all stream messages) or
  67. `None` (implies `sys.stderr`; default).
  68. - `encoding`: The encoding for stderr output.
  69. - `error_handler`: The error handler for stderr output encoding.
  70. """
  71. self.source = source
  72. """The path to or description of the source data."""
  73. self.encoding = encoding
  74. """The character encoding for the stderr output."""
  75. self.error_handler = error_handler
  76. """The character encoding error handler."""
  77. self.debug_flag = debug
  78. """Show debug (level=0) system messages?"""
  79. self.report_level = report_level
  80. """The level at or above which warning output will be sent
  81. to `self.stream`."""
  82. self.halt_level = halt_level
  83. """The level at or above which `SystemMessage` exceptions
  84. will be raised, halting execution."""
  85. if stream is None:
  86. stream = sys.stderr
  87. elif type(stream) in (StringType, UnicodeType):
  88. # Leave stream untouched if it's ''.
  89. if stream != '':
  90. if type(stream) == StringType:
  91. stream = open(stream, 'w')
  92. elif type(stream) == UnicodeType:
  93. stream = open(stream.encode(), 'w')
  94. self.stream = stream
  95. """Where warning output is sent."""
  96. self.observers = []
  97. """List of bound methods or functions to call with each system_message
  98. created."""
  99. self.max_level = -1
  100. """The highest level system message generated so far."""
  101. def set_conditions(self, category, report_level, halt_level,
  102. stream=None, debug=0):
  103. warnings.warn('docutils.utils.Reporter.set_conditions deprecated; '
  104. 'set attributes via configuration settings or directly',
  105. DeprecationWarning, stacklevel=2)
  106. self.report_level = report_level
  107. self.halt_level = halt_level
  108. if stream is None:
  109. stream = sys.stderr
  110. self.stream = stream
  111. self.debug_flag = debug
  112. def attach_observer(self, observer):
  113. """
  114. The `observer` parameter is a function or bound method which takes one
  115. argument, a `nodes.system_message` instance.
  116. """
  117. self.observers.append(observer)
  118. def detach_observer(self, observer):
  119. self.observers.remove(observer)
  120. def notify_observers(self, message):
  121. for observer in self.observers:
  122. observer(message)
  123. def system_message(self, level, message, *children, **kwargs):
  124. """
  125. Return a system_message object.
  126. Raise an exception or generate a warning if appropriate.
  127. """
  128. attributes = kwargs.copy()
  129. if kwargs.has_key('base_node'):
  130. source, line = get_source_line(kwargs['base_node'])
  131. del attributes['base_node']
  132. if source is not None:
  133. attributes.setdefault('source', source)
  134. if line is not None:
  135. attributes.setdefault('line', line)
  136. attributes.setdefault('source', self.source)
  137. msg = nodes.system_message(message, level=level,
  138. type=self.levels[level],
  139. *children, **attributes)
  140. if self.stream and (level >= self.report_level
  141. or self.debug_flag and level == self.DEBUG_LEVEL):
  142. msgtext = msg.astext().encode(self.encoding, self.error_handler)
  143. print >>self.stream, msgtext
  144. if level >= self.halt_level:
  145. raise SystemMessage(msg, level)
  146. if level > self.DEBUG_LEVEL or self.debug_flag:
  147. self.notify_observers(msg)
  148. self.max_level = max(level, self.max_level)
  149. return msg
  150. def debug(self, *args, **kwargs):
  151. """
  152. Level-0, "DEBUG": an internal reporting issue. Typically, there is no
  153. effect on the processing. Level-0 system messages are handled
  154. separately from the others.
  155. """
  156. if self.debug_flag:
  157. return self.system_message(self.DEBUG_LEVEL, *args, **kwargs)
  158. def info(self, *args, **kwargs):
  159. """
  160. Level-1, "INFO": a minor issue that can be ignored. Typically there is
  161. no effect on processing, and level-1 system messages are not reported.
  162. """
  163. return self.system_message(self.INFO_LEVEL, *args, **kwargs)
  164. def warning(self, *args, **kwargs):
  165. """
  166. Level-2, "WARNING": an issue that should be addressed. If ignored,
  167. there may be unpredictable problems with the output.
  168. """
  169. return self.system_message(self.WARNING_LEVEL, *args, **kwargs)
  170. def error(self, *args, **kwargs):
  171. """
  172. Level-3, "ERROR": an error that should be addressed. If ignored, the
  173. output will contain errors.
  174. """
  175. return self.system_message(self.ERROR_LEVEL, *args, **kwargs)
  176. def severe(self, *args, **kwargs):
  177. """
  178. Level-4, "SEVERE": a severe error that must be addressed. If ignored,
  179. the output will contain severe errors. Typically level-4 system
  180. messages are turned into exceptions which halt processing.
  181. """
  182. return self.system_message(self.SEVERE_LEVEL, *args, **kwargs)
  183. class ExtensionOptionError(DataError): pass
  184. class BadOptionError(ExtensionOptionError): pass
  185. class BadOptionDataError(ExtensionOptionError): pass
  186. class DuplicateOptionError(ExtensionOptionError): pass
  187. def extract_extension_options(field_list, options_spec):
  188. """
  189. Return a dictionary mapping extension option names to converted values.
  190. :Parameters:
  191. - `field_list`: A flat field list without field arguments, where each
  192. field body consists of a single paragraph only.
  193. - `options_spec`: Dictionary mapping known option names to a
  194. conversion function such as `int` or `float`.
  195. :Exceptions:
  196. - `KeyError` for unknown option names.
  197. - `ValueError` for invalid option values (raised by the conversion
  198. function).
  199. - `TypeError` for invalid option value types (raised by conversion
  200. function).
  201. - `DuplicateOptionError` for duplicate options.
  202. - `BadOptionError` for invalid fields.
  203. - `BadOptionDataError` for invalid option data (missing name,
  204. missing data, bad quotes, etc.).
  205. """
  206. option_list = extract_options(field_list)
  207. option_dict = assemble_option_dict(option_list, options_spec)
  208. return option_dict
  209. def extract_options(field_list):
  210. """
  211. Return a list of option (name, value) pairs from field names & bodies.
  212. :Parameter:
  213. `field_list`: A flat field list, where each field name is a single
  214. word and each field body consists of a single paragraph only.
  215. :Exceptions:
  216. - `BadOptionError` for invalid fields.
  217. - `BadOptionDataError` for invalid option data (missing name,
  218. missing data, bad quotes, etc.).
  219. """
  220. option_list = []
  221. for field in field_list:
  222. if len(field[0].astext().split()) != 1:
  223. raise BadOptionError(
  224. 'extension option field name may not contain multiple words')
  225. name = str(field[0].astext().lower())
  226. body = field[1]
  227. if len(body) == 0:
  228. data = None
  229. elif len(body) > 1 or not isinstance(body[0], nodes.paragraph) \
  230. or len(body[0]) != 1 or not isinstance(body[0][0], nodes.Text):
  231. raise BadOptionDataError(
  232. 'extension option field body may contain\n'
  233. 'a single paragraph only (option "%s")' % name)
  234. else:
  235. data = body[0][0].astext()
  236. option_list.append((name, data))
  237. return option_list
  238. def assemble_option_dict(option_list, options_spec):
  239. """
  240. Return a mapping of option names to values.
  241. :Parameters:
  242. - `option_list`: A list of (name, value) pairs (the output of
  243. `extract_options()`).
  244. - `options_spec`: Dictionary mapping known option names to a
  245. conversion function such as `int` or `float`.
  246. :Exceptions:
  247. - `KeyError` for unknown option names.
  248. - `DuplicateOptionError` for duplicate options.
  249. - `ValueError` for invalid option values (raised by conversion
  250. function).
  251. - `TypeError` for invalid option value types (raised by conversion
  252. function).
  253. """
  254. options = {}
  255. for name, value in option_list:
  256. convertor = options_spec[name] # raises KeyError if unknown
  257. if convertor is None:
  258. raise KeyError(name) # or if explicitly disabled
  259. if options.has_key(name):
  260. raise DuplicateOptionError('duplicate option "%s"' % name)
  261. try:
  262. options[name] = convertor(value)
  263. except (ValueError, TypeError), detail:
  264. raise detail.__class__('(option: "%s"; value: %r)\n%s'
  265. % (name, value, ' '.join(detail.args)))
  266. return options
  267. class NameValueError(DataError): pass
  268. def extract_name_value(line):
  269. """
  270. Return a list of (name, value) from a line of the form "name=value ...".
  271. :Exception:
  272. `NameValueError` for invalid input (missing name, missing data, bad
  273. quotes, etc.).
  274. """
  275. attlist = []
  276. while line:
  277. equals = line.find('=')
  278. if equals == -1:
  279. raise NameValueError('missing "="')
  280. attname = line[:equals].strip()
  281. if equals == 0 or not attname:
  282. raise NameValueError(
  283. 'missing attribute name before "="')
  284. line = line[equals+1:].lstrip()
  285. if not line:
  286. raise NameValueError(
  287. 'missing value after "%s="' % attname)
  288. if line[0] in '\'"':
  289. endquote = line.find(line[0], 1)
  290. if endquote == -1:
  291. raise NameValueError(
  292. 'attribute "%s" missing end quote (%s)'
  293. % (attname, line[0]))
  294. if len(line) > endquote + 1 and line[endquote + 1].strip():
  295. raise NameValueError(
  296. 'attribute "%s" end quote (%s) not followed by '
  297. 'whitespace' % (attname, line[0]))
  298. data = line[1:endquote]
  299. line = line[endquote+1:].lstrip()
  300. else:
  301. space = line.find(' ')
  302. if space == -1:
  303. data = line
  304. line = ''
  305. else:
  306. data = line[:space]
  307. line = line[space+1:].lstrip()
  308. attlist.append((attname.lower(), data))
  309. return attlist
  310. def new_reporter(source_path, settings):
  311. """
  312. Return a new Reporter object.
  313. :Parameters:
  314. `source` : string
  315. The path to or description of the source text of the document.
  316. `settings` : optparse.Values object
  317. Runtime settings.
  318. """
  319. reporter = Reporter(
  320. source_path, settings.report_level, settings.halt_level,
  321. stream=settings.warning_stream, debug=settings.debug,
  322. encoding=settings.error_encoding,
  323. error_handler=settings.error_encoding_error_handler)
  324. return reporter
  325. def new_document(source_path, settings=None):
  326. """
  327. Return a new empty document object.
  328. :Parameters:
  329. `source_path` : string
  330. The path to or description of the source text of the document.
  331. `settings` : optparse.Values object
  332. Runtime settings. If none provided, a default set will be used.
  333. """
  334. from docutils import frontend
  335. if settings is None:
  336. settings = frontend.OptionParser().get_default_values()
  337. reporter = new_reporter(source_path, settings)
  338. document = nodes.document(settings, reporter, source=source_path)
  339. document.note_source(source_path, -1)
  340. return document
  341. def clean_rcs_keywords(paragraph, keyword_substitutions):
  342. if len(paragraph) == 1 and isinstance(paragraph[0], nodes.Text):
  343. textnode = paragraph[0]
  344. for pattern, substitution in keyword_substitutions:
  345. match = pattern.search(textnode.data)
  346. if match:
  347. textnode.data = pattern.sub(substitution, textnode.data)
  348. return
  349. def relative_path(source, target):
  350. """
  351. Build and return a path to `target`, relative to `source` (both files).
  352. If there is no common prefix, return the absolute path to `target`.
  353. """
  354. source_parts = os.path.abspath(source or 'dummy_file').split(os.sep)
  355. target_parts = os.path.abspath(target).split(os.sep)
  356. # Check first 2 parts because '/dir'.split('/') == ['', 'dir']:
  357. if source_parts[:2] != target_parts[:2]:
  358. # Nothing in common between paths.
  359. # Return absolute path, using '/' for URLs:
  360. return '/'.join(target_parts)
  361. source_parts.reverse()
  362. target_parts.reverse()
  363. while (source_parts and target_parts
  364. and source_parts[-1] == target_parts[-1]):
  365. # Remove path components in common:
  366. source_parts.pop()
  367. target_parts.pop()
  368. target_parts.reverse()
  369. parts = ['..'] * (len(source_parts) - 1) + target_parts
  370. return '/'.join(parts)
  371. def get_stylesheet_reference(settings, relative_to=None):
  372. """
  373. Retrieve a stylesheet reference from the settings object.
  374. """
  375. if settings.stylesheet_path:
  376. assert not settings.stylesheet, \
  377. 'stylesheet and stylesheet_path are mutually exclusive.'
  378. if relative_to == None:
  379. relative_to = settings._destination
  380. return relative_path(relative_to, settings.stylesheet_path)
  381. else:
  382. return settings.stylesheet
  383. def get_trim_footnote_ref_space(settings):
  384. """
  385. Return whether or not to trim footnote space.
  386. If trim_footnote_reference_space is not None, return it.
  387. If trim_footnote_reference_space is None, return False unless the
  388. footnote reference style is 'superscript'.
  389. """
  390. if settings.trim_footnote_reference_space is None:
  391. return hasattr(settings, 'footnote_references') and \
  392. settings.footnote_references == 'superscript'
  393. else:
  394. return settings.trim_footnote_reference_space
  395. def get_source_line(node):
  396. """
  397. Return the "source" and "line" attributes from the `node` given or from
  398. its closest ancestor.
  399. """
  400. while node:
  401. if node.source or node.line:
  402. return node.source, node.line
  403. node = node.parent
  404. return None, None
  405. def escape2null(text):
  406. """Return a string with escape-backslashes converted to nulls."""
  407. parts = []
  408. start = 0
  409. while 1:
  410. found = text.find('\\', start)
  411. if found == -1:
  412. parts.append(text[start:])
  413. return ''.join(parts)
  414. parts.append(text[start:found])
  415. parts.append('\x00' + text[found+1:found+2])
  416. start = found + 2 # skip character after escape
  417. def unescape(text, restore_backslashes=0):
  418. """
  419. Return a string with nulls removed or restored to backslashes.
  420. Backslash-escaped spaces are also removed.
  421. """
  422. if restore_backslashes:
  423. return text.replace('\x00', '\\')
  424. else:
  425. for sep in ['\x00 ', '\x00\n', '\x00']:
  426. text = ''.join(text.split(sep))
  427. return text
  428. east_asian_widths = {'W': 2, # Wide
  429. 'F': 2, # Full-width (wide)
  430. 'Na': 1, # Narrow
  431. 'H': 1, # Half-width (narrow)
  432. 'N': 1, # Neutral (not East Asian, treated as narrow)
  433. 'A': 1} # Ambiguous (s/b wide in East Asian context,
  434. # narrow otherwise, but that doesn't work)
  435. """Mapping of result codes from `unicodedata.east_asian_width()` to character
  436. column widths."""
  437. def east_asian_column_width(text):
  438. if isinstance(text, types.UnicodeType):
  439. total = 0
  440. for c in text:
  441. total += east_asian_widths[unicodedata.east_asian_width(c)]
  442. return total
  443. else:
  444. return len(text)
  445. if hasattr(unicodedata, 'east_asian_width'):
  446. column_width = east_asian_column_width
  447. else:
  448. column_width = len
  449. def uniq(L):
  450. r = []
  451. for item in L:
  452. if not item in r:
  453. r.append(item)
  454. return r
  455. class DependencyList:
  456. """
  457. List of dependencies, with file recording support.
  458. Note that the output file is not automatically closed. You have
  459. to explicitly call the close() method.
  460. """
  461. def __init__(self, output_file=None, dependencies=[]):
  462. """
  463. Initialize the dependency list, automatically setting the
  464. output file to `output_file` (see `set_output()`) and adding
  465. all supplied dependencies.
  466. """
  467. self.set_output(output_file)
  468. for i in dependencies:
  469. self.add(i)
  470. def set_output(self, output_file):
  471. """
  472. Set the output file and clear the list of already added
  473. dependencies.
  474. `output_file` must be a string. The specified file is
  475. immediately overwritten.
  476. If output_file is '-', the output will be written to stdout.
  477. If it is None, no file output is done when calling add().
  478. """
  479. self.list = []
  480. if output_file == '-':
  481. self.file = sys.stdout
  482. elif output_file:
  483. self.file = open(output_file, 'w')
  484. else:
  485. self.file = None
  486. def add(self, filename):
  487. """
  488. If the dependency `filename` has not already been added,
  489. append it to self.list and print it to self.file if self.file
  490. is not None.
  491. """
  492. if not filename in self.list:
  493. self.list.append(filename)
  494. if self.file is not None:
  495. print >>self.file, filename
  496. def close(self):
  497. """
  498. Close the output file.
  499. """
  500. self.file.close()
  501. self.file = None
  502. def __repr__(self):
  503. if self.file:
  504. output_file = self.file.name
  505. else:
  506. output_file = None
  507. return '%s(%r, %s)' % (self.__class__.__name__, output_file, self.list)