Class: AptControl::Exec

Inherits:
Object
  • Object
show all
Defined in:
lib/apt_control/exec.rb

Overview

ripped from vershunt

Defined Under Namespace

Modules: Helpers Classes: UnexpectedExitStatus

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Exec

Returns a new instance of Exec.



46
47
48
49
50
# File 'lib/apt_control/exec.rb', line 46

def initialize(options={})
  @name   = options.fetch(:name,   nil)
  @quiet  = options.fetch(:quiet,  true)
  @output = options.fetch(:output, $stdout)
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



42
43
44
# File 'lib/apt_control/exec.rb', line 42

def name
  @name
end

#quietObject (readonly) Also known as: quiet?

Returns the value of attribute quiet.



43
44
45
# File 'lib/apt_control/exec.rb', line 43

def quiet
  @quiet
end

Class Method Details

.exec(command, options = {}) ⇒ Object



38
39
40
# File 'lib/apt_control/exec.rb', line 38

def self.exec(command, options={})
  new(options).exec(command, options)
end

Instance Method Details

#exec(command, options = {}) ⇒ Object



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/apt_control/exec.rb', line 68

def exec(command, options={})

  expected = to_expected_array(options.fetch(:status, 0))

  @last_stdout = ""
  @last_stderr = ""
  @last_output = ""

  output_semaphore = Mutex.new

  start = name.nil? ? '' : "#{name}: "

  status = POpen4::popen4(command) do |stdout, stderr, stdin, pid|
    t1 = Thread.new do
      stdout.each_line do |line|
        @last_stdout += line
        output_semaphore.synchronize { @last_output += line }
        @output.puts("#{start}#{line}") unless quiet?
      end
    end

    t2 = Thread.new do
      stderr.each_line do |line|
        @last_stderr += line
        output_semaphore.synchronize { @last_output += line }
        @output.puts("#{start}#{line}") unless quiet?
      end
    end

    t1.join
    t2.join
  end

  @last_exitstatus = status.exitstatus

  unless expected.nil? || expected.include?(status.exitstatus)
    raise UnexpectedExitStatus.new(expected, status.exitstatus, command, @last_output, @last_stdout, @last_stderr)
  end

  @last_stdout
end

#last_exitstatusObject



64
65
66
# File 'lib/apt_control/exec.rb', line 64

def last_exitstatus
  @last_exitstatus
end

#last_outputObject



60
61
62
# File 'lib/apt_control/exec.rb', line 60

def last_output
  @last_output
end

#last_stderrObject



56
57
58
# File 'lib/apt_control/exec.rb', line 56

def last_stderr
  @last_stderr
end

#last_stdoutObject



52
53
54
# File 'lib/apt_control/exec.rb', line 52

def last_stdout
  @last_stdout
end