ProjectEnvironment.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. 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 = [
  41. ["--env-file", envFilename]
  42. ];
  43. }
  44. return true;
  45. }
  46. setDockerOptions(options) {
  47. this._dockerOptions = {
  48. ...this._dockerOptions,
  49. ...options
  50. };
  51. }
  52. getDockerOptions() {
  53. return this._dockerOptions;
  54. }
  55. getCwd() {
  56. return this._cwd;
  57. }
  58. getEnv() {
  59. return this._env;
  60. }
  61. async getServices() {
  62. const data = await docker.configServices({ ...this.getDockerOptions(), ...{ log: false } });
  63. const services = data.out.split('\n');
  64. services.pop();
  65. return services;
  66. }
  67. }
  68. module.exports = ProjectEnvironment;