setupEnv.mjs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /**
  2. * Post install script: create or replace the symlink .env
  3. * to the .env file matching the current environment
  4. *
  5. * To force an hostname, define an env variable named HOST :
  6. *
  7. * HOST=ci node ./env/setupEnv.mjs
  8. *
  9. */
  10. import os from "os";
  11. import fs from "fs";
  12. import {fileURLToPath} from "node:url";
  13. import path from 'path';
  14. const projectDir = path.join(path.dirname(fileURLToPath(import.meta.url)), '..')
  15. const hostname = process.env.HOST ?? os.hostname()
  16. const environments = {
  17. 'app': '.env.docker',
  18. 'prod-v2': '.env.prod',
  19. 'test-v2': '.env.test',
  20. 'test1': '.env.test1',
  21. 'test2': '.env.test2',
  22. 'test3': '.env.test3',
  23. 'test4': '.env.test4',
  24. 'test5': '.env.test5',
  25. 'ci': '.env.ci',
  26. }
  27. if (!environments.hasOwnProperty(hostname)) {
  28. throw Error("Critical : unknown environment [" + hostname + "]")
  29. }
  30. const targetEnvFile = path.join(projectDir, 'env', environments[hostname])
  31. const mainEnvFile = path.join(projectDir, '.env')
  32. fs.unlink(mainEnvFile, (err) => {
  33. // 'ENOENT' is the error code for "no such file or directory", we ignore this one
  34. if (err && err.code !== 'ENOENT') {
  35. throw err
  36. }
  37. console.log(`${mainEnvFile} was deleted`);
  38. });
  39. fs.symlink(
  40. targetEnvFile,
  41. '.env',
  42. 'file',
  43. (err) => {
  44. if (err) {
  45. throw (err);
  46. }
  47. console.log(`Symlink created : ${mainEnvFile} -> ${targetEnvFile}`)
  48. }
  49. )