Skip to content

Commit

Permalink
fix: 增加yaml.read yaml.save
Browse files Browse the repository at this point in the history
  • Loading branch information
sj817 committed Oct 6, 2024
1 parent a16bb28 commit 46021f6
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 2 deletions.
3 changes: 1 addition & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import yaml from 'yaml'
import axios from 'axios'
import moment from 'moment'
import lodash from 'lodash'
Expand All @@ -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 }
1 change: 1 addition & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,4 @@ export * from './core/logger'
export * from './config/updateVersion'
export * from './tools/restart'
export * from './tools/stop'
export * from './tools/yaml'
48 changes: 48 additions & 0 deletions src/utils/tools/yaml.ts
Original file line number Diff line number Diff line change
@@ -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<string, string | { type: 'start' | 'end'; text: string }>

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)

0 comments on commit 46021f6

Please sign in to comment.