1
0
mirror of https://github.com/0O0o0oOoO00/Alas.git synced 2026-05-18 17:39:28 +08:00
Files
Alas/webapp/packages/common/utils/modifyYaml.ts

26 lines
705 B
TypeScript
Raw Normal View History

2023-04-19 19:02:01 +08:00
import type {Pair} from 'yaml';
import {parseDocument, visit} from 'yaml';
2023-04-24 18:57:24 +08:00
const fs = require('fs');
2023-04-19 19:02:01 +08:00
/**
* Modify yaml file https://eemeli.org/yaml/#modifying-nodes
* @param filePath
2023-04-24 18:57:24 +08:00
* @param keyObj
2023-04-19 19:02:01 +08:00
*/
2023-04-24 18:57:24 +08:00
export function modifyYaml(filePath: string, keyObj: {[k in string]: any}) {
2023-04-19 19:02:01 +08:00
try {
const doc = parseDocument(fs.readFileSync(filePath, 'utf8'));
2023-04-24 18:57:24 +08:00
const keysMap = new Map(Object.entries(keyObj));
2023-04-19 19:02:01 +08:00
visit(doc, {
Pair: (_node, pair: Pair<any, any>) => {
2023-04-24 18:57:24 +08:00
if (keysMap.has(pair?.key?.value)) {
pair.value.value = keysMap.get(pair.key.value);
2023-04-19 19:02:01 +08:00
}
},
});
fs.writeFileSync(filePath, doc.toString(), 'utf8');
} catch (e) {
console.error(e);
}
}