Skip to content

Commit

Permalink
give docker a tty output when expecting color
Browse files Browse the repository at this point in the history
this makes the behavior more consistent with the system language
and would help the executable run in a docker container to
produce a colored output.
  • Loading branch information
glehmann authored and asottile committed Mar 2, 2024
1 parent 7b868c3 commit e580096
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 3 deletions.
9 changes: 7 additions & 2 deletions pre_commit/languages/docker.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,10 +108,15 @@ def get_docker_user() -> tuple[str, ...]: # pragma: win32 no cover
return ()


def docker_cmd() -> tuple[str, ...]: # pragma: win32 no cover
def get_docker_tty(*, color: bool) -> tuple[str, ...]: # pragma: win32 no cover # noqa: E501
return (('--tty',) if color else ())


def docker_cmd(*, color: bool) -> tuple[str, ...]: # pragma: win32 no cover
return (
'docker', 'run',
'--rm',
*get_docker_tty(color=color),
*get_docker_user(),
# https://docs.docker.com/engine/reference/commandline/run/#mount-volumes-from-container-volumes-from
# The `Z` option tells Docker to label the content with a private
Expand Down Expand Up @@ -139,7 +144,7 @@ def run_hook(

entry_tag = ('--entrypoint', entry_exe, docker_tag(prefix))
return lang_base.run_xargs(
(*docker_cmd(), *entry_tag, *cmd_rest),
(*docker_cmd(color=color), *entry_tag, *cmd_rest),
file_args,
require_serial=require_serial,
color=color,
Expand Down
2 changes: 1 addition & 1 deletion pre_commit/languages/docker_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def run_hook(
require_serial: bool,
color: bool,
) -> tuple[int, bytes]: # pragma: win32 no cover
cmd = docker_cmd() + lang_base.hook_cmd(entry, args)
cmd = docker_cmd(color=color) + lang_base.hook_cmd(entry, args)
return lang_base.run_xargs(
cmd,
file_args,
Expand Down
24 changes: 24 additions & 0 deletions tests/languages/docker_image_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,27 @@ def test_docker_image_hook_via_args(tmp_path):
args=('hello hello world',),
)
assert ret == (0, b'hello hello world\n')


@xfailif_windows # pragma: win32 no cover
def test_docker_image_color_tty(tmp_path):
ret = run_language(
tmp_path,
docker_image,
'ubuntu:22.04',
args=('grep', '--color', 'root', '/etc/group'),
color=True,
)
assert ret == (0, b'\x1b[01;31m\x1b[Kroot\x1b[m\x1b[K:x:0:\n')


@xfailif_windows # pragma: win32 no cover
def test_docker_image_no_color_no_tty(tmp_path):
ret = run_language(
tmp_path,
docker_image,
'ubuntu:22.04',
args=('grep', '--color', 'root', '/etc/group'),
color=False,
)
assert ret == (0, b'root:x:0:\n')

0 comments on commit e580096

Please sign in to comment.