Skip to content

Commit

Permalink
Fix env file parsing related to quotes (#230)
Browse files Browse the repository at this point in the history
This should support these cases more correctly:

```
KEY="'val'" -> {"KEY": "'val'"}
KEY="'val' something else" -> {"KEY": "'val' something else"}
```
  • Loading branch information
willkg committed Nov 6, 2023
1 parent 93b976c commit ce39260
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 3 deletions.
14 changes: 13 additions & 1 deletion src/everett/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,16 @@ def parse_env_file(envfile: Iterable[str]) -> Dict:
raise ConfigurationError(
f"Invalid variable name {k!r} in env file (line {line_no + 1})"
)
v = v.strip().strip("'\"")

v = v.strip()

# Need to strip matching ' and " from beginning and end--but only one
# round
for quote in "'\"":
if v.startswith(quote) and v.endswith(quote):
v = v[1:-1]
break

data[k] = v

return data
Expand Down Expand Up @@ -775,6 +784,9 @@ class ConfigEnvFileEnv:
DB_HOST=localhost
DB_PORT=5432
# CSP reporting
CSP_SCRIPT_SRC="'self' www.googletagmanager.com"
"""

def __init__(self, possible_paths: Union[str, List[str]]):
Expand Down
28 changes: 26 additions & 2 deletions tests/test_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -386,16 +386,40 @@ def test_ConfigEnvFileEnv(datadir):
assert cefe.get("loglevel") is NO_VALUE


def test_parse_env_file():
assert parse_env_file(["PLAN9=outerspace"]) == {"PLAN9": "outerspace"}
@pytest.mark.parametrize(
"line, expected",
[
("PLAN9=outerspace", {"PLAN9": "outerspace"}),
('KEY="val"', {"KEY": "val"}),
("KEY='val'", {"KEY": "val"}),
# Only strips outer-most quote
("KEY=\"'val'\"", {"KEY": "'val'"}),
("KEY='\"val\"'", {"KEY": '"val"'}),
(
"CSP_SCRIPT_SRC='self' www.googletagmanager.com",
{"CSP_SCRIPT_SRC": "'self' www.googletagmanager.com"},
),
(
"CSP_SCRIPT_SRC=\"'self' www.googletagmanager.com\"",
{"CSP_SCRIPT_SRC": "'self' www.googletagmanager.com"},
),
],
)
def test_parse_env_file_line(line, expected):
assert parse_env_file([line]) == expected


def test_parse_env_file_errors():
with pytest.raises(ConfigurationError) as exc_info:
parse_env_file(["3AMIGOS=infamous"])
assert str(exc_info.value) == "Invalid variable name '3AMIGOS' in env file (line 1)"

with pytest.raises(ConfigurationError) as exc_info:
parse_env_file(["INVALID-CHAR=value"])
assert str(exc_info.value) == (
"Invalid variable name 'INVALID-CHAR' in env file (line 1)"
)

with pytest.raises(ConfigurationError) as exc_info:
parse_env_file(["", "MISSING-equals"])
assert str(exc_info.value) == "Env file line missing = operator (line 2)"
Expand Down

0 comments on commit ce39260

Please sign in to comment.