All files / src/rc index.js

100% Statements 47/47
100% Branches 16/16
100% Functions 17/17
100% Lines 46/46

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180          15x             15x           15x       10x 10x 2x           10x 10x                   32x 21x   11x                 16x 14x   2x 2x               27x 27x   83x   6x 6x   27x             11x 11x 33x 1x     11x                 6x 6x 6x             10x 10x 10x 10x           10x 10x                 1x                 1x                     4x 4x 4x 4x                   1x 1x 1x                 1x             3x          
import path from 'path';
import fs from 'fs';
import { mkdirpSync } from 'mkdirp';
import { userHomeDir } from '../utils/userHomeDir.js';
 
const REGISTRY_DEFAULT_OPTIONS = {
  endpoint: '',
  datadir: path.resolve(userHomeDir, 'aelf'),
  password: '', // this is not suggested stored in config file
  account: '' // the public address of aelf wallet, encoded with base58
};
 
const ENV_RC_KEYS = {
  endpoint: 'AELF_CLI_ENDPOINT',
  datadir: 'AELF_CLI_DATADIR',
  account: 'AELF_CLI_ACCOUNT'
};
 
const rcHeader = '# THIS IS AN AUTOGENERATED FILE FOR AELF-COMMAND OPTIONS. DO NOT EDIT THIS FILE DIRECTLY.\n\n\n';
 
class Registry {
  constructor() {
    this.globalConfigLoc = path.resolve(userHomeDir, 'aelf/.aelfrc');
    if (!fs.existsSync(path.resolve(userHomeDir, 'aelf'))) {
      mkdirpSync(path.resolve(userHomeDir, 'aelf'));
    }
    /**
     * AELF configuration object.
     * @type {Object.<string, any>}
     */
    this.aelfConfig = {};
    this.init();
  }
 
  /**
   * Retrieves file content or default content if file doesn't exist.
   * @param {string} file - The file path.
   * @param {string} [defaultContent] - Optional default content if file doesn't exist.
   * @returns {*} The content of the file or default content.
   */
  static getFileOrNot(file, defaultContent = '') {
    if (fs.existsSync(file)) {
      return fs.readFileSync(file).toString();
    }
    return defaultContent;
  }
 
  /**
   * Retrieves file content or creates the file if it doesn't exist.
   * @param {string} file - The file path.
   * @returns {string} The file content or an empty string if the file is created.
   */
  static getFileOrCreate(file) {
    if (fs.existsSync(file)) {
      return fs.readFileSync(file).toString();
    }
    fs.writeFileSync(file, rcHeader);
    return '';
  }
  /**
   * Loads configuration from provided content.
   * @param {string} [content] - Optional content to load configuration from.
   * @returns {Object.<string, any>} The loaded configuration object.
   */
  static loadConfig(content = '') {
    const result = {};
    content
      .split('\n')
      .filter(v => !v.startsWith('#') && v.length > 0)
      .forEach(v => {
        const [key, value] = v.split(' ');
        result[key] = value;
      });
    return result;
  }
  /**
   * Retrieves configuration from environment variables.
   * @returns {Object.<string, any>} The configuration object retrieved from environment variables.
   */
  static getConfigFromEnv() {
    const result = {};
    Object.entries(ENV_RC_KEYS).forEach(([key, value]) => {
      if (process.env[value]) {
        result[key] = process.env[value];
      }
    });
    return result;
  }
 
  /**
   * Converts a one-level object into an array of content.
   * @param {Object.<string, any>} [obj] - The object to stringify.
   * @returns {string[]} Array of content from the object's fields.
   */
  static stringify(obj = {}) {
    let result = Object.entries(obj).map(([key, value]) => `${key} ${value}`);
    result = rcHeader.split('\n').concat(result);
    return result;
  }
  /**
   * Initializes and retrieves initial configuration options.
   * @returns {{ endpoint: string, datadir: string, password: string, account: string }} Initial configuration values.
   */
  init() {
    const pwdRc = Registry.loadConfig(Registry.getFileOrNot(path.resolve(process.cwd(), '.aelfrc')));
    const globalRc = Registry.loadConfig(Registry.getFileOrCreate(this.globalConfigLoc));
    const envRc = Registry.getConfigFromEnv();
    const rc = {
      ...REGISTRY_DEFAULT_OPTIONS,
      ...envRc,
      ...globalRc,
      ...pwdRc
    };
    this.aelfConfig = rc;
    return rc;
  }
 
  /**
   * Retrieves a configuration option by key.
   * @param {string} key - The option key.
   * @returns {*} The value of the option.
   */
  getOption(key) {
    return this.aelfConfig[key];
  }
 
  /**
   * Sets a configuration option.
   * @param {string} key - The option key.
   * @param {*} value - The value to set.
   */
  setOption(key, value) {
    this.aelfConfig[key] = value;
  }
 
  /**
   * Saves an option to configuration file.
   * @param {string} key - The option key.
   * @param {*} value - The value to save.
   * @param {*} [filePath] - Optional file path to save configuration.
   * @returns {*} Result of saving operation.
   */
  saveOption(key, value, filePath = this.globalConfigLoc) {
    this.aelfConfig[key] = value;
    const rc = Registry.loadConfig(Registry.getFileOrCreate(filePath));
    rc[key] = value;
    return fs.writeFileSync(filePath, `${Registry.stringify(rc).join('\n')}\n`);
  }
 
  /**
   * Deletes a configuration key from file.
   * @param {string} key - The option key to delete.
   * @param {*} [filePath] - Optional file path to delete from.
   * @returns {*} Result of deletion operation.
   */
  deleteConfig(key, filePath = this.globalConfigLoc) {
    const rc = Registry.loadConfig(Registry.getFileOrCreate(filePath));
    delete rc[key];
    return fs.writeFileSync(filePath, `${Registry.stringify(rc).join('\n')}\n`);
  }
 
  /**
   * Retrieves configurations from file.
   * @param {string} [filePath] - Optional file path to retrieve configurations.
   * @returns {Object.<string, any>} The configurations retrieved from file.
   */
  getFileConfigs(filePath = this.globalConfigLoc) {
    return Registry.loadConfig(Registry.getFileOrCreate(filePath));
  }
  /**
   * Retrieves all configurations.
   * @returns {Object.<string, any>} All configurations.
   */
  getConfigs() {
    return this.aelfConfig;
  }
}
 
export default Registry;