module MJ; module Tools module SubProcess module ClassMethods # Executes command # # Executes the given command and yields each line of output. # Returns +$?+ . def execute( command, wd = nil, env = nil ) cwd ||= Dir.getwd $log.cmd( "(#{wd}) > #{command} 2>&1" ) if !$noop adjust_environment( wd, env ) { IO.popen( "#{command} 2>&1" ) { |f| begin while line = f.readline $log.cmdout( line.chomp ) yield line if block_given? end rescue EOFError: # Expected. Do nothing end } $log.cmdout( "= #{$?}" ) return $? } else $log.cmdout( "= 0 # noop" ) return 0 end end ######### protected ######### # Helper method to adjust LANG to "C" def adjust_environment( wd=nil, env=nil, lang="C" ) if wd cwd = Dir.getwd Dir.chdir(wd) end # Set the environment the user wants oldenv = Hash.new if env env.each do |var, value| oldenv[var] = ENV[var] $log.debug "#{var} = #{value}" ENV[var] = value end end # Save old LANG setting and switch to 'C' oldlang = ENV['LANG'] ENV['LANG'] = lang yield # Reset the old LANG setting ENV['LANG'] = oldlang # Reset our changes to ENV oldenv.each do |var, value| ENV[var] = value end # Reset the current working directory if wd Dir.chdir(cwd) end end end def self.included( klass ) klass.extend( ClassMethods ) end end end; end