mirror of
https://github.com/Koenkk/zigbee2mqtt.git
synced 2026-07-02 18:11:36 +00:00
b67888f938
* Always return an object when loading a YAML file, even when it is empty or containing the `null` value. Fixes #20283 * Add unit test for having multiple device files, with one is empty. This test breaks without the proposed.
38 lines
1008 B
TypeScript
38 lines
1008 B
TypeScript
import yaml from 'js-yaml';
|
|
import fs from 'fs';
|
|
import equals from 'fast-deep-equal/es6';
|
|
|
|
function read(file: string): KeyValue {
|
|
try {
|
|
const result = yaml.load(fs.readFileSync(file, 'utf8'));
|
|
return result as KeyValue ?? {};
|
|
} catch (error) {
|
|
if (error.name === 'YAMLException') {
|
|
error.file = file;
|
|
}
|
|
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
function readIfExists(file: string, default_?: KeyValue): KeyValue {
|
|
return fs.existsSync(file) ? read(file) : default_;
|
|
}
|
|
|
|
function writeIfChanged(file: string, content: KeyValue): void {
|
|
const before = readIfExists(file);
|
|
if (!equals(before, content)) {
|
|
fs.writeFileSync(file, yaml.dump(content));
|
|
}
|
|
}
|
|
|
|
function updateIfChanged(file: string, key: string, value: KeyValue): void {
|
|
const content = read(file);
|
|
if (content[key] !== value) {
|
|
content[key] = value;
|
|
writeIfChanged(file, content);
|
|
}
|
|
}
|
|
|
|
export default {read, readIfExists, updateIfChanged, writeIfChanged};
|