Class: CMD
- Inherits:
-
Hash
- Object
- Hash
- CMD
- Defined in:
- lib/cmd.rb,
lib/cmd_windows.rb
Class Method Summary collapse
Instance Method Summary collapse
- #execute ⇒ Object
- #execute_as(username) ⇒ Object
-
#initialize(cmd, options = nil) ⇒ CMD
constructor
A new instance of CMD.
- #system ⇒ Object
Constructor Details
#initialize(cmd, options = nil) ⇒ CMD
Returns a new instance of CMD.
9 10 11 12 13 14 15 16 17 |
# File 'lib/cmd.rb', line 9 def initialize(cmd, =nil) initialize_defaults if(.nil?) self[:output] = '' self[:error] = '' .each { |key, value| self[key] = value} .each { |key, value| self[key] = value} unless(.nil?) self[:command]=cmd end |
Class Method Details
.default_options(hash) ⇒ Object
20 21 22 |
# File 'lib/cmd.rb', line 20 def self.(hash) hash.each { |key, value| [key] = value} end |
Instance Method Details
#execute ⇒ Object
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/cmd.rb', line 24 def execute if(self[:quiet]) self[:echo_output] = false self[:echo_command] = false end puts self[:command] if(self[:echo_command] || self[:debug]) system if(self[:debug]) puts "command: #{self[:command]}" puts "output: #{self[:output]}" puts "error: #{self[:error]}" puts "exit_code: #{self[:exit_code]}" end puts "exit_code: #{self[:exit_code]}" if((self[:exit_code] != 0) && !self[:ignore_exit_code]) exception_text = "Exit code: #{self[:exit_code]}" exception_text = "#{exception_text}\nError: '#{self[:error]}'" exception_text = "#{exception_text}\nOutput: '#{self[:output]}'" raise StandardError.new(exception_text) end end |
#execute_as(username) ⇒ Object
6 7 8 9 |
# File 'lib/cmd_windows.rb', line 6 def execute_as(username) self[:command] = "runas /noprofile /savecred /user:#{username} \"#{self[:command]}\"" wait_on_spawned_process(self) { self.execute } end |
#system ⇒ Object
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
# File 'lib/cmd.rb', line 49 def system begin output = '' error = '' Thread.abort_on_exception = true mutex = Mutex.new Open3.popen3(self[:command]) do |stdin, stdout, stderr, wait_thr| self[:pid] = wait_thr.pid {:output => stdout,:error => stderr}.each do |key, stream| Thread.new do while wait_thr.alive? do if(!(char = stream.getc).nil?) case key when :output output << char when :error error << char end mutex.synchronize { putc char if(self[:echo_output]) } else sleep(0.1) end end end end wait_thr.join self[:output] = output.join unless(output.empty?) self[:error] = error.join unless(error.empty?) self[:exit_code] = wait_thr.value.to_i end rescue Exception => e self[:error] = "#{self[:error]}\nException: #{e.to_s}" self[:exit_code]=1 unless(self[:exit_code].nil? || (self[:exit_code] == 0)) rescue => e self[:error] = "#{self[:error]}\nException: #{e.to_s}" self[:exit_code]=1 unless(self[:exit_code].nil? || (self[:exit_code] == 0)) end end |