From c43858d8735d11595161f24c67891333e851e0dc Mon Sep 17 00:00:00 2001 From: vrabe Date: Sun, 21 Jun 2020 21:37:25 +0800 Subject: [PATCH] fix: only ISO date strings are parsed to Date objects (#3923) --- .../src/formats/__tests__/yaml.spec.js | 27 +++++++++++++++++++ packages/netlify-cms-core/src/formats/yaml.js | 18 ++++++++++++- 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/packages/netlify-cms-core/src/formats/__tests__/yaml.spec.js b/packages/netlify-cms-core/src/formats/__tests__/yaml.spec.js index 95c0c5c4..123bcbdf 100644 --- a/packages/netlify-cms-core/src/formats/__tests__/yaml.spec.js +++ b/packages/netlify-cms-core/src/formats/__tests__/yaml.spec.js @@ -8,11 +8,13 @@ describe('yaml', () => { const result = yaml.fromFile(stripIndent` date: 2020-04-02T16:08:03.327Z + dateString: 2020-04-02 boolean: true number: 1 `); expect(result).toEqual({ date: new Date('2020-04-02T16:08:03.327Z'), + dateString: '2020-04-02', boolean: true, number: 1, }); @@ -57,6 +59,31 @@ describe('yaml', () => { test('does not fail on closing separator', () => { expect(yaml.fromFile('---\n[]\n---')).toEqual([]); }); + + test('parses single quoted string as string', () => { + expect(yaml.fromFile('name: y')).toEqual({ name: 'y' }); + }); + + test('parses ISO date string as date', () => { + expect(yaml.fromFile('date: 2020-04-02T16:08:03.327Z')).toEqual({ + date: new Date('2020-04-02T16:08:03.327Z'), + }); + }); + + test('parses partial date string as string', () => { + expect(yaml.fromFile('date: 2020-06-12')).toEqual({ + date: '2020-06-12', + }); + expect(yaml.fromFile('date: 12-06-2012')).toEqual({ + date: '12-06-2012', + }); + }); + + test('parses partial time value as string', () => { + expect(yaml.fromFile('time: 10:05')).toEqual({ + time: '10:05', + }); + }); }); describe('toFile', () => { test('outputs valid yaml', () => { diff --git a/packages/netlify-cms-core/src/formats/yaml.js b/packages/netlify-cms-core/src/formats/yaml.js index 17394e24..d4ed37d3 100644 --- a/packages/netlify-cms-core/src/formats/yaml.js +++ b/packages/netlify-cms-core/src/formats/yaml.js @@ -17,12 +17,28 @@ const addComments = (items, comments, prefix = '') => { }); }; +const timestampTag = { + identify: value => value instanceof Date, + default: true, + tag: '!timestamp', + test: RegExp( + '^' + + '([0-9]{4})-([0-9]{2})-([0-9]{2})' + // YYYY-MM-DD + 'T' + // T + '([0-9]{2}):([0-9]{2}):([0-9]{2}(\\.[0-9]+)?)' + // HH:MM:SS(.ss)? + 'Z' + // Z + '$', + ), + resolve: str => new Date(str), + stringify: value => value.toISOString(), +}; + export default { fromFile(content) { if (content && content.trim().endsWith('---')) { content = content.trim().slice(0, -3); } - return yaml.parse(content, { version: '1.1' }); + return yaml.parse(content, { customTags: [timestampTag] }); }, toFile(data, sortedKeys = [], comments = {}) {