|
| 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 | +import fnmatch |
| 18 | + |
| 19 | + |
| 20 | +class DockerfileHandler(models.DatafileHandler): |
| 21 | + datasource_id = 'dockerfile_oci_labels' |
| 22 | + |
| 23 | + @classmethod |
| 24 | + def is_datafile(cls, path): |
| 25 | + patterns = ['Dockerfile', 'containerfile', '*.dockerfile'] |
| 26 | + filename=os.path.basename(path) |
| 27 | + for pattern in patterns: |
| 28 | + if fnmatch.fnmatch(filename, pattern): |
| 29 | + return True |
| 30 | + return False |
| 31 | + |
| 32 | + @classmethod |
| 33 | + def parse(cls, location, package_only=False): |
| 34 | + """ |
| 35 | + Parse a Dockerfile and yield one or more PackageData objects with OCI labels and metadata. |
| 36 | + """ |
| 37 | + labels = cls.extract_oci_labels_from_dockerfile(location) |
| 38 | + package_data = { |
| 39 | + 'datasource_id': cls.datasource_id, |
| 40 | + 'type': cls.default_package_type, |
| 41 | + 'name': labels.get('name', 'None'), |
| 42 | + 'version': labels.get('version', 'None'), |
| 43 | + 'license_expression': labels.get('license', 'None'), |
| 44 | + 'labels': labels, |
| 45 | + } |
| 46 | + |
| 47 | + yield models.PackageData.from_data(package_data, package_only) |
| 48 | + |
| 49 | + @classmethod |
| 50 | + def extract_oci_labels_from_dockerfile(cls, dockerfile_path): |
| 51 | + """ |
| 52 | + Extract OCI labels from the Dockerfile using DockerfileParser. |
| 53 | + """ |
| 54 | + labels = {} |
| 55 | + parser = DockerfileParser() |
| 56 | + with open(dockerfile_path, 'r') as dockerfile: |
| 57 | + parser.content = dockerfile.read() |
| 58 | + labels = parser.labels |
| 59 | + return labels |
0 commit comments