Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Do not quote valid json values during processing. #4

Merged
merged 1 commit into from
Sep 8, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "configly"
version = "0.2.1"
version = "0.2.2"
description = ""
authors = []
license = "MIT"
Expand Down
13 changes: 12 additions & 1 deletion src/configly/utilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,24 @@ def quote_string(value: str):

>>> quote_string('''q"u'x''')
'"q\\"u\'x"'

>>> quote_string('{"log_level": "INFO"}')
'{"log_level": "INFO"}'
"""
if (value.startswith('"') and value.endswith('"')) or (
value.startswith("'") and value.endswith("'")
):
# NOTE:
# Single quotes aren't always accepted as valid syntax.
# And just because a value is surrounded by quotes, does not mean it is correctly quoted.
# In that case we would rely on the user of this fn to raise a helpful error.
return value

return json.dumps(value)
try:
json.loads(value)
except json.decoder.JSONDecodeError:
# If the value is unable to load via json.loads, this means we have to quote it
# and perform any necessary escaping.
return json.dumps(value)

return value
7 changes: 7 additions & 0 deletions tests/test_process.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,3 +128,10 @@ def test_null_default_value_with_pre_and_post(self):
input_ = {"foo": "1<% ENV[foo, null] %>2"}
config = Config(post_process(yaml, input_))
assert config.foo == "1null2"

@patch("os.environ", new={"foo": '{"hello": "world"}'})
def test_object_values(self):
input_ = {"foo": "<% ENV[foo] %>"}
config = Config(post_process(yaml, input_))
assert type(config.foo) == Config
assert config.foo.to_dict() == {"hello": "world"}