config.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. const CONFIG_DIR = `${process.env.HOME}/.wormhole`;
  2. const CONFIG_FILE = `${CONFIG_DIR}/default.json`;
  3. process.env["NODE_CONFIG_DIR"] = CONFIG_DIR;
  4. process.env["SUPPRESS_NO_CONFIG_WARNING"] = "y";
  5. import c from 'config';
  6. import fs from 'fs';
  7. export interface Config {
  8. // Path to the wormhole repository
  9. wormholeDir: string;
  10. }
  11. const defaultConfig: Required<Config> = {
  12. wormholeDir: computeRepoRootPath(),
  13. }
  14. /**
  15. * Global config object.
  16. * Importing this module will read the config file and update it if necessary.
  17. */
  18. export const config: Readonly<Config> = readAndUpdateConfig();
  19. // Computes the path to the root of the wormhole repository based on the
  20. // location of this file (well, the compiled version of this file).
  21. function computeRepoRootPath(): string {
  22. let rel = "/clients/js/build/config.js";
  23. // check if mainPath matches $DIR/clients/js/build/config.js
  24. if (__filename.endsWith(rel)) {
  25. // if so, grab $DIR from mainPath
  26. return __filename.substring(0, __filename.length - rel.length);
  27. } else {
  28. // otherwise, throw an error
  29. throw new Error(`Could not compute repo root path for ${__filename}`);
  30. }
  31. }
  32. function readAndUpdateConfig(): Readonly<Config> {
  33. if (config !== undefined) {
  34. return config;
  35. }
  36. let conf = defaultConfig;
  37. // iterate through all the keys in defaultConfig
  38. for (const key in conf) {
  39. // if the key is not in config, set it to the default value
  40. if (c.has(key)) {
  41. conf[key] = c.get(key);
  42. }
  43. }
  44. let json_conf = JSON.stringify(conf, null, 2) + "\n";
  45. // if the config file does not exist or does not have some of the default
  46. // values, create/update it
  47. let write = false;
  48. if (!fs.existsSync(CONFIG_FILE)) {
  49. console.error('\x1b[33m%s\x1b[0m', `NOTE: Created config file at ${CONFIG_FILE}`);
  50. write = true;
  51. } else if (json_conf !== fs.readFileSync(CONFIG_FILE, "utf8")) {
  52. // ^ this will also normalise the config file, but the main thing is
  53. // that it writes out defaults if they are missing
  54. console.error('\x1b[33m%s\x1b[0m', `NOTE: Updated config file at ${CONFIG_FILE}`);
  55. write = true;
  56. }
  57. if (write) {
  58. if (!fs.existsSync(CONFIG_DIR)){
  59. fs.mkdirSync(CONFIG_DIR, { recursive: true });
  60. }
  61. fs.writeFileSync(CONFIG_FILE, json_conf);
  62. }
  63. return conf;
  64. }