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