Skip to content

Commit 64d6c3f

Browse files
peteristhegreatph-conn
authored andcommitted
Add stream and timestamp args to client.build
1 parent 9ad4bdd commit 64d6c3f

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

docker/models/images.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -217,7 +217,7 @@ def reload(self):
217217
class ImageCollection(Collection):
218218
model = Image
219219

220-
def build(self, **kwargs):
220+
def build(self, stream=False, timestamp=False, **kwargs):
221221
"""
222222
Build an image and return it. Similar to the ``docker build``
223223
command. Either ``path`` or ``fileobj`` must be set.
@@ -245,6 +245,10 @@ def build(self, **kwargs):
245245
custom_context (bool): Optional if using ``fileobj``
246246
encoding (str): The encoding for a stream. Set to ``gzip`` for
247247
compressing
248+
stream (bool): Print the build output to stdout and stderr while
249+
the build runs
250+
timestamp (bool): Prefix build output stream with a timestamp
251+
"%Y-%m-%d %H:%M:%S"
248252
pull (bool): Downloads any updates to the FROM image in Dockerfiles
249253
forcerm (bool): Always remove intermediate containers, even after
250254
unsuccessful builds
@@ -300,9 +304,20 @@ def build(self, **kwargs):
300304
image_id = None
301305
result_stream, internal_stream = itertools.tee(json_stream(resp))
302306
for chunk in internal_stream:
307+
if timestamp:
308+
timestamp_str = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
303309
if 'error' in chunk:
310+
if stream:
311+
if timestamp:
312+
print(timestamp_str, "- ", end='', file=sys.stderr)
313+
print("Error:", chunk['error'].strip(), flush=True, file=sys.stderr))
304314
raise BuildError(chunk['error'], result_stream)
305315
if 'stream' in chunk:
316+
if stream:
317+
for line in chunk["stream"].splitlines():
318+
if timestamp:
319+
print(timestamp_str, "- ", end='')
320+
print(line.strip(), flush=True)
306321
match = re.search(
307322
r'(^Successfully built |sha256:)([0-9a-f]+)$',
308323
chunk['stream']

tests/unit/api_build_test.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,21 @@ def test_build_container(self):
2828

2929
self.client.build(fileobj=script)
3030

31+
def test_build_container_with_stream_with_timestamp(self):
32+
script = io.BytesIO(
33+
"\n".join(
34+
[
35+
"FROM busybox",
36+
"RUN mkdir -p /tmp/test",
37+
"EXPOSE 8080",
38+
"ADD https://dl.dropboxusercontent.com/u/20637798/silence.tar.gz"
39+
" /tmp/silence.tar.gz",
40+
]
41+
).encode("ascii")
42+
)
43+
44+
self.client.build(fileobj=script, stream=True, timestamp=True)
45+
3146
def test_build_container_pull(self):
3247
script = io.BytesIO(
3348
"\n".join(

0 commit comments

Comments
 (0)