Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2024-06-17 07:07:23

0001 import sys
0002 
0003 class Reporter:
0004     """Collect and report errors."""
0005 
0006     # Marker to show that an expected value hasn't been provided.
0007     # (Can't use 'None' because that might be a legitimate value.)
0008     _DEFAULT_REPORTER = []
0009 
0010     def __init__(self):
0011         """Constructor."""
0012         self.messages = []
0013 
0014     def check_field(self, filename, name, values, key, expected=_DEFAULT_REPORTER):
0015         """Check that a dictionary has an expected value."""
0016 
0017         if key not in values:
0018             self.add(filename, '{0} does not contain {1}', name, key)
0019         elif expected is self._DEFAULT_REPORTER:
0020             pass
0021         elif type(expected) in (tuple, set, list):
0022             if values[key] not in expected:
0023                 self.add(
0024                     filename, '{0} {1} value {2} is not in {3}', name, key, values[key], expected)
0025         elif values[key] != expected:
0026             self.add(filename, '{0} {1} is {2} not {3}',
0027                      name, key, values[key], expected)
0028 
0029     def check(self, condition, location, fmt, *args):
0030         """Append error if condition not met."""
0031 
0032         if not condition:
0033             self.add(location, fmt, *args)
0034 
0035     def add(self, location, fmt, *args):
0036         """Append error unilaterally."""
0037 
0038         self.messages.append((location, fmt.format(*args)))
0039 
0040     @staticmethod
0041     def pretty(item):
0042         location, message = item
0043         if isinstance(location, type(None)):
0044             return message
0045         elif isinstance(location, str):
0046             return location + ': ' + message
0047         elif isinstance(location, tuple):
0048             return '{0}:{1}: '.format(*location) + message
0049 
0050         print('Unknown item "{0}"'.format(item), file=sys.stderr)
0051         return NotImplemented
0052 
0053     @staticmethod
0054     def key(item):
0055         location, message = item
0056         if isinstance(location, type(None)):
0057             return ('', -1, message)
0058         elif isinstance(location, str):
0059             return (location, -1, message)
0060         elif isinstance(location, tuple):
0061             return (location[0], location[1], message)
0062 
0063         print('Unknown item "{0}"'.format(item), file=sys.stderr)
0064         return NotImplemented
0065 
0066     def report(self, stream=sys.stdout):
0067         """Report all messages in order."""
0068 
0069         if not self.messages:
0070             return
0071 
0072         for m in sorted(self.messages, key=self.key):
0073             print(self.pretty(m), file=stream)
0074 
0075