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