From 46021f6c17579483f955bfd974e64f187228f08f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=97=B6=E7=91=BE?= Date: Sun, 6 Oct 2024 11:57:21 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E5=A2=9E=E5=8A=A0`yaml.read`=20`yaml.sa?= =?UTF-8?q?ve`?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/index.ts | 3 +-- src/utils/index.ts | 1 + src/utils/tools/yaml.ts | 48 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 50 insertions(+), 2 deletions(-) create mode 100644 src/utils/tools/yaml.ts diff --git a/src/index.ts b/src/index.ts index 085b628..0025d44 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,4 +1,3 @@ -import yaml from 'yaml' import axios from 'axios' import moment from 'moment' import lodash from 'lodash' @@ -13,4 +12,4 @@ export * from 'karin/types' export * from 'karin/adapter' export { karin as default } from 'karin/core' -export { axios, moment, lodash, express, yaml } +export { axios, moment, lodash, express } diff --git a/src/utils/index.ts b/src/utils/index.ts index f2c5c52..8ef18c4 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -11,3 +11,4 @@ export * from './core/logger' export * from './config/updateVersion' export * from './tools/restart' export * from './tools/stop' +export * from './tools/yaml' diff --git a/src/utils/tools/yaml.ts b/src/utils/tools/yaml.ts new file mode 100644 index 0000000..728ab7c --- /dev/null +++ b/src/utils/tools/yaml.ts @@ -0,0 +1,48 @@ +import fs from 'fs' +import Yaml from 'yaml' +import logger from '../core/logger' +import { YamlEditor } from '../config/yamlEditor' + +type Comment = Record + +const yamlNew = { + /** + * 传入yaml文件路径 自动读取并解析 + * @param path yaml文件路径 + */ + read: (path: string) => { + const data = fs.readFileSync(path, 'utf-8') + return Yaml.parse(data) + }, + /** + * 保存并写入注释 + * @param path 保存的路径 + * @param value 保存的数据 + * @param commentConfig 注释配置文件路径或json + */ + save: (path: string, value: any, commentConfig?: string) => { + if (!commentConfig) { + fs.writeFileSync(path, Yaml.stringify(value)) + return + } + + const editor = new YamlEditor(Yaml.stringify(value)) + const comment = JSON.parse(fs.existsSync(commentConfig) ? fs.readFileSync(commentConfig, 'utf8') : commentConfig) as Comment + + for (const [key, value] of Object.entries(comment)) { + try { + if (typeof value === 'object') { + editor.comment(key, value.text, value.type === 'start') + } else if (typeof value === 'string') { + editor.comment(key, value, true) + } + } catch (error: any) { + logger.error(`[YamlEditor] 添加注释时出错,已跳过:${error.stack || error.message || error}`) + } + } + + fs.writeFileSync(path, editor.document.toString()) + }, +} + +export const yaml = Object.assign(Yaml, yamlNew)