Checking consolidated links
[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.3'
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 # Pattern to match internally-defined Markdown links.
51 P_INTERNAL_LINK_REF = re.compile(r'\[([^\]]+)\]\[([^\]]+)\]')
52
53 # Pattern to match reference links (to resolve internally-defined references).
54 P_INTERNAL_LINK_DEF = re.compile(r'^\[([^\]]+)\]:\s*(.+)')
55
56 # What kinds of blockquotes are allowed?
57 KNOWN_BLOCKQUOTES = {
58     'callout',
59     'challenge',
60     'checklist',
61     'discussion',
62     'keypoints',
63     'objectives',
64     'prereq',
65     'quotation',
66     'solution',
67     'testimonial'
68 }
69
70 # What kinds of code fragments are allowed?
71 KNOWN_CODEBLOCKS = {
72     'error',
73     'output',
74     'source',
75     'bash',
76     'make',
77     'matlab',
78     'python',
79     'r',
80     'sql'
81 }
82
83 # What fields are required in teaching episode metadata?
84 TEACHING_METADATA_FIELDS = {
85     ('title', str),
86     ('teaching', int),
87     ('exercises', int),
88     ('questions', list),
89     ('objectives', list),
90     ('keypoints', list)
91 }
92
93 # What fields are required in break episode metadata?
94 BREAK_METADATA_FIELDS = {
95     ('layout', str),
96     ('title', str),
97     ('break', int)
98 }
99
100 # How long are lines allowed to be?
101 MAX_LINE_LEN = 100
102
103 def main():
104     """Main driver."""
105
106     args = parse_args()
107     args.reporter = Reporter()
108     check_config(args.reporter, args.source_dir)
109     args.references = read_references(args.reporter, args.reference_path)
110
111     docs = read_all_markdown(args.source_dir, args.parser)
112     check_fileset(args.source_dir, args.reporter, docs.keys())
113     check_unwanted_files(args.source_dir, args.reporter)
114     for filename in docs.keys():
115         checker = create_checker(args, filename, docs[filename])
116         checker.check()
117     check_figures(args.source_dir, args.reporter)
118
119     args.reporter.report()
120
121
122 def parse_args():
123     """Parse command-line arguments."""
124
125     parser = OptionParser()
126     parser.add_option('-l', '--linelen',
127                       default=False,
128                       action="store_true",
129                       dest='line_lengths',
130                       help='Check line lengths')
131     parser.add_option('-p', '--parser',
132                       default=None,
133                       dest='parser',
134                       help='path to Markdown parser')
135     parser.add_option('-r', '--references',
136                       default=None,
137                       dest='reference_path',
138                       help='path to Markdown file of external references')
139     parser.add_option('-s', '--source',
140                       default=os.curdir,
141                       dest='source_dir',
142                       help='source directory')
143     parser.add_option('-w', '--whitespace',
144                       default=False,
145                       action="store_true",
146                       dest='trailing_whitespace',
147                       help='Check for trailing whitespace')
148
149     args, extras = parser.parse_args()
150     require(args.parser is not None,
151             'Path to Markdown parser not provided')
152     require(not extras,
153             'Unexpected trailing command-line arguments "{0}"'.format(extras))
154
155     return args
156
157
158 def check_config(reporter, source_dir):
159     """Check configuration file."""
160
161     config_file = os.path.join(source_dir, '_config.yml')
162     config = load_yaml(config_file)
163     reporter.check_field(config_file, 'configuration', config, 'kind', 'lesson')
164     reporter.check_field(config_file, 'configuration', config, 'carpentry', ('swc', 'dc', 'lc'))
165     reporter.check_field(config_file, 'configuration', config, 'title')
166     reporter.check_field(config_file, 'configuration', config, 'contact')
167
168     reporter.check({'values': {'root': '..'}} in config.get('defaults', []),
169                    'configuration',
170                    '"root" not set to ".." in configuration')
171
172
173 def read_references(reporter, ref_path):
174     """Read shared file of reference links, returning dictionary of valid references
175     {symbolic_name : URL}
176     """
177
178     result = {}
179     urls_seen = set()
180     if ref_path:
181         with open(ref_path, 'r') as reader:
182             for (num, line) in enumerate(reader):
183                 line_num = num + 1
184                 m = P_INTERNAL_LINK_DEF.search(line)
185                 require(m,
186                         '{0}:{1} not valid reference:\n{2}'.format(ref_path, line_num, line.rstrip()))
187                 name = m.group(1)
188                 url = m.group(2)
189                 require(name,
190                         'Empty reference at {0}:{1}'.format(ref_path, line_num))
191                 reporter.check(name not in result,
192                                ref_path,
193                                'Duplicate reference {0} at line {1}',
194                                name, line_num)
195                 reporter.check(url not in urls_seen,
196                                ref_path,
197                                'Duplicate definition of URL {0} at line {1}',
198                                url, line_num)
199                 result[name] = url
200                 urls_seen.add(url)
201     return result
202
203
204 def read_all_markdown(source_dir, parser):
205     """Read source files, returning
206     {path : {'metadata':yaml, 'metadata_len':N, 'text':text, 'lines':[(i, line, len)], 'doc':doc}}
207     """
208
209     all_dirs = [os.path.join(source_dir, d) for d in SOURCE_DIRS]
210     all_patterns = [os.path.join(d, '*.md') for d in all_dirs]
211     result = {}
212     for pat in all_patterns:
213         for filename in glob.glob(pat):
214             data = read_markdown(parser, filename)
215             if data:
216                 result[filename] = data
217     return result
218
219
220 def check_fileset(source_dir, reporter, filenames_present):
221     """Are all required files present? Are extraneous files present?"""
222
223     # Check files with predictable names.
224     required = [p.replace('%', source_dir) for p in REQUIRED_FILES]
225     missing = set(required) - set(filenames_present)
226     for m in missing:
227         reporter.add(None, 'Missing required file {0}', m)
228
229     # Check episode files' names.
230     seen = []
231     for filename in filenames_present:
232         if '_episodes' not in filename:
233             continue
234         m = P_EPISODE_FILENAME.search(filename)
235         if m and m.group(1):
236             seen.append(m.group(1))
237         else:
238             reporter.add(None, 'Episode {0} has badly-formatted filename', filename)
239
240     # Check for duplicate episode numbers.
241     reporter.check(len(seen) == len(set(seen)),
242                         None,
243                         'Duplicate episode numbers {0} vs {1}',
244                         sorted(seen), sorted(set(seen)))
245
246     # Check that numbers are consecutive.
247     seen = [int(s) for s in seen]
248     seen.sort()
249     clean = True
250     for i in range(len(seen) - 1):
251         clean = clean and ((seen[i+1] - seen[i]) == 1)
252     reporter.check(clean,
253                    None,
254                    'Missing or non-consecutive episode numbers {0}',
255                    seen)
256
257
258 def check_figures(source_dir, reporter):
259     """Check that all figures are present and referenced."""
260
261     # Get references.
262     try:
263         all_figures_html = os.path.join(source_dir, '_includes', 'all_figures.html')
264         with open(all_figures_html, 'r') as reader:
265             text = reader.read()
266         figures = P_FIGURE_REFS.findall(text)
267         referenced = [os.path.split(f)[1] for f in figures if '/fig/' in f]
268     except FileNotFoundError as e:
269         reporter.add(all_figures_html,
270                      'File not found')
271         return
272
273     # Get actual image files (ignore non-image files).
274     fig_dir_path = os.path.join(source_dir, 'fig')
275     actual = [f for f in os.listdir(fig_dir_path) if os.path.splitext(f)[1] in IMAGE_FILE_SUFFIX]
276
277     # Report differences.
278     unexpected = set(actual) - set(referenced)
279     reporter.check(not unexpected,
280                    None,
281                    'Unexpected image files: {0}',
282                    ', '.join(sorted(unexpected)))
283     missing = set(referenced) - set(actual)
284     reporter.check(not missing,
285                    None,
286                    'Missing image files: {0}',
287                    ', '.join(sorted(missing)))
288
289
290 def create_checker(args, filename, info):
291     """Create appropriate checker for file."""
292
293     for (pat, cls) in CHECKERS:
294         if pat.search(filename):
295             return cls(args, filename, **info)
296
297
298 class CheckBase(object):
299     """Base class for checking Markdown files."""
300
301     def __init__(self, args, filename, metadata, metadata_len, text, lines, doc):
302         """Cache arguments for checking."""
303
304         super(CheckBase, self).__init__()
305         self.args = args
306         self.reporter = self.args.reporter # for convenience
307         self.filename = filename
308         self.metadata = metadata
309         self.metadata_len = metadata_len
310         self.text = text
311         self.lines = lines
312         self.doc = doc
313
314         self.layout = None
315
316
317     def check(self):
318         """Run tests."""
319
320         self.check_metadata()
321         self.check_line_lengths()
322         self.check_trailing_whitespace()
323         self.check_blockquote_classes()
324         self.check_codeblock_classes()
325         self.check_defined_link_references()
326
327
328     def check_metadata(self):
329         """Check the YAML metadata."""
330
331         self.reporter.check(self.metadata is not None,
332                             self.filename,
333                             'Missing metadata entirely')
334
335         if self.metadata and (self.layout is not None):
336             self.reporter.check_field(self.filename, 'metadata', self.metadata, 'layout', self.layout)
337
338
339     def check_line_lengths(self):
340         """Check the raw text of the lesson body."""
341
342         if self.args.line_lengths:
343             over = [i for (i, l, n) in self.lines if (n > MAX_LINE_LEN) and (not l.startswith('!'))]
344             self.reporter.check(not over,
345                                 self.filename,
346                                 'Line(s) are too long: {0}',
347                                 ', '.join([str(i) for i in over]))
348
349
350     def check_trailing_whitespace(self):
351         """Check for whitespace at the ends of lines."""
352
353         if self.args.trailing_whitespace:
354             trailing = [i for (i, l, n) in self.lines if P_TRAILING_WHITESPACE.match(l)]
355             self.reporter.check(not trailing,
356                                 self.filename,
357                                 'Line(s) end with whitespace: {0}',
358                                 ', '.join([str(i) for i in trailing]))
359
360
361     def check_blockquote_classes(self):
362         """Check that all blockquotes have known classes."""
363
364         for node in self.find_all(self.doc, {'type' : 'blockquote'}):
365             cls = self.get_val(node, 'attr', 'class')
366             self.reporter.check(cls in KNOWN_BLOCKQUOTES,
367                                 (self.filename, self.get_loc(node)),
368                                 'Unknown or missing blockquote type {0}',
369                                 cls)
370
371
372     def check_codeblock_classes(self):
373         """Check that all code blocks have known classes."""
374
375         for node in self.find_all(self.doc, {'type' : 'codeblock'}):
376             cls = self.get_val(node, 'attr', 'class')
377             self.reporter.check(cls in KNOWN_CODEBLOCKS,
378                                 (self.filename, self.get_loc(node)),
379                                 'Unknown or missing code block type {0}',
380                                 cls)
381
382
383     def check_defined_link_references(self):
384         """Check that defined links resolve in the file.
385
386         Internally-defined links match the pattern [text][label].
387         """
388
389         result = set()
390         for node in self.find_all(self.doc, {'type' : 'text'}):
391             for match in P_INTERNAL_LINK_REF.findall(node['value']):
392                 text = match[0]
393                 link = match[1]
394                 if link not in self.args.references:
395                     result.add('"{0}"=>"{1}"'.format(text, link))
396         self.reporter.check(not result,
397                             self.filename,
398                             'Internally-defined links may be missing definitions: {0}',
399                             ', '.join(sorted(result)))
400
401
402     def find_all(self, node, pattern, accum=None):
403         """Find all matches for a pattern."""
404
405         assert type(pattern) == dict, 'Patterns must be dictionaries'
406         if accum is None:
407             accum = []
408         if self.match(node, pattern):
409             accum.append(node)
410         for child in node.get('children', []):
411             self.find_all(child, pattern, accum)
412         return accum
413
414
415     def match(self, node, pattern):
416         """Does this node match the given pattern?"""
417
418         for key in pattern:
419             if key not in node:
420                 return False
421             val = pattern[key]
422             if type(val) == str:
423                 if node[key] != val:
424                     return False
425             elif type(val) == dict:
426                 if not self.match(node[key], val):
427                     return False
428         return True
429
430
431     def get_val(self, node, *chain):
432         """Get value one or more levels down."""
433
434         curr = node
435         for selector in chain:
436             curr = curr.get(selector, None)
437             if curr is None:
438                 break
439         return curr
440
441
442     def get_loc(self, node):
443         """Convenience method to get node's line number."""
444
445         result = self.get_val(node, 'options', 'location')
446         if self.metadata_len is not None:
447             result += self.metadata_len
448         return result
449
450
451 class CheckNonJekyll(CheckBase):
452     """Check a file that isn't translated by Jekyll."""
453
454     def __init__(self, args, filename, metadata, metadata_len, text, lines, doc):
455         super(CheckNonJekyll, self).__init__(args, filename, metadata, metadata_len, text, lines, doc)
456
457
458     def check_metadata(self):
459         self.reporter.check(self.metadata is None,
460                             self.filename,
461                             'Unexpected metadata')
462
463
464 class CheckIndex(CheckBase):
465     """Check the main index page."""
466
467     def __init__(self, args, filename, metadata, metadata_len, text, lines, doc):
468         super(CheckIndex, self).__init__(args, filename, metadata, metadata_len, text, lines, doc)
469         self.layout = 'lesson'
470
471     def check_metadata(self):
472         super(CheckIndex, self).check_metadata()
473         self.reporter.check(self.metadata.get('root', '') == '.',
474                             self.filename,
475                             'Root not set to "."')
476
477
478 class CheckEpisode(CheckBase):
479     """Check an episode page."""
480
481     def __init__(self, args, filename, metadata, metadata_len, text, lines, doc):
482         super(CheckEpisode, self).__init__(args, filename, metadata, metadata_len, text, lines, doc)
483
484
485     def check(self):
486         """Run extra tests."""
487
488         super(CheckEpisode, self).check()
489         self.check_reference_inclusion()
490
491
492     def check_metadata(self):
493         super(CheckEpisode, self).check_metadata()
494         if self.metadata:
495             if 'layout' in self.metadata:
496                 if self.metadata['layout'] == 'break':
497                     self.check_metadata_fields(BREAK_METADATA_FIELDS)
498                 else:
499                     self.reporter.add(self.filename,
500                                       'Unknown episode layout "{0}"',
501                                       self.metadata['layout'])
502             else:
503                 self.check_metadata_fields(TEACHING_METADATA_FIELDS)
504
505
506     def check_metadata_fields(self, expected):
507         for (name, type_) in expected:
508             if name not in self.metadata:
509                 self.reporter.add(self.filename,
510                                   'Missing metadata field {0}',
511                                   name)
512             elif type(self.metadata[name]) != type_:
513                 self.reporter.add(self.filename,
514                                   '"{0}" has wrong type in metadata ({1} instead of {2})',
515                                   name, type(self.metadata[name]), type_)
516
517
518     def check_reference_inclusion(self):
519         """Check that links file has been included."""
520
521         if not self.args.reference_path:
522             return
523
524         for (i, last_line, line_len) in reversed(self.lines):
525             if last_line:
526                 break
527
528         require(last_line,
529                 'No non-empty lines in {0}'.format(self.filename))
530
531         include_filename = os.path.split(self.args.reference_path)[-1]
532         if include_filename not in last_line:
533             self.reporter.add(self.filename,
534                               'episode does not include "{0}"',
535                               include_filename)
536
537
538 class CheckReference(CheckBase):
539     """Check the reference page."""
540
541     def __init__(self, args, filename, metadata, metadata_len, text, lines, doc):
542         super(CheckReference, self).__init__(args, filename, metadata, metadata_len, text, lines, doc)
543         self.layout = 'reference'
544
545
546 class CheckGeneric(CheckBase):
547     """Check a generic page."""
548
549     def __init__(self, args, filename, metadata, metadata_len, text, lines, doc):
550         super(CheckGeneric, self).__init__(args, filename, metadata, metadata_len, text, lines, doc)
551         self.layout = 'page'
552
553
554 CHECKERS = [
555     (re.compile(r'CONTRIBUTING\.md'), CheckNonJekyll),
556     (re.compile(r'README\.md'), CheckNonJekyll),
557     (re.compile(r'index\.md'), CheckIndex),
558     (re.compile(r'reference\.md'), CheckReference),
559     (re.compile(r'_episodes/.*\.md'), CheckEpisode),
560     (re.compile(r'.*\.md'), CheckGeneric)
561 ]
562
563
564 if __name__ == '__main__':
565     main()