uv-metadata 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,205 @@
1
+ Metadata-Version: 2.4
2
+ Name: uv-metadata
3
+ Version: 1.0.0
4
+ Summary: Inspect any Python package metadata without installing
5
+ Author: Zoran Simic
6
+ Project-URL: Homepage, https://github.com/zsimic/uv-metadata
7
+ Requires-Python: >=3.11
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: build
11
+ Requires-Dist: pyproject-hooks
12
+ Requires-Dist: seekablehttpfile
13
+ Dynamic: license-file
14
+
15
+ # uv-metadata
16
+
17
+ Inspect any Python package metadata from any source without installing.
18
+
19
+ ```shell
20
+ $ uvx uv-metadata requests -kversion
21
+ 2.32.4
22
+
23
+ $ uvx uv-metadata requests -krequires_python
24
+ >=3.10
25
+
26
+ $ uvx uv-metadata 'pip<23' -kversion
27
+ 22.3.1
28
+ ```
29
+
30
+ Works with published packages, local wheels/sdists, project folders, and git repos.
31
+ For published packages, metadata is streamed directly from the remote wheel via HTTP range
32
+ requests — typically a few KB, no full download needed.
33
+
34
+
35
+ ## Why this is useful
36
+
37
+ Getting package metadata as JSON from a simple CLI opens up a lot of possibilities:
38
+
39
+ - **Scripting**: what's the latest version of a package? What about the last 2.x release?
40
+ What's the latest version that still supports Python 3.7?
41
+ (`uvx uv-metadata -p3.7 setuptools -kversion`)
42
+ - **Validation**: CI checks that verify your package metadata is complete before publishing —
43
+ are author, URL, license, classifiers all present?
44
+ - **Verifying your own project**: after setting up dynamic versioning (e.g. `setuptools-scm`),
45
+ just run `uvx uv-metadata .` to confirm your metadata looks right — no need to build or install
46
+ - **Dependency auditing**: quickly check what a package requires, what Python versions it supports,
47
+ or what entry points it exposes — all without installing anything
48
+
49
+ This project also serves as a reference implementation for a proposed native
50
+ [`uv metadata`](https://github.com/zsimic/uv-metadata/blob/main/uv-metadata-spec.md) subcommand
51
+ (see [astral-sh/uv#6037](https://github.com/astral-sh/uv/issues/6037) and the [spec](https://github.com/zsimic/uv-metadata/blob/main/uv-metadata-spec.md)).
52
+
53
+ Requires `uv` on `PATH`.
54
+
55
+
56
+ ## Installation
57
+
58
+ ```shell
59
+ # Run directly (no install needed)
60
+ uvx uv-metadata requests
61
+
62
+ # Or install permanently
63
+ uv tool install uv-metadata
64
+ ```
65
+
66
+
67
+ ## Quick examples
68
+
69
+ ```shell
70
+ # Full metadata as JSON
71
+ uvx uv-metadata flask
72
+
73
+ # Single key
74
+ uvx uv-metadata flask -kversion
75
+
76
+ # Version constraint
77
+ uvx uv-metadata 'flask<3' -kversion
78
+
79
+ # Local project
80
+ uvx uv-metadata .
81
+
82
+ # Local wheel or sdist
83
+ uvx uv-metadata ./dist/mypackage-1.0.0-py3-none-any.whl
84
+
85
+ # Git repo
86
+ uvx uv-metadata git+https://github.com/psf/requests@main
87
+
88
+ # Target a specific Python version
89
+ uvx uv-metadata numpy -p3.9 -kversion
90
+ ```
91
+
92
+
93
+ ## Input routing
94
+
95
+ | Input | Strategy |
96
+ |---|---|
97
+ | `.`, `./path`, `/abs/path`, or any existing filesystem path | |
98
+ | &emsp;directory with `pyproject.toml` or `setup.py` | Build metadata via PEP 517 |
99
+ | &emsp;`*.dist-info` or `*.egg-info` directory | Read directly |
100
+ | &emsp;`*.whl` or `*.zip` file | Extract from zip archive |
101
+ | &emsp;`*.tar.gz` file | Extract from tarball |
102
+ | `git+https://...`, `git@...`, or `pkg @ url` | Install to temp dir, read dist-info |
103
+ | plain name or version constraint (`name`, `name>=x`, etc.) | Resolve via uv, stream dist-info from remote wheel; fall back to downloading sdist |
104
+
105
+
106
+ ## Output format
107
+
108
+ JSON with sorted keys. The `description` (long description) field is omitted by default
109
+ as it is typically very large; use `--full` to include it.
110
+
111
+ ```shell
112
+ $ uvx uv-metadata pip
113
+ {
114
+ "author_email": "The pip developers <distutils-sig@python.org>",
115
+ "classifiers": [
116
+ "Development Status :: 5 - Production/Stable",
117
+ ...
118
+ ],
119
+ "description_content_type": "text/x-rst",
120
+ "entry_points": {
121
+ "console_scripts": {
122
+ "pip": "pip._internal.cli.main:main",
123
+ "pip3": "pip._internal.cli.main:main"
124
+ }
125
+ },
126
+ "license_expression": "MIT",
127
+ "metadata_version": "2.4",
128
+ "name": "pip",
129
+ "project_url": [
130
+ "Documentation, https://pip.pypa.io",
131
+ "Source, https://github.com/pypa/pip"
132
+ ],
133
+ "requires_python": ">=3.9",
134
+ "summary": "The PyPA recommended tool for installing Python packages.",
135
+ "version": "26.0.1"
136
+ }
137
+ ```
138
+
139
+ Structural rules:
140
+ - Keys are `lower_snake_case`
141
+ - Single-occurrence fields: plain string
142
+ - Multi-occurrence fields: list of strings
143
+ - `entry_points`: `{"group": {"name": "module:attr"}}`
144
+ - `top_level`: list of top-level importable names
145
+ - `UNKNOWN` values are omitted
146
+
147
+
148
+ ## CLI reference
149
+
150
+ ```
151
+ usage: uv-metadata [-h] [-p PYTHON] [-k KEY] [--full] [package]
152
+
153
+ Output the metadata of a package, in machine-readable format
154
+
155
+ positional arguments:
156
+ package Package to inspect (default: current folder)
157
+
158
+ options:
159
+ -h, --help show this help message and exit
160
+ -p, --python PYTHON Python version to target (e.g. 3.11)
161
+ -k, --key KEY Show only this key from the metadata
162
+ --full Include full description in output
163
+ ```
164
+
165
+
166
+ ## How it works
167
+
168
+ ### Fast path for published packages
169
+
170
+ 1. `uv pip compile --format pylock.toml` resolves to a concrete wheel URL without downloading
171
+ 2. `SeekableHttpFile` + `ZipFile` streams only the dist-info files via HTTP range requests
172
+ 3. Falls back to downloading the sdist when no wheel is available
173
+
174
+ ### Unified metadata reading
175
+
176
+ All extraction strategies produce a dist-info folder which is read by
177
+ `importlib.metadata.PathDistribution`. Both `METADATA` (wheels) and `PKG-INFO` (sdists)
178
+ are handled transparently.
179
+
180
+ ### Archive extraction
181
+
182
+ A `MetadataReader` base class with `ZipReader` and `TarReader` implementations provides
183
+ uniform member discovery and extraction across archive formats.
184
+
185
+
186
+ ## Dependencies
187
+
188
+ | Package | Purpose |
189
+ |---|---|
190
+ | [`build`](https://pypi.org/project/build/) | PEP 517 metadata building for local project folders |
191
+ | [`pyproject-hooks`](https://pypi.org/project/pyproject-hooks/) | Quiet subprocess runner used by `build` |
192
+ | [`seekablehttpfile`](https://pypi.org/project/seekablehttpfile/) | HTTP range requests for streaming dist-info from remote wheels |
193
+
194
+
195
+ ## Relevant PEPs
196
+
197
+ - [PEP 241](https://peps.python.org/pep-0241/) – Metadata for Python Software Packages 1.0
198
+ - [PEP 314](https://peps.python.org/pep-0314/) – Metadata for Python Software Packages 1.1
199
+ - [PEP 345](https://peps.python.org/pep-0345/) – Metadata for Python Software Packages 1.2
200
+ - [PEP 566](https://peps.python.org/pep-0566/) – Metadata for Python Software Packages 2.1
201
+ - [PEP 508](https://peps.python.org/pep-0508/) – Dependency specification for Python Software Packages
202
+ - [PEP 517](https://peps.python.org/pep-0517/) – A build-system independent format for source trees
203
+ - [PEP 643](https://peps.python.org/pep-0643/) – Metadata for Package Source Distributions
204
+ - [PEP 658](https://peps.python.org/pep-0658/) – Serve Distribution Metadata in the Simple Repository API
205
+ - [PEP 639](https://peps.python.org/pep-0639/) – Improving License Clarity with Better Package Metadata
@@ -0,0 +1,7 @@
1
+ uv_metadata.py,sha256=3IJjUC2hTFWDc-b-gfkEgVtgASm352TVCkbqACGAsTw,14275
2
+ uv_metadata-1.0.0.dist-info/licenses/LICENSE,sha256=Wg8W1zKdVdkZG_QoZHrymsB4tVDfDp0sins7rX6I8Wc,1068
3
+ uv_metadata-1.0.0.dist-info/METADATA,sha256=trUS0spywi815IyIuX4CzO5q3WpEotPwOJIsq_py1Zw,6929
4
+ uv_metadata-1.0.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
5
+ uv_metadata-1.0.0.dist-info/entry_points.txt,sha256=l2EWpbBjzrirgT76hfTBb9yWw8doTcEPiBjj-kD7pxc,49
6
+ uv_metadata-1.0.0.dist-info/top_level.txt,sha256=jn_269ii1E0GGNYjKi4pYn8-9w5srCfsPkVlhiLalCQ,12
7
+ uv_metadata-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ uv-metadata = uv_metadata:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Zoran Simic
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ uv_metadata
uv_metadata.py ADDED
@@ -0,0 +1,409 @@
1
+ import argparse
2
+ import json
3
+ import os
4
+ import re
5
+ import shutil
6
+ import subprocess
7
+ import sys
8
+ import tarfile
9
+ import tempfile
10
+ from abc import ABC, abstractmethod
11
+ from importlib.metadata import PathDistribution
12
+ from pathlib import Path
13
+ from typing import NoReturn
14
+ from zipfile import ZipFile
15
+
16
+ import pyproject_hooks
17
+ from build import ProjectBuilder
18
+ from build.env import IsolatedEnv
19
+ from seekablehttpfile import SeekableHttpFile
20
+
21
+ METADATA_FILES = ("METADATA", "PKG-INFO", "entry_points.txt", "top_level.txt")
22
+ _INFO_DIR_RX = re.compile(r"^(.+\.(dist|egg)-info)/(" + "|".join(re.escape(f) for f in METADATA_FILES) + r")$")
23
+ _ROOT_PKG_INFO_RX = re.compile(r"^([^/]+)/PKG-INFO$")
24
+ UV_PATH = shutil.which("uv")
25
+
26
+
27
+ def abort(msg: str = "") -> NoReturn:
28
+ sys.exit(msg)
29
+
30
+
31
+ def abort_if(condition, msg: str = ""):
32
+ if condition:
33
+ sys.exit(msg)
34
+
35
+
36
+ def canonical_git_url(url: str) -> str:
37
+ if url.startswith("git@"):
38
+ # Autocorrect default git SSH URLs (allows copy-pasting from github.com)
39
+ url = "git+ssh://" + url.replace(":", "/", 1)
40
+
41
+ elif url.startswith("https://") and not url.endswith(".git"):
42
+ url = f"git+{url}"
43
+
44
+ return url
45
+
46
+
47
+ def run_uv(*args, fatal=True, env=None, input=None):
48
+ assert UV_PATH is not None
49
+ full_cmd = [UV_PATH, *args]
50
+ result = subprocess.run(full_cmd, input=input, capture_output=True, check=False, env=env, text=True)
51
+ if result.returncode:
52
+ args = " ".join(x for x in args)
53
+ abort_if(fatal, f"'uv {args}' failed with exit code {result.returncode}:\n{result.stderr}")
54
+
55
+ return result
56
+
57
+
58
+ # ---------------------------------------------------------------------------
59
+ # Routing
60
+ # ---------------------------------------------------------------------------
61
+
62
+
63
+ def get_metadata_from_pip_spec(pip_spec: str, python: str | None = None) -> dict:
64
+ """
65
+ Get metadata for a package, routing to the best extraction strategy:
66
+
67
+ - local folder (contains pyproject.toml or setup.py) → build metadata via ProjectBuilder
68
+ - local *.dist-info or *.egg-info folder → read directly
69
+ - local .whl or .tar.gz file → extract from archive
70
+ - git URL or direct reference → install to temp dir, read dist-info
71
+ - plain package name (optionally version-constrained) → resolve via uv without installing,
72
+ then stream only the metadata from the remote wheel (much faster than a full install)
73
+
74
+ Examples::
75
+
76
+ get_metadata_from_pip_spec(".")
77
+ get_metadata_from_pip_spec("requests")
78
+ get_metadata_from_pip_spec("requests>=2.28")
79
+ get_metadata_from_pip_spec("./dist/mypackage-1.0.0.whl")
80
+ get_metadata_from_pip_spec("git+https://github.com/user/repo@main")
81
+ """
82
+ if not pip_spec:
83
+ pip_spec = str(Path(".").absolute())
84
+
85
+ # Path-like: starts with common path prefixes or is an existing file/dir
86
+ if pip_spec.startswith(("~", ".", "/")) or os.path.exists(pip_spec):
87
+ path = Path(pip_spec).expanduser().resolve()
88
+ if not path.is_dir():
89
+ abort_if(not path.name.lower().endswith((".whl", ".zip", ".tar.gz")), f"Unknown package type '{path.name}'")
90
+ return extract_metadata_from_file(path)
91
+
92
+ if path.name.lower().endswith("-info"):
93
+ return extract_metadata_from_dist_info(path)
94
+
95
+ return extract_metadata_from_project_folder(path, python)
96
+
97
+ if "://" in pip_spec or pip_spec.startswith("git@") or (" @ " in pip_spec):
98
+ # Git SSH shorthand: git@github.com:user/repo or direct reference: pkg @ url
99
+ return extract_metadata_from_uv_install(canonical_git_url(pip_spec), python)
100
+
101
+ # Plain package name (optionally version-constrained): use fast resolve path
102
+ return extract_metadata_from_uv_resolve(pip_spec, python)
103
+
104
+
105
+ # ---------------------------------------------------------------------------
106
+ # Extraction functions
107
+ # ---------------------------------------------------------------------------
108
+
109
+
110
+ def extract_metadata_from_dist_info(folder: Path) -> dict:
111
+ """Convert a .(egg|dist)-info directory to a clean metadata dict via importlib.metadata"""
112
+ dist = PathDistribution(folder)
113
+ if not dist.metadata:
114
+ abort(f"No metadata files in {folder.name}")
115
+
116
+ result: dict = {}
117
+ for key, value in dist.metadata.json.items():
118
+ if isinstance(value, list):
119
+ value = [v for v in value if v != "UNKNOWN"]
120
+
121
+ elif value == "UNKNOWN":
122
+ value = None
123
+
124
+ if value:
125
+ result[key] = value
126
+
127
+ eps = dist.entry_points
128
+ if eps:
129
+ grouped: dict = {}
130
+ for ep in eps:
131
+ grouped.setdefault(ep.group, {})[ep.name] = ep.value
132
+
133
+ result["entry_points"] = grouped
134
+
135
+ top_level = dist.read_text("top_level.txt")
136
+ if top_level:
137
+ result["top_level"] = top_level.strip().splitlines()
138
+
139
+ return result
140
+
141
+
142
+ def extract_metadata_from_project_folder(project_folder: Path, python: str | None = None) -> dict:
143
+ """Build package metadata from a source tree using PEP 517 (via the 'build' library)"""
144
+ abort_if(not project_folder.is_dir(), "folder does not exist")
145
+ abort_if(
146
+ not (project_folder / "pyproject.toml").exists() and not (project_folder / "setup.py").exists(),
147
+ "no pyproject.toml or setup.py",
148
+ )
149
+
150
+ with tempfile.TemporaryDirectory() as tmpdir:
151
+ tmpdir_path = Path(tmpdir)
152
+ venv_folder = tmpdir_path / ".venv"
153
+ env = dict(os.environ)
154
+ env["UV_VENV_SEED"] = "0"
155
+ env["VIRTUAL_ENV"] = str(venv_folder)
156
+ venv_args = ["venv"]
157
+ if python:
158
+ venv_args.append(f"-p{python}")
159
+
160
+ run_uv(*venv_args, str(venv_folder), env=env)
161
+ isolated_env = _UvIsolatedEnv(venv_folder)
162
+ builder = ProjectBuilder.from_isolated_env(isolated_env, project_folder, runner=pyproject_hooks.quiet_subprocess_runner)
163
+ isolated_env.install(builder.build_system_requires)
164
+ isolated_env.install(builder.get_requires_for_build("wheel"))
165
+ meta_path = builder.metadata_path(tmpdir_path)
166
+ return extract_metadata_from_dist_info(Path(meta_path))
167
+
168
+
169
+ def extract_metadata_from_file(path: Path) -> dict:
170
+ """Extract metadata from a local .whl or .tar.gz file"""
171
+ abort_if(not path.is_file(), f"File '{path}' does not exist")
172
+ with tempfile.TemporaryDirectory() as tmpdir:
173
+ tmpdir_path = Path(tmpdir)
174
+ reader_type = ZipReader if path.name.lower().endswith((".whl", ".zip")) else TarReader
175
+ with reader_type(path) as reader:
176
+ return reader.extracted_metadata_members(tmpdir_path)
177
+
178
+
179
+ def extract_metadata_from_uv_install(pip_spec: str, python: str | None = None) -> dict:
180
+ """Install package to a temp dir and read the resulting dist-info (used for git/URL specs)"""
181
+ with tempfile.TemporaryDirectory() as tmpdir:
182
+ target = Path(tmpdir) / "target"
183
+ args = ["-q", "pip", "install", "--no-deps", "--target", str(target)]
184
+ if python:
185
+ args.append(f"-p{python}")
186
+ args.append(pip_spec)
187
+ run_uv(*args)
188
+ info = list(target.glob("*.dist-info"))
189
+ abort_if(len(info) != 1, f"expected 1 dist-info folder, got: {[p.name for p in info]}")
190
+ return extract_metadata_from_dist_info(info[0])
191
+
192
+
193
+ def extract_metadata_from_uv_resolve(pip_spec: str, python: str | None = None) -> dict:
194
+ """
195
+ Resolve package metadata without installing — much faster than a full install.
196
+
197
+ Uses 'uv pip compile --format pylock.toml' to find the wheel URL, then streams
198
+ only the metadata section from the remote .whl via HTTP range requests.
199
+ Falls back to downloading the sdist when no wheel is available.
200
+ """
201
+ args = [
202
+ "-q",
203
+ "pip",
204
+ "compile",
205
+ "--no-deps",
206
+ "--no-header",
207
+ "--universal",
208
+ "--no-sources",
209
+ "--format",
210
+ "pylock.toml",
211
+ "--fork-strategy",
212
+ "fewest",
213
+ "--resolution",
214
+ "highest",
215
+ # Use python-version '99' to get latest metadata regardless of local python.
216
+ # When the caller specifies a python version, honor it so metadata reflects that target.
217
+ "--python-version",
218
+ python or "99",
219
+ ]
220
+ r = run_uv(*args, "-", input=pip_spec, fatal=False)
221
+ if not r.returncode and r.stdout:
222
+ m = re.search(r'\burl\s*=\s*"([^"]+\.whl)"', r.stdout)
223
+ if m:
224
+ wheel_url = m.group(1)
225
+ with tempfile.TemporaryDirectory() as tmpdir:
226
+ streamed = SeekableHttpFile(wheel_url, check_etag=False)
227
+ with ZipReader(streamed) as reader:
228
+ return reader.extracted_metadata_members(Path(tmpdir))
229
+
230
+ # Fallback: download sdist and extract metadata from it
231
+ m = re.search(r'\burl\s*=\s*"([^"]+)"', r.stdout)
232
+ if m:
233
+ return _download_and_extract(m.group(1))
234
+
235
+ msg = (r.stderr or "uv resolve failed with an empty stderr").strip()
236
+ if "not found in the package registry" in " ".join(x.strip() for x in msg.splitlines()):
237
+ msg = f"Package '{pip_spec}' does not exist"
238
+
239
+ abort(msg)
240
+
241
+
242
+ # ---------------------------------------------------------------------------
243
+ # Internal helpers
244
+ # ---------------------------------------------------------------------------
245
+
246
+
247
+ def _download_and_extract(url: str) -> dict:
248
+ """Download an archive from a URL and extract metadata from it"""
249
+ from urllib.request import urlopen
250
+
251
+ with tempfile.TemporaryDirectory() as tmpdir:
252
+ dest = Path(tmpdir) / url.rsplit("/", 1)[-1]
253
+ with urlopen(url) as resp:
254
+ dest.write_bytes(resp.read())
255
+
256
+ return extract_metadata_from_file(dest)
257
+
258
+
259
+ class MetadataReader(ABC):
260
+ """Context manager that abstracts extraction of metadata from zip/tar files"""
261
+
262
+ def __enter__(self):
263
+ return self
264
+
265
+ def __exit__(self, *_args):
266
+ self.close()
267
+
268
+ @abstractmethod
269
+ def close(self) -> None:
270
+ """Release underlying archive resources"""
271
+
272
+ def find_metadata_members(self) -> list:
273
+ """Find archive members containing package metadata.
274
+
275
+ Prefers .dist-info/.egg-info directories, falls back to root-level PKG-INFO.
276
+ """
277
+ members = self.getmembers()
278
+ matched = [m for m in members if _INFO_DIR_RX.match(self.filepath(m))]
279
+ if not matched:
280
+ matched = [m for m in members if _ROOT_PKG_INFO_RX.match(self.filepath(m))]
281
+
282
+ abort_if(not matched, f"No metadata found in {self}")
283
+ return matched
284
+
285
+ def extracted_metadata_members(self, tmpdir: Path) -> dict:
286
+ members = self.find_metadata_members()
287
+ info_dir = tmpdir / "tmp.dist-info"
288
+ info_dir.mkdir()
289
+ for m in members:
290
+ b = self.read_bytes(m)
291
+ name = os.path.basename(self.filepath(m))
292
+ if name == "PKG-INFO":
293
+ name = "METADATA"
294
+
295
+ (info_dir / name).write_bytes(b)
296
+
297
+ return extract_metadata_from_dist_info(info_dir)
298
+
299
+ @abstractmethod
300
+ def filepath(self, member) -> str:
301
+ """Path of `member` within the archive"""
302
+
303
+ @abstractmethod
304
+ def getmembers(self) -> list:
305
+ """Return a list of contained file members"""
306
+
307
+ @abstractmethod
308
+ def read_bytes(self, member) -> bytes:
309
+ """Read bytes from `member`"""
310
+
311
+
312
+ class ZipReader(MetadataReader):
313
+ def __init__(self, source: Path | SeekableHttpFile):
314
+ self.source = source
315
+ self.zip_file = ZipFile(source) # type: ignore[arg-type]
316
+
317
+ def __repr__(self):
318
+ return str(self.source)
319
+
320
+ def close(self) -> None:
321
+ self.zip_file.close()
322
+
323
+ def filepath(self, member) -> str:
324
+ return member.filename
325
+
326
+ def getmembers(self) -> list:
327
+ return self.zip_file.filelist
328
+
329
+ def read_bytes(self, member) -> bytes:
330
+ return self.zip_file.read(member.filename)
331
+
332
+
333
+ class TarReader(MetadataReader):
334
+ def __init__(self, path: Path):
335
+ self.path = path
336
+ self.tar_file = tarfile.open(path)
337
+
338
+ def __repr__(self):
339
+ return str(self.path)
340
+
341
+ def close(self) -> None:
342
+ self.tar_file.close()
343
+
344
+ def filepath(self, member) -> str:
345
+ return member.name
346
+
347
+ def getmembers(self) -> list:
348
+ return self.tar_file.getmembers()
349
+
350
+ def read_bytes(self, member) -> bytes:
351
+ f = self.tar_file.extractfile(member)
352
+ return f.read() if f else b""
353
+
354
+
355
+ class _UvIsolatedEnv(IsolatedEnv):
356
+ def __init__(self, venv_folder: Path):
357
+ self.venv_folder = venv_folder
358
+
359
+ @property
360
+ def python_executable(self) -> str:
361
+ return str(self.venv_folder / "bin/python")
362
+
363
+ def make_extra_environ(self) -> dict:
364
+ return {}
365
+
366
+ def install(self, requirements) -> None:
367
+ if requirements:
368
+ run_uv("pip", "install", "--python", self.python_executable, *requirements)
369
+
370
+
371
+ # ---------------------------------------------------------------------------
372
+ # CLI
373
+ # ---------------------------------------------------------------------------
374
+
375
+
376
+ def main(args=None):
377
+ """
378
+ Output the metadata of a package, in machine-readable format
379
+
380
+ Examples:
381
+ uv-metadata requests
382
+ uv-metadata "requests>=2.28"
383
+ uv-metadata .
384
+ uv-metadata ./dist/mypackage-1.0.0.whl
385
+ uv-metadata ./dist/mypackage-1.0.0.tar.gz
386
+ uv-metadata git+https://github.com/zsimic/uv-metadata@main
387
+ """
388
+ parser = argparse.ArgumentParser(description=main.__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
389
+ parser.add_argument("-p", "--python", help="Python version to target (e.g. 3.11)")
390
+ parser.add_argument("-k", "--key", help="Show only this key from the metadata")
391
+ parser.add_argument("--full", action="store_true", help="Include full description in output")
392
+ parser.add_argument("package", default=None, nargs="?", help="Package to inspect (default: current folder)")
393
+ args = parser.parse_args(args=args)
394
+
395
+ meta_dict = get_metadata_from_pip_spec(args.package, args.python)
396
+ if not args.full:
397
+ meta_dict.pop("description", None)
398
+
399
+ if args.key is None:
400
+ print(json.dumps(meta_dict, indent=4, sort_keys=True))
401
+
402
+ else:
403
+ value = meta_dict.get(args.key)
404
+ abort_if(value is None, f"no key '{args.key}' in metadata")
405
+ print(value if isinstance(value, str) else json.dumps(value, indent=4, sort_keys=True))
406
+
407
+
408
+ if __name__ == "__main__":
409
+ sys.exit(main())