require 'mj/tools/subprocess' module BuildTool # # Encapsulates all environment related options for a build # class Environment include MJ::Tools::SubProcess # Name for the environment attr_reader :name # Parent environment attr_accessor :parent attr_accessor :feature # Create a environment object def initialize( name ) raise StandardError.new "Environment.name has to be set" if name.nil? @name = name @vars = Hash.new @parent = nil @feature = nil end def active? if @feature.nil? true else @feature.active? end end # Set a environment variable def append( name, value ) if @vars.has_key?(name.to_s) and !@vars[name.to_s].empty? @vars[name.to_s] = "#{@vars[name.to_s]}:#{value.to_s}" else set( name, "$#{name.to_s}:#{value}" ) end end # Execute command in a shell with the environment set. def execute( command, wd = nil, envadd = nil ) env = Hash.new for var in vars do env[var] = self[var] end env.merge!( envadd ) if envadd return self.class.execute( command.to_s, wd, env ) end # Prepend +value+ to variable +name+. A ':' is added when necessary. def prepend( name, value ) if @vars.has_key?(name.to_s) and !@vars[name.to_s].empty? @vars[name.to_s] = "#{value.to_s}:#{@vars[name.to_s]}" else set( name, "#{value}:$#{name.to_s}" ) end end def set( name, value ) @vars[name.to_s] = value.to_s end # Open a shell with the environment set. # # It sets an environment variable *BUILD_TOOL_ENV* with the name of # the environment set. This can be used to add this information to # the prompt. def shell( wd = nil ) begin ENV['BUILD_TOOL_ENV'] = name self.class.adjust_environment( wd, values ) { logger.info "Starting #{ENV['SHELL']}" system( ENV['SHELL'] ) logger.info "#{ENV['SHELL']} stopped." return 0; } ensure ENV['BUILD_TOOL_ENV'] = nil end end def vars if @parent ( @vars.keys + @parent.vars ).uniq else @vars.keys end end def values vals = {} vars.each do |var| vals[var] = self[var] end vals end # Get the value of a environment variable def []( name ) parentval = "" # Get the value from the parent if @parent parentval = @parent[name] end # If we don't know the var or the env is not active return the parents value if !@vars.has_key?( name.to_s ) or !active? return parentval end if parentval.empty? val = @vars[name.to_s].sub( ":$#{name.to_s}:", "" ) val.sub!( ":$#{name.to_s}", "" ) val.sub!( "$#{name.to_s}:", "" ) return val else return @vars[name.to_s].sub( "$#{name.to_s}", parentval ) end end def to_s "Environment: #{name}" end end # class Environment end # module BuildTool