pip-runner 0.2.0a1__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.
- pip_runner/__about__.py +4 -0
- pip_runner/__init__.py +7 -0
- pip_runner/_pip.py +857 -0
- pip_runner/_pip_cmd.py +88 -0
- pip_runner/py.typed +1 -0
- pip_runner-0.2.0a1.dist-info/METADATA +163 -0
- pip_runner-0.2.0a1.dist-info/RECORD +11 -0
- pip_runner-0.2.0a1.dist-info/WHEEL +5 -0
- pip_runner-0.2.0a1.dist-info/licenses/LICENSE +19 -0
- pip_runner-0.2.0a1.dist-info/top_level.txt +1 -0
- pip_runner-0.2.0a1.dist-info/zip-safe +1 -0
pip_runner/__about__.py
ADDED
pip_runner/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
# Copyright (c) 2026 Adam Karpierz
|
|
2
|
+
# SPDX-License-Identifier: Zlib
|
|
3
|
+
|
|
4
|
+
from .__about__ import * ; del __about__ # type: ignore[name-defined] # noqa
|
|
5
|
+
|
|
6
|
+
from ._pip import * ; del _pip # type: ignore[name-defined] # noqa
|
|
7
|
+
from ._pip_cmd import * ; del _pip_cmd # type: ignore[name-defined] # noqa
|
pip_runner/_pip.py
ADDED
|
@@ -0,0 +1,857 @@
|
|
|
1
|
+
# Copyright (c) 2026 Adam Karpierz
|
|
2
|
+
# SPDX-License-Identifier: Zlib
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from typing import TypeAlias, Any, NamedTuple
|
|
7
|
+
from typing import List # due to conflict with builtins.list
|
|
8
|
+
from typing_extensions import Self, sentinel
|
|
9
|
+
from os import PathLike
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
import builtins
|
|
13
|
+
import json
|
|
14
|
+
from textwrap import indent, dedent
|
|
15
|
+
from email.parser import Parser as EmailParser
|
|
16
|
+
from email.policy import Compat32 as EmailPolicy
|
|
17
|
+
|
|
18
|
+
import packaging.version
|
|
19
|
+
from utlx import public
|
|
20
|
+
from utlx import run
|
|
21
|
+
import regex as re
|
|
22
|
+
|
|
23
|
+
from ._pip_cmd import PipCmd
|
|
24
|
+
|
|
25
|
+
StrPath: TypeAlias = str | PathLike[str]
|
|
26
|
+
|
|
27
|
+
MISSING = sentinel("missing")
|
|
28
|
+
|
|
29
|
+
version_info = packaging.version.Version
|
|
30
|
+
public(version_info = version_info)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@public
|
|
34
|
+
@dataclass(kw_only=True)
|
|
35
|
+
class Package:
|
|
36
|
+
name: str
|
|
37
|
+
version: str
|
|
38
|
+
location: Path | None | sentinel = MISSING
|
|
39
|
+
editable_project_location: Path | None = None
|
|
40
|
+
latest_version: str | sentinel = MISSING
|
|
41
|
+
latest_filetype: str | sentinel = MISSING
|
|
42
|
+
installer: str | sentinel = MISSING
|
|
43
|
+
|
|
44
|
+
def get(self, key: str, default: Any = None) -> Any:
|
|
45
|
+
"""Like dict.get"""
|
|
46
|
+
value = getattr(self, key, default)
|
|
47
|
+
return value if value is not MISSING else default
|
|
48
|
+
|
|
49
|
+
def __contains__(self, key: str) -> bool:
|
|
50
|
+
"""Allows usage: 'name' in obj"""
|
|
51
|
+
return hasattr(self, key) and getattr(self, key) is not MISSING
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def editable(self) -> bool:
|
|
55
|
+
return self.editable_project_location is not None
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@public
|
|
59
|
+
class PackageInfo(NamedTuple):
|
|
60
|
+
name: str
|
|
61
|
+
version: str
|
|
62
|
+
location: Path | None
|
|
63
|
+
editable_project_location: Path | None
|
|
64
|
+
requires: list[str]
|
|
65
|
+
required_by: list[str]
|
|
66
|
+
installer: str
|
|
67
|
+
metadata_version: str
|
|
68
|
+
classifiers: list[str]
|
|
69
|
+
summary: str
|
|
70
|
+
homepage: str
|
|
71
|
+
project_urls: list[str]
|
|
72
|
+
author: str
|
|
73
|
+
author_email: str
|
|
74
|
+
license: str # noqa: A003
|
|
75
|
+
license_expression: str
|
|
76
|
+
entry_points: list[str]
|
|
77
|
+
files: list[str] | None
|
|
78
|
+
|
|
79
|
+
@property
|
|
80
|
+
def editable(self) -> bool:
|
|
81
|
+
return self.editable_project_location is not None
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@public
|
|
85
|
+
@dataclass
|
|
86
|
+
class PackageVersions:
|
|
87
|
+
name: str
|
|
88
|
+
versions: list[str]
|
|
89
|
+
latest: str | None
|
|
90
|
+
installed: str | None
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@public
|
|
94
|
+
@dataclass
|
|
95
|
+
class FileHash:
|
|
96
|
+
file: Path
|
|
97
|
+
hash: str # noqa: A003
|
|
98
|
+
algorithm: str
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@public
|
|
102
|
+
class ConfigIniFile(NamedTuple):
|
|
103
|
+
path: Path
|
|
104
|
+
exists: bool
|
|
105
|
+
config: dict[str, Any]
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
@public
|
|
109
|
+
class CacheInfoResult(NamedTuple):
|
|
110
|
+
cache_location: Path | None
|
|
111
|
+
cache_location_old: Path | None
|
|
112
|
+
http_files_number: int
|
|
113
|
+
built_wheels_location: Path | None
|
|
114
|
+
built_wheels_number: int
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
@public
|
|
118
|
+
class CacheRemoveResult(NamedTuple):
|
|
119
|
+
files: int
|
|
120
|
+
directories: int
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
@public
|
|
124
|
+
class Pip:
|
|
125
|
+
"""High-level API for pip CLI (thin wrapper)."""
|
|
126
|
+
|
|
127
|
+
cmd: PipCmd
|
|
128
|
+
|
|
129
|
+
def __new__(cls, python_executable: str | None = None) -> Self:
|
|
130
|
+
"""Constructor"""
|
|
131
|
+
self = super().__new__(cls)
|
|
132
|
+
self.cmd = PipCmd(python_executable)
|
|
133
|
+
return self
|
|
134
|
+
|
|
135
|
+
## High-level API ##
|
|
136
|
+
|
|
137
|
+
@property
|
|
138
|
+
def version(self) -> str:
|
|
139
|
+
"""Gets the pip version."""
|
|
140
|
+
output = self.pip(version=True, capture_output=True)
|
|
141
|
+
return output.stdout.strip()
|
|
142
|
+
|
|
143
|
+
@property
|
|
144
|
+
def version_info(self) -> version_info:
|
|
145
|
+
"""Gets the pip version info."""
|
|
146
|
+
version = self.version
|
|
147
|
+
match = re.match(r"((\w|\d)*\s+)*(?P<version>\d+\.\d+(\.\d+)?\S*)\s*", version)
|
|
148
|
+
if match is None:
|
|
149
|
+
raise self.ValueError(f"Unable to parse pip version: '{version}'")
|
|
150
|
+
return packaging.version.parse(match.group("version"))
|
|
151
|
+
|
|
152
|
+
def pip(self, *args: Any, **kwargs: Any) -> run.CompletedTextProcess:
|
|
153
|
+
"""Run raw pip executable."""
|
|
154
|
+
self._update_capture(kwargs, False)
|
|
155
|
+
try:
|
|
156
|
+
# result=self.cmd.pip(*args, text=bool(kwargs["capture_output"]), **kwargs)
|
|
157
|
+
result = self.cmd.pip(*args, text=True, **kwargs)
|
|
158
|
+
except run.CalledProcessError as exc:
|
|
159
|
+
self._handle_exception(exc)
|
|
160
|
+
return result
|
|
161
|
+
|
|
162
|
+
def help(self, command: str | None = None, **kwargs: Any) -> str | None: # noqa: A003
|
|
163
|
+
"""Gets the help information for pip and pip commands."""
|
|
164
|
+
self._omit_kwargs(kwargs, "help")
|
|
165
|
+
self._update_capture(kwargs, True)
|
|
166
|
+
if not command:
|
|
167
|
+
output = self.pip("help", **kwargs)
|
|
168
|
+
else:
|
|
169
|
+
# output=self.pip(command, help=True, **kwargs)
|
|
170
|
+
output = self.pip("help", command, **kwargs)
|
|
171
|
+
return self._parse_output_help(output)
|
|
172
|
+
|
|
173
|
+
def install(self, *packages: str,
|
|
174
|
+
target: StrPath | bool = False,
|
|
175
|
+
root: StrPath | bool = False,
|
|
176
|
+
editable: StrPath | str | bool = False,
|
|
177
|
+
prefix: StrPath | bool = False,
|
|
178
|
+
report: StrPath | bool = False,
|
|
179
|
+
# extra_args: List[str] | None = None, # ???
|
|
180
|
+
**kwargs: Any) -> None:
|
|
181
|
+
"""Install packages."""
|
|
182
|
+
self._update_capture(kwargs, False)
|
|
183
|
+
# if extra_args: args.extend(extra_args) # ???
|
|
184
|
+
self.pip("install", *packages,
|
|
185
|
+
target=target, root=root, editable=editable, prefix=prefix,
|
|
186
|
+
report=report, **kwargs) # extra_args=extra_args, **kwargs)
|
|
187
|
+
|
|
188
|
+
def upgrade(self, *packages: str,
|
|
189
|
+
target: StrPath | bool = False,
|
|
190
|
+
root: StrPath | bool = False,
|
|
191
|
+
editable: StrPath | str | bool = False,
|
|
192
|
+
prefix: StrPath | bool = False,
|
|
193
|
+
report: StrPath | bool = False,
|
|
194
|
+
# extra_args: List[str] | None = None, # ???
|
|
195
|
+
**kwargs: Any) -> None:
|
|
196
|
+
"""Upgrade packages."""
|
|
197
|
+
self._omit_kwargs(kwargs, "upgrade")
|
|
198
|
+
self._update_capture(kwargs, False)
|
|
199
|
+
# if extra_args: args.extend(extra_args) # ???
|
|
200
|
+
self.pip("install", *packages, upgrade=True,
|
|
201
|
+
target=target, root=root, editable=editable, prefix=prefix,
|
|
202
|
+
report=report, **kwargs) # extra_args=extra_args, **kwargs)
|
|
203
|
+
|
|
204
|
+
def download(self, *packages: str,
|
|
205
|
+
dest: StrPath | bool = False,
|
|
206
|
+
src: StrPath | bool = False, **kwargs: Any) -> None:
|
|
207
|
+
"""Download packages."""
|
|
208
|
+
self._update_capture(kwargs, False)
|
|
209
|
+
self.pip("download", *packages, dest=dest, src=src, **kwargs)
|
|
210
|
+
|
|
211
|
+
def lock(self, *packages: str,
|
|
212
|
+
output: StrPath | bool = False,
|
|
213
|
+
editable: StrPath | str | bool = False,
|
|
214
|
+
src: StrPath | bool = False, **kwargs: Any) -> None:
|
|
215
|
+
"""Generate a lock file."""
|
|
216
|
+
if not self.command_exists("lock"): # pragma: no cover
|
|
217
|
+
raise self.NotImplementedError("command 'lock' is not implemented for "
|
|
218
|
+
f"this version of pip: {self.version_info}")
|
|
219
|
+
self._update_capture(kwargs, False)
|
|
220
|
+
self.pip("lock", *packages,
|
|
221
|
+
output=output, editable=editable, src=src, **kwargs)
|
|
222
|
+
|
|
223
|
+
def wheel(self, *packages: str,
|
|
224
|
+
wheel_dir: StrPath | bool = False,
|
|
225
|
+
editable: StrPath | str | bool = False,
|
|
226
|
+
src: StrPath | bool = False, **kwargs: Any) -> None:
|
|
227
|
+
"""Build wheels from your requirements."""
|
|
228
|
+
self._update_capture(kwargs, False)
|
|
229
|
+
self.pip("wheel", *packages,
|
|
230
|
+
wheel_dir=wheel_dir, editable=editable, src=src, **kwargs)
|
|
231
|
+
|
|
232
|
+
def uninstall(self, *packages: str, **kwargs: Any) -> None:
|
|
233
|
+
"""Uninstall packages."""
|
|
234
|
+
self._update_kwarg(kwargs, "yes", True)
|
|
235
|
+
self._update_capture(kwargs, False)
|
|
236
|
+
self.pip("uninstall", *packages, **kwargs)
|
|
237
|
+
|
|
238
|
+
def list(self, **kwargs: Any) -> dict[str, Package] | None: # noqa: A003
|
|
239
|
+
"""List installed packages, including editables."""
|
|
240
|
+
self._update_capture(kwargs, True)
|
|
241
|
+
if kwargs["capture_output"]:
|
|
242
|
+
kwargs["format"] = "json"
|
|
243
|
+
output = self.pip("list", **kwargs)
|
|
244
|
+
return self._parse_list_json(output)
|
|
245
|
+
|
|
246
|
+
def freeze(self, **kwargs: Any) -> List[str] | None:
|
|
247
|
+
"""Output installed packages in requirements format."""
|
|
248
|
+
self._update_capture(kwargs, True)
|
|
249
|
+
output = self.pip("freeze", **kwargs)
|
|
250
|
+
return self._parse_freeze(output)
|
|
251
|
+
|
|
252
|
+
def inspect(self, **kwargs: Any) -> dict[str, Any] | None:
|
|
253
|
+
"""Inspect the python environment."""
|
|
254
|
+
self._update_capture(kwargs, True)
|
|
255
|
+
output = self.pip("inspect", **kwargs)
|
|
256
|
+
return self._parse_inspect(output)
|
|
257
|
+
|
|
258
|
+
def show(self, *packages: str, **kwargs: Any) -> dict[str, PackageInfo] | None:
|
|
259
|
+
"""Show information about one or more installed packages."""
|
|
260
|
+
self._omit_kwargs(kwargs, "verbose")
|
|
261
|
+
self._update_capture(kwargs, True)
|
|
262
|
+
output = self.pip("show", *packages, verbose=True, **kwargs)
|
|
263
|
+
return self._parse_show(output)
|
|
264
|
+
|
|
265
|
+
def check(self, **kwargs: Any) -> tuple[int, str | None]:
|
|
266
|
+
"""Verify installed packages have compatible dependencies."""
|
|
267
|
+
self._update_capture(kwargs, True)
|
|
268
|
+
output = self.pip("check", check=False, **kwargs)
|
|
269
|
+
return (output.returncode, self._parse_output_str(output))
|
|
270
|
+
|
|
271
|
+
def config(self, command: str, *args: Any, **kwargs: Any) \
|
|
272
|
+
-> dict[str, Any] | str | None:
|
|
273
|
+
"""Manage local and global configuration."""
|
|
274
|
+
match command:
|
|
275
|
+
case "list":
|
|
276
|
+
return self.config_list(*args, **kwargs)
|
|
277
|
+
case "edit":
|
|
278
|
+
self.config_edit(*args, **kwargs)
|
|
279
|
+
return None # pragma: no cover
|
|
280
|
+
case "get":
|
|
281
|
+
return self.config_get(*args, **kwargs)
|
|
282
|
+
case "set":
|
|
283
|
+
self.config_set(*args, **kwargs)
|
|
284
|
+
return None
|
|
285
|
+
case "unset":
|
|
286
|
+
self.config_unset(*args, **kwargs)
|
|
287
|
+
return None
|
|
288
|
+
case "debug":
|
|
289
|
+
return self.config_debug(*args, **kwargs)
|
|
290
|
+
case _:
|
|
291
|
+
self._update_capture(kwargs, True)
|
|
292
|
+
output = self.pip("config", command, *args, **kwargs)
|
|
293
|
+
return self._parse_output_str(output) # pragma: no cover
|
|
294
|
+
# raise self.RuntimeError(f"Unsupported config command: {command}")
|
|
295
|
+
|
|
296
|
+
def config_list(self, **kwargs: Any) -> dict[str, Any] | None:
|
|
297
|
+
"""List the active configuration (or from the file specified)."""
|
|
298
|
+
self._omit_kwargs(kwargs, "quiet")
|
|
299
|
+
self._update_capture(kwargs, True)
|
|
300
|
+
output = self.pip("config", "list", **kwargs)
|
|
301
|
+
return self._parse_config_list(output)
|
|
302
|
+
|
|
303
|
+
def config_edit(self, **kwargs: Any) -> None:
|
|
304
|
+
"""Edit the configuration file in an editor."""
|
|
305
|
+
self._update_capture(kwargs, True)
|
|
306
|
+
# self.pip("config", "edit", **kwargs)
|
|
307
|
+
raise self.NotImplementedError("pip_runner.edit() is not implemented.")
|
|
308
|
+
|
|
309
|
+
def config_get(self, option: str, **kwargs: Any) -> str | None:
|
|
310
|
+
"""Get the value associated with command.option."""
|
|
311
|
+
self._omit_kwargs(kwargs, "quiet")
|
|
312
|
+
self._update_capture(kwargs, True)
|
|
313
|
+
output = self.pip("config", "get", option, **kwargs)
|
|
314
|
+
return self._parse_config_get(output)
|
|
315
|
+
|
|
316
|
+
def config_set(self, option: str, value: str, **kwargs: Any) -> None:
|
|
317
|
+
"""Set the command.option=value."""
|
|
318
|
+
self._update_capture(kwargs, True)
|
|
319
|
+
self.pip("config", "set", option, value, **kwargs)
|
|
320
|
+
|
|
321
|
+
def config_unset(self, option: str, **kwargs: Any) -> None:
|
|
322
|
+
"""Unset the value associated with command.option."""
|
|
323
|
+
self._update_capture(kwargs, True)
|
|
324
|
+
self.pip("config", "unset", option, **kwargs)
|
|
325
|
+
|
|
326
|
+
def config_debug(self, **kwargs: Any) -> dict[str, Any] | None:
|
|
327
|
+
"""List the configuration files and values defined under them."""
|
|
328
|
+
self._omit_kwargs(kwargs, "quiet")
|
|
329
|
+
self._update_capture(kwargs, True)
|
|
330
|
+
output = self.pip("config", "debug", **kwargs)
|
|
331
|
+
return self._parse_config_debug(output)
|
|
332
|
+
|
|
333
|
+
def cache(self, command: str, *args: Any, **kwargs: Any) \
|
|
334
|
+
-> Path | CacheInfoResult | List[Path] | CacheRemoveResult | str | None:
|
|
335
|
+
"""Inspect and manage pip's wheel cache."""
|
|
336
|
+
self._update_kwarg(kwargs, "verbose", True)
|
|
337
|
+
match command:
|
|
338
|
+
case "dir":
|
|
339
|
+
return self.cache_dir(*args, **kwargs)
|
|
340
|
+
case "info":
|
|
341
|
+
return self.cache_info(*args, **kwargs)
|
|
342
|
+
case "list":
|
|
343
|
+
return self.cache_list(*args, **kwargs)
|
|
344
|
+
case "remove":
|
|
345
|
+
return self.cache_remove(*args, **kwargs)
|
|
346
|
+
case "purge":
|
|
347
|
+
return self.cache_purge(*args, **kwargs)
|
|
348
|
+
case _:
|
|
349
|
+
self._update_capture(kwargs, True)
|
|
350
|
+
output = self.pip("cache", command, *args, **kwargs)
|
|
351
|
+
return self._parse_output_str(output) # pragma: no cover
|
|
352
|
+
# raise self.RuntimeError(f"Unsupported cache command: {command}")
|
|
353
|
+
|
|
354
|
+
def cache_dir(self, **kwargs: Any) -> Path | None:
|
|
355
|
+
"""Show the cache directory."""
|
|
356
|
+
self._update_kwarg(kwargs, "verbose", True)
|
|
357
|
+
self._update_capture(kwargs, True)
|
|
358
|
+
output = self.pip("cache", "dir", **kwargs)
|
|
359
|
+
return self._parse_cache_dir(output)
|
|
360
|
+
|
|
361
|
+
def cache_info(self, **kwargs: Any) -> CacheInfoResult | None:
|
|
362
|
+
"""Show information about the cache."""
|
|
363
|
+
self._update_kwarg(kwargs, "verbose", True)
|
|
364
|
+
self._update_capture(kwargs, True)
|
|
365
|
+
output = self.pip("cache", "info", **kwargs)
|
|
366
|
+
return self._parse_cache_info(output)
|
|
367
|
+
|
|
368
|
+
def cache_list(self, pattern: str | None = None, **kwargs: Any) -> List[Path] | None:
|
|
369
|
+
"""List filenames of packages stored in the cache.
|
|
370
|
+
|
|
371
|
+
<pattern> - can be a glob expression or a package name.
|
|
372
|
+
"""
|
|
373
|
+
# pip cache list [<pattern>] [--format=[human, abspath]]
|
|
374
|
+
self._update_kwarg(kwargs, "format", "abspath")
|
|
375
|
+
self._update_kwarg(kwargs, "verbose", True)
|
|
376
|
+
self._update_capture(kwargs, True)
|
|
377
|
+
if pattern is None: # pragma: no cover
|
|
378
|
+
output = self.pip("cache", "list", **kwargs)
|
|
379
|
+
else:
|
|
380
|
+
output = self.pip("cache", "list", pattern, **kwargs)
|
|
381
|
+
return self._parse_cache_list(output)
|
|
382
|
+
|
|
383
|
+
def cache_remove(self, pattern: str, **kwargs: Any) -> CacheRemoveResult | None:
|
|
384
|
+
"""Remove one or more package from the cache.
|
|
385
|
+
|
|
386
|
+
<pattern> - can be a glob expression or a package name.
|
|
387
|
+
"""
|
|
388
|
+
self._update_kwarg(kwargs, "verbose", True)
|
|
389
|
+
self._update_capture(kwargs, True)
|
|
390
|
+
output = self.pip("cache", "remove", pattern, **kwargs)
|
|
391
|
+
return self._parse_cache_remove(output)
|
|
392
|
+
|
|
393
|
+
def cache_purge(self, **kwargs: Any) -> CacheRemoveResult | None:
|
|
394
|
+
"""Remove all items from the cache."""
|
|
395
|
+
self._update_kwarg(kwargs, "verbose", True)
|
|
396
|
+
self._update_capture(kwargs, True)
|
|
397
|
+
output = self.pip("cache", "purge", **kwargs)
|
|
398
|
+
return self._parse_cache_remove(output)
|
|
399
|
+
|
|
400
|
+
def search(self, query: str, **kwargs: Any) -> "None" | None:
|
|
401
|
+
"""Search PyPI for packages."""
|
|
402
|
+
self._update_capture(kwargs, True)
|
|
403
|
+
output = self._pip_search(query, **kwargs)
|
|
404
|
+
return self._parse_search(output) # pragma: no cover # TODO...
|
|
405
|
+
|
|
406
|
+
def _pip_search(self, query: str, **kwargs: Any) -> run.CompletedTextProcess:
|
|
407
|
+
raise self.NotImplementedError("pip_runner.search() is not implemented for now."
|
|
408
|
+
"Please be patient.")
|
|
409
|
+
|
|
410
|
+
def index(self, action: str, package: str, **kwargs: Any) -> PackageVersions | str | None:
|
|
411
|
+
"""Inspect information available from package indexes."""
|
|
412
|
+
self._update_capture(kwargs, True)
|
|
413
|
+
match action:
|
|
414
|
+
case "versions": # pragma: no branch
|
|
415
|
+
if kwargs["capture_output"]:
|
|
416
|
+
kwargs["json"] = (self.version_info >= version_info("25.1"))
|
|
417
|
+
output = self.pip("index", action, package, **kwargs)
|
|
418
|
+
match action:
|
|
419
|
+
case "versions":
|
|
420
|
+
if kwargs.get("json", False):
|
|
421
|
+
return self._parse_index_versions_json(output)
|
|
422
|
+
else:
|
|
423
|
+
return self._parse_index_versions(output)
|
|
424
|
+
case _: # pragma: no cover
|
|
425
|
+
return self._parse_output_str(output)
|
|
426
|
+
|
|
427
|
+
def hash(self, *files: StrPath, **kwargs: Any) -> dict[str, FileHash] | None: # noqa: A003
|
|
428
|
+
"""Compute hashes of package archives."""
|
|
429
|
+
self._update_capture(kwargs, True)
|
|
430
|
+
output = self.pip("hash", *files, **kwargs)
|
|
431
|
+
return self._parse_hashes(output)
|
|
432
|
+
|
|
433
|
+
def completion(self, **kwargs: Any) -> str | None:
|
|
434
|
+
"""A helper command used for command completion."""
|
|
435
|
+
self._update_capture(kwargs, True)
|
|
436
|
+
if not any((opt in kwargs) for opt in ("bash", "fish", "powershell", "zsh",)):
|
|
437
|
+
raise self.ValueError("You must pass --bash or --fish or --powershell or --zsh")
|
|
438
|
+
output = self.pip("completion", **kwargs)
|
|
439
|
+
return self._parse_output_str(output)
|
|
440
|
+
|
|
441
|
+
def debug(self, **kwargs: Any) -> str | None:
|
|
442
|
+
"""Show information useful for debugging."""
|
|
443
|
+
self._update_capture(kwargs, True)
|
|
444
|
+
output = self.pip("debug", **kwargs)
|
|
445
|
+
return self._parse_debug(output)
|
|
446
|
+
|
|
447
|
+
def command_exists(self, command: str) -> bool:
|
|
448
|
+
try:
|
|
449
|
+
self.help(command)
|
|
450
|
+
return True
|
|
451
|
+
except self.RuntimeError:
|
|
452
|
+
return False
|
|
453
|
+
|
|
454
|
+
# Exceptions
|
|
455
|
+
|
|
456
|
+
class Error(Exception):
|
|
457
|
+
"""pip error."""
|
|
458
|
+
|
|
459
|
+
class TypeError(builtins.TypeError, Error): # noqa: A001
|
|
460
|
+
"""Type error."""
|
|
461
|
+
|
|
462
|
+
class ValueError(builtins.ValueError, Error): # noqa: A001
|
|
463
|
+
"""Value error."""
|
|
464
|
+
|
|
465
|
+
class RuntimeError(builtins.RuntimeError, Error): # noqa: A001
|
|
466
|
+
"""Runtime error."""
|
|
467
|
+
|
|
468
|
+
class NotImplementedError(builtins.NotImplementedError, Error): # noqa: A001
|
|
469
|
+
"""Not implemented error."""
|
|
470
|
+
|
|
471
|
+
# ---- Helpers and internals ---- #
|
|
472
|
+
|
|
473
|
+
def _parse_output_str(self, output: run.CompletedTextProcess) -> str | None:
|
|
474
|
+
out = output.stdout
|
|
475
|
+
if out is None: return None
|
|
476
|
+
return out
|
|
477
|
+
|
|
478
|
+
def _parse_output_help(self, output: run.CompletedTextProcess) -> str | None:
|
|
479
|
+
out = output.stdout
|
|
480
|
+
if out is None: return None
|
|
481
|
+
return out.lstrip()
|
|
482
|
+
|
|
483
|
+
def _parse_output_lines(self, output: run.CompletedTextProcess) -> List[str] | None:
|
|
484
|
+
out = output.stdout
|
|
485
|
+
if out is None: return None
|
|
486
|
+
return out.splitlines()
|
|
487
|
+
|
|
488
|
+
def _parse_list_json(self, output: run.CompletedTextProcess) -> dict[str, Package] | None:
|
|
489
|
+
out = output.stdout
|
|
490
|
+
if out is None: return None
|
|
491
|
+
pkgs: dict[str, Package] = {}
|
|
492
|
+
for pkg_dict in json.loads(out):
|
|
493
|
+
pkg_name, version = pkg_dict["name"], pkg_dict["version"]
|
|
494
|
+
pkgs[pkg_name] = pkg = Package(name=pkg_name, version=version)
|
|
495
|
+
optional_attributes = [
|
|
496
|
+
"location",
|
|
497
|
+
"editable_project_location",
|
|
498
|
+
"latest_version",
|
|
499
|
+
"latest_filetype",
|
|
500
|
+
"installer",
|
|
501
|
+
]
|
|
502
|
+
for attr_name in optional_attributes:
|
|
503
|
+
if attr_name in pkg_dict:
|
|
504
|
+
value = pkg_dict[attr_name]
|
|
505
|
+
match attr_name:
|
|
506
|
+
case "location" | "editable_project_location":
|
|
507
|
+
value = Path(value.strip()) if value.strip() else None
|
|
508
|
+
setattr(pkg, attr_name, value)
|
|
509
|
+
return pkgs
|
|
510
|
+
|
|
511
|
+
def _parse_freeze(self, output: run.CompletedTextProcess) -> List[str] | None:
|
|
512
|
+
out = output.stdout
|
|
513
|
+
if out is None: return None
|
|
514
|
+
result: List[str] = []
|
|
515
|
+
for line in out.splitlines():
|
|
516
|
+
line = line.strip()
|
|
517
|
+
if not line or line.startswith("#"):
|
|
518
|
+
continue # pragma: no cover
|
|
519
|
+
result.append(line)
|
|
520
|
+
return result
|
|
521
|
+
|
|
522
|
+
def _parse_inspect(self, output: run.CompletedTextProcess) -> dict[str, Any] | None:
|
|
523
|
+
out = output.stdout
|
|
524
|
+
if out is None: return None
|
|
525
|
+
out = self._sanitize_string(out)
|
|
526
|
+
result: dict[str, Any] = json.loads(out)
|
|
527
|
+
return result
|
|
528
|
+
|
|
529
|
+
def _parse_show(self, output: run.CompletedTextProcess) -> dict[str, PackageInfo] | None:
|
|
530
|
+
out = output.stdout
|
|
531
|
+
if out is None: return None
|
|
532
|
+
supported_keys = (
|
|
533
|
+
"Name",
|
|
534
|
+
"Version",
|
|
535
|
+
"Summary",
|
|
536
|
+
"Home-page",
|
|
537
|
+
"Author",
|
|
538
|
+
"Author-email",
|
|
539
|
+
"License-Expression",
|
|
540
|
+
"License",
|
|
541
|
+
"Location",
|
|
542
|
+
"Editable project location",
|
|
543
|
+
"Editable-project-location", # because spaces transform
|
|
544
|
+
"Requires",
|
|
545
|
+
"Required-by",
|
|
546
|
+
"Metadata-Version",
|
|
547
|
+
"Installer",
|
|
548
|
+
"Classifiers",
|
|
549
|
+
"Entry-points",
|
|
550
|
+
"Project-URLs",
|
|
551
|
+
"Files",
|
|
552
|
+
)
|
|
553
|
+
supported_keys_regex = "|".join((key[0]+"(?i:"+key[1:]+")").replace("-", r"[\-_]")
|
|
554
|
+
for key in supported_keys)
|
|
555
|
+
supported_keys_pattern = re.compile(supported_keys_regex)
|
|
556
|
+
key_regex = supported_keys_regex + "|" + r"[A-Z][A-Za-z0-9\-_]*"
|
|
557
|
+
policy = EmailPolicy(max_line_length=None)
|
|
558
|
+
# policy_strict = policy.clone(raise_on_defect=True)
|
|
559
|
+
|
|
560
|
+
pkgs: dict[str, PackageInfo] = {}
|
|
561
|
+
for info_str in re.split(r"\n---\n(?=Name:)", out):
|
|
562
|
+
# print(f"\n@@@@@ info_str:\n{info_str}")
|
|
563
|
+
info_str = self._preparse_email(info_str, key_regex=key_regex)
|
|
564
|
+
# print(f"\n@@@@@ info_str preparsed:\n{info_str}")
|
|
565
|
+
pkg_info = EmailParser(policy=policy).parsestr(info_str, headersonly=True)
|
|
566
|
+
# print(f"\n@@@@@ pkg_info:\n{pkg_info.items()}")
|
|
567
|
+
params: dict[str, Any] = dict(
|
|
568
|
+
editable_project_location=None,
|
|
569
|
+
license="",
|
|
570
|
+
license_expression="",
|
|
571
|
+
files=None,
|
|
572
|
+
)
|
|
573
|
+
for key, val in pkg_info.items():
|
|
574
|
+
if not supported_keys_pattern.match(key):
|
|
575
|
+
# omit unsupported keys
|
|
576
|
+
continue # pragma: no cover
|
|
577
|
+
value: Any = str(val)
|
|
578
|
+
attr_name = key.lower().replace("-", "_").replace(" ", "_")
|
|
579
|
+
match attr_name:
|
|
580
|
+
case "home_page":
|
|
581
|
+
attr_name = attr_name.replace("_", "")
|
|
582
|
+
case "location" | "editable_project_location":
|
|
583
|
+
value = Path(value.strip()) if value.strip() else None
|
|
584
|
+
case "requires" | "required_by":
|
|
585
|
+
value = [line.strip() for line in value.split(",") if line.strip()]
|
|
586
|
+
case "classifiers" | "entry_points" | "project_urls":
|
|
587
|
+
value = [line.lstrip() for line in value.splitlines() if line.strip()]
|
|
588
|
+
case "files":
|
|
589
|
+
if value.strip().lower() == "cannot locate record or installed-files.txt":
|
|
590
|
+
continue # pragma: no cover
|
|
591
|
+
value = [line.lstrip() for line in value.splitlines() if line.strip()]
|
|
592
|
+
params[attr_name] = value
|
|
593
|
+
pkg = PackageInfo(**params)
|
|
594
|
+
pkgs[pkg.name] = pkg
|
|
595
|
+
|
|
596
|
+
return pkgs
|
|
597
|
+
|
|
598
|
+
def _parse_config_list(self, output: run.CompletedTextProcess) -> dict[str, Any] | None:
|
|
599
|
+
out = output.stdout
|
|
600
|
+
if out is None: return None
|
|
601
|
+
return self._parse_config_string(out)
|
|
602
|
+
|
|
603
|
+
def _parse_config_get(self, output: run.CompletedTextProcess) -> str | None:
|
|
604
|
+
out = self._parse_output_str(output)
|
|
605
|
+
if out is None: return None
|
|
606
|
+
return out.rstrip("\n")
|
|
607
|
+
|
|
608
|
+
def _parse_config_debug(self, output: run.CompletedTextProcess) -> dict[str, Any] | None:
|
|
609
|
+
out = output.stdout
|
|
610
|
+
if out is None: return None
|
|
611
|
+
key_regex = r"[\w\-]+"
|
|
612
|
+
section_pattern = re.compile(rf"(^|\n)(?P<head>({key_regex})):"
|
|
613
|
+
rf"(?P<body>[\s\S]*?)((?=\n({key_regex}):)|$)")
|
|
614
|
+
key_regex = r"([\h\S]+),\h*exists\h*:\h*(?i:(True|False))"
|
|
615
|
+
file_pattern = re.compile(rf"(^|\n)({key_regex})"
|
|
616
|
+
rf"(?P<body>[\s\S]*?)((?=\n({key_regex}))|$)")
|
|
617
|
+
|
|
618
|
+
debug_info: dict[str, Any] = {}
|
|
619
|
+
for match in section_pattern.finditer(out):
|
|
620
|
+
head = match.group("head").strip()
|
|
621
|
+
body = dedent(match.group("body").removeprefix("\n"))
|
|
622
|
+
if head.lower() == "env_var":
|
|
623
|
+
head = head.lower()
|
|
624
|
+
options = self._parse_config_string(body)
|
|
625
|
+
elif not body.strip():
|
|
626
|
+
options = {}
|
|
627
|
+
else:
|
|
628
|
+
files = []
|
|
629
|
+
for match in file_pattern.finditer(body):
|
|
630
|
+
path = Path(match.group(3).strip())
|
|
631
|
+
exists = (match.group(4).capitalize() == "True")
|
|
632
|
+
body = dedent(match.group("body").removeprefix("\n"))
|
|
633
|
+
config = self._parse_config_string(body,
|
|
634
|
+
option_regex=r"^(?P<key>[^:]+):"
|
|
635
|
+
r"\s*(?P<value>.*)\s*$")
|
|
636
|
+
files.append(ConfigIniFile(path=path, exists=exists, config=config))
|
|
637
|
+
options = {"files": files} if files else {}
|
|
638
|
+
debug_info[head] = options
|
|
639
|
+
|
|
640
|
+
return debug_info
|
|
641
|
+
|
|
642
|
+
@classmethod
|
|
643
|
+
def _parse_config_string(cls, config_string: str, *,
|
|
644
|
+
option_regex: str = r"^(?P<key>[^=]+)="
|
|
645
|
+
r"\s*(['\"])(?P<value>.*)\2\s*$") \
|
|
646
|
+
-> dict[str, Any]:
|
|
647
|
+
"""Parses a string of the format: key.subkey='value'"""
|
|
648
|
+
option_pattern = re.compile(option_regex)
|
|
649
|
+
|
|
650
|
+
config: dict[str, Any] = {}
|
|
651
|
+
for line in config_string.strip().splitlines():
|
|
652
|
+
line = line.lstrip()
|
|
653
|
+
if not line or line.startswith("#"):
|
|
654
|
+
continue # pragma: no cover
|
|
655
|
+
|
|
656
|
+
# Regex: key='value' or key="value"
|
|
657
|
+
match = option_pattern.match(line)
|
|
658
|
+
if not match:
|
|
659
|
+
continue # pragma: no cover
|
|
660
|
+
|
|
661
|
+
key_path = [key.strip() for key in match.group("key").split(".")]
|
|
662
|
+
value = match.group("value")
|
|
663
|
+
|
|
664
|
+
# Attempts to cast to an float and integer
|
|
665
|
+
try:
|
|
666
|
+
value = int(value)
|
|
667
|
+
except ValueError:
|
|
668
|
+
try:
|
|
669
|
+
value = float(value)
|
|
670
|
+
except ValueError:
|
|
671
|
+
pass
|
|
672
|
+
|
|
673
|
+
# Creates a nested structure
|
|
674
|
+
current = config
|
|
675
|
+
for key in key_path[:-1]:
|
|
676
|
+
current = current.setdefault(key, {})
|
|
677
|
+
current[key_path[-1]] = value
|
|
678
|
+
|
|
679
|
+
return config
|
|
680
|
+
|
|
681
|
+
def _parse_cache_dir(self, output: run.CompletedTextProcess) -> Path | None:
|
|
682
|
+
path = self._parse_output_str(output)
|
|
683
|
+
if path is None: return None
|
|
684
|
+
return Path(path.strip())
|
|
685
|
+
|
|
686
|
+
def _parse_cache_info(self, output: run.CompletedTextProcess) -> CacheInfoResult | None:
|
|
687
|
+
out = output.stdout
|
|
688
|
+
if out is None: return None
|
|
689
|
+
outlines = [line.strip() for line in out.strip().splitlines()]
|
|
690
|
+
beg_line = "Package index page cache location (pip "
|
|
691
|
+
cache_loc = next((line.split(":", maxsplit=1)[1].strip()
|
|
692
|
+
for line in outlines if line.startswith(beg_line)), None)
|
|
693
|
+
beg_line = "Package index page cache location (older pip"
|
|
694
|
+
cache_loc_old = next((line.split(":", maxsplit=1)[1].strip()
|
|
695
|
+
for line in outlines if line.startswith(beg_line)), None)
|
|
696
|
+
beg_line = "Number of HTTP files:"
|
|
697
|
+
http_files = next((line.removeprefix(beg_line).strip()
|
|
698
|
+
for line in outlines if line.startswith(beg_line)), None)
|
|
699
|
+
beg_line = "Locally built wheels location:"
|
|
700
|
+
wheels_loc = next((line.removeprefix(beg_line).strip()
|
|
701
|
+
for line in outlines if line.startswith(beg_line)), None)
|
|
702
|
+
beg_line = "Number of locally built wheels:"
|
|
703
|
+
built_wheels = next((line.removeprefix(beg_line).strip()
|
|
704
|
+
for line in outlines if line.startswith(beg_line)), None)
|
|
705
|
+
return CacheInfoResult(cache_location=Path(cache_loc) if cache_loc else None,
|
|
706
|
+
cache_location_old=Path(cache_loc_old) if cache_loc_old else None,
|
|
707
|
+
http_files_number=int(http_files) if http_files else -1,
|
|
708
|
+
built_wheels_location=Path(wheels_loc) if wheels_loc else None,
|
|
709
|
+
built_wheels_number=int(built_wheels) if built_wheels else -1)
|
|
710
|
+
|
|
711
|
+
def _parse_cache_list(self, output: run.CompletedTextProcess) -> List[Path] | None:
|
|
712
|
+
lines = self._parse_output_lines(output)
|
|
713
|
+
if lines is None: return None
|
|
714
|
+
return [Path(line.strip()) for line in lines if line is not None and line.strip()]
|
|
715
|
+
|
|
716
|
+
def _parse_cache_remove(self, output: run.CompletedTextProcess) -> CacheRemoveResult | None:
|
|
717
|
+
out = output.stdout
|
|
718
|
+
if out is None: return None
|
|
719
|
+
outlines = [line.strip() for line in out.strip().splitlines()]
|
|
720
|
+
# Files removed: 4538 (965.4 MB)
|
|
721
|
+
# Directories removed: 87
|
|
722
|
+
beg_line = "Files removed:"
|
|
723
|
+
files = next((line.removeprefix(beg_line).strip()
|
|
724
|
+
for line in outlines if line.startswith(beg_line)), None)
|
|
725
|
+
beg_line = "Directories removed:"
|
|
726
|
+
dirs = next((line.removeprefix(beg_line).strip()
|
|
727
|
+
for line in outlines if line.startswith(beg_line)), None)
|
|
728
|
+
return CacheRemoveResult(files=int(files.split()[0]) if files else -1,
|
|
729
|
+
directories=int(dirs.split()[0]) if dirs else -1)
|
|
730
|
+
|
|
731
|
+
# NOK
|
|
732
|
+
def _parse_search(self, output: run.CompletedTextProcess) \
|
|
733
|
+
-> "None" | None: # pragma: no cover # TODO...
|
|
734
|
+
out = output.stdout
|
|
735
|
+
if out is None: return None
|
|
736
|
+
# TODO...
|
|
737
|
+
return None
|
|
738
|
+
|
|
739
|
+
def _parse_index_versions_json(self, output: run.CompletedTextProcess) \
|
|
740
|
+
-> PackageVersions | None:
|
|
741
|
+
out = output.stdout
|
|
742
|
+
if out is None: return None
|
|
743
|
+
pkg_index = json.loads(out)
|
|
744
|
+
return PackageVersions(name=pkg_index["name"],
|
|
745
|
+
versions=pkg_index["versions"],
|
|
746
|
+
latest=pkg_index["latest"] or None,
|
|
747
|
+
installed=pkg_index.get("installed_version"))
|
|
748
|
+
|
|
749
|
+
def _parse_index_versions(self, output: run.CompletedTextProcess) \
|
|
750
|
+
-> PackageVersions | None:
|
|
751
|
+
out = output.stdout
|
|
752
|
+
if out is None: return None
|
|
753
|
+
option_pattern = re.compile(r"^(?P<key>[^:]+):\s*(?P<value>.*)\s*$", re.MULTILINE)
|
|
754
|
+
head, body = out.strip().split("\n", maxsplit=1)
|
|
755
|
+
pkg_versions = PackageVersions(name=head.split("(", maxsplit=1)[0].strip(),
|
|
756
|
+
versions=[], latest=None, installed=None)
|
|
757
|
+
for match in option_pattern.finditer(body):
|
|
758
|
+
key = match.group("key").strip()
|
|
759
|
+
value = match.group("value").strip()
|
|
760
|
+
match key.lower():
|
|
761
|
+
case "available versions":
|
|
762
|
+
pkg_versions.versions = [ver.strip() for ver in value.split(", ")]
|
|
763
|
+
case "latest":
|
|
764
|
+
pkg_versions.latest = value.split("(", maxsplit=1)[0].strip() or None
|
|
765
|
+
case "installed": # pragma: no branch
|
|
766
|
+
pkg_versions.installed = value.split("(", maxsplit=1)[0].strip() or None
|
|
767
|
+
if "(latest" in value: # pragma: no cover # due to pip bug
|
|
768
|
+
pkg_versions.latest = pkg_versions.installed
|
|
769
|
+
return pkg_versions
|
|
770
|
+
|
|
771
|
+
def _parse_hashes(self, output: run.CompletedTextProcess) -> dict[str, FileHash] | None:
|
|
772
|
+
out = output.stdout
|
|
773
|
+
if out is None: return None
|
|
774
|
+
# result is of the form:
|
|
775
|
+
# <filename>:\n--hash=<algorithm>:<hash>\n
|
|
776
|
+
hashes: dict[str, FileHash] = {}
|
|
777
|
+
outlines = out.strip().splitlines()
|
|
778
|
+
for line1, line2 in list(zip(*[iter(outlines)]*2)):
|
|
779
|
+
line1, line2 = line1.strip(), line2.strip()
|
|
780
|
+
file = line1.removesuffix(":")
|
|
781
|
+
algo, _, hval = line2.removeprefix("--hash=").partition(":")
|
|
782
|
+
hashes[file] = FileHash(file=Path(file), hash=hval, algorithm=algo)
|
|
783
|
+
return hashes
|
|
784
|
+
|
|
785
|
+
def _parse_debug(self, output: run.CompletedTextProcess) -> str | None:
|
|
786
|
+
return self._parse_output_str(output)
|
|
787
|
+
|
|
788
|
+
def _handle_exception(self, exc: BaseException, **kwargs: Any) -> None:
|
|
789
|
+
if isinstance(exc, run.CalledProcessError):
|
|
790
|
+
msg = exc.stderr.strip() if exc.stderr is not None else str(exc)
|
|
791
|
+
else: # pragma: no cover
|
|
792
|
+
msg = str(exc)
|
|
793
|
+
raise self.RuntimeError(msg) from None
|
|
794
|
+
|
|
795
|
+
# Utils
|
|
796
|
+
|
|
797
|
+
@classmethod # pragma: no cover # not in use
|
|
798
|
+
def _normalize_newlines(cls, text: str) -> str:
|
|
799
|
+
"""Standardizes line endings to <LF>"""
|
|
800
|
+
return text.replace("\r\n", "\n").replace("\r", "\n")
|
|
801
|
+
|
|
802
|
+
@classmethod
|
|
803
|
+
def _sanitize_string(cls, text: str) -> str:
|
|
804
|
+
"""Replace non-ASCII characters with '?'."""
|
|
805
|
+
return text.encode("ascii", errors="replace").decode("ascii")
|
|
806
|
+
|
|
807
|
+
@classmethod
|
|
808
|
+
def _preparse_email(cls, text: str, *,
|
|
809
|
+
key_regex: str = r"[A-Z][A-Za-z0-9\-_]*") -> str:
|
|
810
|
+
preparse_pattern = re.compile(rf"(?P<head>(^|\n)({key_regex}):)"
|
|
811
|
+
rf"(?P<body>[\s\S]*?)((?=\n({key_regex}):)|$)")
|
|
812
|
+
head_pattern = re.compile(r"(?<=\S)\s+(?=\S)")
|
|
813
|
+
|
|
814
|
+
preparsed = ""
|
|
815
|
+
for match in preparse_pattern.finditer(text):
|
|
816
|
+
head = match.group("head")
|
|
817
|
+
body = match.group("body")
|
|
818
|
+
# print(f"HEAD: |{head}|")
|
|
819
|
+
# print(f"BODY: |{body}|")
|
|
820
|
+
head = head_pattern.sub("-", head)
|
|
821
|
+
if "\n" in body:
|
|
822
|
+
indent_count = cls._get_indent(body)
|
|
823
|
+
if indent_count == 0: # if body == dedent(body):
|
|
824
|
+
prefix = " "
|
|
825
|
+
body = indent(body, prefix, lambda line: True)
|
|
826
|
+
if body.endswith("\n"): body += prefix
|
|
827
|
+
else:
|
|
828
|
+
lines = body.splitlines(True)
|
|
829
|
+
if lines: # pragma: no branch
|
|
830
|
+
prefix = " "
|
|
831
|
+
body = lines[0] + "".join((prefix + line) if len(line) == 1
|
|
832
|
+
else line for line in lines[1:])
|
|
833
|
+
if body.endswith("\n"): body += prefix
|
|
834
|
+
preparsed += head + body
|
|
835
|
+
|
|
836
|
+
return preparsed
|
|
837
|
+
|
|
838
|
+
@classmethod
|
|
839
|
+
def _get_indent(cls, text: str) -> int:
|
|
840
|
+
non_empty_lines = [line.expandtabs(4)
|
|
841
|
+
for line in text.splitlines() if line.strip()]
|
|
842
|
+
return min(len(line) - len(line.lstrip())
|
|
843
|
+
for line in non_empty_lines) if non_empty_lines else 0
|
|
844
|
+
|
|
845
|
+
@classmethod
|
|
846
|
+
def _omit_kwargs(cls, kwargs: dict[str, Any], *unnecessary: str) -> None:
|
|
847
|
+
for omit in unnecessary:
|
|
848
|
+
kwargs.pop(omit, None)
|
|
849
|
+
|
|
850
|
+
@classmethod
|
|
851
|
+
def _update_kwarg(cls, kwargs: dict[str, Any], key: str, default: Any) -> None:
|
|
852
|
+
if key not in kwargs:
|
|
853
|
+
kwargs[key] = default
|
|
854
|
+
|
|
855
|
+
@classmethod
|
|
856
|
+
def _update_capture(cls, kwargs: dict[str, Any], default: bool) -> None:
|
|
857
|
+
cls._update_kwarg(kwargs, "capture_output", default)
|
pip_runner/_pip_cmd.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# Copyright (c) 2026 Adam Karpierz
|
|
2
|
+
# SPDX-License-Identifier: Zlib
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
"""Low-level pip API"""
|
|
7
|
+
|
|
8
|
+
import typing
|
|
9
|
+
from typing import TypeAlias, Any
|
|
10
|
+
from typing_extensions import Self
|
|
11
|
+
from collections.abc import Callable
|
|
12
|
+
from functools import partialmethod
|
|
13
|
+
import sys
|
|
14
|
+
import os
|
|
15
|
+
from keyword import iskeyword
|
|
16
|
+
|
|
17
|
+
from utlx import public
|
|
18
|
+
from utlx import run
|
|
19
|
+
from utlx import issequence
|
|
20
|
+
|
|
21
|
+
CompletedProcessCallable: TypeAlias = Callable[..., run.CompletedTextProcess]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@public
|
|
25
|
+
class PipCmd:
|
|
26
|
+
"""Low-level pip command runner (uses `python -m pip`)."""
|
|
27
|
+
|
|
28
|
+
python: str | None
|
|
29
|
+
|
|
30
|
+
def __new__(cls, python_executable: str | None = None) -> Self:
|
|
31
|
+
"""Constructor"""
|
|
32
|
+
self = super().__new__(cls)
|
|
33
|
+
self.python = python_executable or sys.executable
|
|
34
|
+
return self
|
|
35
|
+
|
|
36
|
+
## Low-level pip API ##
|
|
37
|
+
|
|
38
|
+
def py(self, *args: Any, **kwargs: Any) -> run.CompletedTextProcess:
|
|
39
|
+
"""Run raw python executable."""
|
|
40
|
+
return self._cmd(self.python, *args, **kwargs)
|
|
41
|
+
|
|
42
|
+
def pip(self, *args: Any, **kwargs: Any) -> run.CompletedTextProcess:
|
|
43
|
+
"""Run raw pip executable."""
|
|
44
|
+
encoding = kwargs.pop("encoding", "utf-8")
|
|
45
|
+
env = kwargs.pop("env", os.environ).copy()
|
|
46
|
+
env.update(dict(
|
|
47
|
+
# PIP_YES = "true",
|
|
48
|
+
PIP_DISABLE_PIP_VERSION_CHECK = "1",
|
|
49
|
+
PIP_NO_PYTHON_VERSION_WARNING = "1",
|
|
50
|
+
PIP_NO_COLOR = "yes",
|
|
51
|
+
# COLUMNS = str(135),
|
|
52
|
+
# Make sure that Python writes output in UTF-8
|
|
53
|
+
PYTHONIOENCODING = "utf-8",
|
|
54
|
+
PYTHONLEGACYWINDOWSSTDIO = "utf-8",
|
|
55
|
+
))
|
|
56
|
+
return self._cmd(self.python, "-m", "pip", *args,
|
|
57
|
+
*self._pip_common_args,
|
|
58
|
+
encoding=encoding, env=env, **kwargs)
|
|
59
|
+
|
|
60
|
+
# ---- Helpers and internals ---- #
|
|
61
|
+
|
|
62
|
+
_pip_common_args: tuple[str, ...] = (
|
|
63
|
+
"--disable-pip-version-check",
|
|
64
|
+
"--no-python-version-warning",
|
|
65
|
+
# "--no-color",
|
|
66
|
+
)
|
|
67
|
+
_common_args: tuple[str, ...] = ()
|
|
68
|
+
|
|
69
|
+
@classmethod
|
|
70
|
+
def _run_wrapper(cls, run_fun: CompletedProcessCallable, *args: Any,
|
|
71
|
+
__format: str = "--{}", **kwargs: Any) -> run.CompletedTextProcess:
|
|
72
|
+
normal_args = [arg for arg in args if arg is not None]
|
|
73
|
+
allowed_kwargs, reserved_kwargs = run.split_kwargs(kwargs, cls._run_reserved_kwargs)
|
|
74
|
+
allowed_args: list[str] = []
|
|
75
|
+
for key, vals in allowed_kwargs.items():
|
|
76
|
+
if key.endswith("_") and iskeyword(key[:-1]): key = key[:-1]
|
|
77
|
+
key = key.replace("_", "-")
|
|
78
|
+
vals = list(vals) if issequence(vals) else [vals]
|
|
79
|
+
allowed_args += (__format.format(key if val is True else f"{key}={val}")
|
|
80
|
+
for val in vals if val is not False)
|
|
81
|
+
return run_fun(*normal_args, *allowed_args, *cls._common_args, **reserved_kwargs)
|
|
82
|
+
|
|
83
|
+
_run_reserved_kwargs: set[str] = {
|
|
84
|
+
"check", "text", "capture_output", "input", "stdin", "stdout", "stderr",
|
|
85
|
+
"shell", "cwd", "timeout", "encoding", "errors", "env", "universal_newlines",
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
_cmd = typing.cast(CompletedProcessCallable, partialmethod(_run_wrapper, run))
|
pip_runner/py.typed
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# Marker file for PEP 561
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pip_runner
|
|
3
|
+
Version: 0.2.0a1
|
|
4
|
+
Summary: A small high-level wrapper around pip CLI (python -m pip).
|
|
5
|
+
Author-email: Adam Karpierz <adam@karpierz.net>
|
|
6
|
+
Maintainer-email: Adam Karpierz <adam@karpierz.net>
|
|
7
|
+
License-Expression: Zlib
|
|
8
|
+
Project-URL: Homepage, https://pypi.org/project/pip-runner/
|
|
9
|
+
Project-URL: Documentation, https://karpierz.github.io/pip_runner/
|
|
10
|
+
Project-URL: History, https://karpierz.github.io/pip_runner/CHANGES.html
|
|
11
|
+
Project-URL: Download, https://pypi.org/project/pip-runner/
|
|
12
|
+
Project-URL: Repository, https://github.com/karpierz/pip_runner
|
|
13
|
+
Project-URL: Tracker, https://github.com/karpierz/pip_runner/issues
|
|
14
|
+
Project-URL: Sponsoring, https://www.paypal.com/donate/?hosted_button_id=FX8L7CJUGLW7S
|
|
15
|
+
Keywords: pip,pip_runner,pip-runner,pipwrapper,pip_api,pip-api
|
|
16
|
+
Platform: any
|
|
17
|
+
Classifier: Development Status :: 3 - Alpha
|
|
18
|
+
Classifier: Intended Audience :: Developers
|
|
19
|
+
Classifier: Natural Language :: Polish
|
|
20
|
+
Classifier: Operating System :: OS Independent
|
|
21
|
+
Classifier: Programming Language :: Python
|
|
22
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
24
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
25
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
26
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
27
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
28
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
29
|
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
30
|
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
|
31
|
+
Classifier: Programming Language :: Python :: Implementation :: GraalPy
|
|
32
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
33
|
+
Classifier: Typing :: Typed
|
|
34
|
+
Requires-Python: <4.0.0,>=3.10.0
|
|
35
|
+
Description-Content-Type: text/x-rst; charset=UTF-8
|
|
36
|
+
License-File: LICENSE
|
|
37
|
+
Requires-Dist: pip>=23.3.2
|
|
38
|
+
Requires-Dist: typing-extensions>=4.16.0
|
|
39
|
+
Requires-Dist: packaging>=26.3.0
|
|
40
|
+
Requires-Dist: pkg-about>=2.4.0; python_version >= "3.11"
|
|
41
|
+
Requires-Dist: pkg-about>=2.3.0; python_version < "3.11"
|
|
42
|
+
Requires-Dist: py-utlx>=2.5.0; python_version >= "3.11"
|
|
43
|
+
Requires-Dist: py-utlx>=2.3.0; python_version < "3.11"
|
|
44
|
+
Requires-Dist: nocasedict>=2.2.1
|
|
45
|
+
Requires-Dist: regex>=2026.9.3
|
|
46
|
+
Dynamic: license-file
|
|
47
|
+
|
|
48
|
+
pip_runner
|
|
49
|
+
==========
|
|
50
|
+
|
|
51
|
+
| |package_bold| is a small, extendable Python wrapper around the pip command-line
|
|
52
|
+
interface.
|
|
53
|
+
| It provides a thin, high-level API that executes `python -m pip` and parses
|
|
54
|
+
commonly used outputs (freeze / list).
|
|
55
|
+
|
|
56
|
+
Overview
|
|
57
|
+
========
|
|
58
|
+
|
|
59
|
+
Key features
|
|
60
|
+
------------
|
|
61
|
+
- Thin wrapper using subprocess to run pip commands via Python executable.
|
|
62
|
+
- High-level Pip class with convenient methods: install, uninstall,
|
|
63
|
+
list_installed, freeze, show, search, download, wheel, help.
|
|
64
|
+
- Easy to extend, test and integrate with virtual environments (pass custom
|
|
65
|
+
python_executable).
|
|
66
|
+
|
|
67
|
+
`PyPI record`_.
|
|
68
|
+
|
|
69
|
+
`Documentation`_.
|
|
70
|
+
|
|
71
|
+
Usage
|
|
72
|
+
-----
|
|
73
|
+
|
|
74
|
+
Basic usage:
|
|
75
|
+
|
|
76
|
+
.. code:: python
|
|
77
|
+
|
|
78
|
+
from pip_runner import Pip
|
|
79
|
+
pip = Pip()
|
|
80
|
+
pip.install("requests")
|
|
81
|
+
print(pip.list().get("requests"))
|
|
82
|
+
|
|
83
|
+
Installation
|
|
84
|
+
============
|
|
85
|
+
|
|
86
|
+
Prerequisites:
|
|
87
|
+
|
|
88
|
+
+ Python 3.10 or higher
|
|
89
|
+
|
|
90
|
+
* https://www.python.org/
|
|
91
|
+
|
|
92
|
+
+ pip
|
|
93
|
+
|
|
94
|
+
* https://pypi.org/project/pip/
|
|
95
|
+
|
|
96
|
+
To install run:
|
|
97
|
+
|
|
98
|
+
.. parsed-literal::
|
|
99
|
+
|
|
100
|
+
python -m pip install --upgrade |package|
|
|
101
|
+
|
|
102
|
+
Development
|
|
103
|
+
===========
|
|
104
|
+
|
|
105
|
+
Prerequisites:
|
|
106
|
+
|
|
107
|
+
+ Development is strictly based on *nox*. To install it run::
|
|
108
|
+
|
|
109
|
+
python -m pip install --upgrade nox
|
|
110
|
+
|
|
111
|
+
Visit `Development page`_.
|
|
112
|
+
|
|
113
|
+
Installation from sources:
|
|
114
|
+
|
|
115
|
+
clone the sources:
|
|
116
|
+
|
|
117
|
+
.. parsed-literal::
|
|
118
|
+
|
|
119
|
+
git clone |respository| |package|
|
|
120
|
+
|
|
121
|
+
and run:
|
|
122
|
+
|
|
123
|
+
.. parsed-literal::
|
|
124
|
+
|
|
125
|
+
python -m pip install ./|package|
|
|
126
|
+
|
|
127
|
+
or on development mode:
|
|
128
|
+
|
|
129
|
+
.. parsed-literal::
|
|
130
|
+
|
|
131
|
+
python -m pip install --editable ./|package|
|
|
132
|
+
|
|
133
|
+
License
|
|
134
|
+
=======
|
|
135
|
+
|
|
136
|
+
| |copyright|
|
|
137
|
+
| Licensed under the zlib/libpng License
|
|
138
|
+
| https://opensource.org/license/zlib
|
|
139
|
+
| Please refer to the accompanying LICENSE file.
|
|
140
|
+
|
|
141
|
+
Authors
|
|
142
|
+
=======
|
|
143
|
+
|
|
144
|
+
* Adam Karpierz <adam@karpierz.net>
|
|
145
|
+
|
|
146
|
+
Sponsoring
|
|
147
|
+
==========
|
|
148
|
+
|
|
149
|
+
| If you would like to sponsor the development of this project, your contribution
|
|
150
|
+
is greatly appreciated.
|
|
151
|
+
| As I am now retired, any support helps me dedicate more time to maintaining and
|
|
152
|
+
improving this work.
|
|
153
|
+
|
|
154
|
+
`Donate`_
|
|
155
|
+
|
|
156
|
+
.. |package| replace:: pip_runner
|
|
157
|
+
.. |package_bold| replace:: **pip_runner**
|
|
158
|
+
.. |copyright| replace:: Copyright (c) 2026-2026 Adam Karpierz
|
|
159
|
+
.. |respository| replace:: https://github.com/karpierz/pip_runner
|
|
160
|
+
.. _Development page: https://github.com/karpierz/pip_runner
|
|
161
|
+
.. _PyPI record: https://pypi.org/project/pip-runner/
|
|
162
|
+
.. _Documentation: https://karpierz.github.io/pip_runner/
|
|
163
|
+
.. _Donate: https://www.paypal.com/donate/?hosted_button_id=FX8L7CJUGLW7S
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
pip_runner/__about__.py,sha256=_ZSZZ2-mny071V8ampB1ZjHILFU8TKXjv0ttBEs5dAw,100
|
|
2
|
+
pip_runner/__init__.py,sha256=bl-M8lYYXCvaQkTR6bPSKSkyW8ssDgmXSqqIgYLsiMc,302
|
|
3
|
+
pip_runner/_pip.py,sha256=YUXSuvXqRRTdALsL3JK7FyvWHK7UoesoROHZULyqjqQ,35363
|
|
4
|
+
pip_runner/_pip_cmd.py,sha256=6LcnvhHQsJ22Qq7oJMXXH589owC50ibzu6u6gTT98VM,3141
|
|
5
|
+
pip_runner/py.typed,sha256=8PjyZ1aVoQpRVvt71muvuq5qE-jTFZkK-GLHkhdebmc,26
|
|
6
|
+
pip_runner-0.2.0a1.dist-info/licenses/LICENSE,sha256=Qq-eqDs_q68zDLQfOD2FdwKomedn6WsrYLodu93FE4s,872
|
|
7
|
+
pip_runner-0.2.0a1.dist-info/METADATA,sha256=-kxL6zrZwHvDyP6ZHgiG_ga15oEuheuz7cAnUmWybrg,4760
|
|
8
|
+
pip_runner-0.2.0a1.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
|
|
9
|
+
pip_runner-0.2.0a1.dist-info/top_level.txt,sha256=eLQ9fRMZJCeJAzGjSGGq75FG3en-epU9AW0JNU1N1wc,11
|
|
10
|
+
pip_runner-0.2.0a1.dist-info/zip-safe,sha256=frcCV1k9oG9oKj3dpUqdJg1PxRT2RSN_XKdLCPjaYaY,2
|
|
11
|
+
pip_runner-0.2.0a1.dist-info/RECORD,,
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
zlib License
|
|
2
|
+
|
|
3
|
+
Copyright (C) 2026-2026 Adam Karpierz
|
|
4
|
+
|
|
5
|
+
This software is provided 'as-is', without any express or implied
|
|
6
|
+
warranty. In no event will the authors be held liable for any damages
|
|
7
|
+
arising from the use of this software.
|
|
8
|
+
|
|
9
|
+
Permission is granted to anyone to use this software for any purpose,
|
|
10
|
+
including commercial applications, and to alter it and redistribute it
|
|
11
|
+
freely, subject to the following restrictions:
|
|
12
|
+
|
|
13
|
+
1. The origin of this software must not be misrepresented; you must not
|
|
14
|
+
claim that you wrote the original software. If you use this software
|
|
15
|
+
in a product, an acknowledgment in the product documentation would be
|
|
16
|
+
appreciated but is not required.
|
|
17
|
+
2. Altered source versions must be plainly marked as such, and must not be
|
|
18
|
+
misrepresented as being the original software.
|
|
19
|
+
3. This notice may not be removed or altered from any source distribution.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
pip_runner
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|