3a43ba37467c5377dd351a1e143653e351fcd812
[rnaseq-cwl-training.git] / bin / lesson_check.py
1 #!/usr/bin/env python
2
3 """
4 Check lesson files and their contents.
5 """
6
7 import sys
8 import os
9 import glob
10 import json
11 import re
12 from optparse import OptionParser
13
14 from util import Reporter, read_markdown, load_yaml, check_unwanted_files, require
15
16 __version__ = '0.2'
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 specially.
26 # This list must include all the Markdown files listed in the 'bin/initialize' script.
27 REQUIRED_FILES = {
28     '%/CONDUCT.md': True,
29     '%/CONTRIBUTING.md': False,
30     '%/LICENSE.md': True,
31     '%/README.md': False,
32     '%/_extras/discuss.md': True,
33     '%/_extras/figures.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 # What kinds of blockquotes are allowed?
50 KNOWN_BLOCKQUOTES = {
51     'callout',
52     'challenge',
53     'checklist',
54     'discussion',
55     'keypoints',
56     'objectives',
57     'prereq',
58     'quotation',
59     'solution',
60     'testimonial'
61 }
62
63 # What kinds of code fragments are allowed?
64 KNOWN_CODEBLOCKS = {
65     'error',
66     'output',
67     'source',
68     'bash',
69     'make',
70     'python',
71     'r',
72     'sql'
73 }
74
75 # What fields are required in teaching episode metadata?
76 TEACHING_METADATA_FIELDS = {
77     ('title', str),
78     ('teaching', int),
79     ('exercises', int),
80     ('questions', list),
81     ('objectives', list),
82     ('keypoints', list)
83 }
84
85 # What fields are required in break episode metadata?
86 BREAK_METADATA_FIELDS = {
87     ('layout', str),
88     ('title', str),
89     ('break', int)
90 }
91
92 # How long are lines allowed to be?
93 MAX_LINE_LEN = 100
94
95 def main():
96     """Main driver."""
97
98     args = parse_args()
99     args.reporter = Reporter()
100     check_config(args.reporter, args.source_dir)
101     docs = read_all_markdown(args.source_dir, args.parser)
102     check_fileset(args.source_dir, args.reporter, docs.keys())
103     check_unwanted_files(args.source_dir, args.reporter)
104     for filename in docs.keys():
105         checker = create_checker(args, filename, docs[filename])
106         checker.check()
107     check_figures(args.source_dir, args.reporter)
108     args.reporter.report()
109
110
111 def parse_args():
112     """Parse command-line arguments."""
113
114     parser = OptionParser()
115     parser.add_option('-l', '--linelen',
116                       default=False,
117                       action="store_true",
118                       dest='line_lengths',
119                       help='Check line lengths')
120     parser.add_option('-p', '--parser',
121                       default=None,
122                       dest='parser',
123                       help='path to Markdown parser')
124     parser.add_option('-s', '--source',
125                       default=os.curdir,
126                       dest='source_dir',
127                       help='source directory')
128     parser.add_option('-w', '--whitespace',
129                       default=False,
130                       action="store_true",
131                       dest='trailing_whitespace',
132                       help='Check for trailing whitespace')
133
134     args, extras = parser.parse_args()
135     require(args.parser is not None,
136             'Path to Markdown parser not provided')
137     require(not extras,
138             'Unexpected trailing command-line arguments "{0}"'.format(extras))
139
140     return args
141
142
143 def check_config(reporter, source_dir):
144     """Check configuration file."""
145
146     config_file = os.path.join(source_dir, '_config.yml')
147     config = load_yaml(config_file)
148     reporter.check_field(config_file, 'configuration', config, 'kind', 'lesson')
149     reporter.check_field(config_file, 'configuration', config, 'carpentry', ('swc', 'dc'))
150     reporter.check_field(config_file, 'configuration', config, 'title')
151     reporter.check_field(config_file, 'configuration', config, 'email')
152     reporter.check_field(config_file, 'configuration', config, 'repo')
153     reporter.check_field(config_file, 'configuration', config, 'root')
154     if ('repo' in config) and ('root' in config):
155         reporter.check(config['repo'].endswith(config['root']),
156                        config_file,
157                        'Repository name "{0}" not consistent with root "{1}"',
158                        config['repo'], config['root'])
159
160
161 def read_all_markdown(source_dir, parser):
162     """Read source files, returning
163     {path : {'metadata':yaml, 'metadata_len':N, 'text':text, 'lines':[(i, line, len)], 'doc':doc}}
164     """
165
166     all_dirs = [os.path.join(source_dir, d) for d in SOURCE_DIRS]
167     all_patterns = [os.path.join(d, '*.md') for d in all_dirs]
168     result = {}
169     for pat in all_patterns:
170         for filename in glob.glob(pat):
171             data = read_markdown(parser, filename)
172             if data:
173                 result[filename] = data
174     return result
175
176
177 def check_fileset(source_dir, reporter, filenames_present):
178     """Are all required files present? Are extraneous files present?"""
179
180     # Check files with predictable names.
181     required = [p.replace('%', source_dir) for p in REQUIRED_FILES]
182     missing = set(required) - set(filenames_present)
183     for m in missing:
184         reporter.add(None, 'Missing required file {0}', m)
185
186     # Check episode files' names.
187     seen = []
188     for filename in filenames_present:
189         if '_episodes' not in filename:
190             continue
191         m = P_EPISODE_FILENAME.search(filename)
192         if m and m.group(1):
193             seen.append(m.group(1))
194         else:
195             reporter.add(None, 'Episode {0} has badly-formatted filename', filename)
196
197     # Check for duplicate episode numbers.
198     reporter.check(len(seen) == len(set(seen)),
199                         None,
200                         'Duplicate episode numbers {0} vs {1}',
201                         sorted(seen), sorted(set(seen)))
202
203     # Check that numbers are consecutive.
204     seen = [int(s) for s in seen]
205     seen.sort()
206     clean = True
207     for i in range(len(seen) - 1):
208         clean = clean and ((seen[i+1] - seen[i]) == 1)
209     reporter.check(clean,
210                    None,
211                    'Missing or non-consecutive episode numbers {0}',
212                    seen)
213
214
215 def check_figures(source_dir, reporter):
216     """Check that all figures are present and referenced."""
217
218     # Get references.
219     try:
220         all_figures_html = os.path.join(source_dir, '_includes', 'all_figures.html')
221         with open(all_figures_html, 'r') as reader:
222             text = reader.read()
223         figures = P_FIGURE_REFS.findall(text)
224         referenced = [os.path.split(f)[1] for f in figures if '/fig/' in f]
225     except FileNotFoundError as e:
226         reporter.add(all_figures_html,
227                      'File not found')
228         return
229
230     # Get actual files.
231     fig_dir_path = os.path.join(source_dir, 'fig')
232     actual = [f for f in os.listdir(fig_dir_path) if not f.startswith('.')]
233
234     # Report differences.
235     unexpected = set(actual) - set(referenced)
236     reporter.check(not unexpected,
237                    None,
238                    'Unexpected image files: {0}',
239                    ', '.join(sorted(unexpected)))
240     missing = set(referenced) - set(actual)
241     reporter.check(not missing,
242                    None,
243                    'Missing image files: {0}',
244                    ', '.join(sorted(missing)))
245
246
247 def create_checker(args, filename, info):
248     """Create appropriate checker for file."""
249
250     for (pat, cls) in CHECKERS:
251         if pat.search(filename):
252             return cls(args, filename, **info)
253
254
255 class CheckBase(object):
256     """Base class for checking Markdown files."""
257
258     def __init__(self, args, filename, metadata, metadata_len, text, lines, doc):
259         """Cache arguments for checking."""
260
261         super(CheckBase, self).__init__()
262         self.args = args
263         self.reporter = self.args.reporter # for convenience
264         self.filename = filename
265         self.metadata = metadata
266         self.metadata_len = metadata_len
267         self.text = text
268         self.lines = lines
269         self.doc = doc
270
271         self.layout = None
272
273
274     def check(self):
275         """Run tests on metadata."""
276
277         self.check_metadata()
278         self.check_line_lengths()
279         self.check_trailing_whitespace()
280         self.check_blockquote_classes()
281         self.check_codeblock_classes()
282
283
284     def check_metadata(self):
285         """Check the YAML metadata."""
286
287         self.reporter.check(self.metadata is not None,
288                             self.filename,
289                             'Missing metadata entirely')
290
291         if self.metadata and (self.layout is not None):
292             self.reporter.check_field(self.filename, 'metadata', self.metadata, 'layout', self.layout)
293
294
295     def check_line_lengths(self):
296         """Check the raw text of the lesson body."""
297
298         if self.args.line_lengths:
299             over = [i for (i, l, n) in self.lines if (n > MAX_LINE_LEN) and (not l.startswith('!'))]
300             self.reporter.check(not over,
301                                 self.filename,
302                                 'Line(s) are too long: {0}',
303                                 ', '.join([str(i) for i in over]))
304
305
306     def check_trailing_whitespace(self):
307         """Check for whitespace at the ends of lines."""
308
309         if self.args.trailing_whitespace:
310             trailing = [i for (i, l, n) in self.lines if P_TRAILING_WHITESPACE.match(l)]
311             self.reporter.check(not trailing,
312                                 self.filename,
313                                 'Line(s) end with whitespace: {0}',
314                                 ', '.join([str(i) for i in trailing]))
315
316
317     def check_blockquote_classes(self):
318         """Check that all blockquotes have known classes."""
319
320         for node in self.find_all(self.doc, {'type' : 'blockquote'}):
321             cls = self.get_val(node, 'attr', 'class')
322             self.reporter.check(cls in KNOWN_BLOCKQUOTES,
323                                 (self.filename, self.get_loc(node)),
324                                 'Unknown or missing blockquote type {0}',
325                                 cls)
326
327
328     def check_codeblock_classes(self):
329         """Check that all code blocks have known classes."""
330
331         for node in self.find_all(self.doc, {'type' : 'codeblock'}):
332             cls = self.get_val(node, 'attr', 'class')
333             self.reporter.check(cls in KNOWN_CODEBLOCKS,
334                                 (self.filename, self.get_loc(node)),
335                                 'Unknown or missing code block type {0}',
336                                 cls)
337
338
339     def find_all(self, node, pattern, accum=None):
340         """Find all matches for a pattern."""
341
342         assert type(pattern) == dict, 'Patterns must be dictionaries'
343         if accum is None:
344             accum = []
345         if self.match(node, pattern):
346             accum.append(node)
347         for child in node.get('children', []):
348             self.find_all(child, pattern, accum)
349         return accum
350
351
352     def match(self, node, pattern):
353         """Does this node match the given pattern?"""
354
355         for key in pattern:
356             if key not in node:
357                 return False
358             val = pattern[key]
359             if type(val) == str:
360                 if node[key] != val:
361                     return False
362             elif type(val) == dict:
363                 if not self.match(node[key], val):
364                     return False
365         return True
366
367
368     def get_val(self, node, *chain):
369         """Get value one or more levels down."""
370
371         curr = node
372         for selector in chain:
373             curr = curr.get(selector, None)
374             if curr is None:
375                 break
376         return curr
377
378
379     def get_loc(self, node):
380         """Convenience method to get node's line number."""
381
382         result = self.get_val(node, 'options', 'location')
383         if self.metadata_len is not None:
384             result += self.metadata_len
385         return result
386
387
388 class CheckNonJekyll(CheckBase):
389     """Check a file that isn't translated by Jekyll."""
390
391     def __init__(self, args, filename, metadata, metadata_len, text, lines, doc):
392         super(CheckNonJekyll, self).__init__(args, filename, metadata, metadata_len, text, lines, doc)
393
394
395     def check_metadata(self):
396         self.reporter.check(self.metadata is None,
397                             self.filename,
398                             'Unexpected metadata')
399
400
401 class CheckIndex(CheckBase):
402     """Check the main index page."""
403
404     def __init__(self, args, filename, metadata, metadata_len, text, lines, doc):
405         super(CheckIndex, self).__init__(args, filename, metadata, metadata_len, text, lines, doc)
406         self.layout = 'lesson'
407
408
409 class CheckEpisode(CheckBase):
410     """Check an episode page."""
411
412     def __init__(self, args, filename, metadata, metadata_len, text, lines, doc):
413         super(CheckEpisode, self).__init__(args, filename, metadata, metadata_len, text, lines, doc)
414
415     def check_metadata(self):
416         super(CheckEpisode, self).check_metadata()
417         if self.metadata:
418             if 'layout' in self.metadata:
419                 if self.metadata['layout'] == 'break':
420                     self.check_metadata_fields(BREAK_METADATA_FIELDS)
421                 else:
422                     self.reporter.add(self.filename,
423                                       'Unknown episode layout "{0}"',
424                                       self.metadata['layout'])
425             else:
426                 self.check_metadata_fields(TEACHING_METADATA_FIELDS)
427
428
429     def check_metadata_fields(self, expected):
430         for (name, type_) in expected:
431             if name not in self.metadata:
432                 self.reporter.add(self.filename,
433                                   'Missing metadata field {0}',
434                                   name)
435             elif type(self.metadata[name]) != type_:
436                 self.reporter.add(self.filename,
437                                   '"{0}" has wrong type in metadata ({1} instead of {2})',
438                                   name, type(self.metadata[name]), type_)
439
440
441 class CheckReference(CheckBase):
442     """Check the reference page."""
443
444     def __init__(self, args, filename, metadata, metadata_len, text, lines, doc):
445         super(CheckReference, self).__init__(args, filename, metadata, metadata_len, text, lines, doc)
446         self.layout = 'reference'
447
448
449 class CheckGeneric(CheckBase):
450     """Check a generic page."""
451
452     def __init__(self, args, filename, metadata, metadata_len, text, lines, doc):
453         super(CheckGeneric, self).__init__(args, filename, metadata, metadata_len, text, lines, doc)
454         self.layout = 'page'
455
456
457 CHECKERS = [
458     (re.compile(r'CONTRIBUTING\.md'), CheckNonJekyll),
459     (re.compile(r'README\.md'), CheckNonJekyll),
460     (re.compile(r'index\.md'), CheckIndex),
461     (re.compile(r'reference\.md'), CheckReference),
462     (re.compile(r'_episodes/.*\.md'), CheckEpisode),
463     (re.compile(r'.*\.md'), CheckGeneric)
464 ]
465
466
467 if __name__ == '__main__':
468     main()