Skip to content

Commit 21eb63f

Browse files
committed
Ensure strings that may be confused as YAML1.2 numbers are quoted
1 parent 0eb96cb commit 21eb63f

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

lib/psych/visitors/yaml_tree.rb

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -274,7 +274,7 @@ def visit_String o
274274
style = Nodes::Scalar::FOLDED
275275
elsif o.match?(/^[^[:word:]][^"]*$/)
276276
style = Nodes::Scalar::DOUBLE_QUOTED
277-
elsif not String === @ss.tokenize(o) or /\A0[0-7]*[89]/.match?(o)
277+
elsif not String === @ss.tokenize(o) or may_be_confused_as_yaml12?(o)
278278
style = Nodes::Scalar::SINGLE_QUOTED
279279
end
280280

@@ -388,6 +388,19 @@ def binary? string
388388
string.encoding == Encoding::ASCII_8BIT && !string.ascii_only?
389389
end
390390

391+
def may_be_confused_as_yaml12? string
392+
case string
393+
when /\A0[0-7]*[89]\z/ # YAML 1.1 int (Base 8)
394+
true
395+
when /\A0o[0-7]+\z/ # YAML 1.2 int (Base 8)
396+
true
397+
when /\A[-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?\z/ # YAML 1.2 float (Number)
398+
true
399+
else
400+
false
401+
end
402+
end
403+
391404
def visit_array_subclass o
392405
tag = "!ruby/array:#{o.class}"
393406
ivars = o.instance_variables

test/psych/visitors/test_yaml_tree.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,9 +167,22 @@ def test_float
167167
end
168168

169169
def test_string
170+
# YAML 1.1 int Base 8
170171
assert_include(Psych.dump({'a' => '017'}), "'017'")
171172
assert_include(Psych.dump({'a' => '019'}), "'019'")
172173
assert_include(Psych.dump({'a' => '01818'}), "'01818'")
174+
175+
# YAML 1.1 float Number
176+
assert_include(Psych.dump({'a' => '.2e3'}), '".2e3"')
177+
178+
# YAML 1.2 int Base 8
179+
assert_include(Psych.dump({'a' => '0o17'}), "'0o17'")
180+
assert_include(Psych.dump({'a' => '0o111'}), "'0o111'")
181+
182+
# YAML 1.2 float Number
183+
assert_include(Psych.dump({'a' => '12e03'}), "'12e03'")
184+
assert_include(Psych.dump({'a' => '0e447890'}), "'0e447890'")
185+
assert_include(Psych.dump({'a' => '1.2e3'}), "'1.2e3'")
173186
end
174187

175188
# http://yaml.org/type/null.html

0 commit comments

Comments
 (0)