Skip to content

Commit 9ae719c

Browse files
committed
Ensure strings that may be confused as YAML1.2 numbers are quoted
1 parent 2cad18c commit 9ae719c

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

lib/psych/visitors/yaml_tree.rb

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

@@ -392,6 +392,19 @@ def binary? string
392392
string.encoding == Encoding::ASCII_8BIT && !string.ascii_only?
393393
end
394394

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

test/psych/visitors/test_yaml_tree.rb

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

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

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

0 commit comments

Comments
 (0)