setupEnv.mjs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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(targetEnvFile, '.env', 'file', (err) => {
  40. if (err) {
  41. throw err
  42. }
  43. console.log(`Symlink created : ${mainEnvFile} -> ${targetEnvFile}`)
  44. })