-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
plugin.py
380 lines (351 loc) · 13.8 KB
/
plugin.py
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
"""
hatch-pip-compile plugin
"""
import functools
import hashlib
import logging
import os
import pathlib
import shutil
import tempfile
from subprocess import CompletedProcess
from typing import Any, Dict, List, Optional, Union
from hatch.env.virtual import VirtualEnvironment
from hatch.utils.platform import Platform
from hatchling.dep.core import dependencies_in_sync
from packaging.requirements import Requirement
from hatch_pip_compile.exceptions import HatchPipCompileError
from hatch_pip_compile.installer import PipInstaller, PipSyncInstaller, PluginInstaller
from hatch_pip_compile.lock import PipCompileLock
logger = logging.getLogger(__name__)
class PipCompileEnvironment(VirtualEnvironment):
"""
Virtual Environment supported by pip-compile
"""
PLUGIN_NAME = "pip-compile"
default_env_name = "default"
def __repr__(self):
"""
Get representation of PipCompileEnvironment
"""
return f"<{self.__class__.__name__} - {self.name}>"
def __init__(self, *args, **kwargs) -> None:
"""
Initialize PipCompileEnvironment with extra attributes
"""
super().__init__(*args, **kwargs)
lock_filename_config = self.config.get("lock-filename")
if lock_filename_config is None:
if self.name == self.default_env_name:
lock_filename = "requirements.txt"
else:
lock_filename = f"requirements/requirements-{self.name}.txt"
else:
with self.metadata.context.apply_context(self.context):
lock_filename = self.metadata.context.format(lock_filename_config)
self.piptools_lock_file = self.root / lock_filename
self.piptools_lock = PipCompileLock(
lock_file=self.piptools_lock_file,
dependencies=self.dependencies,
virtualenv=self.virtual_env,
constraints_file=self.piptools_constraints_file,
project_root=self.root,
env_name=self.name,
project_name=self.metadata.name,
)
install_method = self.config.get("pip-compile-installer", "pip")
self.installer: PluginInstaller
if install_method == "pip":
self.installer = PipInstaller(environment=self)
elif install_method == "pip-sync":
self.installer = PipSyncInstaller(environment=self)
else:
msg = (
f"Invalid pip-tools install method: {install_method} - "
"must be 'pip' or 'pip-sync'"
)
raise HatchPipCompileError(msg)
@staticmethod
def get_option_types() -> Dict[str, Any]:
"""
Get option types
"""
return { # pragma: no cover
"lock-filename": str,
"pip-compile-hashes": bool,
"pip-compile-args": List[str],
"pip-compile-constraint": str,
"pip-compile-installer": str,
"pip-compile-install-args": List[str],
}
def dependency_hash(self) -> str:
"""
Get the dependency hash
"""
self.run_pip_compile()
hatch_hash = super().dependency_hash()
if not self.dependencies:
return hatch_hash
else:
lockfile_hash = self.piptools_lock.get_file_content_hash()
return hashlib.sha256(f"{hatch_hash}-{lockfile_hash}".encode()).hexdigest()
def install_pip_tools(self) -> None:
"""
Install pip-tools (if not already installed)
"""
with self.safe_activation():
in_sync = dependencies_in_sync(
requirements=[Requirement("pip-tools")],
sys_path=self.virtual_env.sys_path,
environment=self.virtual_env.environment,
)
if not in_sync:
self.plugin_check_command(self.construct_pip_install_command(["pip-tools"]))
def run_pip_compile(self) -> None:
"""
Run pip-compile if necessary
"""
if not self.lockfile_up_to_date:
with self.safe_activation():
self.install_pip_tools()
if self.piptools_lock_file.exists():
_ = self.piptools_lock.compare_python_versions(
verbose=self.config.get("pip-compile-verbose", None)
)
self.pip_compile_cli()
def pip_compile_cli(self) -> None:
"""
Run pip-compile
"""
if not self.dependencies:
self.piptools_lock_file.unlink(missing_ok=True)
self.lockfile_up_to_date = True
return
no_compile = bool(os.getenv("PIP_COMPILE_DISABLE"))
if no_compile:
msg = "hatch-pip-compile is disabled but attempted to run a lockfile update."
raise HatchPipCompileError(msg)
upgrade = bool(os.getenv("PIP_COMPILE_UPGRADE"))
upgrade_packages = os.getenv("PIP_COMPILE_UPGRADE_PACKAGE") or None
upgrade_args = []
upgrade_package_args = []
if upgrade:
upgrade_args.append("--upgrade")
if upgrade_packages:
upgrade_packages_sep = upgrade_packages.split(",")
for package in upgrade_packages_sep:
upgrade_package_args.append(f"--upgrade-package={package.strip()}")
cmd = [
self.virtual_env.python_info.executable,
"-m",
"piptools",
"compile",
"--verbose" if self.config.get("pip-compile-verbose", None) is True else "--quiet",
"--strip-extras",
"--no-header",
"--resolver=backtracking",
]
if self.config.get("pip-compile-hashes", False) is True:
cmd.append("--generate-hashes")
if self.piptools_constraints_file is not None:
cmd.extend(["--constraint", str(self.piptools_constraints_file)])
cmd.extend(self.config.get("pip-compile-args", []))
cmd.extend(upgrade_args)
cmd.extend(upgrade_package_args)
with tempfile.TemporaryDirectory() as tmpdir:
tmp_path = pathlib.Path(tmpdir)
input_file = tmp_path / f"{self.name}.in"
output_file = tmp_path / "lock.txt"
cmd.extend(["--output-file", str(output_file), str(input_file)])
input_file.write_text("\n".join([*self.dependencies, ""]))
if self.piptools_lock_file.exists():
shutil.copy(self.piptools_lock_file, output_file)
self.piptools_lock_file.parent.mkdir(exist_ok=True, parents=True)
self.plugin_check_command(cmd)
self.piptools_lock.process_lock(lockfile=output_file)
shutil.move(output_file, self.piptools_lock_file)
self.lockfile_up_to_date = True
def install_project(self) -> None:
"""
Install the project (`--no-deps`)
"""
self.installer.install_project()
def install_project_dev_mode(self) -> None:
"""
Install the project in editable mode (`--no-deps`)
"""
self.installer.install_project_dev_mode()
@functools.cached_property
def lockfile_up_to_date(self) -> bool:
"""
Check if the lockfile is up-to-date
Behavior
--------
1) If there are no dependencies and no lock file, exit early and return True.
2) If the constraint file / environment is out of date, sync it and return False.
3) If there are no dependencies and a lock file, return False.
4) If there are dependencies and no lock file, return False.
5) If a force upgrade is requested, return False.
6) If there are dependencies and a lock file...
a) If there is a constraint file...
i) If the file is valid but the SHA is different, return False.
b) If the lock file dependencies aren't current, return False.
c) If the lock file dependencies are current but the lockfile
has a different sha than its constraints file, return False.
7) Otherwise, return True.
"""
upgrade = os.getenv("PIP_COMPILE_UPGRADE") or False
upgrade_packages = os.getenv("PIP_COMPILE_UPGRADE_PACKAGE") or False
pip_compile_force = bool(os.getenv("__PIP_COMPILE_FORCE__"))
force_upgrade = any(
[
upgrade is not False,
upgrade_packages is not False,
pip_compile_force is not False,
]
)
if not self.dependencies and not self.piptools_lock_file.exists():
return True
if self.piptools_constraints_file:
valid_constraint = self.validate_constraints_file(
constraints_file=self.piptools_constraints_file, environment=self.constraint_env
)
if not valid_constraint:
return False
if not self.dependencies and self.piptools_lock_file.exists():
return False
elif force_upgrade:
return False
elif self.dependencies and not self.piptools_lock_file.exists():
return False
elif self.dependencies and self.piptools_lock_file.exists():
if self.piptools_constraints_file:
current_sha = self.constraint_env.piptools_lock.get_file_content_hash()
sha_match = self.piptools_lock.compare_constraint_sha(sha=current_sha)
if sha_match is False:
return False
expected_dependencies = self.piptools_lock.compare_requirements(
requirements=self.dependencies_complex
)
if not expected_dependencies:
return False
return True
def dependencies_in_sync(self):
"""
Whether the dependencies are in sync
"""
if not self.lockfile_up_to_date:
return False
else:
with self.safe_activation():
return dependencies_in_sync(
self.piptools_lock.read_lock_requirements(),
sys_path=self.virtual_env.sys_path,
environment=self.virtual_env.environment,
)
def sync_dependencies(self) -> None:
"""
Sync dependencies
"""
self.run_pip_compile()
self.installer.sync_dependencies()
@property
def piptools_constraints_file(self) -> Optional[pathlib.Path]:
"""
Get the constraint file path
"""
if self.constraint_env.name == self.name:
return None
else:
return self.constraint_env.piptools_lock_file
def get_piptools_environment(self, environment_name: str) -> "PipCompileEnvironment":
"""
Get a `PipCompileEnvironment` instance for an environment
other than the current instance. This is useful
for recursively checking other environments for lock file
validity and defining inheritance.
"""
if environment_name not in self.pipools_environment_dict.keys():
error_message = (
f"[hatch-pip-compile] The environment {environment_name} does not exist."
)
raise HatchPipCompileError(error_message)
return PipCompileEnvironment(
root=self.root,
metadata=self.metadata,
name=environment_name,
config=self.pipools_environment_dict.get(environment_name, {}),
matrix_variables=self.matrix_variables,
data_directory=self.data_directory,
isolated_data_directory=self.isolated_data_directory,
platform=Platform(),
verbosity=self.verbosity,
app=None,
)
@functools.cached_property
def constraint_env(self) -> "PipCompileEnvironment":
"""
Get the constraint environment
"""
constraint_env = self.config.get("pip-compile-constraint")
if not constraint_env:
return self
elif self.name == constraint_env:
return self
environment = self.get_piptools_environment(environment_name=constraint_env)
if environment.config.get("type") != self.PLUGIN_NAME:
logger.error("The constraint environment is not a hatch-pip-compile environment.")
return self
elif not environment.dependencies:
return self
else:
try:
_ = environment.virtual_env.executables_directory
except OSError:
environment.create()
return environment
def validate_constraints_file(
self, constraints_file: pathlib.Path, environment: "PipCompileEnvironment"
) -> bool:
"""
Validate the constraints file
Parameters
----------
constraints_file : pathlib.Path
The lock file
environment : PipCompileEnvironment
The environment to validate against
Returns
-------
bool
Whether the constraints file is valid
"""
if not constraints_file.exists():
self.constraint_env.run_pip_compile()
return False
else:
up_to_date = environment.piptools_lock.compare_requirements(
requirements=environment.dependencies_complex
)
if not up_to_date:
self.constraint_env.run_pip_compile()
return False
return True
@property
def pipools_environment_dict(self) -> Dict[str, Any]:
"""
Get the environment dictionary
"""
return self.metadata.hatch.config.get("envs", {})
def plugin_check_command(
self, command: Union[str, List[str]], *, shell: bool = False, **kwargs: Any
) -> CompletedProcess:
"""
Run a command from the virtualenv
"""
with self.safe_activation():
return self.virtual_env.platform.check_command(
command=command,
shell=shell,
**kwargs,
)