|
| 1 | +import contextlib |
| 2 | +import os |
| 3 | +from typing import Generator |
| 4 | +from typing import Sequence |
| 5 | +from typing import Tuple |
| 6 | + |
| 7 | +from pre_commit.envcontext import envcontext |
| 8 | +from pre_commit.envcontext import PatchesT |
| 9 | +from pre_commit.envcontext import Var |
| 10 | +from pre_commit.hook import Hook |
| 11 | +from pre_commit.languages import helpers |
| 12 | +from pre_commit.prefix import Prefix |
| 13 | +from pre_commit.util import clean_path_on_failure |
| 14 | + |
| 15 | +ENVIRONMENT_DIR = 'coursier' |
| 16 | + |
| 17 | +get_default_version = helpers.basic_get_default_version |
| 18 | +healthy = helpers.basic_healthy |
| 19 | + |
| 20 | + |
| 21 | +def install_environment( |
| 22 | + prefix: Prefix, |
| 23 | + version: str, |
| 24 | + additional_dependencies: Sequence[str], |
| 25 | +) -> None: # pragma: win32 no cover |
| 26 | + helpers.assert_version_default('coursier', version) |
| 27 | + helpers.assert_no_additional_deps('coursier', additional_dependencies) |
| 28 | + |
| 29 | + envdir = prefix.path(helpers.environment_dir(ENVIRONMENT_DIR, version)) |
| 30 | + channel = prefix.path('.pre-commit-channel') |
| 31 | + with clean_path_on_failure(envdir): |
| 32 | + for app_descriptor in os.listdir(channel): |
| 33 | + _, app_file = os.path.split(app_descriptor) |
| 34 | + app, _ = os.path.splitext(app_file) |
| 35 | + helpers.run_setup_cmd( |
| 36 | + prefix, |
| 37 | + ( |
| 38 | + 'cs', |
| 39 | + 'install', |
| 40 | + '--default-channels=false', |
| 41 | + f'--channel={channel}', |
| 42 | + app, |
| 43 | + f'--dir={envdir}', |
| 44 | + ), |
| 45 | + ) |
| 46 | + |
| 47 | + |
| 48 | +def get_env_patch(target_dir: str) -> PatchesT: # pragma: win32 no cover |
| 49 | + return ( |
| 50 | + ('PATH', (target_dir, os.pathsep, Var('PATH'))), |
| 51 | + ) |
| 52 | + |
| 53 | + |
| 54 | +@contextlib.contextmanager |
| 55 | +def in_env( |
| 56 | + prefix: Prefix, |
| 57 | +) -> Generator[None, None, None]: # pragma: win32 no cover |
| 58 | + target_dir = prefix.path( |
| 59 | + helpers.environment_dir(ENVIRONMENT_DIR, get_default_version()), |
| 60 | + ) |
| 61 | + with envcontext(get_env_patch(target_dir)): |
| 62 | + yield |
| 63 | + |
| 64 | + |
| 65 | +def run_hook( |
| 66 | + hook: Hook, |
| 67 | + file_args: Sequence[str], |
| 68 | + color: bool, |
| 69 | +) -> Tuple[int, bytes]: # pragma: win32 no cover |
| 70 | + with in_env(hook.prefix): |
| 71 | + return helpers.run_xargs(hook, hook.cmd, file_args, color=color) |
0 commit comments