Skip to content

Commit

Permalink
Require !!omap keys to be unique
Browse files Browse the repository at this point in the history
  • Loading branch information
eemeli committed Dec 30, 2018
1 parent 410483b commit 9d1d5b3
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
11 changes: 11 additions & 0 deletions __tests__/types.js
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,17 @@ date (00:00:00Z): 2002-12-14\n`)
expect(String(doc)).toBe(src)
})

test('require unique keys', () => {
const src = `!!omap\n- a: 1\n- b: 2\n- b: 9\n`
const doc = YAML.parseDocument(src, { version: '1.1' })
expect(doc.errors).toMatchObject([
{
name: 'YAMLSemanticError',
message: 'Ordered maps must not include duplicate keys'
}
])
})

test('stringify', () => {
const map = new Map([['a', 1], ['b', 2], ['c', 3]])
const str = YAML.stringify(map, { version: '1.1' })
Expand Down
13 changes: 12 additions & 1 deletion src/schema/_omap.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export class YAMLOMap extends YAMLSeq {
key = toJSON(pair, '', opt)
}
if (map.has(key))
throw new Error('Ordered maps must not include duplicate values')
throw new Error('Ordered maps must not include duplicate keys')
map.set(key, value)
}
return map
Expand All @@ -26,6 +26,17 @@ export class YAMLOMap extends YAMLSeq {

function parseOMap(doc, cst) {
const pairs = parsePairs(doc, cst)
const seenKeys = []
for (const { key } of pairs.items) {
if (key instanceof Scalar) {
if (seenKeys.includes(key.value)) {
const msg = 'Ordered maps must not include duplicate keys'
throw new YAMLSemanticError(cst, msg)
} else {
seenKeys.push(key.value)
}
}
}
return Object.assign(new YAMLOMap(), pairs)
}

Expand Down

0 comments on commit 9d1d5b3

Please sign in to comment.