|
| 1 | +# -------------------------------------------------------------------------------------------- |
| 2 | +# Copyright (c) Microsoft Corporation. All rights reserved. |
| 3 | +# Licensed under the MIT License. See License.txt in the project root for license information. |
| 4 | +# -------------------------------------------------------------------------------------------- |
| 5 | + |
| 6 | +""" |
| 7 | +Extension metadata extraction. |
| 8 | +
|
| 9 | +Replaces the legacy wheel-0.30.0 ``metadata.json`` read path with a |
| 10 | +``pkginfo``-based reader of the spec-compliant ``METADATA`` file inside each |
| 11 | +extension wheel, merged with the extension's ``azext_metadata.json``. |
| 12 | +
|
| 13 | +Used by ``azdev.operations.extensions.util.get_ext_metadata`` to build the |
| 14 | +entries stored in ``index.json``. |
| 15 | +""" |
| 16 | + |
| 17 | +from __future__ import annotations |
| 18 | + |
| 19 | +import json |
| 20 | +import re |
| 21 | +from pathlib import Path |
| 22 | +from typing import Any, Dict, List, Optional, Tuple |
| 23 | + |
| 24 | + |
| 25 | +# Splits a requirement string into (name, spec). Accepts both shapes that may |
| 26 | +# appear in METADATA Requires-Dist: |
| 27 | +# * PEP 508 form: "oras==0.1.30" (modern setuptools / wheel) |
| 28 | +# * PEP 314 form: "oras (==0.1.30)" (older setuptools, wheel 0.30.0) |
| 29 | +# Either spec form is captured into a single, normalized spec string. |
| 30 | +_REQ_SPLIT_RE = re.compile( |
| 31 | + r"^\s*(?P<name>[A-Za-z0-9_.\-]+)\s*" |
| 32 | + r"(?:\(\s*(?P<paren_spec>[^)]+?)\s*\)|(?P<bare_spec>[<>=!~].*?))?\s*$" |
| 33 | +) |
| 34 | + |
| 35 | + |
| 36 | +def _get_extension_modname(ext_dir: Path) -> str: |
| 37 | + pos = [d.name for d in ext_dir.iterdir() if d.is_dir() and d.name.startswith("azext_")] |
| 38 | + if len(pos) != 1: |
| 39 | + raise AssertionError( |
| 40 | + "Expected exactly one azext_* module in {}, found: {}".format(ext_dir, pos) |
| 41 | + ) |
| 42 | + return pos[0] |
| 43 | + |
| 44 | + |
| 45 | +def read_azext_metadata(ext_dir: Path) -> Dict[str, Any]: |
| 46 | + modname = _get_extension_modname(ext_dir) |
| 47 | + path = ext_dir / modname / "azext_metadata.json" |
| 48 | + if not path.is_file(): |
| 49 | + return {} |
| 50 | + with path.open(encoding="utf-8") as fh: |
| 51 | + return json.load(fh) |
| 52 | + |
| 53 | + |
| 54 | +def pkginfo_to_dict(ext_file) -> Dict[str, Any]: |
| 55 | + """Build an index.json-shaped metadata dict from a wheel file. |
| 56 | +
|
| 57 | + This replaces the legacy ``metadata.json`` read path (which only existed |
| 58 | + in wheels produced by ``wheel==0.30.0``) with a ``pkginfo.Wheel`` based |
| 59 | + reader of the spec-defined ``METADATA`` file. Used by |
| 60 | + ``azdev.operations.extensions.util.get_ext_metadata``. |
| 61 | + """ |
| 62 | + return merge_to_index_metadata(read_pkginfo(Path(str(ext_file))), {}) |
| 63 | + |
| 64 | + |
| 65 | +def read_pkginfo(wheel_path: Path) -> Dict[str, Any]: |
| 66 | + """Read spec-defined wheel metadata via pkginfo.Wheel.""" |
| 67 | + import pkginfo |
| 68 | + |
| 69 | + whl = pkginfo.Wheel(str(wheel_path)) |
| 70 | + return { |
| 71 | + "name": whl.name, |
| 72 | + "version": whl.version, |
| 73 | + "summary": whl.summary, |
| 74 | + "description": whl.description, |
| 75 | + "description_content_type": whl.description_content_type, |
| 76 | + "license": whl.license, |
| 77 | + "classifiers": list(whl.classifiers or []), |
| 78 | + "requires_dist": list(whl.requires_dist or []), |
| 79 | + "requires_python": whl.requires_python, |
| 80 | + "author": whl.author, |
| 81 | + "author_email": whl.author_email, |
| 82 | + "home_page": whl.home_page, |
| 83 | + "project_urls": list(whl.project_urls or []), |
| 84 | + "metadata_version": whl.metadata_version, |
| 85 | + "keywords": whl.keywords, |
| 86 | + } |
| 87 | + |
| 88 | + |
| 89 | +def _coerce_run_requires(requires_dist: List[str]) -> List[Dict[str, Any]]: |
| 90 | + """Approximate the legacy `run_requires` block produced by wheel 0.30.0. |
| 91 | +
|
| 92 | + Wheel 0.30.0 emitted each requirement in two forms inside `run_requires`: |
| 93 | + * the PEP 314 / PEP 345 form: ``"oras (==0.1.30)"`` (name space then |
| 94 | + version specifier wrapped in parentheses), and |
| 95 | + * the canonical PEP 508 form: ``"oras==0.1.30"`` (no space, no parens). |
| 96 | +
|
| 97 | + It also sorted entries alphabetically by package name (this is observable in |
| 98 | + `src/index.json`: every `run_requires` block is name-sorted regardless of |
| 99 | + `install_requires` order in `setup.py`). |
| 100 | +
|
| 101 | + Modern wheel metadata (`METADATA` Requires-Dist) only carries PEP 508 and |
| 102 | + preserves source order, so we reproduce both transformations here. |
| 103 | + """ |
| 104 | + if not requires_dist: |
| 105 | + return [] |
| 106 | + |
| 107 | + parsed: List[Tuple[str, Optional[str], str]] = [] |
| 108 | + seen: set = set() |
| 109 | + for req in requires_dist: |
| 110 | + canonical = req.strip() |
| 111 | + match = _REQ_SPLIT_RE.match(canonical) |
| 112 | + if match: |
| 113 | + name = match.group("name") |
| 114 | + spec = match.group("paren_spec") or match.group("bare_spec") |
| 115 | + spec = spec.strip() if spec else None |
| 116 | + else: |
| 117 | + name, spec = canonical, None |
| 118 | + # Older setuptools (e.g. 70.0.0) writes Requires-Dist twice per |
| 119 | + # package in METADATA -- once as "name (spec)" and once as |
| 120 | + # "name==spec". Modern setuptools writes only the canonical PEP 508 |
| 121 | + # form. Deduplicate on (lowercase name, normalized spec) so the |
| 122 | + # doubling step below produces the same output regardless of which |
| 123 | + # setuptools generated the wheel. |
| 124 | + key = (name.lower(), (spec or "").replace(" ", "")) |
| 125 | + if key in seen: |
| 126 | + continue |
| 127 | + seen.add(key) |
| 128 | + parsed.append((name, spec, canonical)) |
| 129 | + |
| 130 | + parsed.sort(key=lambda t: t[0].lower()) |
| 131 | + |
| 132 | + doubled: List[str] = [] |
| 133 | + for name, spec, canonical in parsed: |
| 134 | + if spec: |
| 135 | + doubled.append("{} ({})".format(name, spec)) |
| 136 | + doubled.append("{}{}".format(name, spec)) |
| 137 | + else: |
| 138 | + doubled.append(canonical) |
| 139 | + doubled.append(canonical) |
| 140 | + return [{"requires": doubled}] |
| 141 | + |
| 142 | + |
| 143 | +def _coerce_project_urls(project_urls: List[str], home_page: Optional[str]) -> Dict[str, str]: |
| 144 | + out: Dict[str, str] = {} |
| 145 | + if home_page: |
| 146 | + out["Home"] = home_page |
| 147 | + for entry in project_urls or []: |
| 148 | + if "," in entry: |
| 149 | + label, url = entry.split(",", 1) |
| 150 | + out[label.strip()] = url.strip() |
| 151 | + return out |
| 152 | + |
| 153 | + |
| 154 | +def _coerce_contacts(author: Optional[str], author_email: Optional[str]) -> List[Dict[str, str]]: |
| 155 | + if not author and not author_email: |
| 156 | + return [] |
| 157 | + contact: Dict[str, str] = {"role": "author"} |
| 158 | + if author: |
| 159 | + contact["name"] = author |
| 160 | + if author_email: |
| 161 | + contact["email"] = author_email |
| 162 | + return [contact] |
| 163 | + |
| 164 | + |
| 165 | +def merge_to_index_metadata(pkg: Dict[str, Any], azext: Dict[str, Any]) -> Dict[str, Any]: |
| 166 | + """Merge `pkginfo` output and `azext_metadata.json` into the index.json shape. |
| 167 | +
|
| 168 | + Precedence (highest first): azext_metadata > pkginfo > derived defaults. |
| 169 | + """ |
| 170 | + metadata: Dict[str, Any] = {} |
| 171 | + |
| 172 | + metadata["name"] = pkg.get("name") |
| 173 | + metadata["version"] = pkg.get("version") |
| 174 | + metadata["summary"] = pkg.get("summary") |
| 175 | + metadata["license"] = pkg.get("license") |
| 176 | + metadata["metadata_version"] = pkg.get("metadata_version") |
| 177 | + metadata["classifiers"] = pkg.get("classifiers") or [] |
| 178 | + metadata["extras"] = [] |
| 179 | + metadata["run_requires"] = _coerce_run_requires(pkg.get("requires_dist") or []) |
| 180 | + metadata["requires_python"] = pkg.get("requires_python") |
| 181 | + metadata["description_content_type"] = pkg.get("description_content_type") |
| 182 | + |
| 183 | + contacts = _coerce_contacts(pkg.get("author"), pkg.get("author_email")) |
| 184 | + project_urls = _coerce_project_urls(pkg.get("project_urls") or [], pkg.get("home_page")) |
| 185 | + details: Dict[str, Any] = {} |
| 186 | + if contacts: |
| 187 | + details["contacts"] = contacts |
| 188 | + if project_urls: |
| 189 | + details["project_urls"] = project_urls |
| 190 | + if details: |
| 191 | + metadata["extensions"] = {"python.details": details} |
| 192 | + |
| 193 | + metadata.update(azext) |
| 194 | + |
| 195 | + return {k: v for k, v in metadata.items() if v is not None} |
0 commit comments