2020-04-07 15:00:06 +03:00
|
|
|
import yaml from 'yaml';
|
2017-10-26 12:43:28 -06:00
|
|
|
import { sortKeys } from './helpers';
|
2021-04-18 15:02:24 +03:00
|
|
|
import { YAMLMap, YAMLSeq, Pair, Node } from 'yaml/types';
|
2016-02-25 20:40:35 -08:00
|
|
|
|
2021-04-18 15:02:24 +03:00
|
|
|
function addComments(items: Array<Pair>, comments: Record<string, string>, prefix = '') {
|
2020-04-07 15:00:06 +03:00
|
|
|
items.forEach(item => {
|
|
|
|
if (item.key !== undefined) {
|
|
|
|
const itemKey = item.key.toString();
|
|
|
|
const key = prefix ? `${prefix}.${itemKey}` : itemKey;
|
|
|
|
if (comments[key]) {
|
|
|
|
const value = comments[key].split('\\n').join('\n ');
|
|
|
|
item.commentBefore = ` ${value}`;
|
|
|
|
}
|
|
|
|
if (Array.isArray(item.value?.items)) {
|
|
|
|
addComments(item.value.items, comments, key);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
2021-02-08 20:01:21 +02:00
|
|
|
}
|
2016-06-06 21:53:22 -03:00
|
|
|
|
2020-06-21 21:37:25 +08:00
|
|
|
const timestampTag = {
|
2021-04-18 15:02:24 +03:00
|
|
|
identify: (value: unknown) => value instanceof Date,
|
2020-06-21 21:37:25 +08:00
|
|
|
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
|
|
|
|
'$',
|
|
|
|
),
|
2021-04-18 15:02:24 +03:00
|
|
|
resolve: (str: string) => new Date(str),
|
|
|
|
stringify: (value: Node) => (value as Date).toISOString(),
|
|
|
|
} as const;
|
2020-06-21 21:37:25 +08:00
|
|
|
|
2017-10-30 13:48:19 -06:00
|
|
|
export default {
|
2021-04-18 15:02:24 +03:00
|
|
|
fromFile(content: string) {
|
2020-02-05 03:14:40 -05:00
|
|
|
if (content && content.trim().endsWith('---')) {
|
|
|
|
content = content.trim().slice(0, -3);
|
|
|
|
}
|
2020-06-21 21:37:25 +08:00
|
|
|
return yaml.parse(content, { customTags: [timestampTag] });
|
2017-10-30 13:48:19 -06:00
|
|
|
},
|
2016-02-25 20:40:35 -08:00
|
|
|
|
2021-04-18 15:02:24 +03:00
|
|
|
toFile(data: object, sortedKeys: string[] = [], comments: Record<string, string> = {}) {
|
|
|
|
const contents = yaml.createNode(data) as YAMLMap | YAMLSeq;
|
2020-04-07 15:00:06 +03:00
|
|
|
|
|
|
|
addComments(contents.items, comments);
|
|
|
|
|
|
|
|
contents.items.sort(sortKeys(sortedKeys, item => item.key?.toString()));
|
2020-04-09 14:17:12 +03:00
|
|
|
const doc = new yaml.Document();
|
2020-04-07 15:00:06 +03:00
|
|
|
doc.contents = contents;
|
|
|
|
|
|
|
|
return doc.toString();
|
2018-08-07 14:46:54 -06:00
|
|
|
},
|
|
|
|
};
|