Browse Source

move docker_build to DockerImage.build()

Fabian Peter Hammerle 5 years ago
parent
commit
f5dc336b0d
1 changed files with 12 additions and 15 deletions
  1. 12 15
      rc.xsh

+ 12 - 15
rc.xsh

@@ -91,6 +91,18 @@ class DockerImage:
     def __repr__(self):
         return '{}(id={!r}, tags={!r})'.format(type(self).__name__, self._id, self._tags)
 
+    @classmethod
+    def build(cls, dockerfile):
+        out = io.BytesIO()
+        with StdoutTee(out) as tee:
+            p = subprocess.Popen(['sudo', 'docker', 'build', '-'],
+                                  stdin=subprocess.PIPE, stdout=tee)
+            p.stdin.write(dockerfile.encode())
+            p.stdin.close()
+            assert p.wait() == 0, 'docker build failed'
+        image_id, = re.search(rb'^Successfully built (\S+)$', out.getvalue(), re.MULTILINE).groups()
+        return cls(image_id.decode(sys.stdout.encoding))
+
     @classmethod
     def pull(cls, image):
         out = io.BytesIO()
@@ -169,21 +181,6 @@ def dpkg_which(cmd):
     assert len(matches) == 1
     return matches[0]
 
-def docker_build(dockerfile):
-    p = subprocess.Popen(['sudo', 'docker', 'build', '-'],
-                         stdin=subprocess.PIPE, stdout=subprocess.PIPE)
-    p.stdin.write(dockerfile.encode())
-    p.stdin.close()
-    image_id_regex = re.compile(rb'^Successfully built (\S+)\n$')
-    image_id = None
-    for line in p.stdout:
-        sys.stdout.write(line.decode(sys.stdout.encoding))
-        image_id_match = image_id_regex.search(line)
-        if image_id_match:
-            image_id, = image_id_match.groups()
-    assert not image_id is None, 'could not determine image id'
-    return image_id.decode(sys.stdout.encoding)
-
 def locate(*patterns, match_all=True, ignore_case=True):
     params = []
     if match_all: