|
| 1 | +# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- |
| 2 | +"""Snapcraft metadata linter. |
| 3 | +
|
| 4 | +Validates that the snap's ``snapcraft.yaml`` (represented by ``SnapMetadata``) |
| 5 | +contains the minimum viable set of metadata fields and that their values look |
| 6 | +sane. The checks are grouped into *levels* so the user can prioritise the |
| 7 | +highest-impact fixes first. |
| 8 | +""" |
| 9 | + |
| 10 | +from collections.abc import Callable |
| 11 | +from dataclasses import dataclass |
| 12 | +from typing import Any, Optional |
| 13 | + |
| 14 | +from overrides import overrides |
| 15 | + |
| 16 | +from snapcraft.meta.snap_yaml import SnapMetadata |
| 17 | + |
| 18 | +from .base import Linter, LinterIssue, LinterResult |
| 19 | + |
| 20 | +_HELP_URL = "https://documentation.ubuntu.com/snapcraft/stable/reference/project-file/snapcraft-yaml/" |
| 21 | + |
| 22 | + |
| 23 | +@dataclass |
| 24 | +class MetadataField: |
| 25 | + name: str |
| 26 | + severity: LinterResult |
| 27 | + extract: Callable[["SnapMetadata"], Any] |
| 28 | + help_url: str |
| 29 | + |
| 30 | + |
| 31 | +# Helper to pull the matching attribute values from all the apps |
| 32 | +def _get_apps_attr(meta: SnapMetadata, key: str) -> dict[str, list[str]] | None: |
| 33 | + if not meta.apps: |
| 34 | + return None |
| 35 | + |
| 36 | + values: dict[str, list[str]] = {} |
| 37 | + for name, app in meta.apps.items(): |
| 38 | + value: str | list[str] | None = getattr(app, key, None) |
| 39 | + if value and isinstance(value, list): |
| 40 | + values[name] = value |
| 41 | + elif isinstance(value, str): |
| 42 | + values[name] = [value] |
| 43 | + else: |
| 44 | + values[name] = [] |
| 45 | + |
| 46 | + return values if values else None |
| 47 | + |
| 48 | + |
| 49 | +# Helper to pull the matching attribute values from the links |
| 50 | +def _get_links_attr(meta: SnapMetadata, key: str) -> list[str] | str | None: |
| 51 | + if not meta.links: |
| 52 | + return None |
| 53 | + |
| 54 | + return getattr(meta.links, key, None) |
| 55 | + |
| 56 | + |
| 57 | +_FIELDS: list[MetadataField] = [ |
| 58 | + # TODO: implement desktop field in Rank1 |
| 59 | + # TODO: implement icon field in Rank1 |
| 60 | + # Rank 1 fields |
| 61 | + MetadataField( |
| 62 | + "title", LinterResult.WARNING, lambda meta: meta.title, f"{_HELP_URL}#title" |
| 63 | + ), |
| 64 | + MetadataField( |
| 65 | + "contact", |
| 66 | + LinterResult.WARNING, |
| 67 | + lambda meta: _get_links_attr(meta, "contact"), |
| 68 | + f"{_HELP_URL}#contact", |
| 69 | + ), |
| 70 | + MetadataField( |
| 71 | + "license", |
| 72 | + LinterResult.WARNING, |
| 73 | + lambda meta: meta.license, |
| 74 | + f"{_HELP_URL}#license", |
| 75 | + ), |
| 76 | + MetadataField( |
| 77 | + "common_id", |
| 78 | + LinterResult.WARNING, |
| 79 | + lambda meta: _get_apps_attr(meta, "common_id"), |
| 80 | + f"{_HELP_URL}#apps.<app-name>.common-id", |
| 81 | + ), |
| 82 | + # Rank 2 fields |
| 83 | + MetadataField( |
| 84 | + "donation", |
| 85 | + LinterResult.INFO, |
| 86 | + lambda meta: _get_links_attr(meta, "donation"), |
| 87 | + f"{_HELP_URL}#donation", |
| 88 | + ), |
| 89 | + MetadataField( |
| 90 | + "issues", |
| 91 | + LinterResult.INFO, |
| 92 | + lambda meta: _get_links_attr(meta, "issues"), |
| 93 | + f"{_HELP_URL}#issues", |
| 94 | + ), |
| 95 | + MetadataField( |
| 96 | + "source_code", |
| 97 | + LinterResult.INFO, |
| 98 | + lambda meta: _get_links_attr(meta, "source_code"), |
| 99 | + f"{_HELP_URL}#source-code", |
| 100 | + ), |
| 101 | + MetadataField( |
| 102 | + "website", |
| 103 | + LinterResult.INFO, |
| 104 | + lambda meta: _get_links_attr(meta, "website"), |
| 105 | + f"{_HELP_URL}#website", |
| 106 | + ), |
| 107 | +] |
| 108 | + |
| 109 | + |
| 110 | +class MetadataLinter(Linter): |
| 111 | + """Checks snap metadata completeness and semantic validity.""" |
| 112 | + |
| 113 | + @staticmethod |
| 114 | + def get_categories() -> list[str]: |
| 115 | + return [field.name for field in _FIELDS] |
| 116 | + |
| 117 | + @classmethod |
| 118 | + def _is_dict_empty( |
| 119 | + cls, value: dict[str, list[str]] | None |
| 120 | + ) -> dict[str, bool] | bool: |
| 121 | + """Check if dictionary values are empty or None. |
| 122 | +
|
| 123 | + :param value: Dictionary to check |
| 124 | +
|
| 125 | + :returns: True if all values are empty, Dict mapping keys to empty status otherwise |
| 126 | + """ |
| 127 | + if value is None: |
| 128 | + return True |
| 129 | + result = {} |
| 130 | + for key, values in value.items(): |
| 131 | + if not values: |
| 132 | + result[key] = True |
| 133 | + |
| 134 | + return result if result else False |
| 135 | + |
| 136 | + @classmethod |
| 137 | + def _is_empty( |
| 138 | + cls, |
| 139 | + value: str | dict[str, list[str]] | list[str] | None, |
| 140 | + ) -> dict[str, bool] | bool: |
| 141 | + """Check if a value is empty, handling different types appropriately. |
| 142 | +
|
| 143 | + :param value: The value to check |
| 144 | +
|
| 145 | + :returns: True if empty, False if not empty, or Dict for partial emptiness in dict values |
| 146 | + """ |
| 147 | + if value is None: |
| 148 | + return True |
| 149 | + if isinstance(value, str): |
| 150 | + return value.strip() == "" |
| 151 | + if isinstance(value, list) and not value: |
| 152 | + return True |
| 153 | + if isinstance(value, dict): |
| 154 | + return cls._is_dict_empty(value) |
| 155 | + return False |
| 156 | + |
| 157 | + def _create_issue( |
| 158 | + self, field: MetadataField, text: str, result: Optional["LinterResult"] = None |
| 159 | + ) -> "LinterIssue": |
| 160 | + """Create a linter issue for a metadata field. |
| 161 | +
|
| 162 | + :param field: The metadata field |
| 163 | + :param text: Issue description |
| 164 | + :param result: Override result type (defaults to field rank severity) |
| 165 | +
|
| 166 | + :returns: LinterIssue instance |
| 167 | + """ |
| 168 | + help_url = field.help_url if result is not LinterResult.IGNORED else None |
| 169 | + |
| 170 | + return LinterIssue( |
| 171 | + name=self._name, |
| 172 | + result=result or field.severity, |
| 173 | + text=text, |
| 174 | + url=help_url, |
| 175 | + ) |
| 176 | + |
| 177 | + def _check_field(self, field: MetadataField) -> list["LinterIssue"]: |
| 178 | + """Check if a metadata field is complete and create issues if not. |
| 179 | +
|
| 180 | + :param field: The metadata field to check |
| 181 | +
|
| 182 | + :returns: List of linter issues found |
| 183 | + """ |
| 184 | + issues = [] |
| 185 | + value = field.extract(self._snap_metadata) |
| 186 | + field_name = field.name.replace("_", "-") |
| 187 | + |
| 188 | + result = self._is_empty(value) |
| 189 | + |
| 190 | + if isinstance(result, bool) and result: |
| 191 | + issues.append( |
| 192 | + self._create_issue( |
| 193 | + field, |
| 194 | + f"Metadata field '{field_name}' is missing or empty.", |
| 195 | + ) |
| 196 | + ) |
| 197 | + elif isinstance(result, dict): |
| 198 | + for name, is_empty in result.items(): |
| 199 | + if is_empty: |
| 200 | + issues.append( |
| 201 | + self._create_issue( |
| 202 | + field, |
| 203 | + f"Metadata field '{field_name}' for app '{name}' is missing or empty.", |
| 204 | + ) |
| 205 | + ) |
| 206 | + |
| 207 | + return issues |
| 208 | + |
| 209 | + @overrides |
| 210 | + def run(self) -> list[LinterIssue]: |
| 211 | + meta: SnapMetadata = self._snap_metadata |
| 212 | + |
| 213 | + if meta.grade == "devel": |
| 214 | + return [] |
| 215 | + |
| 216 | + issues: list[LinterIssue] = [] |
| 217 | + for field in _FIELDS: |
| 218 | + if field.name == "common_id" and ( |
| 219 | + (meta.type and meta.type != "app") or not meta.apps |
| 220 | + ): |
| 221 | + continue |
| 222 | + if self._lint and field.name in self._lint.ignored_files(self._name): |
| 223 | + issues.append( |
| 224 | + self._create_issue( |
| 225 | + field, |
| 226 | + f"Metadata field '{field.name}' is ignored.", |
| 227 | + LinterResult.IGNORED, |
| 228 | + ) |
| 229 | + ) |
| 230 | + continue |
| 231 | + |
| 232 | + issues.extend(self._check_field(field)) |
| 233 | + |
| 234 | + return issues |
0 commit comments