0
0
mirror of https://github.com/nodejs/node.git synced 2024-12-01 16:10:02 +01:00
nodejs/tools/checkimports.py
Richard Lau 05db68245b
tools: fix check-imports.py to match on word boundaries
`check-imports.py` was missing some unused `using` statements as it
was not matching on word boundaries (e.g. `MaybeLocal` was considered
a use of `Local`). Fix that and add some unit tests (which required
the script to be renamed to drop the `-` so it could be imported into
the test script).

PR-URL: https://github.com/nodejs/node/pull/33268
Refs: https://github.com/nodejs/node/issues/29226
Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl>
Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de>
Reviewed-By: Christian Clauss <cclauss@me.com>
Reviewed-By: Daniel Bevenius <daniel.bevenius@gmail.com>
Reviewed-By: Beth Griggs <Bethany.Griggs@uk.ibm.com>
2020-05-28 10:02:46 -04:00

46 lines
1.4 KiB
Python
Executable File

#!/usr/bin/env python
from __future__ import print_function
import glob
import io
import re
import sys
def do_exist(file_name, lines, imported):
if not any(not re.match('using \w+::{0};'.format(imported), line) and
re.search('\\b{0}\\b'.format(imported), line) for line in lines):
print('File "{0}" does not use "{1}"'.format(file_name, imported))
return False
return True
def is_valid(file_name):
with io.open(file_name, encoding='utf-8') as source_file:
lines = [line.strip() for line in source_file]
usings, importeds, line_numbers, valid = [], [], [], True
for idx, line in enumerate(lines, 1):
matches = re.search(r'^using (\w+::(\w+));$', line)
if matches:
line_numbers.append(idx)
usings.append(matches.group(1))
importeds.append(matches.group(2))
valid = all([do_exist(file_name, lines, imported) for imported in importeds])
sorted_usings = sorted(usings, key=lambda x: x.lower())
if sorted_usings != usings:
print("using statements aren't sorted in '{0}'.".format(file_name))
for num, actual, expected in zip(line_numbers, usings, sorted_usings):
if actual != expected:
print('\tLine {0}: Actual: {1}, Expected: {2}'
.format(num, actual, expected))
return False
else:
return valid
if __name__ == '__main__':
files = glob.iglob(sys.argv[1] if len(sys.argv) > 1 else 'src/*.cc')
sys.exit(0 if all(map(is_valid, files)) else 1)