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