|
| 1 | +from __future__ import unicode_literals |
| 2 | + |
| 3 | +import contextlib |
| 4 | +import os.path |
| 5 | + |
| 6 | +import toml |
| 7 | + |
| 8 | +from pre_commit.envcontext import envcontext |
| 9 | +from pre_commit.envcontext import Var |
| 10 | +from pre_commit.languages import helpers |
| 11 | +from pre_commit.util import clean_path_on_failure |
| 12 | +from pre_commit.util import cmd_output |
| 13 | +from pre_commit.xargs import xargs |
| 14 | + |
| 15 | + |
| 16 | +ENVIRONMENT_DIR = 'rustenv' |
| 17 | +get_default_version = helpers.basic_get_default_version |
| 18 | +healthy = helpers.basic_healthy |
| 19 | + |
| 20 | + |
| 21 | +def get_env_patch(target_dir): |
| 22 | + return ( |
| 23 | + ( |
| 24 | + 'PATH', |
| 25 | + (os.path.join(target_dir, 'release'), os.pathsep, Var('PATH')), |
| 26 | + ), |
| 27 | + ) |
| 28 | + |
| 29 | + |
| 30 | +@contextlib.contextmanager |
| 31 | +def in_env(prefix): |
| 32 | + target_dir = prefix.path( |
| 33 | + helpers.environment_dir(ENVIRONMENT_DIR, 'default'), |
| 34 | + ) |
| 35 | + with envcontext(get_env_patch(target_dir)): |
| 36 | + yield |
| 37 | + |
| 38 | + |
| 39 | +def _add_dependencies(cargo_toml_path, additional_dependencies): |
| 40 | + with open(cargo_toml_path, 'r+') as f: |
| 41 | + cargo_toml = toml.load(f) |
| 42 | + for dep in additional_dependencies: |
| 43 | + name, _, spec = dep.partition(':') |
| 44 | + cargo_toml['dependencies'][name] = spec or '*' |
| 45 | + f.seek(0) |
| 46 | + toml.dump(cargo_toml, f) |
| 47 | + f.truncate() |
| 48 | + |
| 49 | + |
| 50 | +def install_environment(prefix, version, additional_dependencies): |
| 51 | + helpers.assert_version_default('rust', version) |
| 52 | + directory = prefix.path( |
| 53 | + helpers.environment_dir(ENVIRONMENT_DIR, 'default'), |
| 54 | + ) |
| 55 | + |
| 56 | + if len(additional_dependencies) > 0: |
| 57 | + _add_dependencies(prefix.path('Cargo.toml'), additional_dependencies) |
| 58 | + |
| 59 | + with clean_path_on_failure(directory): |
| 60 | + cmd_output( |
| 61 | + 'cargo', 'build', '--release', '--bins', '--target-dir', directory, |
| 62 | + cwd=prefix.prefix_dir, |
| 63 | + ) |
| 64 | + |
| 65 | + |
| 66 | +def run_hook(prefix, hook, file_args): |
| 67 | + with in_env(prefix): |
| 68 | + return xargs(helpers.to_cmd(hook), file_args) |
0 commit comments