UNPKG

@cliz/gpm

Version:
99 lines (98 loc) 2.87 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ConfigManager = void 0; const cli_1 = require("@cliz/cli"); const config = require("@znode/config"); class ConfigManager { constructor(path) { this.path = path; this.isReady = false; } async load() { if (await cli_1.api.fs.exist(this.path)) { this._config = await config.load({ path: this.path }); } else { this._config = {}; } this.isReady = true; } async nomorlize() { // @TODO fix key with id let isChanged = false; for (const id in this._config) { const project = this._config[id]; if (!project || !project.id) { isChanged = true; delete this._config[id]; } else if (id !== project.id) { isChanged = true; delete this._config[id]; this._config[project.id] = project; } } if (isChanged) { await this.persist(); } } async persist() { try { // sort config const config = Object.keys(this._config) .filter(e => !!e) .sort((a, b) => a.localeCompare(b)) .reduce((all, id) => { all[id] = this._config[id]; return all; }, {}); await cli_1.api.fs.yml.write(this.path, config); } catch (error) { console.error('config persist error:', error); } } ensure() { if (!this.isReady) { throw new Error(`config is not ready`); } } async prepare() { await this.load(); } get(key) { this.ensure(); return cli_1.doreamon.object.get(this._config, key); } set(key, value, persist) { this.ensure(); if (!value) { delete this._config[key]; } else { // if (key.indexOf('.') !== -1) { // // doreamon.object.set(this._config as any, key as any, value); // const paths = key.split('.'); // let object = {}; // for (let i = 0; i < paths.length - 1; i++) { // const path = paths[i]; // if (!this._config[path]) { // this._config[path] = {} as any; // } // object = this._config[path]; // } // object[paths[paths.length - 1]] = value; // } else { // this._config[key] = value; // } this._config[key] = value; } if (!!persist) { this.persist(); } } getAll() { return this._config; } } exports.ConfigManager = ConfigManager;