diff --git a/cpython/search_pypi_top.py b/cpython/search_pypi_top.py index f85acbd..c8b26dc 100755 --- a/cpython/search_pypi_top.py +++ b/cpython/search_pypi_top.py @@ -170,22 +170,45 @@ def grep(args, archive_filename, regex): logger.info(f"ignore: {filename}") continue - matches = [] - ignore = False - lineno = 1 - # Split at Unix newline b'\n' byte - for line in fp: - if lineno == 1 and IGNORE_CYTHON and CYTHON_REGEX.match(line): - logger.info(f"ignore Cython file: {archive_filename}: {filename}") - ignore = True - break - match = regex.search(line) - if match: - matches.append((filename, line, match.span())) - lineno += 1 - - if matches and not ignore: - yield from matches + if args.multiline: + yield from _grep_multiline(archive_filename, filename, fp, regex) + else: + yield from _grep_lines(archive_filename, filename, fp, regex) + + +def _grep_lines(archive_filename, filename, fp, regex): + matches = [] + lineno = 1 + # Split at Unix newline b'\n' byte + for line in fp: + if lineno == 1 and IGNORE_CYTHON and CYTHON_REGEX.match(line): + logger.info(f"ignore Cython file: {archive_filename}: {filename}") + return + match = regex.search(line) + if match: + matches.append((filename, line, match.span())) + lineno += 1 + + yield from matches + + +def _grep_multiline(archive_filename, filename, fp, regex): + # Search the whole file at once, so the regex can match across lines. + data = fp.read() + if IGNORE_CYTHON and CYTHON_REGEX.match(data): + logger.info(f"ignore Cython file: {archive_filename}: {filename}") + return + last_start = -1 + for match in regex.finditer(data): + start = data.rfind(b'\n', 0, match.start()) + 1 + if start == last_start: + continue + last_start = start + end = data.find(b'\n', match.start()) + if end == -1: + end = len(data) + line = data[start:end] + yield filename, line, (match.start() - start, min(match.end(), end) - start) def search_file(filename, index, len_filenames, args, pypi_dir, regex): @@ -219,7 +242,10 @@ def search_dir(args, pypi_dir, pattern): lines = 0 projects = set() all_results = [] - regex = re.compile(pattern) + flags = 0 + if args.multiline: + flags |= re.MULTILINE + regex = re.compile(pattern, flags) filenames = (filename for filename in os.listdir(pypi_dir) if filename != DS_STORE) filenames = sorted(filenames, key=str.lower) @@ -262,6 +288,10 @@ def parse_args(): help="Quiet mode (ex: don't log proceed files)") parser.add_argument('--cython', action='store_true', help="Search also in code generated by Cython") + parser.add_argument('--multiline', action='store_true', + help="Search the whole file at once instead of " + "line by line, so the regex can match " + "across lines") return parser.parse_args()