2020-06-29 22:29:30 -06:00
|
|
|
#!/usr/bin/env python3
|
2021-09-05 20:44:42 -06:00
|
|
|
import argparse
|
2021-09-06 16:22:59 -06:00
|
|
|
import fnmatch
|
2021-09-05 20:44:42 -06:00
|
|
|
import re
|
|
|
|
import os
|
2021-09-06 16:59:08 -06:00
|
|
|
import subprocess
|
2021-09-05 20:44:42 -06:00
|
|
|
import sys
|
2015-02-14 17:59:17 -07:00
|
|
|
|
2021-09-06 16:22:59 -06:00
|
|
|
DFHACK_ROOT = os.path.normpath(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
|
|
|
|
|
|
|
def load_pattern_files(paths):
|
|
|
|
patterns = []
|
|
|
|
for p in paths:
|
|
|
|
with open(p) as f:
|
|
|
|
for line in f.readlines():
|
|
|
|
line = line.strip()
|
|
|
|
if line and not line.startswith('#'):
|
|
|
|
patterns.append(line)
|
|
|
|
return patterns
|
|
|
|
|
|
|
|
def valid_file(rel_path, check_patterns, ignore_patterns):
|
|
|
|
return (
|
|
|
|
any(fnmatch.fnmatch(rel_path, pattern) for pattern in check_patterns)
|
|
|
|
and not any(fnmatch.fnmatch(rel_path, pattern) for pattern in ignore_patterns)
|
|
|
|
)
|
2015-02-14 17:59:17 -07:00
|
|
|
|
|
|
|
success = True
|
2020-06-29 21:58:47 -06:00
|
|
|
def error(msg=None):
|
2015-02-14 17:59:17 -07:00
|
|
|
global success
|
|
|
|
success = False
|
2020-06-29 21:58:47 -06:00
|
|
|
if msg:
|
|
|
|
sys.stderr.write(msg + '\n')
|
2015-02-14 17:59:17 -07:00
|
|
|
|
2020-06-29 21:58:47 -06:00
|
|
|
def format_lines(lines, total):
|
|
|
|
if len(lines) == total - 1:
|
|
|
|
return 'entire file'
|
|
|
|
if not len(lines):
|
|
|
|
# should never happen
|
|
|
|
return 'nowhere'
|
|
|
|
if len(lines) == 1:
|
|
|
|
return 'line %i' % lines[0]
|
|
|
|
s = 'lines '
|
|
|
|
range_start = range_end = lines[0]
|
|
|
|
for i, line in enumerate(lines):
|
|
|
|
if line > range_end + 1:
|
|
|
|
if range_start == range_end:
|
|
|
|
s += ('%i, ' % range_end)
|
|
|
|
else:
|
|
|
|
s += ('%i-%i, ' % (range_start, range_end))
|
|
|
|
range_start = range_end = line
|
|
|
|
if i == len(lines) - 1:
|
|
|
|
s += ('%i' % line)
|
|
|
|
else:
|
|
|
|
range_end = line
|
|
|
|
if i == len(lines) - 1:
|
|
|
|
s += ('%i-%i, ' % (range_start, range_end))
|
|
|
|
return s.rstrip(' ').rstrip(',')
|
|
|
|
|
|
|
|
class LinterError(Exception):
|
|
|
|
def __init__(self, message, lines, total_lines):
|
|
|
|
self.message = message
|
|
|
|
self.lines = lines
|
|
|
|
self.total_lines = total_lines
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return '%s: %s' % (self.message, format_lines(self.lines, self.total_lines))
|
|
|
|
|
|
|
|
def github_actions_workflow_command(self, filename):
|
|
|
|
first_line = self.lines[0] if self.lines else 1
|
|
|
|
return '::error file=%s,line=%i::%s' % (filename, first_line, self)
|
2015-02-14 17:59:17 -07:00
|
|
|
|
|
|
|
class Linter(object):
|
2016-02-01 07:39:40 -07:00
|
|
|
ignore = False
|
2015-02-14 17:59:17 -07:00
|
|
|
def check(self, lines):
|
|
|
|
failures = []
|
|
|
|
for i, line in enumerate(lines):
|
|
|
|
if not self.check_line(line):
|
2015-02-14 19:43:10 -07:00
|
|
|
failures.append(i + 1)
|
2015-02-14 17:59:17 -07:00
|
|
|
if len(failures):
|
2020-06-29 21:58:47 -06:00
|
|
|
raise LinterError(self.msg, failures, len(lines))
|
2015-02-14 17:59:17 -07:00
|
|
|
|
2015-02-14 20:25:10 -07:00
|
|
|
def fix(self, lines):
|
|
|
|
for i in range(len(lines)):
|
|
|
|
lines[i] = self.fix_line(lines[i])
|
|
|
|
|
2015-02-14 17:59:17 -07:00
|
|
|
|
|
|
|
class NewlineLinter(Linter):
|
|
|
|
msg = 'Contains DOS-style newlines'
|
2016-02-01 07:39:40 -07:00
|
|
|
# git supports newline conversion. Catch in CI, ignore on Windows.
|
2021-09-05 20:24:16 -06:00
|
|
|
ignore = os.linesep != '\n' and not os.environ.get('CI')
|
2015-02-14 17:59:17 -07:00
|
|
|
def check_line(self, line):
|
2016-02-01 07:39:40 -07:00
|
|
|
return '\r' not in line
|
2015-02-14 20:25:10 -07:00
|
|
|
def fix_line(self, line):
|
|
|
|
return line.replace('\r', '')
|
2015-02-14 17:59:17 -07:00
|
|
|
|
|
|
|
class TrailingWhitespaceLinter(Linter):
|
|
|
|
msg = 'Contains trailing whitespace'
|
|
|
|
def check_line(self, line):
|
2016-02-01 07:39:40 -07:00
|
|
|
line = line.replace('\r', '').replace('\n', '')
|
|
|
|
return not line.strip() or line == line.rstrip('\t ')
|
2015-02-14 20:25:10 -07:00
|
|
|
def fix_line(self, line):
|
|
|
|
return line.rstrip('\t ')
|
2015-02-14 17:59:17 -07:00
|
|
|
|
2015-02-14 20:07:57 -07:00
|
|
|
class TabLinter(Linter):
|
|
|
|
msg = 'Contains tabs'
|
|
|
|
def check_line(self, line):
|
|
|
|
return '\t' not in line
|
2015-02-14 20:25:10 -07:00
|
|
|
def fix_line(self, line):
|
|
|
|
return line.replace('\t', ' ')
|
2015-02-14 20:07:57 -07:00
|
|
|
|
2016-02-01 07:39:40 -07:00
|
|
|
linters = [cls() for cls in Linter.__subclasses__() if not cls.ignore]
|
2015-02-14 20:07:57 -07:00
|
|
|
|
2021-09-06 16:59:08 -06:00
|
|
|
def walk_all(root_path):
|
|
|
|
for cur, dirnames, filenames in os.walk(root_path):
|
|
|
|
for filename in filenames:
|
|
|
|
full_path = os.path.join(cur, filename)
|
|
|
|
yield full_path
|
|
|
|
|
|
|
|
def walk_git_files(root_path):
|
|
|
|
p = subprocess.Popen(['git', '-C', root_path, 'ls-files', root_path], stdout=subprocess.PIPE)
|
|
|
|
for line in p.stdout.readlines():
|
|
|
|
path = line.decode('utf-8').strip()
|
|
|
|
full_path = os.path.join(root_path, path)
|
|
|
|
yield full_path
|
|
|
|
if p.wait() != 0:
|
|
|
|
raise RuntimeError('git exited with %r' % p.returncode)
|
|
|
|
|
2021-09-05 20:44:42 -06:00
|
|
|
def main(args):
|
|
|
|
root_path = os.path.abspath(args.path)
|
|
|
|
if not os.path.exists(args.path):
|
2015-02-21 21:06:50 -07:00
|
|
|
print('Nonexistent path: %s' % root_path)
|
|
|
|
sys.exit(2)
|
2021-09-05 20:44:42 -06:00
|
|
|
|
2021-09-06 16:22:59 -06:00
|
|
|
check_patterns = load_pattern_files(args.check_patterns)
|
|
|
|
ignore_patterns = load_pattern_files(args.ignore_patterns)
|
2015-02-14 17:59:17 -07:00
|
|
|
|
2021-09-06 16:59:08 -06:00
|
|
|
walk_iter = walk_all
|
|
|
|
if args.git_only:
|
|
|
|
walk_iter = walk_git_files
|
|
|
|
|
|
|
|
for full_path in walk_iter(root_path):
|
|
|
|
rel_path = full_path.replace(root_path, '').replace('\\', '/').lstrip('/')
|
|
|
|
if not valid_file(rel_path, check_patterns, ignore_patterns):
|
|
|
|
continue
|
|
|
|
if args.verbose:
|
|
|
|
print('Checking:', rel_path)
|
|
|
|
lines = []
|
|
|
|
with open(full_path, 'rb') as f:
|
|
|
|
lines = f.read().split(b'\n')
|
|
|
|
for i, line in enumerate(lines):
|
2015-02-14 20:25:10 -07:00
|
|
|
try:
|
2021-09-06 16:59:08 -06:00
|
|
|
lines[i] = line.decode('utf-8')
|
|
|
|
except UnicodeDecodeError:
|
|
|
|
msg_params = (rel_path, i + 1, 'Invalid UTF-8 (other errors will be ignored)')
|
|
|
|
error('%s:%i: %s' % msg_params)
|
2021-09-05 20:44:42 -06:00
|
|
|
if args.github_actions:
|
2021-09-06 16:59:08 -06:00
|
|
|
print('::error file=%s,line=%i::%s' % msg_params)
|
|
|
|
lines[i] = ''
|
|
|
|
for linter in linters:
|
|
|
|
try:
|
|
|
|
linter.check(lines)
|
|
|
|
except LinterError as e:
|
|
|
|
error('%s: %s' % (rel_path, e))
|
|
|
|
if args.github_actions:
|
|
|
|
print(e.github_actions_workflow_command(rel_path))
|
|
|
|
if args.fix:
|
|
|
|
linter.fix(lines)
|
|
|
|
contents = '\n'.join(lines)
|
|
|
|
with open(full_path, 'wb') as f:
|
|
|
|
f.write(contents.encode('utf-8'))
|
2015-02-14 17:59:17 -07:00
|
|
|
|
2015-02-14 20:07:57 -07:00
|
|
|
if success:
|
|
|
|
print('All linters completed successfully')
|
|
|
|
sys.exit(0)
|
|
|
|
else:
|
|
|
|
sys.exit(1)
|
2015-02-14 17:59:17 -07:00
|
|
|
|
2015-02-14 20:07:57 -07:00
|
|
|
if __name__ == '__main__':
|
2021-09-05 20:44:42 -06:00
|
|
|
parser = argparse.ArgumentParser()
|
|
|
|
parser.add_argument('path', nargs='?', default='.',
|
|
|
|
help='Path to scan (default: current directory)')
|
|
|
|
parser.add_argument('--fix', action='store_true',
|
|
|
|
help='Attempt to modify files in-place to fix identified issues')
|
2021-09-06 16:59:08 -06:00
|
|
|
parser.add_argument('--git-only', action='store_true',
|
|
|
|
help='Only check files tracked by git')
|
2021-09-05 20:44:42 -06:00
|
|
|
parser.add_argument('--github-actions', action='store_true',
|
|
|
|
help='Enable GitHub Actions workflow command output')
|
2021-09-06 16:22:59 -06:00
|
|
|
parser.add_argument('-v', '--verbose', action='store_true',
|
|
|
|
help='Log files as they are checked')
|
|
|
|
parser.add_argument('--check-patterns', action='append',
|
|
|
|
default=[os.path.join(DFHACK_ROOT, 'ci', 'lint-check.txt')],
|
|
|
|
help='File(s) containing filename patterns to check')
|
|
|
|
parser.add_argument('--ignore-patterns', action='append',
|
|
|
|
default=[os.path.join(DFHACK_ROOT, 'ci', 'lint-ignore.txt')],
|
|
|
|
help='File(s) containing filename patterns to ignore')
|
2021-09-05 20:44:42 -06:00
|
|
|
args = parser.parse_args()
|
|
|
|
main(args)
|