Class: RightConf::EnvironmentUpdater
- Inherits:
-
Object
- Object
- RightConf::EnvironmentUpdater
- Includes:
- ProgressReporter
- Defined in:
- lib/rconf/support/environment_updater.rb
Class Method Summary collapse
-
.update(code, dependencies = []) ⇒ Object
Update bash resource or profile file to define given environment variable or append to existing environment variable.
Instance Method Summary collapse
-
#do_update(code, dependencies = []) ⇒ Object
Update bash resource or profile file to define given environment variable or append to existing environment variable.
Methods included from ProgressReporter
included, report_to_file, report_to_stdout
Class Method Details
.update(code, dependencies = []) ⇒ Object
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
30 31 32 |
# File 'lib/rconf/support/environment_updater.rb', line 30 def self.update(code, dependencies=[]) new.do_update(code, dependencies) end |
Instance Method Details
#do_update(code, dependencies = []) ⇒ Object
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
46 47 48 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 |
# File 'lib/rconf/support/environment_updater.rb', line 46 def do_update(code, dependencies=[]) if Platform.darwin? candidates = [ '.bash_profile', '.bash_login', '.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 |