|
| 1 | +# |
| 2 | +# Copyright (c) nexB Inc. and others. All rights reserved. |
| 3 | +# ScanCode is a trademark of nexB Inc. |
| 4 | +# SPDX-License-Identifier: Apache-2.0 |
| 5 | +# See http://www.apache.org/licenses/LICENSE-2.0 for the license text. |
| 6 | +# See https://github.com/nexB/scancode-toolkit for support or download. |
| 7 | +# See https://aboutcode.org for more information about nexB OSS projects. |
| 8 | +# |
| 9 | + |
| 10 | + |
| 11 | + |
| 12 | +import io |
| 13 | +from pathlib import Path |
| 14 | +from dockerfile_parse import DockerfileParser |
| 15 | +from packagedcode import models |
| 16 | +from packagedcode import utils |
| 17 | + |
| 18 | + |
| 19 | +class DockerfileHandler(models.DatafileHandler): |
| 20 | + datasource_id = 'dockerfile' |
| 21 | + default_package_type = 'docker-image' |
| 22 | + path_patterns = ('Dockerfile', 'containerfile', '*.dockerfile') |
| 23 | + description = 'Dockerfile (OCI) metadata handler' |
| 24 | + documentation_url = 'https://docs.docker.com/engine/reference/builder/' |
| 25 | + |
| 26 | + @classmethod |
| 27 | + def parse(cls, location, package_only=False): |
| 28 | + """ |
| 29 | + Parse a Dockerfile and yield one or more PackageData objects with OCI labels and metadata. |
| 30 | + """ |
| 31 | + labels = cls.extract_oci_labels_from_dockerfile(location) |
| 32 | + |
| 33 | + |
| 34 | + package_data = { |
| 35 | + 'datasource_id': cls.datasource_id, |
| 36 | + 'type': cls.default_package_type, |
| 37 | + 'name': labels.get('name', 'unknown'), |
| 38 | + 'version': labels.get('version', 'unknown'), |
| 39 | + 'license_expression': labels.get('license', 'unknown'), |
| 40 | + 'labels': labels, |
| 41 | + } |
| 42 | + |
| 43 | + yield models.PackageData.from_data(package_data, package_only) |
| 44 | + |
| 45 | + @classmethod |
| 46 | + def extract_oci_labels_from_dockerfile(cls, dockerfile_path): |
| 47 | + """ |
| 48 | + Extract OCI labels from the Dockerfile using container-inspector. |
| 49 | + """ |
| 50 | + labels = {} |
| 51 | + parser = DockerfileParser() |
| 52 | + parser.parse(dockerfile_path) |
| 53 | + labels = parser.labels |
| 54 | + return labels |
| 55 | + |
| 56 | + @classmethod |
| 57 | + def assemble(cls, package_data, resource, codebase, package_adder): |
| 58 | + """ |
| 59 | + Assemble a Package from the parsed Dockerfile data. |
| 60 | + """ |
| 61 | + if package_data.purl: |
| 62 | + package = models.Package.from_package_data(package_data=package_data, datafile_path=resource.path) |
| 63 | + |
| 64 | + |
| 65 | + package.populate_license_fields() |
| 66 | + |
| 67 | + yield package |
| 68 | + |
| 69 | + |
| 70 | + package_adder(package.package_uid, resource, codebase) |
| 71 | + |
| 72 | + yield resource |
0 commit comments