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

Force strings starting with a zero to be quoted. #43

Merged
merged 1 commit into from
Mar 12, 2018
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
10 changes: 10 additions & 0 deletions cfn_flip/yaml_dumper.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@
from cfn_clean.yaml_dumper import CleanCfnYamlDumper
from cfn_tools.odict import ODict
from cfn_tools.yaml_dumper import CfnYamlDumper
import six

TAG_STR = "tag:yaml.org,2002:str"
TAG_MAP = "tag:yaml.org,2002:map"
CONVERTED_SUFFIXES = ["Ref", "Condition"]

Expand Down Expand Up @@ -46,6 +48,13 @@ class LongCleanDumper(CleanCfnYamlDumper):
"""


def string_representer(dumper, value):
if value.startswith("0"):
return dumper.represent_scalar(TAG_STR, value, style="'")

return dumper.represent_scalar(TAG_STR, value)


def fn_representer(dumper, fn_name, value):
tag = "!{}".format(fn_name)

Expand Down Expand Up @@ -82,6 +91,7 @@ def map_representer(dumper, value):

# Customise our dumpers
Dumper.add_representer(ODict, map_representer)
Dumper.add_representer(six.text_type, string_representer)
CleanDumper.add_representer(ODict, map_representer)


Expand Down
34 changes: 34 additions & 0 deletions tests/test_flip.py
Original file line number Diff line number Diff line change
Expand Up @@ -502,5 +502,39 @@ def test_get_dumper():
When invoking get_dumper use clean_up & long_form
:return: LongCleanDumper
"""

resp = cfn_flip.get_dumper(clean_up=True, long_form=True)
assert resp == cfn_flip.yaml_dumper.LongCleanDumper


def test_quoted_digits():
"""
Any value that is composed entirely of digits
should be quoted for safety.
CloudFormation is happy for numbers to appear as strings.
But the opposite (e.g. account numbers as numbers) can cause issues
See https://github.com/awslabs/aws-cfn-template-flip/issues/41
"""

value = dump_json(ODict((
("int", 123456),
("float", 123.456),
("oct", "0123456"),
("bad-oct", "012345678"),
("safe-oct", "0o123456"),
("string", "abcdef"),
)))

expected = "\n".join((
"int: 123456",
"float: 123.456",
"oct: '0123456'",
"bad-oct: '012345678'",
"safe-oct: '0o123456'",
"string: abcdef",
""
))

actual = cfn_flip.to_yaml(value)

assert actual == expected