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