From a583097bbce25e2938e76f89b42e5fdabc9d6c60 Mon Sep 17 00:00:00 2001 From: Alex Kocharin Date: Mon, 28 Dec 2020 19:05:08 +0300 Subject: [PATCH] Shorthand tags with !! whenever possible fix https://github.com/nodeca/js-yaml/issues/258 --- CHANGELOG.md | 1 + lib/dumper.js | 2 ++ test/issues/0258.js | 26 ++++++++++++++++++++++++++ 3 files changed, 29 insertions(+) create mode 100644 test/issues/0258.js diff --git a/CHANGELOG.md b/CHANGELOG.md index edaa3f9d..f9c7c8e0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `undefined` in mappings, #571. - `dump()` with `skipInvalid=true` now serializes invalid items in collections as null. - Custom tags starting with `!` are now dumped as `!tag` instead of `!`, #576. +- Custom tags starting with `tag:yaml.org,2002:` are now shorthanded using `!!`, #258. ### Added - Added `.mjs` (es modules) support. diff --git a/lib/dumper.js b/lib/dumper.js index 25a92433..f357a6ae 100644 --- a/lib/dumper.js +++ b/lib/dumper.js @@ -888,6 +888,8 @@ function writeNode(state, level, object, block, compact, iskey, isblockseq) { if (state.tag[0] === '!') { tagStr = '!' + tagStr; + } else if (tagStr.slice(0, 18) === 'tag:yaml.org,2002:') { + tagStr = '!!' + tagStr.slice(18); } else { tagStr = '!<' + tagStr + '>'; } diff --git a/test/issues/0258.js b/test/issues/0258.js new file mode 100644 index 00000000..ef89d880 --- /dev/null +++ b/test/issues/0258.js @@ -0,0 +1,26 @@ +'use strict'; + + +const assert = require('assert'); +const yaml = require('../../'); + + +it('should shorthand tags with !! whenever possible', function () { + let regexp = new yaml.Type('tag:yaml.org,2002:js/regexp', { + kind: 'scalar', + resolve: () => true, + construct: str => new RegExp(str), + instanceOf: RegExp, + represent: object => object.source + }); + + let schema = yaml.DEFAULT_SCHEMA.extend(regexp); + + let source = 're: !!js/regexp .*\n'; + + let object = yaml.load(source, { schema }); + assert(object.re instanceof RegExp); + + let str = yaml.dump(object, { schema }); + assert.strictEqual(str, source); +});