ProjectEnvironment.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. cwd: cwd,
  11. config: [
  12. 'docker-compose.yml'
  13. ],
  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. console.log(configFilepath);
  30. if (!fs.existsSync(configFilepath)) {
  31. return false;
  32. }
  33. try {
  34. const config = JSON.parse(fs.readFileSync(configFilepath, 'utf8'));
  35. this._config = config;
  36. } catch (ex) {
  37. return false;
  38. }
  39. return true;
  40. }
  41. _loadDockerComposeFile() {
  42. const dockerComposeFilename = `docker-compose.${this._env}.yml`;
  43. const dockerComposeFilepath = path.join(this._cwd, dockerComposeFilename);
  44. if (!fs.existsSync(dockerComposeFilepath)) {
  45. return false;
  46. }
  47. this._dockerOptions.config.push(dockerComposeFilename);
  48. return true;
  49. }
  50. setDockerOptions(options) {
  51. this._dockerOptions = { ...this._dockerOptions, ...options };
  52. }
  53. getDockerOptions() {
  54. return this._dockerOptions;
  55. }
  56. getCwd() {
  57. return this._cwd;
  58. }
  59. getEnv() {
  60. return this._env;
  61. }
  62. getHosts() {
  63. return this._config['hosts'] || {};
  64. }
  65. async getServices() {
  66. const data = await docker.configServices({ ...this.getDockerOptions(), ...{ log: false } });
  67. const services = data.out.split('\n');
  68. services.pop();
  69. return services;
  70. }
  71. }
  72. module.exports = ProjectEnvironment;