# Copyright (C) 2011 RightScale, Inc, All Rights Reserved Worldwide. # # THIS PROGRAM IS CONFIDENTIAL AND PROPRIETARY TO RIGHTSCALE # AND CONSTITUTES A VALUABLE TRADE SECRET. Any unauthorized use, # reproduction, modification, or disclosure of this program is # strictly prohibited. Any use of this program by an authorized # licensee is strictly subject to the terms and conditions, # including confidentiality obligations, set forth in the applicable # License Agreement between RightScale.com, Inc. and # the licensee module RightConf class EnvironmentUpdater include ProgressReporter # Update bash resource or profile file to define given environment variable # or append to existing environment variable # # === Parameters # code(String):: Code to be inserted in bash resource file # dependencies(Array):: List of environment variables that code will update # (Use to put code after these env var are set in the # existing bash resource file) # # === Return # true:: If bash resource or profile file was updated # false:: Otherwise def self.update(code, dependencies=[]) new.do_update(code, dependencies) end # Update bash resource or profile file to define given environment variable # or append to existing environment variable # # === Parameters # code(String):: Code to be inserted in bash resource file # dependencies(Array):: List of environment variables that code will update # (Use to put code after these env var are set in the # existing bash resource file) # # === Return # true:: If bash resource or profile file was updated # false:: Otherwise def do_update(code, dependencies=[]) if Platform.darwin? candidates = [ '.bash_profile' ] else candidates = ['.bash_profile', '.bashrc'] end candidates.map! { |c| File.join(ENV['HOME'], c) } bashrc_path = candidates.detect { |c| File.exist?(c) } updated = false if bashrc_path content = IO.read(bashrc_path) unless content.include?(code) i = dependencies.inject(nil) do |m, d| index = content.index(/^\s*#{d}=/) m = if m.nil? index else if index.nil? m else [ index, m ].max end end end if i next_line = content.index("\n", i + 1) if next_line content.insert(next_line + 1, code + "\n") else content += "\n" + code end else content = code + "\n" + content end FileUtils.mv(bashrc_path, bashrc_path + '.old') File.open(bashrc_path, 'w') { |f| f.puts content } updated = true end else report_error "Failed to update bash resource or profile: file not found" end end end end