Skip to content

Commit a1e856c

Browse files
committed
Add RepositoryString
1 parent 7c9b250 commit a1e856c

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

decouple.py

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,79 @@ def __getitem__(self, key):
188188
return self.data[key]
189189

190190

191+
class RepositoryString(RepositoryEmpty):
192+
"""
193+
Repository class to retrieve options from a string.
194+
195+
Parses a string formatted like a `.env` file into a dictionary of options.
196+
This class is an extension of the `RepositoryEmpty` class that provides a
197+
way to read configuration keys from an environment string.
198+
199+
Attributes:
200+
data (dict): A dictionary to hold the parsed key-value pairs.
201+
"""
202+
203+
def __init__(self, source):
204+
"""
205+
Initializes the RepositoryString with a given string source.
206+
207+
The provided string should have one "KEY=value" pair per line, similar
208+
to a `.env` file format. Lines starting with `#` are considered as
209+
comments and ignored. Surrounding whitespace is stripped from keys
210+
and values.
211+
212+
Args:
213+
source (str): The string source to parse.
214+
"""
215+
self.data = {}
216+
source_lines = source.split('\n')
217+
218+
for line in source_lines:
219+
line = line.strip()
220+
221+
if not line or line.startswith('#') or '=' not in line:
222+
continue
223+
224+
key, value = line.split('=', 1)
225+
key = key.strip()
226+
value = value.strip()
227+
228+
if len(value) >= 2 and (
229+
(value[0] == "'" and value[-1] == "'")
230+
or (value[0] == '"' and value[-1] == '"')
231+
):
232+
value = value[1:-1]
233+
234+
self.data[key] = value
235+
236+
def __contains__(self, key):
237+
"""
238+
Check if a key is present in the repository or the environment.
239+
240+
Args:
241+
key (str): The key to check for presence.
242+
243+
Returns:
244+
bool: True if key is in the repository or os.environ, False otherwise.
245+
"""
246+
return key in os.environ or key in self.data
247+
248+
def __getitem__(self, key):
249+
"""
250+
Retrieve the value associated with the given key.
251+
252+
Args:
253+
key (str): The key to retrieve the value for.
254+
255+
Returns:
256+
str: The value associated with the key.
257+
258+
Raises:
259+
KeyError: If the key is not found in the repository.
260+
"""
261+
return self.data[key]
262+
263+
191264
class AutoConfig(object):
192265
"""
193266
Autodetects the config file and type.

0 commit comments

Comments
 (0)