|
| 1 | +import argparse |
| 2 | +import fnmatch |
| 3 | +import glob |
| 4 | +import re |
| 5 | +from collections import namedtuple |
| 6 | +from itertools import chain |
| 7 | + |
| 8 | +import yaml |
| 9 | + |
| 10 | + |
| 11 | +def parse_args(): |
| 12 | + parser = argparse.ArgumentParser() |
| 13 | + parser.add_argument( |
| 14 | + 'files', |
| 15 | + metavar='FILE', |
| 16 | + type=str, |
| 17 | + nargs='+', |
| 18 | + help='Path to one or multiple files to be checked.' |
| 19 | + ) |
| 20 | + parser.add_argument( |
| 21 | + '--config', |
| 22 | + '-c', |
| 23 | + metavar='CONFIG_FILE', |
| 24 | + type=str, |
| 25 | + default='.relint.yml', |
| 26 | + help='Path to config file, default: .relint.yml' |
| 27 | + ) |
| 28 | + return parser.parse_args() |
| 29 | + |
| 30 | + |
| 31 | +Test = namedtuple('Test', ('name', 'pattern', 'hint', 'filename')) |
| 32 | + |
| 33 | + |
| 34 | +def load_config(path): |
| 35 | + with open(path) as fs: |
| 36 | + for test in yaml.load(fs): |
| 37 | + filename = test.get('filename', ['*']) |
| 38 | + if not isinstance(filename, list): |
| 39 | + filename = list(filename) |
| 40 | + yield Test( |
| 41 | + name=test['name'], |
| 42 | + pattern=re.compile(test['pattern']), |
| 43 | + hint=test.get('hint'), |
| 44 | + filename=filename, |
| 45 | + ) |
| 46 | + |
| 47 | + |
| 48 | +def lint_file(filename, tests): |
| 49 | + try: |
| 50 | + with open(filename) as fs: |
| 51 | + content = fs.read() |
| 52 | + except (IsADirectoryError, UnicodeDecodeError): |
| 53 | + pass |
| 54 | + else: |
| 55 | + for test in tests: |
| 56 | + if any(fnmatch.fnmatch(filename, fp) for fp in test.filename): |
| 57 | + for match in test.pattern.finditer(content): |
| 58 | + yield filename, test, match |
| 59 | + |
| 60 | + |
| 61 | +def main(): |
| 62 | + args = parse_args() |
| 63 | + paths = { |
| 64 | + path |
| 65 | + for file in args.files |
| 66 | + for path in glob.iglob(file, recursive=True) |
| 67 | + } |
| 68 | + |
| 69 | + tests = list(load_config(args.config)) |
| 70 | + |
| 71 | + matches = chain.from_iterable( |
| 72 | + lint_file(path, tests) |
| 73 | + for path in paths |
| 74 | + ) |
| 75 | + |
| 76 | + _filename = '' |
| 77 | + lines = [] |
| 78 | + |
| 79 | + for filename, test, match in matches: |
| 80 | + if filename != _filename: |
| 81 | + _filename = filename |
| 82 | + lines = match.string.splitlines() |
| 83 | + |
| 84 | + line_no = match.string[:match.start()].count('\n') |
| 85 | + print(f"{filename}:{line_no + 1} {test.name}") |
| 86 | + if test.hint: |
| 87 | + print("Hint:", test.hint) |
| 88 | + print("> ", lines[line_no]) |
| 89 | + |
| 90 | + |
| 91 | +if __name__ == '__main__': |
| 92 | + main() |
0 commit comments