ProjectEnvironment.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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 (!this._loadDockerComposeFile()) {
  20. throw [`Unable to load %s environment`, colors.bold(env)];
  21. }
  22. }
  23. _loadDockerComposeFile() {
  24. const dockerComposeFilename = `docker-compose.${this._env}.yml`;
  25. const dockerComposeFilepath = path.join(this._cwd, dockerComposeFilename);
  26. if (!fs.existsSync(dockerComposeFilepath)) {
  27. return false;
  28. }
  29. this._dockerOptions.config.push(dockerComposeFilename);
  30. let envFilename = `.env.${this._env}`;
  31. let envFilepath = path.join(this._cwd, envFilename);
  32. if (!fs.existsSync(envFilepath)) {
  33. envFilename = `.env`;
  34. envFilepath = path.join(this._cwd, envFilename);
  35. if (!fs.existsSync(envFilepath)) {
  36. envFilename = false;
  37. }
  38. }
  39. if (envFilename) {
  40. this._dockerOptions.composeOptions = [["--env-file", envFilename]];
  41. }
  42. return true;
  43. }
  44. setDockerOptions(options) {
  45. this._dockerOptions = { ...this._dockerOptions, ...options };
  46. }
  47. getDockerOptions() {
  48. return this._dockerOptions;
  49. }
  50. getCwd() {
  51. return this._cwd;
  52. }
  53. getEnv() {
  54. return this._env;
  55. }
  56. async getServices() {
  57. const data = await docker.configServices({ ...this.getDockerOptions(), ...{ log: false } });
  58. const services = data.out.split('\n');
  59. services.pop();
  60. return services;
  61. }
  62. }
  63. module.exports = ProjectEnvironment;