|
2 | 2 | # SPDX-License-Identifier: GPL-3.0-or-later
|
3 | 3 | from __future__ import annotations
|
4 | 4 |
|
| 5 | +import os |
| 6 | +import re |
5 | 7 | import sys
|
6 | 8 |
|
7 | 9 | if sys.version_info >= (3, 10):
|
8 | 10 | from importlib import metadata as importlib_metadata
|
9 | 11 | else:
|
10 | 12 | import importlib_metadata
|
| 13 | +if sys.version_info >= (3, 9): |
| 14 | + import importlib.resources as resources |
| 15 | +else: |
| 16 | + import importlib_resources as resources |
11 | 17 |
|
12 | 18 | from cve_bin_tool.parsers import Parser
|
13 | 19 |
|
14 | 20 | PARSERS_ENTRYPOINT = "cve_bin_tool.parsers"
|
15 | 21 |
|
16 | 22 |
|
| 23 | +def enumerate_builtin_parsers(): |
| 24 | + """Reads the files in cve_bin_tool/parsers/ to auto determine list""" |
| 25 | + parsers = {} |
| 26 | + for path in resources.files("cve_bin_tool.parsers").iterdir(): |
| 27 | + if path.suffix != ".py" or path.stem in ("__init__", "parser"): |
| 28 | + continue |
| 29 | + contents = path.read_text() |
| 30 | + for re_match in re.finditer(r"^class (\w+)", contents, re.MULTILINE): |
| 31 | + parser_cls_name = re_match[1] |
| 32 | + parsers[".".join([path.stem, parser_cls_name])] = ":".join( |
| 33 | + [ |
| 34 | + str(path.relative_to(path.parents[2]).with_suffix("")).replace( |
| 35 | + os.path.sep, "." |
| 36 | + ), |
| 37 | + parser_cls_name, |
| 38 | + ], |
| 39 | + ) |
| 40 | + return parsers |
| 41 | + |
| 42 | + |
| 43 | +BUILTIN_PARSERS = { |
| 44 | + parser_entry_point_name: importlib_metadata.EntryPoint( |
| 45 | + parser_entry_point_name, |
| 46 | + entry_point_path, |
| 47 | + "cve_bin_tool.parsers", |
| 48 | + ) |
| 49 | + for ( |
| 50 | + parser_entry_point_name, |
| 51 | + entry_point_path, |
| 52 | + ) in enumerate_builtin_parsers().items() |
| 53 | +} |
| 54 | + |
| 55 | + |
17 | 56 | def load_valid_files() -> dict[str, list[type[Parser]]]:
|
18 | 57 | """Loads file parsers"""
|
19 | 58 | valid_files: dict[str, list[type[Parser]]] = {}
|
20 |
| - for entrypoint in importlib_metadata.entry_points().select( |
21 |
| - group=PARSERS_ENTRYPOINT |
22 |
| - ): |
| 59 | + |
| 60 | + for entrypoint in [ |
| 61 | + *BUILTIN_PARSERS.values(), |
| 62 | + *importlib_metadata.entry_points().select( |
| 63 | + group=PARSERS_ENTRYPOINT, |
| 64 | + ), |
| 65 | + ]: |
23 | 66 | parser_cls = entrypoint.load()
|
24 | 67 | for match_filename in getattr(parser_cls, "PARSER_MATCH_FILENAMES", []):
|
25 | 68 | valid_files.setdefault(match_filename, [])
|
|
0 commit comments