Browse Source

define class DockerImage with DockerImage.pull() & .__repr__()

Fabian Peter Hammerle 5 years ago
parent
commit
215283c087
1 changed files with 23 additions and 1 deletions
  1. 23 1
      rc.xsh

+ 23 - 1
rc.xsh

@@ -29,6 +29,8 @@ $PROMPT = ''.join([
 $RIGHT_PROMPT = '{gitstatus}{env_name: {}}'
 
 import datetime as dt
+import io
+import json
 import os
 import re
 import select
@@ -77,6 +79,25 @@ $TERMCMD = os.path.join(os.path.dirname(__file__), 'ranger-termite-termcmd')
 # https://docs.docker.com/engine/security/trust/content_trust/
 $DOCKER_CONTENT_TRUST = 1
 
+class DockerImage:
+
+    def __init__(self, image):
+        attrs, = json.loads(subprocess.check_output(['sudo', 'docker', 'image', 'inspect', image])
+                            .decode(sys.stdout.encoding))
+        self._id = attrs['Id']
+        self._tags = attrs['RepoTags']
+
+    def __repr__(self):
+        return '{}(id={!r}, tags={!r})'.format(type(self).__name__, self._id, self._tags)
+
+    @classmethod
+    def pull(cls, image):
+        out = io.BytesIO()
+        with StdoutTee(out) as tee:
+            subprocess.run(['sudo', 'docker', 'image', 'pull', image], stdout=tee)
+        repo_digest, = re.search(rb'^Digest: (sha\S+:\S+)$', out.getvalue(), re.MULTILINE).groups()
+        return cls('{}@{}'.format(image, repo_digest.decode()))
+
 class StdoutTee:
 
     def __init__(self, sink):
@@ -134,7 +155,8 @@ def dpkg_which(cmd):
     return matches[0]
 
 def docker_build(dockerfile):
-    p = subprocess.Popen(['sudo', 'docker', 'build', '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
+    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$')