4 Check lesson files and their contents.
11 from argparse import ArgumentParser
13 from util import (Reporter, read_markdown, load_yaml, check_unwanted_files,
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
26 # specially. This list must include all the Markdown files listed in the
27 # 'bin/initialize' script.
30 '%/CONTRIBUTING.md': False,
33 '%/_extras/discuss.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 # Pattern to match lines ending with whitespace.
44 P_TRAILING_WHITESPACE = re.compile(r'\s+$')
46 # Pattern to match figure references in HTML.
47 P_FIGURE_REFS = re.compile(r'<img[^>]+src="([^"]+)"[^>]*>')
49 # Pattern to match internally-defined Markdown links.
50 P_INTERNAL_LINK_REF = re.compile(r'\[([^\]]+)\]\[([^\]]+)\]')
52 # Pattern to match reference links (to resolve internally-defined references).
53 P_INTERNAL_LINK_DEF = re.compile(r'^\[([^\]]+)\]:\s*(.+)')
55 # What kinds of blockquotes are allowed?
69 # What kinds of code fragments are allowed?
84 # What fields are required in teaching episode metadata?
85 TEACHING_METADATA_FIELDS = {
94 # What fields are required in break episode metadata?
95 BREAK_METADATA_FIELDS = {
101 # How long are lines allowed to be?
109 args.reporter = Reporter()
110 check_config(args.reporter, args.source_dir)
111 args.references = read_references(args.reporter, args.reference_path)
113 docs = read_all_markdown(args.source_dir, args.parser)
114 check_fileset(args.source_dir, args.reporter, list(docs.keys()))
115 check_unwanted_files(args.source_dir, args.reporter)
116 for filename in list(docs.keys()):
117 checker = create_checker(args, filename, docs[filename])
120 args.reporter.report()
121 if args.reporter.messages and not args.permissive:
126 """Parse command-line arguments."""
128 parser = ArgumentParser(description="""Check episode files in a lesson.""")
129 parser.add_argument('-l', '--linelen',
133 help='Check line lengths')
134 parser.add_argument('-p', '--parser',
137 help='path to Markdown parser')
138 parser.add_argument('-r', '--references',
140 dest='reference_path',
141 help='path to Markdown file of external references')
142 parser.add_argument('-s', '--source',
145 help='source directory')
146 parser.add_argument('-w', '--whitespace',
149 dest='trailing_whitespace',
150 help='Check for trailing whitespace')
151 parser.add_argument('--permissive',
155 help='Do not raise an error even if issues are detected')
157 args, extras = parser.parse_known_args()
158 require(args.parser is not None,
159 'Path to Markdown parser not provided')
161 'Unexpected trailing command-line arguments "{0}"'.format(extras))
166 def check_config(reporter, source_dir):
167 """Check configuration file."""
169 config_file = os.path.join(source_dir, '_config.yml')
170 config = load_yaml(config_file)
171 reporter.check_field(config_file, 'configuration',
172 config, 'kind', 'lesson')
173 reporter.check_field(config_file, 'configuration',
174 config, 'carpentry', ('swc', 'dc', 'lc'))
175 reporter.check_field(config_file, 'configuration', config, 'title')
176 reporter.check_field(config_file, 'configuration', config, 'email')
178 reporter.check({'values': {'root': '..'}} in config.get('defaults', []),
180 '"root" not set to ".." in configuration')
183 def read_references(reporter, ref_path):
184 """Read shared file of reference links, returning dictionary of valid references
185 {symbolic_name : URL}
191 with open(ref_path, 'r') as reader:
192 for (num, line) in enumerate(reader):
194 m = P_INTERNAL_LINK_DEF.search(line)
196 '{0}:{1} not valid reference:\n{2}'.format(ref_path, line_num, line.rstrip()))
200 'Empty reference at {0}:{1}'.format(ref_path, line_num))
201 reporter.check(name not in result,
203 'Duplicate reference {0} at line {1}',
205 reporter.check(url not in urls_seen,
207 'Duplicate definition of URL {0} at line {1}',
214 def read_all_markdown(source_dir, parser):
215 """Read source files, returning
216 {path : {'metadata':yaml, 'metadata_len':N, 'text':text, 'lines':[(i, line, len)], 'doc':doc}}
219 all_dirs = [os.path.join(source_dir, d) for d in SOURCE_DIRS]
220 all_patterns = [os.path.join(d, '*.md') for d in all_dirs]
222 for pat in all_patterns:
223 for filename in glob.glob(pat):
224 data = read_markdown(parser, filename)
226 result[filename] = data
230 def check_fileset(source_dir, reporter, filenames_present):
231 """Are all required files present? Are extraneous files present?"""
233 # Check files with predictable names.
234 required = [p.replace('%', source_dir) for p in REQUIRED_FILES]
235 missing = set(required) - set(filenames_present)
237 reporter.add(None, 'Missing required file {0}', m)
239 # Check episode files' names.
241 for filename in filenames_present:
242 if '_episodes' not in filename:
244 m = P_EPISODE_FILENAME.search(filename)
246 seen.append(m.group(1))
249 None, 'Episode {0} has badly-formatted filename', filename)
251 # Check for duplicate episode numbers.
252 reporter.check(len(seen) == len(set(seen)),
254 'Duplicate episode numbers {0} vs {1}',
255 sorted(seen), sorted(set(seen)))
257 # Check that numbers are consecutive.
258 seen = sorted([int(s) for s in seen])
260 for i in range(len(seen) - 1):
261 clean = clean and ((seen[i+1] - seen[i]) == 1)
262 reporter.check(clean,
264 'Missing or non-consecutive episode numbers {0}',
268 def create_checker(args, filename, info):
269 """Create appropriate checker for file."""
271 for (pat, cls) in CHECKERS:
272 if pat.search(filename):
273 return cls(args, filename, **info)
274 return NotImplemented
276 class CheckBase(object):
277 """Base class for checking Markdown files."""
279 def __init__(self, args, filename, metadata, metadata_len, text, lines, doc):
280 """Cache arguments for checking."""
283 self.reporter = self.args.reporter # for convenience
284 self.filename = filename
285 self.metadata = metadata
286 self.metadata_len = metadata_len
296 self.check_metadata()
297 self.check_line_lengths()
298 self.check_trailing_whitespace()
299 self.check_blockquote_classes()
300 self.check_codeblock_classes()
301 self.check_defined_link_references()
303 def check_metadata(self):
304 """Check the YAML metadata."""
306 self.reporter.check(self.metadata is not None,
308 'Missing metadata entirely')
310 if self.metadata and (self.layout is not None):
311 self.reporter.check_field(
312 self.filename, 'metadata', self.metadata, 'layout', self.layout)
314 def check_line_lengths(self):
315 """Check the raw text of the lesson body."""
317 if self.args.line_lengths:
318 over = [i for (i, l, n) in self.lines if (
319 n > MAX_LINE_LEN) and (not l.startswith('!'))]
320 self.reporter.check(not over,
322 'Line(s) are too long: {0}',
323 ', '.join([str(i) for i in over]))
325 def check_trailing_whitespace(self):
326 """Check for whitespace at the ends of lines."""
328 if self.args.trailing_whitespace:
330 i for (i, l, n) in self.lines if P_TRAILING_WHITESPACE.match(l)]
331 self.reporter.check(not trailing,
333 'Line(s) end with whitespace: {0}',
334 ', '.join([str(i) for i in trailing]))
336 def check_blockquote_classes(self):
337 """Check that all blockquotes have known classes."""
339 for node in self.find_all(self.doc, {'type': 'blockquote'}):
340 cls = self.get_val(node, 'attr', 'class')
341 self.reporter.check(cls in KNOWN_BLOCKQUOTES,
342 (self.filename, self.get_loc(node)),
343 'Unknown or missing blockquote type {0}',
346 def check_codeblock_classes(self):
347 """Check that all code blocks have known classes."""
349 for node in self.find_all(self.doc, {'type': 'codeblock'}):
350 cls = self.get_val(node, 'attr', 'class')
351 self.reporter.check(cls in KNOWN_CODEBLOCKS,
352 (self.filename, self.get_loc(node)),
353 'Unknown or missing code block type {0}',
356 def check_defined_link_references(self):
357 """Check that defined links resolve in the file.
359 Internally-defined links match the pattern [text][label].
363 for node in self.find_all(self.doc, {'type': 'text'}):
364 for match in P_INTERNAL_LINK_REF.findall(node['value']):
367 if link not in self.args.references:
368 result.add('"{0}"=>"{1}"'.format(text, link))
369 self.reporter.check(not result,
371 'Internally-defined links may be missing definitions: {0}',
372 ', '.join(sorted(result)))
374 def find_all(self, node, pattern, accum=None):
375 """Find all matches for a pattern."""
377 assert isinstance(pattern, dict), 'Patterns must be dictionaries'
380 if self.match(node, pattern):
382 for child in node.get('children', []):
383 self.find_all(child, pattern, accum)
386 def match(self, node, pattern):
387 """Does this node match the given pattern?"""
393 if isinstance(val, str):
396 elif isinstance(val, dict):
397 if not self.match(node[key], val):
402 def get_val(node, *chain):
403 """Get value one or more levels down."""
406 for selector in chain:
407 curr = curr.get(selector, None)
412 def get_loc(self, node):
413 """Convenience method to get node's line number."""
415 result = self.get_val(node, 'options', 'location')
416 if self.metadata_len is not None:
417 result += self.metadata_len
421 class CheckNonJekyll(CheckBase):
422 """Check a file that isn't translated by Jekyll."""
424 def check_metadata(self):
425 self.reporter.check(self.metadata is None,
427 'Unexpected metadata')
430 class CheckIndex(CheckBase):
431 """Check the main index page."""
433 def __init__(self, args, filename, metadata, metadata_len, text, lines, doc):
434 super().__init__(args, filename, metadata, metadata_len, text, lines, doc)
435 self.layout = 'lesson'
437 def check_metadata(self):
438 super().check_metadata()
439 self.reporter.check(self.metadata.get('root', '') == '.',
441 'Root not set to "."')
444 class CheckEpisode(CheckBase):
445 """Check an episode page."""
448 """Run extra tests."""
451 self.check_reference_inclusion()
453 def check_metadata(self):
454 super().check_metadata()
456 if 'layout' in self.metadata:
457 if self.metadata['layout'] == 'break':
458 self.check_metadata_fields(BREAK_METADATA_FIELDS)
460 self.reporter.add(self.filename,
461 'Unknown episode layout "{0}"',
462 self.metadata['layout'])
464 self.check_metadata_fields(TEACHING_METADATA_FIELDS)
466 def check_metadata_fields(self, expected):
467 """Check metadata fields."""
468 for (name, type_) in expected:
469 if name not in self.metadata:
470 self.reporter.add(self.filename,
471 'Missing metadata field {0}',
473 elif not isinstance(self.metadata[name], type_):
474 self.reporter.add(self.filename,
475 '"{0}" has wrong type in metadata ({1} instead of {2})',
476 name, type(self.metadata[name]), type_)
478 def check_reference_inclusion(self):
479 """Check that links file has been included."""
481 if not self.args.reference_path:
484 for (i, last_line, line_len) in reversed(self.lines):
489 'No non-empty lines in {0}'.format(self.filename))
491 include_filename = os.path.split(self.args.reference_path)[-1]
492 if include_filename not in last_line:
493 self.reporter.add(self.filename,
494 'episode does not include "{0}"',
498 class CheckReference(CheckBase):
499 """Check the reference page."""
501 def __init__(self, args, filename, metadata, metadata_len, text, lines, doc):
502 super().__init__(args, filename, metadata, metadata_len, text, lines, doc)
503 self.layout = 'reference'
506 class CheckGeneric(CheckBase):
507 """Check a generic page."""
509 def __init__(self, args, filename, metadata, metadata_len, text, lines, doc):
510 super().__init__(args, filename, metadata, metadata_len, text, lines, doc)
515 (re.compile(r'CONTRIBUTING\.md'), CheckNonJekyll),
516 (re.compile(r'README\.md'), CheckNonJekyll),
517 (re.compile(r'index\.md'), CheckIndex),
518 (re.compile(r'reference\.md'), CheckReference),
519 (re.compile(r'_episodes/.*\.md'), CheckEpisode),
520 (re.compile(r'.*\.md'), CheckGeneric)
524 if __name__ == '__main__':