lesson_check.py: require _config.yml too
[rnaseq-cwl-training.git] / bin / lesson_check.py
1 #!/usr/bin/env python3
2
3 """
4 Check lesson files and their contents.
5 """
6
7
8 import os
9 import glob
10 import re
11 from argparse import ArgumentParser
12
13 from util import (Reporter, read_markdown, load_yaml, check_unwanted_files,
14                   require)
15
16 __version__ = '0.3'
17
18 # Where to look for source Markdown files.
19 SOURCE_DIRS = ['', '_episodes', '_extras']
20
21 # Where to look for source Rmd files.
22 SOURCE_RMD_DIRS = ['_episodes_rmd']
23
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.
31 REQUIRED_FILES = {
32     '%/CODE_OF_CONDUCT.md': True,
33     '%/CONTRIBUTING.md': False,
34     '%/LICENSE.md': True,
35     '%/README.md': False,
36     '%/_extras/discuss.md': True,
37     '%/_extras/guide.md': True,
38     '%/_config.yml': True,
39     '%/index.md': True,
40     '%/reference.md': True,
41     '%/setup.md': True,
42 }
43
44 # Episode filename pattern.
45 P_EPISODE_FILENAME = re.compile(r'/_episodes/(\d\d)-[-\w]+.md$')
46
47 # Pattern to match lines ending with whitespace.
48 P_TRAILING_WHITESPACE = re.compile(r'\s+$')
49
50 # Pattern to match figure references in HTML.
51 P_FIGURE_REFS = re.compile(r'<img[^>]+src="([^"]+)"[^>]*>')
52
53 # Pattern to match internally-defined Markdown links.
54 P_INTERNAL_LINK_REF = re.compile(r'\[([^\]]+)\]\[([^\]]+)\]')
55
56 # Pattern to match reference links (to resolve internally-defined references).
57 P_INTERNAL_LINK_DEF = re.compile(r'^\[([^\]]+)\]:\s*(.+)')
58
59 # What kinds of blockquotes are allowed?
60 KNOWN_BLOCKQUOTES = {
61     'callout',
62     'challenge',
63     'checklist',
64     'discussion',
65     'keypoints',
66     'objectives',
67     'prereq',
68     'quotation',
69     'solution',
70     'testimonial'
71 }
72
73 # What kinds of code fragments are allowed?
74 KNOWN_CODEBLOCKS = {
75     'error',
76     'output',
77     'source',
78     'language-bash',
79     'html',
80     'language-make',
81     'language-matlab',
82     'language-python',
83     'language-r',
84     'language-shell',
85     'language-sql'
86 }
87
88 # What fields are required in teaching episode metadata?
89 TEACHING_METADATA_FIELDS = {
90     ('title', str),
91     ('teaching', int),
92     ('exercises', int),
93     ('questions', list),
94     ('objectives', list),
95     ('keypoints', list)
96 }
97
98 # What fields are required in break episode metadata?
99 BREAK_METADATA_FIELDS = {
100     ('layout', str),
101     ('title', str),
102     ('break', int)
103 }
104
105 # How long are lines allowed to be?
106 # Please keep this in sync with .editorconfig!
107 MAX_LINE_LEN = 100
108
109
110 def main():
111     """Main driver."""
112
113     args = parse_args()
114     args.reporter = Reporter()
115     check_config(args.reporter, args.source_dir)
116     check_source_rmd(args.reporter, args.source_dir, args.parser)
117     args.references = read_references(args.reporter, args.reference_path)
118
119     docs = read_all_markdown(args.source_dir, args.parser)
120     check_fileset(args.source_dir, args.reporter, list(docs.keys()))
121     check_unwanted_files(args.source_dir, args.reporter)
122     for filename in list(docs.keys()):
123         checker = create_checker(args, filename, docs[filename])
124         checker.check()
125
126     args.reporter.report()
127     if args.reporter.messages and not args.permissive:
128         exit(1)
129
130
131 def parse_args():
132     """Parse command-line arguments."""
133
134     parser = ArgumentParser(description="""Check episode files in a lesson.""")
135     parser.add_argument('-l', '--linelen',
136                         default=False,
137                         action="store_true",
138                         dest='line_lengths',
139                         help='Check line lengths')
140     parser.add_argument('-p', '--parser',
141                         default=None,
142                         dest='parser',
143                         help='path to Markdown parser')
144     parser.add_argument('-r', '--references',
145                         default=None,
146                         dest='reference_path',
147                         help='path to Markdown file of external references')
148     parser.add_argument('-s', '--source',
149                         default=os.curdir,
150                         dest='source_dir',
151                         help='source directory')
152     parser.add_argument('-w', '--whitespace',
153                         default=False,
154                         action="store_true",
155                         dest='trailing_whitespace',
156                         help='Check for trailing whitespace')
157     parser.add_argument('--permissive',
158                         default=False,
159                         action="store_true",
160                         dest='permissive',
161                         help='Do not raise an error even if issues are detected')
162
163     args, extras = parser.parse_known_args()
164     require(args.parser is not None,
165             'Path to Markdown parser not provided')
166     require(not extras,
167             'Unexpected trailing command-line arguments "{0}"'.format(extras))
168
169     return args
170
171
172 def check_config(reporter, source_dir):
173     """Check configuration file."""
174
175     config_file = os.path.join(source_dir, '_config.yml')
176     config = load_yaml(config_file)
177     reporter.check_field(config_file, 'configuration',
178                          config, 'kind', 'lesson')
179     reporter.check_field(config_file, 'configuration',
180                          config, 'carpentry', ('swc', 'dc', 'lc', 'cp'))
181     reporter.check_field(config_file, 'configuration', config, 'title')
182     reporter.check_field(config_file, 'configuration', config, 'email')
183
184     for defaults in [
185             {'values': {'root': '.', 'layout': 'page'}},
186             {'values': {'root': '..', 'layout': 'episode'}, 'scope': {'type': 'episodes', 'path': ''}},
187             {'values': {'root': '..', 'layout': 'page'}, 'scope': {'type': 'extras', 'path': ''}}
188             ]:
189         reporter.check(defaults in config.get('defaults', []),
190                    'configuration',
191                    '"root" not set to "." in configuration')
192
193 def check_source_rmd(reporter, source_dir, parser):
194     """Check that Rmd episode files include `source: Rmd`"""
195
196     episode_rmd_dir = [os.path.join(source_dir, d) for d in SOURCE_RMD_DIRS]
197     episode_rmd_files = [os.path.join(d, '*.Rmd') for d in episode_rmd_dir]
198     results = {}
199     for pat in episode_rmd_files:
200         for f in glob.glob(pat):
201             data = read_markdown(parser, f)
202             dy = data['metadata']
203             if dy:
204                 reporter.check_field(f, 'episode_rmd',
205                                      dy, 'source', 'Rmd')
206
207 def read_references(reporter, ref_path):
208     """Read shared file of reference links, returning dictionary of valid references
209     {symbolic_name : URL}
210     """
211
212     result = {}
213     urls_seen = set()
214     if ref_path:
215         with open(ref_path, 'r') as reader:
216             for (num, line) in enumerate(reader):
217                 line_num = num + 1
218                 m = P_INTERNAL_LINK_DEF.search(line)
219                 require(m,
220                         '{0}:{1} not valid reference:\n{2}'.format(ref_path, line_num, line.rstrip()))
221                 name = m.group(1)
222                 url = m.group(2)
223                 require(name,
224                         'Empty reference at {0}:{1}'.format(ref_path, line_num))
225                 reporter.check(name not in result,
226                                ref_path,
227                                'Duplicate reference {0} at line {1}',
228                                name, line_num)
229                 reporter.check(url not in urls_seen,
230                                ref_path,
231                                'Duplicate definition of URL {0} at line {1}',
232                                url, line_num)
233                 result[name] = url
234                 urls_seen.add(url)
235     return result
236
237
238 def read_all_markdown(source_dir, parser):
239     """Read source files, returning
240     {path : {'metadata':yaml, 'metadata_len':N, 'text':text, 'lines':[(i, line, len)], 'doc':doc}}
241     """
242
243     all_dirs = [os.path.join(source_dir, d) for d in SOURCE_DIRS]
244     all_patterns = [os.path.join(d, '*.md') for d in all_dirs]
245     result = {}
246     for pat in all_patterns:
247         for filename in glob.glob(pat):
248             data = read_markdown(parser, filename)
249             if data:
250                 result[filename] = data
251     return result
252
253
254 def check_fileset(source_dir, reporter, filenames_present):
255     """Are all required files present? Are extraneous files present?"""
256
257     # Check files with predictable names.
258     required = [p.replace('%', source_dir) for p in REQUIRED_FILES]
259     missing = set(required) - set(filenames_present)
260     for m in missing:
261         reporter.add(None, 'Missing required file {0}', m)
262
263     # Check episode files' names.
264     seen = []
265     for filename in filenames_present:
266         if '_episodes' not in filename:
267             continue
268         m = P_EPISODE_FILENAME.search(filename)
269         if m and m.group(1):
270             seen.append(m.group(1))
271         else:
272             reporter.add(
273                 None, 'Episode {0} has badly-formatted filename', filename)
274
275     # Check for duplicate episode numbers.
276     reporter.check(len(seen) == len(set(seen)),
277                    None,
278                    'Duplicate episode numbers {0} vs {1}',
279                    sorted(seen), sorted(set(seen)))
280
281     # Check that numbers are consecutive.
282     seen = sorted([int(s) for s in seen])
283     clean = True
284     for i in range(len(seen) - 1):
285         clean = clean and ((seen[i+1] - seen[i]) == 1)
286     reporter.check(clean,
287                    None,
288                    'Missing or non-consecutive episode numbers {0}',
289                    seen)
290
291
292 def create_checker(args, filename, info):
293     """Create appropriate checker for file."""
294
295     for (pat, cls) in CHECKERS:
296         if pat.search(filename):
297             return cls(args, filename, **info)
298     return NotImplemented
299
300 class CheckBase:
301     """Base class for checking Markdown files."""
302
303     def __init__(self, args, filename, metadata, metadata_len, text, lines, doc):
304         """Cache arguments for checking."""
305
306         self.args = args
307         self.reporter = self.args.reporter  # for convenience
308         self.filename = filename
309         self.metadata = metadata
310         self.metadata_len = metadata_len
311         self.text = text
312         self.lines = lines
313         self.doc = doc
314
315         self.layout = None
316
317     def check(self):
318         """Run tests."""
319
320         self.check_metadata()
321         self.check_line_lengths()
322         self.check_trailing_whitespace()
323         self.check_blockquote_classes()
324         self.check_codeblock_classes()
325         self.check_defined_link_references()
326
327     def check_metadata(self):
328         """Check the YAML metadata."""
329
330         self.reporter.check(self.metadata is not None,
331                             self.filename,
332                             'Missing metadata entirely')
333
334         if self.metadata and (self.layout is not None):
335             self.reporter.check_field(
336                 self.filename, 'metadata', self.metadata, 'layout', self.layout)
337
338     def check_line_lengths(self):
339         """Check the raw text of the lesson body."""
340
341         if self.args.line_lengths:
342             over = [i for (i, l, n) in self.lines if (
343                 n > MAX_LINE_LEN) and (not l.startswith('!'))]
344             self.reporter.check(not over,
345                                 self.filename,
346                                 'Line(s) are too long: {0}',
347                                 ', '.join([str(i) for i in over]))
348
349     def check_trailing_whitespace(self):
350         """Check for whitespace at the ends of lines."""
351
352         if self.args.trailing_whitespace:
353             trailing = [
354                 i for (i, l, n) in self.lines if P_TRAILING_WHITESPACE.match(l)]
355             self.reporter.check(not trailing,
356                                 self.filename,
357                                 'Line(s) end with whitespace: {0}',
358                                 ', '.join([str(i) for i in trailing]))
359
360     def check_blockquote_classes(self):
361         """Check that all blockquotes have known classes."""
362
363         for node in self.find_all(self.doc, {'type': 'blockquote'}):
364             cls = self.get_val(node, 'attr', 'class')
365             self.reporter.check(cls in KNOWN_BLOCKQUOTES,
366                                 (self.filename, self.get_loc(node)),
367                                 'Unknown or missing blockquote type {0}',
368                                 cls)
369
370     def check_codeblock_classes(self):
371         """Check that all code blocks have known classes."""
372
373         for node in self.find_all(self.doc, {'type': 'codeblock'}):
374             cls = self.get_val(node, 'attr', 'class')
375             self.reporter.check(cls in KNOWN_CODEBLOCKS,
376                                 (self.filename, self.get_loc(node)),
377                                 'Unknown or missing code block type {0}',
378                                 cls)
379
380     def check_defined_link_references(self):
381         """Check that defined links resolve in the file.
382
383         Internally-defined links match the pattern [text][label].
384         """
385
386         result = set()
387         for node in self.find_all(self.doc, {'type': 'text'}):
388             for match in P_INTERNAL_LINK_REF.findall(node['value']):
389                 text = match[0]
390                 link = match[1]
391                 if link not in self.args.references:
392                     result.add('"{0}"=>"{1}"'.format(text, link))
393         self.reporter.check(not result,
394                             self.filename,
395                             'Internally-defined links may be missing definitions: {0}',
396                             ', '.join(sorted(result)))
397
398     def find_all(self, node, pattern, accum=None):
399         """Find all matches for a pattern."""
400
401         assert isinstance(pattern, dict), 'Patterns must be dictionaries'
402         if accum is None:
403             accum = []
404         if self.match(node, pattern):
405             accum.append(node)
406         for child in node.get('children', []):
407             self.find_all(child, pattern, accum)
408         return accum
409
410     def match(self, node, pattern):
411         """Does this node match the given pattern?"""
412
413         for key in pattern:
414             if key not in node:
415                 return False
416             val = pattern[key]
417             if isinstance(val, str):
418                 if node[key] != val:
419                     return False
420             elif isinstance(val, dict):
421                 if not self.match(node[key], val):
422                     return False
423         return True
424
425     @staticmethod
426     def get_val(node, *chain):
427         """Get value one or more levels down."""
428
429         curr = node
430         for selector in chain:
431             curr = curr.get(selector, None)
432             if curr is None:
433                 break
434         return curr
435
436     def get_loc(self, node):
437         """Convenience method to get node's line number."""
438
439         result = self.get_val(node, 'options', 'location')
440         if self.metadata_len is not None:
441             result += self.metadata_len
442         return result
443
444
445 class CheckNonJekyll(CheckBase):
446     """Check a file that isn't translated by Jekyll."""
447
448     def check_metadata(self):
449         self.reporter.check(self.metadata is None,
450                             self.filename,
451                             'Unexpected metadata')
452
453
454 class CheckIndex(CheckBase):
455     """Check the main index page."""
456
457     def __init__(self, args, filename, metadata, metadata_len, text, lines, doc):
458         super().__init__(args, filename, metadata, metadata_len, text, lines, doc)
459         self.layout = 'lesson'
460
461     def check_metadata(self):
462         super().check_metadata()
463         self.reporter.check(self.metadata.get('root', '') == '.',
464                             self.filename,
465                             'Root not set to "."')
466
467
468 class CheckEpisode(CheckBase):
469     """Check an episode page."""
470
471     def check(self):
472         """Run extra tests."""
473
474         super().check()
475         self.check_reference_inclusion()
476
477     def check_metadata(self):
478         super().check_metadata()
479         if self.metadata:
480             if 'layout' in self.metadata:
481                 if self.metadata['layout'] == 'break':
482                     self.check_metadata_fields(BREAK_METADATA_FIELDS)
483                 else:
484                     self.reporter.add(self.filename,
485                                       'Unknown episode layout "{0}"',
486                                       self.metadata['layout'])
487             else:
488                 self.check_metadata_fields(TEACHING_METADATA_FIELDS)
489
490     def check_metadata_fields(self, expected):
491         """Check metadata fields."""
492         for (name, type_) in expected:
493             if name not in self.metadata:
494                 self.reporter.add(self.filename,
495                                   'Missing metadata field {0}',
496                                   name)
497             elif not isinstance(self.metadata[name], type_):
498                 self.reporter.add(self.filename,
499                                   '"{0}" has wrong type in metadata ({1} instead of {2})',
500                                   name, type(self.metadata[name]), type_)
501
502     def check_reference_inclusion(self):
503         """Check that links file has been included."""
504
505         if not self.args.reference_path:
506             return
507
508         for (i, last_line, line_len) in reversed(self.lines):
509             if last_line:
510                 break
511
512         require(last_line,
513                 'No non-empty lines in {0}'.format(self.filename))
514
515         include_filename = os.path.split(self.args.reference_path)[-1]
516         if include_filename not in last_line:
517             self.reporter.add(self.filename,
518                               'episode does not include "{0}"',
519                               include_filename)
520
521
522 class CheckReference(CheckBase):
523     """Check the reference page."""
524
525     def __init__(self, args, filename, metadata, metadata_len, text, lines, doc):
526         super().__init__(args, filename, metadata, metadata_len, text, lines, doc)
527         self.layout = 'reference'
528
529
530 class CheckGeneric(CheckBase):
531     """Check a generic page."""
532
533     def __init__(self, args, filename, metadata, metadata_len, text, lines, doc):
534         super().__init__(args, filename, metadata, metadata_len, text, lines, doc)
535
536
537 CHECKERS = [
538     (re.compile(r'CONTRIBUTING\.md'), CheckNonJekyll),
539     (re.compile(r'README\.md'), CheckNonJekyll),
540     (re.compile(r'index\.md'), CheckIndex),
541     (re.compile(r'reference\.md'), CheckReference),
542     (re.compile(r'_episodes/.*\.md'), CheckEpisode),
543     (re.compile(r'aio\.md'), CheckNonJekyll),
544     (re.compile(r'.*\.md'), CheckGeneric)
545 ]
546
547
548 if __name__ == '__main__':
549     main()