|
| 1 | +import os |
| 2 | +import yaml |
| 3 | +import logging |
| 4 | + |
| 5 | +from codeqlsummarize.models import CodeQLDatabase, GitHub |
| 6 | + |
| 7 | +logger = logging.getLogger("codeqlsummarize.exporters.extensions") |
| 8 | + |
| 9 | +CODEQL_EXTENSION = """\ |
| 10 | + - addsTo: |
| 11 | + pack: codeql/{language}-queries |
| 12 | + extensible: {extensible} |
| 13 | + data: |
| 14 | +{rows} |
| 15 | +""" |
| 16 | + |
| 17 | +EXTENSIBLE = { |
| 18 | + "SinkModel": "sinkModel", |
| 19 | + "SourceModel": "sourceModel", |
| 20 | + "SummaryModel": "summaryModel", |
| 21 | +} |
| 22 | + |
| 23 | + |
| 24 | +def exportDataExtensions(database: CodeQLDatabase, output: str, github: GitHub, **kargs): |
| 25 | + logger.info("Running export to Data Extensions") |
| 26 | + |
| 27 | + if database.language == "javascript": |
| 28 | + logger.warning("Skipping JavaScript for now") |
| 29 | + return |
| 30 | + |
| 31 | + # Get the CodeQL pack for the language |
| 32 | + codeqlPack = findCodeQLPack(output, database.language) |
| 33 | + os.makedirs(os.path.join(codeqlPack, "generated"), exist_ok=True) |
| 34 | + |
| 35 | + if github.owner: |
| 36 | + os.makedirs(os.path.join(codeqlPack, "generated", github.owner), exist_ok=True) |
| 37 | + extensions_file = os.path.join(codeqlPack, "generated", github.owner, f"{database.name}.yml") |
| 38 | + else: |
| 39 | + extensions_file = os.path.join(codeqlPack, "generated", f"{database.name}.yml") |
| 40 | + |
| 41 | + data = "extensions:\n" |
| 42 | + for sname, summary in database.summaries.items(): |
| 43 | + if len(summary.rows) == 0: |
| 44 | + continue |
| 45 | + |
| 46 | + summary_rows = "" |
| 47 | + for mad in sorted(summary.rows): |
| 48 | + m = mad.split(";") |
| 49 | + summary_rows += " - " |
| 50 | + summary_rows += f'["{m[0]}", "{m[1]}", {m[2]}, "{m[3]}", "{m[4]}", "{m[5]}", "{m[6]}", "{m[7]}", "{m[8]}"]\n' |
| 51 | + |
| 52 | + data += CODEQL_EXTENSION.format( |
| 53 | + rows=summary_rows, |
| 54 | + language=database.language, |
| 55 | + extensible=EXTENSIBLE.get(sname, "sinkModel") |
| 56 | + ) |
| 57 | + |
| 58 | + logger.info(f"Writing Data Extensions to: {extensions_file}") |
| 59 | + with open(extensions_file, "w") as handle: |
| 60 | + handle.write(data) |
| 61 | + |
| 62 | + |
| 63 | +def findCodeQLPack(location: str, language: str) -> str: |
| 64 | + """Find the CodeQL pack for the given language in the output directory""" |
| 65 | + |
| 66 | + if os.path.isfile(location): |
| 67 | + raise Exception(f"Directory {location} does not exist") |
| 68 | + |
| 69 | + for root, dirs, files in os.walk(location): |
| 70 | + for file in files: |
| 71 | + if file == "qlpack.yml": |
| 72 | + with open(os.path.join(root, file), "r") as f: |
| 73 | + qlpack = yaml.safe_load(f) |
| 74 | + |
| 75 | + if f"codeql/{language}-queries" in qlpack.get("extensionTargets", []): |
| 76 | + return root |
| 77 | + |
| 78 | + raise Exception(f"Could not find CodeQL pack for {language} in {location}") |
0 commit comments