Skip to content

Commit e580096

Browse files
glehmannasottile
authored andcommitted
give docker a tty output when expecting color
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.
1 parent 7b868c3 commit e580096

File tree

3 files changed

+32
-3
lines changed

3 files changed

+32
-3
lines changed

pre_commit/languages/docker.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -108,10 +108,15 @@ def get_docker_user() -> tuple[str, ...]: # pragma: win32 no cover
108108
return ()
109109

110110

111-
def docker_cmd() -> tuple[str, ...]: # pragma: win32 no cover
111+
def get_docker_tty(*, color: bool) -> tuple[str, ...]: # pragma: win32 no cover # noqa: E501
112+
return (('--tty',) if color else ())
113+
114+
115+
def docker_cmd(*, color: bool) -> tuple[str, ...]: # pragma: win32 no cover
112116
return (
113117
'docker', 'run',
114118
'--rm',
119+
*get_docker_tty(color=color),
115120
*get_docker_user(),
116121
# https://docs.docker.com/engine/reference/commandline/run/#mount-volumes-from-container-volumes-from
117122
# The `Z` option tells Docker to label the content with a private
@@ -139,7 +144,7 @@ def run_hook(
139144

140145
entry_tag = ('--entrypoint', entry_exe, docker_tag(prefix))
141146
return lang_base.run_xargs(
142-
(*docker_cmd(), *entry_tag, *cmd_rest),
147+
(*docker_cmd(color=color), *entry_tag, *cmd_rest),
143148
file_args,
144149
require_serial=require_serial,
145150
color=color,

pre_commit/languages/docker_image.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ def run_hook(
2323
require_serial: bool,
2424
color: bool,
2525
) -> tuple[int, bytes]: # pragma: win32 no cover
26-
cmd = docker_cmd() + lang_base.hook_cmd(entry, args)
26+
cmd = docker_cmd(color=color) + lang_base.hook_cmd(entry, args)
2727
return lang_base.run_xargs(
2828
cmd,
2929
file_args,

tests/languages/docker_image_test.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,3 +25,27 @@ def test_docker_image_hook_via_args(tmp_path):
2525
args=('hello hello world',),
2626
)
2727
assert ret == (0, b'hello hello world\n')
28+
29+
30+
@xfailif_windows # pragma: win32 no cover
31+
def test_docker_image_color_tty(tmp_path):
32+
ret = run_language(
33+
tmp_path,
34+
docker_image,
35+
'ubuntu:22.04',
36+
args=('grep', '--color', 'root', '/etc/group'),
37+
color=True,
38+
)
39+
assert ret == (0, b'\x1b[01;31m\x1b[Kroot\x1b[m\x1b[K:x:0:\n')
40+
41+
42+
@xfailif_windows # pragma: win32 no cover
43+
def test_docker_image_no_color_no_tty(tmp_path):
44+
ret = run_language(
45+
tmp_path,
46+
docker_image,
47+
'ubuntu:22.04',
48+
args=('grep', '--color', 'root', '/etc/group'),
49+
color=False,
50+
)
51+
assert ret == (0, b'root:x:0:\n')

0 commit comments

Comments
 (0)