4 Check lesson files and their contents.
12 from optparse import OptionParser
14 from util import Reporter, read_markdown
18 # Where to look for source Markdown files.
19 SOURCE_DIRS = ['', '_episodes', '_extras']
21 # Required files: each entry is ('path': YAML_required).
22 # FIXME: We do not yet validate whether any files have the required
23 # YAML headers, but should in the future.
24 # The '%' is replaced with the source directory path for checking.
25 # Episodes are handled specially, and extra files in '_extras' are also handled specially.
26 # This list must include all the Markdown files listed in the 'bin/initialize' script.
29 '%/CONTRIBUTING.md': False,
32 '%/_extras/discuss.md': True,
33 '%/_extras/figures.md': True,
34 '%/_extras/guide.md': True,
36 '%/reference.md': True,
40 # Episode filename pattern.
41 P_EPISODE_FILENAME = re.compile(r'/_episodes/(\d\d)-[-\w]+.md$')
43 # What kinds of blockquotes are allowed?
57 # What kinds of code fragments are allowed?
69 # What fields are required in teaching episode metadata?
70 TEACHING_METADATA_FIELDS = {
79 # What fields are required in break episode metadata?
80 BREAK_METADATA_FIELDS = {
86 # How long are lines allowed to be?
93 args.reporter = Reporter()
94 check_config(args.reporter, args.source_dir)
95 docs = read_all_markdown(args.source_dir, args.parser)
96 check_fileset(args.source_dir, args.reporter, docs.keys())
97 for filename in docs.keys():
98 checker = create_checker(args, filename, docs[filename])
100 args.reporter.report()
104 """Parse command-line arguments."""
106 parser = OptionParser()
107 parser.add_option('-l', '--linelen',
110 help='Check line lengths')
111 parser.add_option('-p', '--parser',
114 help='path to Markdown parser')
115 parser.add_option('-s', '--source',
118 help='source directory')
120 args, extras = parser.parse_args()
121 require(args.parser is not None,
122 'Path to Markdown parser not provided')
124 'Unexpected trailing command-line arguments "{0}"'.format(extras))
129 def check_config(reporter, source_dir):
130 """Check configuration file."""
132 config_file = os.path.join(source_dir, '_config.yml')
133 config = load_yaml(config_file)
134 reporter.check_field(config_file, 'configuration', config, 'kind', 'lesson')
137 def read_all_markdown(source_dir, parser):
138 """Read source files, returning
139 {path : {'metadata':yaml, 'metadata_len':N, 'text':text, 'lines':[(i, line, len)], 'doc':doc}}
142 all_dirs = [os.path.join(source_dir, d) for d in SOURCE_DIRS]
143 all_patterns = [os.path.join(d, '*.md') for d in all_dirs]
145 for pat in all_patterns:
146 for filename in glob.glob(pat):
147 data = read_markdown(parser, filename)
149 result[filename] = data
153 def check_fileset(source_dir, reporter, filenames_present):
154 """Are all required files present? Are extraneous files present?"""
156 # Check files with predictable names.
157 required = [p.replace('%', source_dir) for p in REQUIRED_FILES]
158 missing = set(required) - set(filenames_present)
160 reporter.add(None, 'Missing required file {0}', m)
162 # Check episode files' names.
164 for filename in filenames_present:
165 if '_episodes' not in filename:
167 m = P_EPISODE_FILENAME.search(filename)
169 seen.append(m.group(1))
171 reporter.add(None, 'Episode {0} has badly-formatted filename', filename)
173 # Check for duplicate episode numbers.
174 reporter.check(len(seen) == len(set(seen)),
176 'Duplicate episode numbers {0} vs {1}',
177 sorted(seen), sorted(set(seen)))
179 # Check that numbers are consecutive.
180 seen = [int(s) for s in seen]
183 for i in range(len(seen) - 1):
184 clean = clean and ((seen[i+1] - seen[i]) == 1)
185 reporter.check(clean,
187 'Missing or non-consecutive episode numbers {0}',
191 def create_checker(args, filename, info):
192 """Create appropriate checker for file."""
194 for (pat, cls) in CHECKERS:
195 if pat.search(filename):
196 return cls(args, filename, **info)
199 def require(condition, message):
200 """Fail if condition not met."""
203 print(message, file=sys.stderr)
207 class CheckBase(object):
208 """Base class for checking Markdown files."""
210 def __init__(self, args, filename, metadata, metadata_len, text, lines, doc):
211 """Cache arguments for checking."""
213 super(CheckBase, self).__init__()
215 self.reporter = self.args.reporter # for convenience
216 self.filename = filename
217 self.metadata = metadata
218 self.metadata_len = metadata_len
227 """Run tests on metadata."""
229 self.check_metadata()
231 self.check_blockquote_classes()
232 self.check_codeblock_classes()
235 def check_metadata(self):
236 """Check the YAML metadata."""
238 self.reporter.check(self.metadata is not None,
240 'Missing metadata entirely')
242 if self.metadata and (self.layout is not None):
243 self.reporter.check_field(self.filename, 'metadata', self.metadata, 'layout', self.layout)
246 def check_text(self):
247 """Check the raw text of the lesson body."""
249 if self.args.line_len:
250 over = [i for (i, l, n) in self.lines if (n > MAX_LINE_LEN) and (not l.startswith('!'))]
251 self.reporter.check(not over,
253 'Line(s) are too long: {0}',
254 ', '.join([str(i) for i in over]))
257 def check_blockquote_classes(self):
258 """Check that all blockquotes have known classes."""
260 for node in self.find_all(self.doc, {'type' : 'blockquote'}):
261 cls = self.get_val(node, 'attr', 'class')
262 self.reporter.check(cls in KNOWN_BLOCKQUOTES,
263 (self.filename, self.get_loc(node)),
264 'Unknown or missing blockquote type {0}',
268 def check_codeblock_classes(self):
269 """Check that all code blocks have known classes."""
271 for node in self.find_all(self.doc, {'type' : 'codeblock'}):
272 cls = self.get_val(node, 'attr', 'class')
273 self.reporter.check(cls in KNOWN_CODEBLOCKS,
274 (self.filename, self.get_loc(node)),
275 'Unknown or missing code block type {0}',
279 def find_all(self, node, pattern, accum=None):
280 """Find all matches for a pattern."""
282 assert type(pattern) == dict, 'Patterns must be dictionaries'
285 if self.match(node, pattern):
287 for child in node.get('children', []):
288 self.find_all(child, pattern, accum)
292 def match(self, node, pattern):
293 """Does this node match the given pattern?"""
302 elif type(val) == dict:
303 if not self.match(node[key], val):
308 def get_val(self, node, *chain):
309 """Get value one or more levels down."""
312 for selector in chain:
313 curr = curr.get(selector, None)
319 def get_loc(self, node):
320 """Convenience method to get node's line number."""
322 result = self.get_val(node, 'options', 'location')
323 if self.metadata_len is not None:
324 result += self.metadata_len
328 class CheckNonJekyll(CheckBase):
329 """Check a file that isn't translated by Jekyll."""
331 def __init__(self, args, filename, metadata, metadata_len, text, lines, doc):
332 super(CheckNonJekyll, self).__init__(args, filename, metadata, metadata_len, text, lines, doc)
335 def check_metadata(self):
336 self.reporter.check(self.metadata is None,
338 'Unexpected metadata')
341 class CheckIndex(CheckBase):
342 """Check the main index page."""
344 def __init__(self, args, filename, metadata, metadata_len, text, lines, doc):
345 super(CheckIndex, self).__init__(args, filename, metadata, metadata_len, text, lines, doc)
346 self.layout = 'lesson'
349 class CheckEpisode(CheckBase):
350 """Check an episode page."""
352 def __init__(self, args, filename, metadata, metadata_len, text, lines, doc):
353 super(CheckEpisode, self).__init__(args, filename, metadata, metadata_len, text, lines, doc)
355 def check_metadata(self):
356 super(CheckEpisode, self).check_metadata()
358 if 'layout' in self.metadata:
359 if self.metadata['layout'] == 'break':
360 self.check_metadata_fields(BREAK_METADATA_FIELDS)
362 self.reporter.add(self.filename,
363 'Unknown episode layout "{0}"',
364 self.metadata['layout'])
366 self.check_metadata_fields(TEACHING_METADATA_FIELDS)
369 def check_metadata_fields(self, expected):
370 for (name, type_) in expected:
371 if name not in self.metadata:
372 self.reporter.add(self.filename,
373 'Missing metadata field {0}',
375 elif type(self.metadata[name]) != type_:
376 self.reporter.add(self.filename,
377 '"{0}" has wrong type in metadata ({1} instead of {2})',
378 name, type(self.metadata[name]), type_)
381 class CheckReference(CheckBase):
382 """Check the reference page."""
384 def __init__(self, args, filename, metadata, metadata_len, text, lines, doc):
385 super(CheckReference, self).__init__(args, filename, metadata, metadata_len, text, lines, doc)
386 self.layout = 'reference'
389 class CheckGeneric(CheckBase):
390 """Check a generic page."""
392 def __init__(self, args, filename, metadata, metadata_len, text, lines, doc):
393 super(CheckGeneric, self).__init__(args, filename, metadata, metadata_len, text, lines, doc)
398 (re.compile(r'CONTRIBUTING\.md'), CheckNonJekyll),
399 (re.compile(r'README\.md'), CheckNonJekyll),
400 (re.compile(r'index\.md'), CheckIndex),
401 (re.compile(r'reference\.md'), CheckReference),
402 (re.compile(r'_episodes/.*\.md'), CheckEpisode),
403 (re.compile(r'.*\.md'), CheckGeneric)
407 if __name__ == '__main__':