1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
|
"""Load and look up packages in lpip-sources.toml."""
from __future__ import annotations
import re
import tomllib
from dataclasses import dataclass, replace
from pathlib import Path
import tomlkit
from packaging.utils import canonicalize_name
from tomlkit.exceptions import TOMLKitError
from lpip.cache import (
CatalogCachePaths,
catalog_cache_paths,
ensure_catalog_checkout,
purge_catalog_cache,
)
from lpip.errors import (
CatalogAlreadyExistsError,
CatalogFileNotFoundError,
CatalogSchemaError,
DisallowedSchemeError,
InvalidPackageNameError,
MissingRevisionError,
PackageAlreadyExistsError,
SubdirectoryEscapeError,
TomlParseError,
UnknownPackageError,
UnknownTomlKeyError,
UnsupportedAuthoringUrlError,
)
from lpip.models import (
EffectiveConfig,
PackageSource,
PolicyConfig,
RefreshMode,
SourceConfig,
SourceType,
)
from lpip.validation import (
CATALOG_TOP_KEYS,
PACKAGE_FIELD_KEYS,
first_unknown_key,
normalize_authoring_git_url,
optional_str,
subdirectory_escapes_repo,
url_scheme,
)
PACKAGE_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._+-]*$")
DEFAULT_CATALOG_FILENAME = "lpip-sources.toml"
CATALOG_INIT_TEMPLATE = """\
# lpip package catalog
# Commit this file in the catalog Git repository. Consumers fetch it
# (source.type = git). Add packages with: lpip catalog add
[packages]
# Example:
# [packages.libfoo]
# url = "git+ssh://git.company/libs/libfoo.git"
# revision = "main"
# subdirectory = "python"
"""
@dataclass(frozen=True)
class Catalog:
path: Path
packages: tuple[PackageSource, ...]
def find(self, name: str) -> PackageSource | None:
"""Match a distribution name, ignoring PEP 503 normalization."""
want = canonicalize_name(name)
for pkg in self.packages:
if canonicalize_name(pkg.name) == want:
return pkg
return None
def get(self, name: str) -> PackageSource:
for pkg in self.packages:
if pkg.name == name:
return pkg
raise UnknownPackageError(name, catalog_path=self.path)
def sorted_by_name(self) -> tuple[PackageSource, ...]:
return tuple(sorted(self.packages, key=lambda p: p.name))
def load_catalog(path: Path, policy: PolicyConfig | None = None) -> Catalog:
"""Parse and validate a catalog file (AC-0003, AC-0010, AC-0011)."""
policy = policy or PolicyConfig()
catalog_path = path.expanduser()
if not catalog_path.is_file():
raise CatalogFileNotFoundError(catalog_path)
try:
with catalog_path.open("rb") as fh:
data = tomllib.load(fh)
except tomllib.TOMLDecodeError as exc:
raise TomlParseError(catalog_path, detail=str(exc)) from exc
unknown_top = first_unknown_key(data, CATALOG_TOP_KEYS)
if unknown_top is not None:
raise UnknownTomlKeyError(unknown_top, path=catalog_path, kind="catalog")
if "packages" not in data:
raise CatalogSchemaError(
"Catalog is missing the packages table.",
path=catalog_path,
hint="Add a [packages.<name>] table for each installable package.",
)
packages_raw = data["packages"]
if not isinstance(packages_raw, dict):
raise CatalogSchemaError(
"'packages' must be a TOML table of package names.",
path=catalog_path,
)
loaded: list[PackageSource] = []
for name, body in packages_raw.items():
loaded.append(_package_from_table(name, body, catalog_path, policy))
return Catalog(path=catalog_path, packages=tuple(loaded))
def _package_from_table(
name: str,
body: object,
catalog_path: Path,
policy: PolicyConfig,
) -> PackageSource:
if not isinstance(body, dict):
raise CatalogSchemaError(
f"Package {name!r} must be a table of fields.",
path=catalog_path,
)
unknown = first_unknown_key(body, PACKAGE_FIELD_KEYS)
if unknown is not None:
raise UnknownTomlKeyError(
f"packages.{name}.{unknown}",
path=catalog_path,
kind="catalog",
)
if "url" not in body:
raise CatalogSchemaError(
f"Package {name!r} is missing required field 'url'.",
path=catalog_path,
)
url = body["url"]
if not isinstance(url, str) or not url.strip():
raise CatalogSchemaError(
f"Package {name!r} field 'url' must be a non-empty string.",
path=catalog_path,
)
url = url.strip()
scheme = url_scheme(url)
if scheme not in {s.lower() for s in policy.allowed_schemes}:
raise DisallowedSchemeError(
url,
allowed=policy.allowed_schemes,
catalog_path=catalog_path,
)
try:
revision = optional_str(body.get("revision"))
subdirectory = optional_str(body.get("subdirectory"))
except TypeError as exc:
raise CatalogSchemaError(
f"Package {name!r} has a non-string optional field: {exc}",
path=catalog_path,
) from exc
if policy.require_pinned_revision and revision is None:
raise MissingRevisionError(name, catalog_path=catalog_path)
if subdirectory is not None and subdirectory_escapes_repo(subdirectory):
raise SubdirectoryEscapeError(subdirectory, catalog_path=catalog_path)
return PackageSource(name=name, url=url, revision=revision, subdirectory=subdirectory)
def local_catalog_path(cfg: EffectiveConfig, *, cwd: Path) -> Path:
return local_path_for_source(cfg.source, cwd=cwd)
def local_path_for_source(source: SourceConfig, *, cwd: Path) -> Path:
raw = Path(source.path).expanduser()
return raw if raw.is_absolute() else (cwd / raw)
@dataclass(frozen=True)
class ResolvedCatalogLocation:
catalog_file: Path
cache: CatalogCachePaths | None
def catalog_file_in_repo(repo: Path, source_path: str) -> Path:
if subdirectory_escapes_repo(source_path.replace("\\", "/")):
raise SubdirectoryEscapeError(source_path)
path = repo / source_path
if not path.is_file():
raise CatalogFileNotFoundError(path)
return path
def resolve_source_location(
source: SourceConfig,
*,
cwd: Path,
cache_home: Path | None = None,
force_refresh: bool = False,
) -> ResolvedCatalogLocation:
"""Resolve one configured catalog (ADR-0021)."""
if source.type is SourceType.FILE:
return ResolvedCatalogLocation(
catalog_file=local_path_for_source(source, cwd=cwd),
cache=None,
)
if not source.url:
raise CatalogSchemaError(
"source.url is required when source.type is git.",
hint="Set source.url in config.toml or LPIP_SOURCE_URL.",
)
refresh = source.refresh or RefreshMode.AUTO
cache = ensure_catalog_checkout(
source.url,
source.revision,
cache_home=cache_home,
refresh=refresh,
force_refresh=force_refresh,
)
return ResolvedCatalogLocation(
catalog_file=catalog_file_in_repo(cache.repo, source.path),
cache=cache,
)
def resolve_catalog_location(
cfg: EffectiveConfig,
*,
cwd: Path,
cache_home: Path | None = None,
force_refresh: bool = False,
) -> ResolvedCatalogLocation:
"""Resolve the first catalog source."""
return resolve_source_location(
cfg.source,
cwd=cwd,
cache_home=cache_home,
force_refresh=force_refresh,
)
def git_sources(cfg: EffectiveConfig) -> tuple[SourceConfig, ...]:
return tuple(src for src in cfg.sources if src.type is SourceType.GIT and src.url)
def planned_git_cache_paths_for(source: SourceConfig) -> CatalogCachePaths:
if source.type is not SourceType.GIT or not source.url:
raise CatalogSchemaError(
"source.type must be git with a url to use the catalog cache.",
hint='Set source.type = "git" and source.url.',
)
return catalog_cache_paths(source.url, source.revision)
def planned_git_cache_paths(cfg: EffectiveConfig) -> CatalogCachePaths:
return planned_git_cache_paths_for(cfg.source)
def purge_git_catalog_cache(cfg: EffectiveConfig) -> CatalogCachePaths:
if cfg.source.type is not SourceType.GIT or not cfg.source.url:
raise CatalogSchemaError(
"source.type must be git with a url to purge the catalog cache.",
hint='Set source.type = "git" and source.url.',
)
return purge_catalog_cache(cfg.source.url, cfg.source.revision)
def purge_all_git_catalog_caches(cfg: EffectiveConfig) -> tuple[CatalogCachePaths, ...]:
caches = tuple(
purge_catalog_cache(src.url, src.revision)
for src in git_sources(cfg)
if src.url is not None
)
if not caches:
raise CatalogSchemaError(
"source.type must be git with a url to purge the catalog cache.",
hint='Set source.type = "git" and source.url.',
)
return caches
@dataclass(frozen=True)
class PackageNameClash:
"""One shadowed package name across catalog sources (AC-0026)."""
name: str
winner_source: str
shadowed_source: str
identical: bool
def _package_definition(package: PackageSource) -> tuple[str, str | None, str | None]:
return (package.url, package.revision, package.subdirectory)
def load_merged_catalog(
cfg: EffectiveConfig,
*,
cwd: Path,
cache_home: Path | None = None,
force_refresh: bool = False,
) -> tuple[Catalog, tuple[PackageNameClash, ...]]:
"""Load every configured source; first package name wins (ADR-0021)."""
merged: list[PackageSource] = []
first_by_key: dict[str, PackageSource] = {}
clashes: list[PackageNameClash] = []
first_path: Path | None = None
for src in cfg.sources:
location = resolve_source_location(
src,
cwd=cwd,
cache_home=cache_home,
force_refresh=force_refresh,
)
if first_path is None:
first_path = location.catalog_file
catalog = load_catalog(location.catalog_file, cfg.policy)
for pkg in catalog.packages:
tagged = replace(pkg, catalog_source=src.name)
key = canonicalize_name(pkg.name)
winner = first_by_key.get(key)
if winner is None:
first_by_key[key] = tagged
merged.append(tagged)
continue
clashes.append(
PackageNameClash(
name=winner.name,
winner_source=winner.catalog_source or "default",
shadowed_source=src.name,
identical=_package_definition(winner) == _package_definition(pkg),
)
)
return (
Catalog(
path=first_path or (cwd / DEFAULT_CATALOG_FILENAME),
packages=tuple(merged),
),
tuple(clashes),
)
def load_catalog_for_config(
cfg: EffectiveConfig,
*,
cwd: Path,
cache_home: Path | None = None,
force_refresh: bool = False,
) -> Catalog:
catalog, _clashes = load_merged_catalog(
cfg,
cwd=cwd,
cache_home=cache_home,
force_refresh=force_refresh,
)
return catalog
def normalize_package_for_catalog(package: PackageSource) -> PackageSource:
"""Normalize authoring URL; fail if the scheme is not a supported Git form."""
stored = normalize_authoring_git_url(package.url)
scheme = url_scheme(stored)
if scheme not in {"git+ssh", "git+https", "git+file"}:
raise UnsupportedAuthoringUrlError(package.url)
return PackageSource(
name=package.name,
url=stored,
revision=package.revision,
subdirectory=package.subdirectory,
)
def _validate_new_package(package: PackageSource, policy: PolicyConfig, catalog_path: Path) -> None:
if not PACKAGE_NAME_RE.fullmatch(package.name):
raise InvalidPackageNameError(package.name)
_package_from_table(
package.name,
{
"url": package.url,
**({"revision": package.revision} if package.revision else {}),
**({"subdirectory": package.subdirectory} if package.subdirectory else {}),
},
catalog_path,
policy,
)
def resolve_authoring_catalog_path(path: str | Path | None, *, cwd: Path) -> Path:
"""Working-tree catalog path (ADR-0015). Does not use consumer source.type."""
raw = Path(path) if path is not None else Path(DEFAULT_CATALOG_FILENAME)
raw = raw.expanduser()
return raw if raw.is_absolute() else (cwd / raw)
def write_catalog_init_template(path: Path) -> Path:
"""Write a commented empty catalog. Fails if the path already exists."""
if path.exists():
raise CatalogAlreadyExistsError(path)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(CATALOG_INIT_TEMPLATE, encoding="utf-8")
return path
def add_package_to_catalog_file(
path: Path,
package: PackageSource,
*,
policy: PolicyConfig | None = None,
force: bool = False,
) -> Path:
"""Append or replace a package table in a working-tree catalog (ADR-0015)."""
path = path.expanduser()
policy = policy or PolicyConfig()
package = normalize_package_for_catalog(package)
_validate_new_package(package, policy, path)
if path.is_file():
try:
document = tomlkit.parse(path.read_text(encoding="utf-8"))
except TOMLKitError as exc:
raise TomlParseError(path, detail=str(exc)) from exc
else:
path.parent.mkdir(parents=True, exist_ok=True)
document = tomlkit.document()
document.add(tomlkit.comment("lpip package catalog"))
packages = document.get("packages")
if packages is None:
packages = tomlkit.table()
document["packages"] = packages
elif not isinstance(packages, dict):
raise CatalogSchemaError(
"'packages' must be a TOML table of package names.",
path=path,
)
if package.name in packages and not force:
raise PackageAlreadyExistsError(package.name, catalog_path=path)
entry = tomlkit.table()
entry["url"] = package.url
if package.revision:
entry["revision"] = package.revision
if package.subdirectory:
entry["subdirectory"] = package.subdirectory
packages[package.name] = entry
path.write_text(tomlkit.dumps(document), encoding="utf-8")
return path
|