DF-Walkthrough/misc/lint.py

77 lines
2.6 KiB
Python
Raw Normal View History

2015-09-30 09:42:17 +10:00
#!/usr/bin/env python3
"""Check for tabs and trailing whitespace in text files in all subdirs.
Any other automatic checks should be in this file too.
"""
from glob import glob
2015-10-22 09:48:05 +11:00
import io
2015-09-30 09:42:17 +10:00
import os
2015-10-22 09:48:05 +11:00
from os.path import basename, dirname, join, relpath
2015-09-30 09:42:17 +10:00
import sys
text_extensions = ('rst', 'md', 'txt', 'html', 'css', 'js')
2015-10-22 09:48:05 +11:00
DIRS = ['chapters', 'tutorials', 'masterclass']
2015-09-30 09:42:17 +10:00
2015-09-30 22:29:52 +10:00
def error(fname, lineno, issue):
"""Print the problem and location."""
print('ERROR: {}:{} - {}'.format(fname, lineno+1, issue))
def lint(path):
2015-09-30 09:42:17 +10:00
"""Run linters on all files, print problem files."""
2015-10-01 12:30:58 +10:00
print('Checking for long lines, tabs, and trailing whitespace...')
2015-09-30 09:42:17 +10:00
failed = False
for root, _, files in os.walk(path):
2015-09-30 09:42:17 +10:00
for f in files:
fname = join(root, f)
2015-09-30 09:42:17 +10:00
if '_build' in fname or not any(
fname.endswith(ext) for ext in text_extensions):
continue
2015-10-22 09:48:05 +11:00
with io.open(fname, encoding='utf-8') as fh:
for i, line in enumerate(fh.readlines()):
if len(line) > 81:
failed = True
2015-09-30 22:29:52 +10:00
error(fname, i, 'too long')
if line.replace('\n', '') != line.rstrip():
failed = True
error(fname, i, 'trailing space')
if '\t' in line:
error(fname, i, 'contains tab')
2015-09-30 09:42:17 +10:00
if failed:
print('Use your text editor to convert tabs to spaces, wrap lines '
2015-09-30 09:42:17 +10:00
'or trim trailing whitespace with minimal effort.')
return failed
def unused_images(path):
"""Check that all files in image subdirs are references in the text."""
print('Checking for unused images...')
failed = False
2015-10-22 09:48:05 +11:00
for d in DIRS:
text = ''
2015-10-22 09:48:05 +11:00
for fname in glob(join(d, '*.rst')):
with io.open(fname, encoding='utf-8') as f:
text += f.read()
2015-10-22 09:48:05 +11:00
for img in glob(join(d, 'images', '*.*')):
img = basename(img)
if img == 'Thumbs.db':
continue
markup = '.. image:: images/{}'.format(img)
if markup not in text:
failed = True
2015-10-22 09:48:05 +11:00
print('Error: not referenced: "{}/images/{}"'.format(d, img))
if failed:
print('Use or or delete these images.')
return failed
2015-09-30 09:42:17 +10:00
if __name__ == '__main__':
# lint everything in the parent directory, wherever the script is run from.
p = relpath(join(dirname(__file__), '..'))
2015-10-22 09:48:05 +11:00
fail_lint = lint(p)
fail_imgs = unused_images(p)
print('lint.py done.')
sys.exit(fail_lint or fail_imgs)