4 from subprocess import Popen, PIPE
6 # Import this way to produce a more useful error message.
10 print('Unable to import YAML module: please install PyYAML', file=sys.stderr)
21 class Reporter(object):
22 """Collect and report errors."""
27 super(Reporter, self).__init__()
31 def check_field(self, filename, name, values, key, expected=REPORTER_NOT_SET):
32 """Check that a dictionary has an expected value."""
35 self.add(filename, '{0} does not contain {1}', name, key)
36 elif expected is REPORTER_NOT_SET:
38 elif type(expected) in (tuple, set, list):
39 if values[key] not in expected:
40 self.add(filename, '{0} {1} value {2} is not in {3}', name, key, values[key], expected)
41 elif values[key] != expected:
42 self.add(filename, '{0} {1} is {2} not {3}', name, key, values[key], expected)
45 def check(self, condition, location, fmt, *args):
46 """Append error if condition not met."""
49 self.add(location, fmt, *args)
52 def add(self, location, fmt, *args):
53 """Append error unilaterally."""
55 if isinstance(location, type(None)):
57 elif isinstance(location, str):
58 coords = '{0}: '.format(location)
59 elif isinstance(location, tuple):
60 filename, line_number = location
61 coords = '{0}:{1}: '.format(*location)
63 assert False, 'Unknown location "{0}"/{1}'.format(location, type(location))
65 self.messages.append(coords + fmt.format(*args))
68 def report(self, stream=sys.stdout):
69 """Report all messages."""
73 for m in sorted(self.messages):
77 def read_markdown(parser, path):
79 Get YAML and AST for Markdown file, returning
80 {'metadata':yaml, 'metadata_len':N, 'text':text, 'lines':[(i, line, len)], 'doc':doc}.
83 # Split and extract YAML (if present).
84 with open(path, 'r') as reader:
86 metadata_raw, metadata_yaml, body = split_metadata(path, body)
89 metadata_len = 0 if metadata_raw is None else metadata_raw.count('\n')
90 lines = [(metadata_len+i+1, line, len(line)) for (i, line) in enumerate(body.split('\n'))]
93 cmd = 'ruby {0}'.format(parser)
94 p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, close_fds=True, universal_newlines=True)
95 stdout_data, stderr_data = p.communicate(body)
96 doc = json.loads(stdout_data)
99 'metadata': metadata_yaml,
100 'metadata_len': metadata_len,
107 def split_metadata(path, text):
109 Get raw (text) metadata, metadata as YAML, and rest of body.
110 If no metadata, return (None, None, body).
117 pieces = text.split('---', 2)
119 metadata_raw = pieces[1]
122 metadata_yaml = yaml.load(metadata_raw)
123 except yaml.YAMLError as e:
124 print('Unable to parse YAML header in {0}:\n{1}'.format(path, e), file=sys.stderr)
127 return metadata_raw, metadata_yaml, text
130 def load_yaml(filename):
132 Wrapper around YAML loading so that 'import yaml' is only needed
137 with open(filename, 'r') as reader:
138 return yaml.load(reader)
139 except (yaml.YAMLError, FileNotFoundError) as e:
140 print('Unable to load YAML file {0}:\n{1}'.format(filename, e), file=sys.stderr)
144 def check_unwanted_files(dir_path, reporter):
146 Check that unwanted files are not present.
149 for filename in UNWANTED_FILES:
150 path = os.path.join(dir_path, filename)
151 reporter.check(not os.path.exists(path),
153 "Unwanted file found")
156 def require(condition, message):
157 """Fail if condition not met."""
160 print(message, file=sys.stderr)