-
Notifications
You must be signed in to change notification settings - Fork 42
/
environment.rb
67 lines (51 loc) · 1.36 KB
/
environment.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# frozen_string_literal: true
require "pathname"
module Dip
class Environment
VAR_REGEX = /\$[\{]?(?<var_name>[a-zA-Z_][a-zA-Z0-9_]*)[\}]?/.freeze
SPECIAL_VARS = %i[os work_dir_rel_path].freeze
attr_reader :vars
def initialize(default_vars)
@vars = {}
merge(default_vars || {})
end
def merge(new_vars)
new_vars.each do |key, value|
key = key.to_s
@vars[key] = ENV.fetch(key) { interpolate(value.to_s) }
end
end
def [](name)
vars.fetch(name) { ENV[name] }
end
def fetch(name)
vars.fetch(name) { ENV.fetch(name) { yield } }
end
def []=(key, value)
@vars[key] = value
end
def interpolate(value)
value.gsub(VAR_REGEX) do
var_name = Regexp.last_match[:var_name]
if special_vars.key?(var_name)
fetch(var_name) { send(special_vars[var_name]) }
else
self[var_name]
end
end
end
alias replace interpolate
private
def special_vars
@special_vars ||= SPECIAL_VARS.each_with_object({}) do |key, memo|
memo["DIP_#{key.to_s.upcase}"] = "find_#{key}"
end
end
def find_os
@dip_os ||= Gem::Platform.local.os
end
def find_work_dir_rel_path
@find_work_dir_rel_path ||= Pathname.getwd.relative_path_from(Dip.config.file_path.parent).to_s
end
end
end