|
| 1 | +from __future__ import unicode_literals |
| 2 | + |
| 3 | +import contextlib |
| 4 | +import os |
| 5 | +import sys |
| 6 | + |
| 7 | +from pre_commit.envcontext import envcontext |
| 8 | +from pre_commit.envcontext import UNSET |
| 9 | +from pre_commit.envcontext import Var |
| 10 | +from pre_commit.languages import helpers |
| 11 | +from pre_commit.languages.python import get_default_version # noqa: F401 |
| 12 | +from pre_commit.languages.python import norm_version |
| 13 | +from pre_commit.util import clean_path_on_failure |
| 14 | +from pre_commit.util import cmd_output |
| 15 | +from pre_commit.xargs import xargs |
| 16 | + |
| 17 | + |
| 18 | +ENVIRONMENT_DIR = 'py_venv' |
| 19 | + |
| 20 | + |
| 21 | +def bin_dir(venv): |
| 22 | + """On windows there's a different directory for the virtualenv""" |
| 23 | + bin_part = 'Scripts' if os.name == 'nt' else 'bin' |
| 24 | + return os.path.join(venv, bin_part) |
| 25 | + |
| 26 | + |
| 27 | +def get_env_patch(venv): |
| 28 | + return ( |
| 29 | + ('PYTHONHOME', UNSET), |
| 30 | + ('VIRTUAL_ENV', venv), |
| 31 | + ('PATH', (bin_dir(venv), os.pathsep, Var('PATH'))), |
| 32 | + ) |
| 33 | + |
| 34 | + |
| 35 | +@contextlib.contextmanager |
| 36 | +def in_env(prefix, language_version): |
| 37 | + envdir = prefix.path( |
| 38 | + helpers.environment_dir(ENVIRONMENT_DIR, language_version), |
| 39 | + ) |
| 40 | + with envcontext(get_env_patch(envdir)): |
| 41 | + yield |
| 42 | + |
| 43 | + |
| 44 | +def healthy(prefix, language_version): |
| 45 | + with in_env(prefix, language_version): |
| 46 | + retcode, _, _ = cmd_output( |
| 47 | + 'python', '-c', 'import ctypes, datetime, io, os, ssl, weakref', |
| 48 | + retcode=None, |
| 49 | + ) |
| 50 | + return retcode == 0 |
| 51 | + |
| 52 | + |
| 53 | +def install_environment(prefix, version, additional_dependencies): |
| 54 | + additional_dependencies = tuple(additional_dependencies) |
| 55 | + directory = helpers.environment_dir(ENVIRONMENT_DIR, version) |
| 56 | + |
| 57 | + # Install a virtualenv |
| 58 | + env_dir = prefix.path(directory) |
| 59 | + with clean_path_on_failure(env_dir): |
| 60 | + if version != 'default': |
| 61 | + executable = norm_version(version) |
| 62 | + else: |
| 63 | + executable = os.path.realpath(sys.executable) |
| 64 | + cmd_output(executable, '-m', 'venv', env_dir, cwd='/') |
| 65 | + with in_env(prefix, version): |
| 66 | + helpers.run_setup_cmd( |
| 67 | + prefix, ('pip', 'install', '.') + additional_dependencies, |
| 68 | + ) |
| 69 | + |
| 70 | + |
| 71 | +def run_hook(prefix, hook, file_args): |
| 72 | + with in_env(prefix, hook['language_version']): |
| 73 | + return xargs(helpers.to_cmd(hook), file_args) |
0 commit comments