4 Check lesson files and their contents.
12 from optparse import OptionParser
14 from util import Reporter, read_markdown, load_yaml, check_unwanted_files
18 # Where to look for source Markdown files.
19 SOURCE_DIRS = ['', '_episodes', '_extras']
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.
29 '%/CONTRIBUTING.md': False,
32 '%/_extras/discuss.md': True,
33 '%/_extras/figures.md': True,
34 '%/_extras/guide.md': True,
36 '%/reference.md': True,
40 # Episode filename pattern.
41 P_EPISODE_FILENAME = re.compile(r'/_episodes/(\d\d)-[-\w]+.md$')
43 # Pattern to match lines ending with whitespace.
44 P_TRAILING_WHITESPACE = re.compile(r'\s+$')
46 # Pattern to match figure references in HTML.
47 P_FIGURE_REFS = re.compile(r'<img[^>]+src="([^"]+)"[^>]*>')
49 # What kinds of blockquotes are allowed?
63 # What kinds of code fragments are allowed?
75 # What fields are required in teaching episode metadata?
76 TEACHING_METADATA_FIELDS = {
85 # What fields are required in break episode metadata?
86 BREAK_METADATA_FIELDS = {
92 # How long are lines allowed to be?
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])
107 check_figures(args.source_dir, args.reporter)
108 args.reporter.report()
112 """Parse command-line arguments."""
114 parser = OptionParser()
115 parser.add_option('-l', '--linelen',
119 help='Check line lengths')
120 parser.add_option('-p', '--parser',
123 help='path to Markdown parser')
124 parser.add_option('-s', '--source',
127 help='source directory')
128 parser.add_option('-w', '--whitespace',
131 dest='trailing_whitespace',
132 help='Check for trailing whitespace')
134 args, extras = parser.parse_args()
135 require(args.parser is not None,
136 'Path to Markdown parser not provided')
138 'Unexpected trailing command-line arguments "{0}"'.format(extras))
143 def check_config(reporter, source_dir):
144 """Check configuration file."""
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']),
157 'Repository name "{0}" not consistent with root "{1}"',
158 config['repo'], config['root'])
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}}
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]
169 for pat in all_patterns:
170 for filename in glob.glob(pat):
171 data = read_markdown(parser, filename)
173 result[filename] = data
177 def check_fileset(source_dir, reporter, filenames_present):
178 """Are all required files present? Are extraneous files present?"""
180 # Check files with predictable names.
181 required = [p.replace('%', source_dir) for p in REQUIRED_FILES]
182 missing = set(required) - set(filenames_present)
184 reporter.add(None, 'Missing required file {0}', m)
186 # Check episode files' names.
188 for filename in filenames_present:
189 if '_episodes' not in filename:
191 m = P_EPISODE_FILENAME.search(filename)
193 seen.append(m.group(1))
195 reporter.add(None, 'Episode {0} has badly-formatted filename', filename)
197 # Check for duplicate episode numbers.
198 reporter.check(len(seen) == len(set(seen)),
200 'Duplicate episode numbers {0} vs {1}',
201 sorted(seen), sorted(set(seen)))
203 # Check that numbers are consecutive.
204 seen = [int(s) for s in seen]
207 for i in range(len(seen) - 1):
208 clean = clean and ((seen[i+1] - seen[i]) == 1)
209 reporter.check(clean,
211 'Missing or non-consecutive episode numbers {0}',
215 def check_figures(source_dir, reporter):
216 """Check that all figures are present and referenced."""
220 all_figures_html = os.path.join(source_dir, '_includes', 'all_figures.html')
221 with open(all_figures_html, 'r') as reader:
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,
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('.')]
234 # Report differences.
235 unexpected = set(actual) - set(referenced)
236 reporter.check(not unexpected,
238 'Unexpected image files: {0}',
239 ', '.join(sorted(unexpected)))
240 missing = set(referenced) - set(actual)
241 reporter.check(not missing,
243 'Missing image files: {0}',
244 ', '.join(sorted(missing)))
247 def create_checker(args, filename, info):
248 """Create appropriate checker for file."""
250 for (pat, cls) in CHECKERS:
251 if pat.search(filename):
252 return cls(args, filename, **info)
255 def require(condition, message):
256 """Fail if condition not met."""
259 print(message, file=sys.stderr)
263 class CheckBase(object):
264 """Base class for checking Markdown files."""
266 def __init__(self, args, filename, metadata, metadata_len, text, lines, doc):
267 """Cache arguments for checking."""
269 super(CheckBase, self).__init__()
271 self.reporter = self.args.reporter # for convenience
272 self.filename = filename
273 self.metadata = metadata
274 self.metadata_len = metadata_len
283 """Run tests on metadata."""
285 self.check_metadata()
286 self.check_line_lengths()
287 self.check_trailing_whitespace()
288 self.check_blockquote_classes()
289 self.check_codeblock_classes()
292 def check_metadata(self):
293 """Check the YAML metadata."""
295 self.reporter.check(self.metadata is not None,
297 'Missing metadata entirely')
299 if self.metadata and (self.layout is not None):
300 self.reporter.check_field(self.filename, 'metadata', self.metadata, 'layout', self.layout)
303 def check_line_lengths(self):
304 """Check the raw text of the lesson body."""
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,
310 'Line(s) are too long: {0}',
311 ', '.join([str(i) for i in over]))
314 def check_trailing_whitespace(self):
315 """Check for whitespace at the ends of lines."""
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,
321 'Line(s) end with whitespace: {0}',
322 ', '.join([str(i) for i in trailing]))
325 def check_blockquote_classes(self):
326 """Check that all blockquotes have known classes."""
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}',
336 def check_codeblock_classes(self):
337 """Check that all code blocks have known classes."""
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}',
347 def find_all(self, node, pattern, accum=None):
348 """Find all matches for a pattern."""
350 assert type(pattern) == dict, 'Patterns must be dictionaries'
353 if self.match(node, pattern):
355 for child in node.get('children', []):
356 self.find_all(child, pattern, accum)
360 def match(self, node, pattern):
361 """Does this node match the given pattern?"""
370 elif type(val) == dict:
371 if not self.match(node[key], val):
376 def get_val(self, node, *chain):
377 """Get value one or more levels down."""
380 for selector in chain:
381 curr = curr.get(selector, None)
387 def get_loc(self, node):
388 """Convenience method to get node's line number."""
390 result = self.get_val(node, 'options', 'location')
391 if self.metadata_len is not None:
392 result += self.metadata_len
396 class CheckNonJekyll(CheckBase):
397 """Check a file that isn't translated by Jekyll."""
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)
403 def check_metadata(self):
404 self.reporter.check(self.metadata is None,
406 'Unexpected metadata')
409 class CheckIndex(CheckBase):
410 """Check the main index page."""
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'
417 class CheckEpisode(CheckBase):
418 """Check an episode page."""
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)
423 def check_metadata(self):
424 super(CheckEpisode, self).check_metadata()
426 if 'layout' in self.metadata:
427 if self.metadata['layout'] == 'break':
428 self.check_metadata_fields(BREAK_METADATA_FIELDS)
430 self.reporter.add(self.filename,
431 'Unknown episode layout "{0}"',
432 self.metadata['layout'])
434 self.check_metadata_fields(TEACHING_METADATA_FIELDS)
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}',
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_)
449 class CheckReference(CheckBase):
450 """Check the reference page."""
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'
457 class CheckGeneric(CheckBase):
458 """Check a generic page."""
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)
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)
475 if __name__ == '__main__':