-
Notifications
You must be signed in to change notification settings - Fork 0
/
dotenv
executable file
·132 lines (103 loc) · 2.32 KB
/
dotenv
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
#!/usr/bin/env ruby
class Dotenv
ALLOWED_ENVS = %w(production test development staging preview qa xingbox dev prod).freeze
QUOTES = ["\"", "'"]
COMMAND_REGEXP = /\$\((.+)\)/
attr_reader :argv, :env, :loaded_vars
def initialize(argv, env)
@argv = argv
@env = env
@loaded_vars = {}
end
def run
load_dotenv(file)
load_dotenv(env_file)
load_dotenv('.env.local')
load_dotenv(local_env_file)
add_loaded_environment_variables
if command != ''
exec command
else
puts 'dotenv: exec needs a command to run'
end
end
def command
if file_passed?
if exec_arg?(2)
args_from(3)
else
args_from(2)
end
elsif env_passed?
if exec_arg?(1)
args_from(2)
else
args_from(1)
end
else
if exec_arg?(0)
args_from(1)
else
args_from(0)
end
end
end
def file
file_passed? ? argv[1] : '.env'
end
def current_env
return argv[0] if env_passed?
env['RAILS_ENV'] || env['ENV'] || 'development'
end
def env_file
".env.#{current_env}"
end
def local_env_file
"#{env_file}.local"
end
def add_loaded_environment_variables
loaded_vars.each { |key, value| env[key] = value }
end
def file_passed?
argv[0] == '-f'
end
def env_passed?
ALLOWED_ENVS.include?(argv[0])
end
def args_from(index)
argv[index..-1].join(' ')
end
def exec_arg?(index)
argv[index] == 'exec'
end
def load_dotenv(file)
return unless file
return unless File.exists?(file)
text = File.read(file)
text.lines.each do |line|
line = line.gsub("\n", '').gsub('export ', '')
next if line.length.zero? || line[0] == '#'
key, value = line.split('=')
value ||= ''
strip_quotes!(value)
substitute_commands(value)
loaded_vars[key] = value || ''
end
end
def strip_quotes!(value)
strip_quote!(value, 0)
strip_quote!(value, -1)
end
def strip_quote!(value, position)
value[position] = '' if QUOTES.include?(value[position])
end
def substitute_commands(value)
commands = value.scan(COMMAND_REGEXP).flatten
commands.each do |command|
key = "$(#{command})"
result = `#{command}`.gsub("\n", '')
value.gsub!(key, result)
end
end
end
Dotenv.new(ARGV, ENV).run