016b395451659e299cdeb2f60af299cd0f9e96bc
[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
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 def require(condition, message):
256     """Fail if condition not met."""
257
258     if not condition:
259         print(message, file=sys.stderr)
260         sys.exit(1)
261
262
263 class CheckBase(object):
264     """Base class for checking Markdown files."""
265
266     def __init__(self, args, filename, metadata, metadata_len, text, lines, doc):
267         """Cache arguments for checking."""
268
269         super(CheckBase, self).__init__()
270         self.args = args
271         self.reporter = self.args.reporter # for convenience
272         self.filename = filename
273         self.metadata = metadata
274         self.metadata_len = metadata_len
275         self.text = text
276         self.lines = lines
277         self.doc = doc
278
279         self.layout = None
280
281
282     def check(self):
283         """Run tests on metadata."""
284
285         self.check_metadata()
286         self.check_line_lengths()
287         self.check_trailing_whitespace()
288         self.check_blockquote_classes()
289         self.check_codeblock_classes()
290
291
292     def check_metadata(self):
293         """Check the YAML metadata."""
294
295         self.reporter.check(self.metadata is not None,
296                             self.filename,
297                             'Missing metadata entirely')
298
299         if self.metadata and (self.layout is not None):
300             self.reporter.check_field(self.filename, 'metadata', self.metadata, 'layout', self.layout)
301
302
303     def check_line_lengths(self):
304         """Check the raw text of the lesson body."""
305
306         if self.args.line_lengths:
307             over = [i for (i, l, n) in self.lines if (n > MAX_LINE_LEN) and (not l.startswith('!'))]
308             self.reporter.check(not over,
309                                 self.filename,
310                                 'Line(s) are too long: {0}',
311                                 ', '.join([str(i) for i in over]))
312
313
314     def check_trailing_whitespace(self):
315         """Check for whitespace at the ends of lines."""
316
317         if self.args.trailing_whitespace:
318             trailing = [i for (i, l, n) in self.lines if P_TRAILING_WHITESPACE.match(l)]
319             self.reporter.check(not trailing,
320                                 self.filename,
321                                 'Line(s) end with whitespace: {0}',
322                                 ', '.join([str(i) for i in trailing]))
323
324
325     def check_blockquote_classes(self):
326         """Check that all blockquotes have known classes."""
327
328         for node in self.find_all(self.doc, {'type' : 'blockquote'}):
329             cls = self.get_val(node, 'attr', 'class')
330             self.reporter.check(cls in KNOWN_BLOCKQUOTES,
331                                 (self.filename, self.get_loc(node)),
332                                 'Unknown or missing blockquote type {0}',
333                                 cls)
334
335
336     def check_codeblock_classes(self):
337         """Check that all code blocks have known classes."""
338
339         for node in self.find_all(self.doc, {'type' : 'codeblock'}):
340             cls = self.get_val(node, 'attr', 'class')
341             self.reporter.check(cls in KNOWN_CODEBLOCKS,
342                                 (self.filename, self.get_loc(node)),
343                                 'Unknown or missing code block type {0}',
344                                 cls)
345
346
347     def find_all(self, node, pattern, accum=None):
348         """Find all matches for a pattern."""
349
350         assert type(pattern) == dict, 'Patterns must be dictionaries'
351         if accum is None:
352             accum = []
353         if self.match(node, pattern):
354             accum.append(node)
355         for child in node.get('children', []):
356             self.find_all(child, pattern, accum)
357         return accum
358
359
360     def match(self, node, pattern):
361         """Does this node match the given pattern?"""
362
363         for key in pattern:
364             if key not in node:
365                 return False
366             val = pattern[key]
367             if type(val) == str:
368                 if node[key] != val:
369                     return False
370             elif type(val) == dict:
371                 if not self.match(node[key], val):
372                     return False
373         return True
374
375
376     def get_val(self, node, *chain):
377         """Get value one or more levels down."""
378
379         curr = node
380         for selector in chain:
381             curr = curr.get(selector, None)
382             if curr is None:
383                 break
384         return curr
385
386
387     def get_loc(self, node):
388         """Convenience method to get node's line number."""
389
390         result = self.get_val(node, 'options', 'location')
391         if self.metadata_len is not None:
392             result += self.metadata_len
393         return result
394
395
396 class CheckNonJekyll(CheckBase):
397     """Check a file that isn't translated by Jekyll."""
398
399     def __init__(self, args, filename, metadata, metadata_len, text, lines, doc):
400         super(CheckNonJekyll, self).__init__(args, filename, metadata, metadata_len, text, lines, doc)
401
402
403     def check_metadata(self):
404         self.reporter.check(self.metadata is None,
405                             self.filename,
406                             'Unexpected metadata')
407
408
409 class CheckIndex(CheckBase):
410     """Check the main index page."""
411
412     def __init__(self, args, filename, metadata, metadata_len, text, lines, doc):
413         super(CheckIndex, self).__init__(args, filename, metadata, metadata_len, text, lines, doc)
414         self.layout = 'lesson'
415
416
417 class CheckEpisode(CheckBase):
418     """Check an episode page."""
419
420     def __init__(self, args, filename, metadata, metadata_len, text, lines, doc):
421         super(CheckEpisode, self).__init__(args, filename, metadata, metadata_len, text, lines, doc)
422
423     def check_metadata(self):
424         super(CheckEpisode, self).check_metadata()
425         if self.metadata:
426             if 'layout' in self.metadata:
427                 if self.metadata['layout'] == 'break':
428                     self.check_metadata_fields(BREAK_METADATA_FIELDS)
429                 else:
430                     self.reporter.add(self.filename,
431                                       'Unknown episode layout "{0}"',
432                                       self.metadata['layout'])
433             else:
434                 self.check_metadata_fields(TEACHING_METADATA_FIELDS)
435
436
437     def check_metadata_fields(self, expected):
438         for (name, type_) in expected:
439             if name not in self.metadata:
440                 self.reporter.add(self.filename,
441                                   'Missing metadata field {0}',
442                                   name)
443             elif type(self.metadata[name]) != type_:
444                 self.reporter.add(self.filename,
445                                   '"{0}" has wrong type in metadata ({1} instead of {2})',
446                                   name, type(self.metadata[name]), type_)
447
448
449 class CheckReference(CheckBase):
450     """Check the reference page."""
451
452     def __init__(self, args, filename, metadata, metadata_len, text, lines, doc):
453         super(CheckReference, self).__init__(args, filename, metadata, metadata_len, text, lines, doc)
454         self.layout = 'reference'
455
456
457 class CheckGeneric(CheckBase):
458     """Check a generic page."""
459
460     def __init__(self, args, filename, metadata, metadata_len, text, lines, doc):
461         super(CheckGeneric, self).__init__(args, filename, metadata, metadata_len, text, lines, doc)
462         self.layout = 'page'
463
464
465 CHECKERS = [
466     (re.compile(r'CONTRIBUTING\.md'), CheckNonJekyll),
467     (re.compile(r'README\.md'), CheckNonJekyll),
468     (re.compile(r'index\.md'), CheckIndex),
469     (re.compile(r'reference\.md'), CheckReference),
470     (re.compile(r'_episodes/.*\.md'), CheckEpisode),
471     (re.compile(r'.*\.md'), CheckGeneric)
472 ]
473
474
475 if __name__ == '__main__':
476     main()