ProjectEnvironment.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. const path = require('path');
  2. const colors = require('colors');
  3. const fs = require('fs');
  4. const docker = require('docker-compose');
  5. class ProjectEnvironment {
  6. constructor(cwd, env) {
  7. this._cwd = cwd;
  8. this._env = env;
  9. this._dockerOptions = {
  10. config: [
  11. 'docker-compose.yml'
  12. ],
  13. cwd: cwd,
  14. log: true
  15. };
  16. this._setEnvironment(env);
  17. }
  18. _setEnvironment(env) {
  19. if (
  20. !this._loadConfigFile() ||
  21. !this._loadDockerComposeFile()
  22. ) {
  23. throw [`Unable to load %s environment`, colors.bold(env)];
  24. }
  25. }
  26. _loadConfigFile() {
  27. const configFilename = `config.${this._env}.json`;
  28. const configFilepath = path.join(this._cwd, configFilename);
  29. if (!fs.existsSync(configFilepath)) {
  30. return false;
  31. }
  32. try {
  33. const config = JSON.parse(fs.readFileSync(configFilepath, 'utf8'));
  34. this._config = config;
  35. } catch (ex) {
  36. return false;
  37. }
  38. return true;
  39. }
  40. _loadDockerComposeFile() {
  41. const dockerComposeFilename = `docker-compose.${this._env}.yml`;
  42. const dockerComposeFilepath = path.join(this._cwd, dockerComposeFilename);
  43. if (!fs.existsSync(dockerComposeFilepath)) {
  44. return false;
  45. }
  46. this._dockerOptions.config.push(dockerComposeFilename);
  47. let envFilename = `.env.${this._env}`;
  48. let envFilepath = path.join(this._cwd, envFilename);
  49. if (!fs.existsSync(envFilepath)) {
  50. envFilename = `.env`;
  51. envFilepath = path.join(this._cwd, envFilename);
  52. if (!fs.existsSync(envFilepath)) {
  53. envFilename = false;
  54. }
  55. }
  56. if (envFilename) {
  57. this._dockerOptions.composeOptions = [["--env-file", envFilename]];
  58. }
  59. return true;
  60. }
  61. setDockerOptions(options) {
  62. this._dockerOptions = { ...this._dockerOptions, ...options };
  63. }
  64. getDockerOptions() {
  65. return this._dockerOptions;
  66. }
  67. getCwd() {
  68. return this._cwd;
  69. }
  70. getEnv() {
  71. return this._env;
  72. }
  73. getHosts() {
  74. return this._config['hosts'] || {};
  75. }
  76. async getServices() {
  77. const data = await docker.configServices({ ...this.getDockerOptions(), ...{ log: false } });
  78. const services = data.out.split('\n');
  79. services.pop();
  80. return services;
  81. }
  82. }
  83. module.exports = ProjectEnvironment;