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