check.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. """distutils.command.check
  2. Implements the Distutils 'check' command.
  3. """
  4. from email.utils import getaddresses
  5. from distutils.core import Command
  6. from distutils.errors import DistutilsSetupError
  7. try:
  8. # docutils is installed
  9. from docutils.utils import Reporter
  10. from docutils.parsers.rst import Parser
  11. from docutils import frontend
  12. from docutils import nodes
  13. class SilentReporter(Reporter):
  14. def __init__(
  15. self,
  16. source,
  17. report_level,
  18. halt_level,
  19. stream=None,
  20. debug=0,
  21. encoding='ascii',
  22. error_handler='replace',
  23. ):
  24. self.messages = []
  25. super().__init__(
  26. source, report_level, halt_level, stream, debug, encoding, error_handler
  27. )
  28. def system_message(self, level, message, *children, **kwargs):
  29. self.messages.append((level, message, children, kwargs))
  30. return nodes.system_message(
  31. message, level=level, type=self.levels[level], *children, **kwargs
  32. )
  33. HAS_DOCUTILS = True
  34. except Exception:
  35. # Catch all exceptions because exceptions besides ImportError probably
  36. # indicate that docutils is not ported to Py3k.
  37. HAS_DOCUTILS = False
  38. class check(Command):
  39. """This command checks the meta-data of the package."""
  40. description = "perform some checks on the package"
  41. user_options = [
  42. ('metadata', 'm', 'Verify meta-data'),
  43. (
  44. 'restructuredtext',
  45. 'r',
  46. (
  47. 'Checks if long string meta-data syntax '
  48. 'are reStructuredText-compliant'
  49. ),
  50. ),
  51. ('strict', 's', 'Will exit with an error if a check fails'),
  52. ]
  53. boolean_options = ['metadata', 'restructuredtext', 'strict']
  54. def initialize_options(self):
  55. """Sets default values for options."""
  56. self.restructuredtext = 0
  57. self.metadata = 1
  58. self.strict = 0
  59. self._warnings = 0
  60. def finalize_options(self):
  61. pass
  62. def warn(self, msg):
  63. """Counts the number of warnings that occurs."""
  64. self._warnings += 1
  65. return Command.warn(self, msg)
  66. def run(self):
  67. """Runs the command."""
  68. # perform the various tests
  69. if self.metadata:
  70. self.check_metadata()
  71. if self.restructuredtext:
  72. if HAS_DOCUTILS:
  73. self.check_restructuredtext()
  74. elif self.strict:
  75. raise DistutilsSetupError('The docutils package is needed.')
  76. # let's raise an error in strict mode, if we have at least
  77. # one warning
  78. if self.strict and self._warnings > 0:
  79. raise DistutilsSetupError('Please correct your package.')
  80. def check_metadata(self):
  81. """Ensures that all required elements of meta-data are supplied.
  82. Required fields:
  83. name, version
  84. Warns if any are missing.
  85. """
  86. metadata = self.distribution.metadata
  87. missing = []
  88. for attr in 'name', 'version':
  89. if not getattr(metadata, attr, None):
  90. missing.append(attr)
  91. if missing:
  92. self.warn("missing required meta-data: %s" % ', '.join(missing))
  93. def check_restructuredtext(self):
  94. """Checks if the long string fields are reST-compliant."""
  95. data = self.distribution.get_long_description()
  96. for warning in self._check_rst_data(data):
  97. line = warning[-1].get('line')
  98. if line is None:
  99. warning = warning[1]
  100. else:
  101. warning = '%s (line %s)' % (warning[1], line)
  102. self.warn(warning)
  103. def _check_rst_data(self, data):
  104. """Returns warnings when the provided data doesn't compile."""
  105. # the include and csv_table directives need this to be a path
  106. source_path = self.distribution.script_name or 'setup.py'
  107. parser = Parser()
  108. settings = frontend.OptionParser(components=(Parser,)).get_default_values()
  109. settings.tab_width = 4
  110. settings.pep_references = None
  111. settings.rfc_references = None
  112. reporter = SilentReporter(
  113. source_path,
  114. settings.report_level,
  115. settings.halt_level,
  116. stream=settings.warning_stream,
  117. debug=settings.debug,
  118. encoding=settings.error_encoding,
  119. error_handler=settings.error_encoding_error_handler,
  120. )
  121. document = nodes.document(settings, reporter, source=source_path)
  122. document.note_source(source_path, -1)
  123. try:
  124. parser.parse(data, document)
  125. except AttributeError as e:
  126. reporter.messages.append(
  127. (-1, 'Could not finish the parsing: %s.' % e, '', {})
  128. )
  129. return reporter.messages