Skip to content

Commit a0b2bd8

Browse files
Use default values in POSIX-style variable expansions
1 parent 40ed1b1 commit a0b2bd8

File tree

1 file changed

+25
-4
lines changed

1 file changed

+25
-4
lines changed

dotenv/main.py

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -181,21 +181,42 @@ def unset_key(dotenv_path, key_to_unset, quote_mode="always"):
181181

182182

183183
def resolve_nested_variables(values):
184-
def _replacement(name):
184+
def _replacement(name, default=None):
185185
"""
186186
get appropriate value for a variable name.
187187
first search in environ, if not found,
188188
then look into the dotenv variables
189189
"""
190-
ret = os.getenv(name, new_values.get(name, ""))
191-
return ret
190+
191+
# If name is set as an environment variable, use its value
192+
if name in os.environ:
193+
return os.getenv(name)
194+
195+
# If name is the same as k, we need to handle the situation special, or we will have ${K}
196+
# or ${K:-default} as the return value. Note that k comes from the for loop below
197+
if name == k:
198+
# If we have a default set, return it
199+
if default:
200+
return default
201+
202+
# Otherwise, return an empty string
203+
return ''
204+
205+
# If all the above failed, try getting name from the environments, revert to the value
206+
# from values, and if it’s not in values yet, revert to the default value
207+
return os.getenv(name, values.get(name, default or ''))
192208

193209
def _re_sub_callback(match_object):
194210
"""
195211
From a match object gets the variable name and returns
196212
the correct replacement
197213
"""
198-
return _replacement(match_object.group()[2:-1])
214+
215+
replacement = match_object.group()[2:-1].split(sep=':-', maxsplit=1)
216+
name = replacement.pop(0)
217+
default = replacement[0] if replacement else None
218+
219+
return _replacement(name, default=default)
199220

200221
new_values = {}
201222

0 commit comments

Comments
 (0)