ProjectEnvironment.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. const path = require('path');
  2. const colors = require('colors');
  3. const fs = require('fs');
  4. const docker = require('docker-compose/dist/v2');
  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. this._dockerOptions.config.push(dockerComposeFilename);
  28. let envFilename = `.env.${this._env}`;
  29. let envFilepath = path.join(this._cwd, envFilename);
  30. if (!fs.existsSync(envFilepath)) {
  31. envFilename = `.env`;
  32. envFilepath = path.join(this._cwd, envFilename);
  33. if (!fs.existsSync(envFilepath)) {
  34. envFilename = false;
  35. }
  36. }
  37. if (envFilename) {
  38. this._dockerOptions.composeOptions = [
  39. ["--env-file", envFilename]
  40. ];
  41. }
  42. }
  43. return true;
  44. }
  45. setDockerOptions(options) {
  46. this._dockerOptions = {
  47. ...this._dockerOptions,
  48. ...options
  49. };
  50. }
  51. getDockerOptions() {
  52. return this._dockerOptions;
  53. }
  54. getCwd() {
  55. return this._cwd;
  56. }
  57. getEnv() {
  58. return this._env;
  59. }
  60. async getServices() {
  61. const data = await docker.configServices({ ...this.getDockerOptions(), ...{ log: false } });
  62. const services = data.out.split('\n');
  63. services.pop();
  64. return services;
  65. }
  66. }
  67. module.exports = ProjectEnvironment;