|
| 1 | +# SPDX-License-Identifier: Apache-2.0 |
| 2 | +# |
| 3 | +# http://nexb.com and https://github.com/nexB/scancode.io |
| 4 | +# The ScanCode.io software is licensed under the Apache License version 2.0. |
| 5 | +# Data generated with ScanCode.io is provided as-is without warranties. |
| 6 | +# ScanCode is a trademark of nexB Inc. |
| 7 | +# |
| 8 | +# You may not use this software except in compliance with the License. |
| 9 | +# You may obtain a copy of the License at: http://apache.org/licenses/LICENSE-2.0 |
| 10 | +# Unless required by applicable law or agreed to in writing, software distributed |
| 11 | +# under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR |
| 12 | +# CONDITIONS OF ANY KIND, either express or implied. See the License for the |
| 13 | +# specific language governing permissions and limitations under the License. |
| 14 | +# |
| 15 | +# Data Generated with ScanCode.io is provided on an "AS IS" BASIS, WITHOUT WARRANTIES |
| 16 | +# OR CONDITIONS OF ANY KIND, either express or implied. No content created from |
| 17 | +# ScanCode.io should be considered or used as legal advice. Consult an Attorney |
| 18 | +# for any legal advice. |
| 19 | +# |
| 20 | +# ScanCode.io is a free software code scanning tool from nexB Inc. and others. |
| 21 | +# Visit https://github.com/nexB/scancode.io for support and download. |
| 22 | + |
| 23 | +# clarity_thresholds.py (updated) |
| 24 | +""" |
| 25 | +License Clarity Thresholds Management |
| 26 | +
|
| 27 | +This module provides an independent mechanism to read, validate, and evaluate |
| 28 | +license clarity score thresholds from policy files. Unlike license policies |
| 29 | +which are applied during scan processing, clarity thresholds are evaluated |
| 30 | +post-scan during summary generation. |
| 31 | +
|
| 32 | +The clarity thresholds system uses a simple key-value mapping where: |
| 33 | +- Keys are integer threshold values (minimum scores) |
| 34 | +- Values are compliance alert levels ('ok', 'warning', 'error') |
| 35 | +
|
| 36 | +Example policies.yml structure: |
| 37 | +
|
| 38 | +license_clarity_thresholds: |
| 39 | + 80: ok # Scores >= 80 get 'ok' alert |
| 40 | + 50: warning # Scores 50-79 get 'warning' alert |
| 41 | +""" |
| 42 | + |
| 43 | +from django.core.exceptions import ValidationError |
| 44 | + |
| 45 | +import saneyaml |
| 46 | + |
| 47 | + |
| 48 | +def load_yaml_content(yaml_content): |
| 49 | + """Load and parse YAML content into a Python dictionary.""" |
| 50 | + try: |
| 51 | + return saneyaml.load(yaml_content) |
| 52 | + except saneyaml.YAMLError as e: |
| 53 | + raise ValidationError(f"Policies file format error: {e}") |
| 54 | + |
| 55 | + |
| 56 | +class ClarityThresholdsPolicy: |
| 57 | + """ |
| 58 | + Manages clarity score thresholds and compliance evaluation. |
| 59 | +
|
| 60 | + This class reads clarity thresholds from a dictionary, validates them |
| 61 | + against threshold configurations and determines compliance alerts based on |
| 62 | + clarity scores. |
| 63 | + """ |
| 64 | + |
| 65 | + def __init__(self, threshold_dict): |
| 66 | + """Initialize with validated threshold dictionary.""" |
| 67 | + self.thresholds = self.validate_thresholds(threshold_dict) |
| 68 | + |
| 69 | + @staticmethod |
| 70 | + def validate_thresholds(threshold_dict): |
| 71 | + if not isinstance(threshold_dict, dict): |
| 72 | + raise ValidationError( |
| 73 | + "The `license_clarity_thresholds` must be a dictionary" |
| 74 | + ) |
| 75 | + validated = {} |
| 76 | + seen = set() |
| 77 | + for key, value in threshold_dict.items(): |
| 78 | + try: |
| 79 | + threshold = int(key) |
| 80 | + except (ValueError, TypeError): |
| 81 | + raise ValidationError(f"Threshold keys must be integers, got: {key}") |
| 82 | + if threshold in seen: |
| 83 | + raise ValidationError(f"Duplicate threshold key: {threshold}") |
| 84 | + seen.add(threshold) |
| 85 | + if value not in ["ok", "warning", "error"]: |
| 86 | + raise ValidationError( |
| 87 | + f"Compliance alert must be one of 'ok', 'warning', 'error', " |
| 88 | + f"got: {value}" |
| 89 | + ) |
| 90 | + validated[threshold] = value |
| 91 | + sorted_keys = sorted(validated.keys(), reverse=True) |
| 92 | + if list(validated.keys()) != sorted_keys: |
| 93 | + raise ValidationError("Thresholds must be strictly descending") |
| 94 | + return validated |
| 95 | + |
| 96 | + def get_alert_for_score(self, score): |
| 97 | + """ |
| 98 | + Determine compliance alert level for a given clarity score |
| 99 | +
|
| 100 | + Returns: |
| 101 | + str: Compliance alert level ('ok', 'warning', 'error') |
| 102 | +
|
| 103 | + """ |
| 104 | + if score is None: |
| 105 | + return "error" |
| 106 | + |
| 107 | + # Find the highest threshold that the score meets or exceeds |
| 108 | + applicable_thresholds = [t for t in self.thresholds if score >= t] |
| 109 | + if not applicable_thresholds: |
| 110 | + return "error" |
| 111 | + |
| 112 | + max_threshold = max(applicable_thresholds) |
| 113 | + return self.thresholds[max_threshold] |
| 114 | + |
| 115 | + def get_thresholds_summary(self): |
| 116 | + """ |
| 117 | + Get a summary of configured thresholds for reporting |
| 118 | +
|
| 119 | + Returns: |
| 120 | + dict: Summary of thresholds and their alert levels |
| 121 | +
|
| 122 | + """ |
| 123 | + return dict(sorted(self.thresholds.items(), reverse=True)) |
| 124 | + |
| 125 | + |
| 126 | +def load_clarity_thresholds_from_yaml(yaml_content): |
| 127 | + """ |
| 128 | + Load clarity thresholds from YAML content. |
| 129 | +
|
| 130 | + Returns: |
| 131 | + ClarityThresholdsPolicy: Configured policy object |
| 132 | +
|
| 133 | + """ |
| 134 | + data = load_yaml_content(yaml_content) |
| 135 | + |
| 136 | + if not isinstance(data, dict): |
| 137 | + raise ValidationError("YAML content must be a dictionary.") |
| 138 | + |
| 139 | + if "license_clarity_thresholds" not in data: |
| 140 | + raise ValidationError( |
| 141 | + "Missing 'license_clarity_thresholds' key in policies file." |
| 142 | + ) |
| 143 | + |
| 144 | + return ClarityThresholdsPolicy(data["license_clarity_thresholds"]) |
| 145 | + |
| 146 | + |
| 147 | +def load_clarity_thresholds_from_file(file_path): |
| 148 | + """ |
| 149 | + Load clarity thresholds from a YAML file. |
| 150 | +
|
| 151 | + Returns: |
| 152 | + ClarityThresholdsPolicy: Configured policy object or None if file not found |
| 153 | +
|
| 154 | + """ |
| 155 | + from pathlib import Path |
| 156 | + |
| 157 | + file_path = Path(file_path) |
| 158 | + |
| 159 | + if not file_path.exists(): |
| 160 | + return None |
| 161 | + |
| 162 | + try: |
| 163 | + yaml_content = file_path.read_text(encoding="utf-8") |
| 164 | + return load_clarity_thresholds_from_yaml(yaml_content) |
| 165 | + except (OSError, UnicodeDecodeError) as e: |
| 166 | + raise ValidationError(f"Error reading file {file_path}: {e}") |
0 commit comments