Skip to content

Commit

Permalink
Fix number strings being converted to numbers
Browse files Browse the repository at this point in the history
Fixes mohsen1#78. This also fixes numbers larger than
Number.MAX_SAFE_INTEGER represented as strings being rounded
when the yaml is loaded and serialized again.

Causes a slight regression with the styling of string values.
Specifically, any strings that are modified in the JSON are quoted
in the resulting yaml, even if they weren't in the original.
  • Loading branch information
Dragory committed Oct 17, 2020
1 parent aab6ee9 commit 2cfb09a
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 3 deletions.
6 changes: 5 additions & 1 deletion src/index.js
Expand Up @@ -293,7 +293,7 @@ function updateMap(ast, newJson, json, yaml, offset) {
*/
function replacePrimitive(node, value, yaml, offset) {
return yaml.substr(0, node.start_mark.pointer + offset) +
String(value) +
JSON.stringify(value) +
yaml.substring(node.end_mark.pointer + offset);
}

Expand Down Expand Up @@ -417,6 +417,10 @@ function indent(str, depth) {
*
*/
function cleanDump(value) {
if (value === null || isString(value) || isNumber(value)) {
return value;
}

let yaml = dump(value).replace(/\n$/, '');

if (EOL !== '\n') {
Expand Down
2 changes: 1 addition & 1 deletion test/object.js
Expand Up @@ -210,7 +210,7 @@ describe('preserves comments and styling in objects when', ()=> {
expect(yawn.yaml).to.equal(`
# leading comment
a:
x: abc
x: "abc"

This comment has been minimized.

Copy link
@wickedest

wickedest Oct 21, 2020

Are you sure about this change? Previously, it was x: abc, now it will be x: "abc". I would think that replacePrimitive might need to test the type of value.

b:
y: 'b'
z: abc
Expand Down
17 changes: 16 additions & 1 deletion test/string.js
Expand Up @@ -18,7 +18,7 @@ describe('preserves comments and styling when', ()=> {

expect(yawn.yaml).to.equal(`
# leading comment
newValue # inline comment
"newValue" # inline comment
# trailing comment`);
});

Expand All @@ -36,5 +36,20 @@ describe('preserves comments and styling when', ()=> {
null # inline comment
# trailing comment`);
});

it('string numbers stay as numbers', ()=> {

This comment has been minimized.

Copy link
@alasdairhurst

alasdairhurst Oct 21, 2020

I think you meant "string numbers stay as strings"?

let str = `
# leading comment
foo: "1000" # inline comment
# trailing comment`;

let yawn = new YAWN(str);
yawn.json = { foo: "1001" };

expect(yawn.yaml).to.equal(`
# leading comment
foo: "1001" # inline comment
# trailing comment`);
});
});
});

0 comments on commit 2cfb09a

Please sign in to comment.