|
| 1 | +from __future__ import unicode_literals |
| 2 | + |
| 3 | +import contextlib |
| 4 | +import os.path |
| 5 | + |
| 6 | +from pre_commit import git |
| 7 | +from pre_commit.envcontext import envcontext |
| 8 | +from pre_commit.envcontext import Var |
| 9 | +from pre_commit.languages import helpers |
| 10 | +from pre_commit.util import clean_path_on_failure |
| 11 | +from pre_commit.util import cmd_output |
| 12 | +from pre_commit.xargs import xargs |
| 13 | + |
| 14 | + |
| 15 | +ENVIRONMENT_DIR = 'golangenv' |
| 16 | + |
| 17 | + |
| 18 | +def get_env_patch(venv): # pragma: windows no cover |
| 19 | + return ( |
| 20 | + ('PATH', (os.path.join(venv, 'bin'), os.pathsep, Var('PATH'))), |
| 21 | + ) |
| 22 | + |
| 23 | + |
| 24 | +@contextlib.contextmanager |
| 25 | +def in_env(repo_cmd_runner): # pragma: windows no cover |
| 26 | + envdir = repo_cmd_runner.path( |
| 27 | + helpers.environment_dir(ENVIRONMENT_DIR, 'default'), |
| 28 | + ) |
| 29 | + with envcontext(get_env_patch(envdir)): |
| 30 | + yield |
| 31 | + |
| 32 | + |
| 33 | +def guess_go_dir(remote_url): |
| 34 | + if remote_url.endswith('.git'): |
| 35 | + remote_url = remote_url[:-1 * len('.git')] |
| 36 | + remote_url = remote_url.replace(':', '/') |
| 37 | + looks_like_url = '//' in remote_url or '@' in remote_url |
| 38 | + if looks_like_url: |
| 39 | + _, _, remote_url = remote_url.rpartition('//') |
| 40 | + _, _, remote_url = remote_url.rpartition('@') |
| 41 | + return remote_url |
| 42 | + else: |
| 43 | + return 'unknown_src_dir' |
| 44 | + |
| 45 | + |
| 46 | +def install_environment( |
| 47 | + repo_cmd_runner, |
| 48 | + version='default', |
| 49 | + additional_dependencies=(), |
| 50 | +): # pragma: windows no cover |
| 51 | + helpers.assert_version_default('golang', version) |
| 52 | + helpers.assert_no_additional_deps('golang', additional_dependencies) |
| 53 | + directory = repo_cmd_runner.path( |
| 54 | + helpers.environment_dir(ENVIRONMENT_DIR, 'default'), |
| 55 | + ) |
| 56 | + |
| 57 | + with clean_path_on_failure(directory): |
| 58 | + remote = git.get_remote_url(repo_cmd_runner.path()) |
| 59 | + repo_src_dir = os.path.join(directory, 'src', guess_go_dir(remote)) |
| 60 | + |
| 61 | + # Clone into the goenv we'll create |
| 62 | + helpers.run_setup_cmd( |
| 63 | + repo_cmd_runner, ('git', 'clone', '.', repo_src_dir), |
| 64 | + ) |
| 65 | + |
| 66 | + env = dict(os.environ, GOPATH=directory) |
| 67 | + cmd_output('go', 'get', './...', cwd=repo_src_dir, env=env) |
| 68 | + |
| 69 | + |
| 70 | +def run_hook(repo_cmd_runner, hook, file_args): # pragma: windows no cover |
| 71 | + with in_env(repo_cmd_runner): |
| 72 | + return xargs(helpers.to_cmd(hook), file_args) |
0 commit comments