Class: Kuby::Docker::CLI

Inherits:
CLIBase show all
Defined in:
lib/kuby/docker/cli.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from CLIBase

#after_execute, #before_execute, #last_status

Constructor Details

#initialize(executable = nil) ⇒ CLI

Returns a new instance of CLI.



9
10
11
# File 'lib/kuby/docker/cli.rb', line 9

def initialize(executable = nil)
  @executable = executable || `which docker`.strip
end

Instance Attribute Details

#executableObject (readonly)

Returns the value of attribute executable.



7
8
9
# File 'lib/kuby/docker/cli.rb', line 7

def executable
  @executable
end

Instance Method Details

#build(dockerfile:, image_url:, tags:) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/kuby/docker/cli.rb', line 13

def build(dockerfile:, image_url:, tags:)
  cmd = [
    executable, 'build',
    *tags.flat_map { |tag| ['-t', "#{image_url}:#{tag}"] },
    '-f-', '.'
  ]

  open3_w({}, cmd) do |stdin, _wait_threads|
    stdin.puts(dockerfile.to_s)
  end

  unless last_status.success?
    raise BuildError, 'build failed: docker command exited with '\
      "status code #{last_status.exitstatus}"
  end
end

#images(image_url) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/kuby/docker/cli.rb', line 43

def images(image_url)
  cmd = [
    executable, 'images', image_url,
    '--format', '"{{json . }}"'
  ]

  backticks(cmd).split("\n").map do |image_data|
    JSON.parse(image_data).each_with_object({}) do |(k, v), ret|
      ret[k.underscore.to_sym] = v
    end
  end
end

#push(image_url, tag) ⇒ Object



56
57
58
59
60
61
62
63
64
65
# File 'lib/kuby/docker/cli.rb', line 56

def push(image_url, tag)
  systemm([
    executable, 'push', "#{image_url}:#{tag}"
  ])

  unless last_status.success?
    raise PushError, 'push failed: docker command exited with '\
      "status code #{last_status.exitstatus}"
  end
end

#run(image_url:, tag: 'latest', env: {}, ports: []) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/kuby/docker/cli.rb', line 30

def run(image_url:, tag: 'latest', env: {}, ports: [])
  cmd = [
    executable, 'run',
    *env.flat_map { |k, v| ['-e', "#{k}=#{v}"] },
    *ports.flat_map { |port| ['-p', "#{port}:#{port}"] },
    '--init',
    '--rm',
    "#{image_url}:#{tag}"
  ]

  execc(cmd)
end

#status_keyObject



67
68
69
# File 'lib/kuby/docker/cli.rb', line 67

def status_key
  :kuby_docker_cli_last_status
end