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 # Where to look for source Rmd files.
22 SOURCE_RMD_DIRS = ['_episodes_rmd']
24 # Required files: each entry is ('path': YAML_required).
25 # FIXME: We do not yet validate whether any files have the required
26 # YAML headers, but should in the future.
27 # The '%' is replaced with the source directory path for checking.
28 # Episodes are handled specially, and extra files in '_extras' are also handled
29 # specially. This list must include all the Markdown files listed in the
30 # 'bin/initialize' script.
32 '%/CODE_OF_CONDUCT.md': True,
33 '%/CONTRIBUTING.md': False,
36 '%/_extras/discuss.md': True,
37 '%/_extras/guide.md': True,
39 '%/reference.md': True,
43 # Episode filename pattern.
44 P_EPISODE_FILENAME = re.compile(r'/_episodes/(\d\d)-[-\w]+.md$')
46 # Pattern to match lines ending with whitespace.
47 P_TRAILING_WHITESPACE = re.compile(r'\s+$')
49 # Pattern to match figure references in HTML.
50 P_FIGURE_REFS = re.compile(r'<img[^>]+src="([^"]+)"[^>]*>')
52 # Pattern to match internally-defined Markdown links.
53 P_INTERNAL_LINK_REF = re.compile(r'\[([^\]]+)\]\[([^\]]+)\]')
55 # Pattern to match reference links (to resolve internally-defined references).
56 P_INTERNAL_LINK_DEF = re.compile(r'^\[([^\]]+)\]:\s*(.+)')
58 # What kinds of blockquotes are allowed?
72 # What kinds of code fragments are allowed?
87 # What fields are required in teaching episode metadata?
88 TEACHING_METADATA_FIELDS = {
97 # What fields are required in break episode metadata?
98 BREAK_METADATA_FIELDS = {
104 # How long are lines allowed to be?
105 # Please keep this in sync with .editorconfig!
113 args.reporter = Reporter()
114 check_config(args.reporter, args.source_dir)
115 check_source_rmd(args.reporter, args.source_dir, args.parser)
116 args.references = read_references(args.reporter, args.reference_path)
118 docs = read_all_markdown(args.source_dir, args.parser)
119 check_fileset(args.source_dir, args.reporter, list(docs.keys()))
120 check_unwanted_files(args.source_dir, args.reporter)
121 for filename in list(docs.keys()):
122 checker = create_checker(args, filename, docs[filename])
125 args.reporter.report()
126 if args.reporter.messages and not args.permissive:
131 """Parse command-line arguments."""
133 parser = ArgumentParser(description="""Check episode files in a lesson.""")
134 parser.add_argument('-l', '--linelen',
138 help='Check line lengths')
139 parser.add_argument('-p', '--parser',
142 help='path to Markdown parser')
143 parser.add_argument('-r', '--references',
145 dest='reference_path',
146 help='path to Markdown file of external references')
147 parser.add_argument('-s', '--source',
150 help='source directory')
151 parser.add_argument('-w', '--whitespace',
154 dest='trailing_whitespace',
155 help='Check for trailing whitespace')
156 parser.add_argument('--permissive',
160 help='Do not raise an error even if issues are detected')
162 args, extras = parser.parse_known_args()
163 require(args.parser is not None,
164 'Path to Markdown parser not provided')
166 'Unexpected trailing command-line arguments "{0}"'.format(extras))
171 def check_config(reporter, source_dir):
172 """Check configuration file."""
174 config_file = os.path.join(source_dir, '_config.yml')
175 config = load_yaml(config_file)
176 reporter.check_field(config_file, 'configuration',
177 config, 'kind', 'lesson')
178 reporter.check_field(config_file, 'configuration',
179 config, 'carpentry', ('swc', 'dc', 'lc', 'cp'))
180 reporter.check_field(config_file, 'configuration', config, 'title')
181 reporter.check_field(config_file, 'configuration', config, 'email')
184 {'values': {'root': '.', 'layout': 'page'}},
185 {'values': {'root': '..', 'layout': 'episode'}, 'scope': {'type': 'episodes', 'path': ''}},
186 {'values': {'root': '..', 'layout': 'page'}, 'scope': {'type': 'extras', 'path': ''}}
188 reporter.check(defaults in config.get('defaults', []),
190 '"root" not set to "." in configuration')
192 def check_source_rmd(reporter, source_dir, parser):
193 """Check that Rmd episode files include `source: Rmd`"""
195 episode_rmd_dir = [os.path.join(source_dir, d) for d in SOURCE_RMD_DIRS]
196 episode_rmd_files = [os.path.join(d, '*.Rmd') for d in episode_rmd_dir]
198 for pat in episode_rmd_files:
199 for f in glob.glob(pat):
200 data = read_markdown(parser, f)
201 dy = data['metadata']
203 reporter.check_field(f, 'episode_rmd',
206 def read_references(reporter, ref_path):
207 """Read shared file of reference links, returning dictionary of valid references
208 {symbolic_name : URL}
214 with open(ref_path, 'r') as reader:
215 for (num, line) in enumerate(reader):
217 m = P_INTERNAL_LINK_DEF.search(line)
219 '{0}:{1} not valid reference:\n{2}'.format(ref_path, line_num, line.rstrip()))
223 'Empty reference at {0}:{1}'.format(ref_path, line_num))
224 reporter.check(name not in result,
226 'Duplicate reference {0} at line {1}',
228 reporter.check(url not in urls_seen,
230 'Duplicate definition of URL {0} at line {1}',
237 def read_all_markdown(source_dir, parser):
238 """Read source files, returning
239 {path : {'metadata':yaml, 'metadata_len':N, 'text':text, 'lines':[(i, line, len)], 'doc':doc}}
242 all_dirs = [os.path.join(source_dir, d) for d in SOURCE_DIRS]
243 all_patterns = [os.path.join(d, '*.md') for d in all_dirs]
245 for pat in all_patterns:
246 for filename in glob.glob(pat):
247 data = read_markdown(parser, filename)
249 result[filename] = data
253 def check_fileset(source_dir, reporter, filenames_present):
254 """Are all required files present? Are extraneous files present?"""
256 # Check files with predictable names.
257 required = [p.replace('%', source_dir) for p in REQUIRED_FILES]
258 missing = set(required) - set(filenames_present)
260 reporter.add(None, 'Missing required file {0}', m)
262 # Check episode files' names.
264 for filename in filenames_present:
265 if '_episodes' not in filename:
267 m = P_EPISODE_FILENAME.search(filename)
269 seen.append(m.group(1))
272 None, 'Episode {0} has badly-formatted filename', filename)
274 # Check for duplicate episode numbers.
275 reporter.check(len(seen) == len(set(seen)),
277 'Duplicate episode numbers {0} vs {1}',
278 sorted(seen), sorted(set(seen)))
280 # Check that numbers are consecutive.
281 seen = sorted([int(s) for s in seen])
283 for i in range(len(seen) - 1):
284 clean = clean and ((seen[i+1] - seen[i]) == 1)
285 reporter.check(clean,
287 'Missing or non-consecutive episode numbers {0}',
291 def create_checker(args, filename, info):
292 """Create appropriate checker for file."""
294 for (pat, cls) in CHECKERS:
295 if pat.search(filename):
296 return cls(args, filename, **info)
297 return NotImplemented
300 """Base class for checking Markdown files."""
302 def __init__(self, args, filename, metadata, metadata_len, text, lines, doc):
303 """Cache arguments for checking."""
306 self.reporter = self.args.reporter # for convenience
307 self.filename = filename
308 self.metadata = metadata
309 self.metadata_len = metadata_len
319 self.check_metadata()
320 self.check_line_lengths()
321 self.check_trailing_whitespace()
322 self.check_blockquote_classes()
323 self.check_codeblock_classes()
324 self.check_defined_link_references()
326 def check_metadata(self):
327 """Check the YAML metadata."""
329 self.reporter.check(self.metadata is not None,
331 'Missing metadata entirely')
333 if self.metadata and (self.layout is not None):
334 self.reporter.check_field(
335 self.filename, 'metadata', self.metadata, 'layout', self.layout)
337 def check_line_lengths(self):
338 """Check the raw text of the lesson body."""
340 if self.args.line_lengths:
341 over = [i for (i, l, n) in self.lines if (
342 n > MAX_LINE_LEN) and (not l.startswith('!'))]
343 self.reporter.check(not over,
345 'Line(s) are too long: {0}',
346 ', '.join([str(i) for i in over]))
348 def check_trailing_whitespace(self):
349 """Check for whitespace at the ends of lines."""
351 if self.args.trailing_whitespace:
353 i for (i, l, n) in self.lines if P_TRAILING_WHITESPACE.match(l)]
354 self.reporter.check(not trailing,
356 'Line(s) end with whitespace: {0}',
357 ', '.join([str(i) for i in trailing]))
359 def check_blockquote_classes(self):
360 """Check that all blockquotes have known classes."""
362 for node in self.find_all(self.doc, {'type': 'blockquote'}):
363 cls = self.get_val(node, 'attr', 'class')
364 self.reporter.check(cls in KNOWN_BLOCKQUOTES,
365 (self.filename, self.get_loc(node)),
366 'Unknown or missing blockquote type {0}',
369 def check_codeblock_classes(self):
370 """Check that all code blocks have known classes."""
372 for node in self.find_all(self.doc, {'type': 'codeblock'}):
373 cls = self.get_val(node, 'attr', 'class')
374 self.reporter.check(cls in KNOWN_CODEBLOCKS,
375 (self.filename, self.get_loc(node)),
376 'Unknown or missing code block type {0}',
379 def check_defined_link_references(self):
380 """Check that defined links resolve in the file.
382 Internally-defined links match the pattern [text][label].
386 for node in self.find_all(self.doc, {'type': 'text'}):
387 for match in P_INTERNAL_LINK_REF.findall(node['value']):
390 if link not in self.args.references:
391 result.add('"{0}"=>"{1}"'.format(text, link))
392 self.reporter.check(not result,
394 'Internally-defined links may be missing definitions: {0}',
395 ', '.join(sorted(result)))
397 def find_all(self, node, pattern, accum=None):
398 """Find all matches for a pattern."""
400 assert isinstance(pattern, dict), 'Patterns must be dictionaries'
403 if self.match(node, pattern):
405 for child in node.get('children', []):
406 self.find_all(child, pattern, accum)
409 def match(self, node, pattern):
410 """Does this node match the given pattern?"""
416 if isinstance(val, str):
419 elif isinstance(val, dict):
420 if not self.match(node[key], val):
425 def get_val(node, *chain):
426 """Get value one or more levels down."""
429 for selector in chain:
430 curr = curr.get(selector, None)
435 def get_loc(self, node):
436 """Convenience method to get node's line number."""
438 result = self.get_val(node, 'options', 'location')
439 if self.metadata_len is not None:
440 result += self.metadata_len
444 class CheckNonJekyll(CheckBase):
445 """Check a file that isn't translated by Jekyll."""
447 def check_metadata(self):
448 self.reporter.check(self.metadata is None,
450 'Unexpected metadata')
453 class CheckIndex(CheckBase):
454 """Check the main index page."""
456 def __init__(self, args, filename, metadata, metadata_len, text, lines, doc):
457 super().__init__(args, filename, metadata, metadata_len, text, lines, doc)
458 self.layout = 'lesson'
460 def check_metadata(self):
461 super().check_metadata()
462 self.reporter.check(self.metadata.get('root', '') == '.',
464 'Root not set to "."')
467 class CheckEpisode(CheckBase):
468 """Check an episode page."""
471 """Run extra tests."""
474 self.check_reference_inclusion()
476 def check_metadata(self):
477 super().check_metadata()
479 if 'layout' in self.metadata:
480 if self.metadata['layout'] == 'break':
481 self.check_metadata_fields(BREAK_METADATA_FIELDS)
483 self.reporter.add(self.filename,
484 'Unknown episode layout "{0}"',
485 self.metadata['layout'])
487 self.check_metadata_fields(TEACHING_METADATA_FIELDS)
489 def check_metadata_fields(self, expected):
490 """Check metadata fields."""
491 for (name, type_) in expected:
492 if name not in self.metadata:
493 self.reporter.add(self.filename,
494 'Missing metadata field {0}',
496 elif not isinstance(self.metadata[name], type_):
497 self.reporter.add(self.filename,
498 '"{0}" has wrong type in metadata ({1} instead of {2})',
499 name, type(self.metadata[name]), type_)
501 def check_reference_inclusion(self):
502 """Check that links file has been included."""
504 if not self.args.reference_path:
507 for (i, last_line, line_len) in reversed(self.lines):
512 'No non-empty lines in {0}'.format(self.filename))
514 include_filename = os.path.split(self.args.reference_path)[-1]
515 if include_filename not in last_line:
516 self.reporter.add(self.filename,
517 'episode does not include "{0}"',
521 class CheckReference(CheckBase):
522 """Check the reference page."""
524 def __init__(self, args, filename, metadata, metadata_len, text, lines, doc):
525 super().__init__(args, filename, metadata, metadata_len, text, lines, doc)
526 self.layout = 'reference'
529 class CheckGeneric(CheckBase):
530 """Check a generic page."""
532 def __init__(self, args, filename, metadata, metadata_len, text, lines, doc):
533 super().__init__(args, filename, metadata, metadata_len, text, lines, doc)
537 (re.compile(r'CONTRIBUTING\.md'), CheckNonJekyll),
538 (re.compile(r'README\.md'), CheckNonJekyll),
539 (re.compile(r'index\.md'), CheckIndex),
540 (re.compile(r'reference\.md'), CheckReference),
541 (re.compile(r'_episodes/.*\.md'), CheckEpisode),
542 (re.compile(r'aio\.md'), CheckNonJekyll),
543 (re.compile(r'.*\.md'), CheckGeneric)
547 if __name__ == '__main__':