Class: Dockerhelper::Command

Inherits:
Object
  • Object
show all
Defined in:
lib/dockerhelper/command.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(cmd, label: '', chdir: Dir.pwd) ⇒ Command

Returns a new instance of Command.



7
8
9
10
11
# File 'lib/dockerhelper/command.rb', line 7

def initialize(cmd, label: '', chdir: Dir.pwd)
  @label = " #{label}" if label.size > 0
  @cmd = cmd
  @chdir = chdir
end

Instance Attribute Details

#chdirObject (readonly)

Returns the value of attribute chdir.



5
6
7
# File 'lib/dockerhelper/command.rb', line 5

def chdir
  @chdir
end

#cmdObject (readonly)

Returns the value of attribute cmd.



5
6
7
# File 'lib/dockerhelper/command.rb', line 5

def cmd
  @cmd
end

#labelObject (readonly)

Returns the value of attribute label.



5
6
7
# File 'lib/dockerhelper/command.rb', line 5

def label
  @label
end

Instance Method Details

#captureObject



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/dockerhelper/command.rb', line 13

def capture
  stdout, stderr, status = Open3.capture3(cmd)
  pid = status.pid
  cmd_prefix = "[#{pid}#{label}]"

  $stdout.puts ">> #{yellow(cmd_prefix)} cwd: #{chdir} cmd: #{cmd}"
  unless stdout.empty?
    stdout.lines.each do |line|
      $stdout.puts "   #{green(cmd_prefix)} #{line}"
    end
  end

  unless stderr.empty?
    stderr.lines.each do |line|
      $stderr.puts "   #{red(cmd_prefix)} #{line}"
    end
  end

  $stdout.puts "<< #{yellow(cmd_prefix)} exit_status: #{status}"
  stdout
end

#colorize(text, color_code) ⇒ Object



62
63
64
# File 'lib/dockerhelper/command.rb', line 62

def colorize(text, color_code)
  "\e[#{color_code}m#{text}\e[0m"
end

#green(text) ⇒ Object



67
# File 'lib/dockerhelper/command.rb', line 67

def green(text); colorize(text, 32); end

#red(text) ⇒ Object



66
# File 'lib/dockerhelper/command.rb', line 66

def red(text); colorize(text, 31); end

#runObject



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/dockerhelper/command.rb', line 35

def run
  Open3.popen3(cmd, chdir: chdir) do |stdin, stdout, stderr, wait_thr|
    pid = wait_thr.pid
    cmd_prefix = "[#{pid}#{label}]"
    $stdout.puts ">> #{yellow(cmd_prefix)} cwd: #{chdir} cmd: #{cmd}"

    stdin.close
    stderr_thr = Thread.new do
      while line = stderr.gets
        $stderr.puts "   #{red(cmd_prefix)} #{line}"
      end
    end

    stdout_thr = Thread.new do
      while line = stdout.gets
        $stdout.puts "   #{green(cmd_prefix)} #{line}"
      end
    end

    stderr_thr.join
    stdout_thr.join

    exit_status = wait_thr.value
    $stdout.puts "<< #{yellow(cmd_prefix)} exit_status: #{exit_status}"
  end
end

#yellow(text) ⇒ Object



68
# File 'lib/dockerhelper/command.rb', line 68

def yellow(text); colorize(text, 33); end