Skip to content

Commit 7e383c5

Browse files
committed
Fix Yaml/Syml stringify with keys longer than 1024 chars
1 parent b730176 commit 7e383c5

File tree

2 files changed

+30
-8
lines changed

2 files changed

+30
-8
lines changed

packages/yarnpkg-parsers/sources/syml.ts

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -91,11 +91,21 @@ function stringifyValue(value: any, indentLevel: number, newLineIfObject: boolea
9191
? indent
9292
: ``;
9393

94-
if (stringifiedValue.startsWith(`\n`)) {
95-
return `${recordIndentation}${stringifiedKey}:${stringifiedValue}`;
96-
} else {
97-
return `${recordIndentation}${stringifiedKey}: ${stringifiedValue}`;
98-
}
94+
95+
let keyPart: string;
96+
let valuePart: string;
97+
98+
// Yaml 1.2 spec says that keys over 1024 characters need to be prefixed with ? and the : goes in a new line
99+
if (stringifiedKey.length > 1024)
100+
keyPart = `? ${stringifiedKey}\n:`;
101+
else keyPart = `${stringifiedKey}:`;
102+
103+
if (stringifiedValue.startsWith(`\n`))
104+
valuePart = stringifiedValue;
105+
else valuePart = ` ${stringifiedValue}`;
106+
107+
108+
return `${recordIndentation}${keyPart}${valuePart}`;
99109
}).join(indentLevel === 0 ? `\n` : ``) || `\n`;
100110

101111
if (!newLineIfObject) {

packages/yarnpkg-parsers/tests/syml.test.js

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import {parseSyml} from '@yarnpkg/parsers';
1+
import {parseSyml, stringifySyml} from '@yarnpkg/parsers';
22

33
describe(`Syml parser`, () => {
44
it(`shouldn't confuse old-style values with new-style keys`, () => {
@@ -21,13 +21,25 @@ describe(`Syml parser`, () => {
2121

2222
it(`should merge duplicates`, () => {
2323
expect(
24-
parseSyml(`
24+
parseSyml(`
2525
"lodash@npm:^4.17.20":
2626
version: 4.17.20
27-
27+
2828
"lodash@npm:^4.17.20":
2929
version: 4.17.20
3030
`),
3131
).toEqual({'lodash@npm:^4.17.20': {version: `4.17.20`}});
3232
});
3333
});
34+
35+
describe(`Syml stringifyer`, () => {
36+
it(`stringifies an object`, () => {
37+
expect(stringifySyml({foo: {bar: `true`, baz: `quux`}})).toEqual(`foo:\n bar: true\n baz: quux\n`);
38+
});
39+
40+
it(`stringifies an object with a long key with yaml 1.2 spec`, () => {
41+
const longKey = `a`.repeat(1025); // long key is a string of length > 1024
42+
expect(stringifySyml({[longKey]: {bar: `true`, baz: `quux`}})).toEqual(`? ${longKey}\n:\n bar: true\n baz: quux\n`);
43+
expect(stringifySyml({[longKey]: {[longKey]: `quux`, baz: `quux`}})).toEqual(`? ${longKey}\n:\n ? ${longKey}\n: quux\n baz: quux\n`);
44+
});
45+
});

0 commit comments

Comments
 (0)