Code cleanup and tests

This commit is contained in:
Ben Picolo 2017-01-04 10:35:00 -05:00
parent 5f392f0ba5
commit 9b92f96ed0
7 changed files with 92 additions and 21 deletions

View file

@ -1,8 +1,10 @@
from __future__ import absolute_import
from __future__ import unicode_literals
import hashlib
import os
from pre_commit import five
from pre_commit.languages import helpers
from pre_commit.util import clean_path_on_failure
from pre_commit.util import mkdirp
@ -10,12 +12,11 @@ from pre_commit.xargs import xargs
ENVIRONMENT_DIR = 'docker'
PRE_COMMIT_LABEL = 'PRE_COMMIT'
def md5(s):
m = hashlib.md5()
m.update(s)
return m.hexdigest()
return five.to_text(hashlib.md5(s).hexdigest())
def docker_tag(repo_cmd_runner):
@ -24,39 +25,62 @@ def docker_tag(repo_cmd_runner):
).lower()
def docker_is_running():
return xargs(('docker',), ['ps'])[0] == 0
def assert_docker_available():
assert docker_is_running(), (
'Docker is either not running or not configured in this environment'
)
def build_docker_image(repo_cmd_runner):
cmd = (
'docker', 'build', '--pull',
'--tag', docker_tag(repo_cmd_runner),
'--label', PRE_COMMIT_LABEL,
'.'
)
helpers.run_setup_cmd(repo_cmd_runner, cmd)
def install_environment(
repo_cmd_runner,
version='default',
additional_dependencies=(),
):
assert repo_cmd_runner.exists('Dockerfile')
# I don't know of anybody trying to juggle multiple docker installations
# so this seems sufficient
assert repo_cmd_runner.exists('Dockerfile'), (
'No Dockerfile was found in the hook repository'
)
assert version == 'default', (
'Pre-commit does not support language_version for docker '
)
assert_docker_available()
directory = helpers.environment_dir(ENVIRONMENT_DIR, 'default')
mkdirp(os.path.join(repo_cmd_runner.path(), directory))
cmd = (
'docker', 'build', '--pull',
'--tag', docker_tag(repo_cmd_runner),
'.'
)
# Docker doesn't really have relevant disk environment, but pre-commit
# still needs to cleanup it's state files on failure
env_dir = repo_cmd_runner.path(directory)
with clean_path_on_failure(env_dir):
helpers.run_setup_cmd(repo_cmd_runner, cmd)
build_docker_image(repo_cmd_runner)
def run_hook(repo_cmd_runner, hook, file_args):
assert_docker_available()
# Rebuild the docker image in case it has gone missing, as many people do
# automated cleanup of docker images.
build_docker_image(repo_cmd_runner)
# the docker lib doesn't return stdout on non-zero exit codes,
# so we run the container directly on the command line
cmd = (
'docker', 'run',
'-t',
'--rm',
'-v', '{}:/src'.format(os.getcwd()),
'--workdir', '/src',
'--entrypoint', hook['entry'],
docker_tag(repo_cmd_runner)
)
return xargs(
cmd + (hook['entry'],) + tuple(hook['args']), file_args,
)
return xargs(cmd + tuple(hook['args']), file_args)