Debian Codegraph @

third_party/python/pip_tools/piptools/cache.py

raw
1 from __future__ import annotations
2
3 import json
4 import os
5 import platform
6 import sys
7 from typing import Dict, Iterable, List, Tuple, cast
8
9 from pip._internal.req import InstallRequirement
10 from pip._vendor.packaging.requirements import Requirement
11
12 from .exceptions import PipToolsError
13 from .utils import as_tuple, key_from_req, lookup_table_from_tuples
14
15 CacheKey = Tuple[str, str]
16 CacheLookup = Dict[str, List[str]]
17 CacheDict = Dict[str, CacheLookup]
18
19 _PEP425_PY_TAGS = {"cpython": "cp", "pypy": "pp", "ironpython": "ip", "jython": "jy"}
20
21
22 def _implementation_name() -> str:
23 """
24 Similar to PEP 425, however the minor version is separated from the major to
25 differentiate "3.10" and "31.0".
26 """
27 implementation_name = platform.python_implementation().lower()
28 implementation = _PEP425_PY_TAGS.get(implementation_name, "??")
29 return "{}{}.{}".format(implementation, *sys.version_info)
30
31
32 class CorruptCacheError(PipToolsError):
33 def __init__(self, path: str):
34 self.path = path
35
36 def __str__(self) -> str:
37 lines = [
38 "The dependency cache seems to have been corrupted.",
39 "Inspect, or delete, the following file:",
40 f" {self.path}",
41 ]
42 return os.linesep.join(lines)
43
44
45 def read_cache_file(cache_file_path: str) -> CacheDict:
46 with open(cache_file_path, encoding="utf-8") as cache_file:
47 try:
48 doc = json.load(cache_file)
49 except (json.JSONDecodeError, UnicodeDecodeError):
50 raise CorruptCacheError(cache_file_path)
51
52 # Check version and load the contents
53 if doc["__format__"] != 1:
54 raise ValueError("Unknown cache file format")
55 return cast(CacheDict, doc["dependencies"])
56
57
58 class DependencyCache:
59 """
60 Creates a new persistent dependency cache for the current Python version.
61 The cache file is written to the appropriate user cache dir for the
62 current platform, i.e.
63
64 ~/.cache/pip-tools/depcache-pyX.Y.json
65
66 Where py indicates the Python implementation.
67 Where X.Y indicates the Python version.
68 """
69
70 def __init__(self, cache_dir: str):
71 os.makedirs(cache_dir, exist_ok=True)
72 cache_filename = f"depcache-{_implementation_name()}.json"
73
74 self._cache_file = os.path.join(cache_dir, cache_filename)
75 self._cache: CacheDict | None = None
76
77 @property
78 def cache(self) -> CacheDict:
79 """
80 The dictionary that is the actual in-memory cache. This property
81 lazily loads the cache from disk.
82 """
83 if self._cache is None:
84 try:
85 self._cache = read_cache_file(self._cache_file)
86 except FileNotFoundError:
87 self._cache = {}
88 return self._cache
89
90 def as_cache_key(self, ireq: InstallRequirement) -> CacheKey:
91 """
92 Given a requirement, return its cache key. This behavior is a little weird
93 in order to allow backwards compatibility with cache files. For a requirement
94 without extras, this will return, for example:
95
96 ("ipython", "2.1.0")
97
98 For a requirement with extras, the extras will be comma-separated and appended
99 to the version, inside brackets, like so:
100
101 ("ipython", "2.1.0[nbconvert,notebook]")
102 """
103 name, version, extras = as_tuple(ireq)
104 if not extras:
105 extras_string = ""
106 else:
107 extras_string = f"[{','.join(extras)}]"
108 return name, f"{version}{extras_string}"
109
110 def write_cache(self) -> None:
111 """Writes the cache to disk as JSON."""
112 doc = {"__format__": 1, "dependencies": self._cache}
113 with open(self._cache_file, "w", encoding="utf-8") as f:
114 json.dump(doc, f, sort_keys=True)
115
116 def clear(self) -> None:
117 self._cache = {}
118 self.write_cache()
119
120 def __contains__(self, ireq: InstallRequirement) -> bool:
121 pkgname, pkgversion_and_extras = self.as_cache_key(ireq)
122 return pkgversion_and_extras in self.cache.get(pkgname, {})
123
124 def __getitem__(self, ireq: InstallRequirement) -> list[str]:
125 pkgname, pkgversion_and_extras = self.as_cache_key(ireq)
126 return self.cache[pkgname][pkgversion_and_extras]
127
128 def __setitem__(self, ireq: InstallRequirement, values: list[str]) -> None:
129 pkgname, pkgversion_and_extras = self.as_cache_key(ireq)
130 self.cache.setdefault(pkgname, {})
131 self.cache[pkgname][pkgversion_and_extras] = values
132 self.write_cache()
133
134 def reverse_dependencies(
135 self, ireqs: Iterable[InstallRequirement]
136 ) -> dict[str, set[str]]:
137 """
138 Returns a lookup table of reverse dependencies for all the given ireqs.
139
140 Since this is all static, it only works if the dependency cache
141 contains the complete data, otherwise you end up with a partial view.
142 This is typically no problem if you use this function after the entire
143 dependency tree is resolved.
144 """
145 ireqs_as_cache_values = [self.as_cache_key(ireq) for ireq in ireqs]
146 return self._reverse_dependencies(ireqs_as_cache_values)
147
148 def _reverse_dependencies(
149 self, cache_keys: Iterable[tuple[str, str]]
150 ) -> dict[str, set[str]]:
151 """
152 Returns a lookup table of reverse dependencies for all the given cache keys.
153
154 Example input:
155
156 [('pep8', '1.5.7'),
157 ('flake8', '2.4.0'),
158 ('mccabe', '0.3'),
159 ('pyflakes', '0.8.1')]
160
161 Example output:
162
163 {'pep8': ['flake8'],
164 'flake8': [],
165 'mccabe': ['flake8'],
166 'pyflakes': ['flake8']}
167
168 """
169 # First, collect all the dependencies into a sequence of (parent, child)
170 # tuples, like [('flake8', 'pep8'), ('flake8', 'mccabe'), ...]
171 return lookup_table_from_tuples(
172 (key_from_req(Requirement(dep_name)), name)
173 for name, version_and_extras in cache_keys
174 for dep_name in self.cache[name][version_and_extras]
175 )