const path = require('path'); const colors = require('colors'); const fs = require('fs'); const docker = require('docker-compose/dist/v2'); class ProjectEnvironment { constructor(cwd, env) { this._cwd = cwd; this._env = env; this._dockerOptions = { config: [ 'docker-compose.yml' ], cwd: cwd, log: true }; this._setEnvironment(env); } _setEnvironment(env) { if (!this._loadDockerComposeFile()) { throw [`Unable to load %s environment`, colors.bold(env)]; } } _loadDockerComposeFile() { const dockerComposeFilename = `docker-compose.${this._env}.yml`; const dockerComposeFilepath = path.join(this._cwd, dockerComposeFilename); if (fs.existsSync(dockerComposeFilepath)) { this._dockerOptions.config.push(dockerComposeFilename); let envFilename = `.env.${this._env}`; let envFilepath = path.join(this._cwd, envFilename); if (!fs.existsSync(envFilepath)) { envFilename = `.env`; envFilepath = path.join(this._cwd, envFilename); if (!fs.existsSync(envFilepath)) { envFilename = false; } } if (envFilename) { this._dockerOptions.composeOptions = [ ["--env-file", envFilename] ]; } } return true; } setDockerOptions(options) { this._dockerOptions = { ...this._dockerOptions, ...options }; } getDockerOptions() { return this._dockerOptions; } getCwd() { return this._cwd; } getEnv() { return this._env; } async getServices() { const data = await docker.configServices({ ...this.getDockerOptions(), ...{ log: false } }); const services = data.out.split('\n'); services.pop(); return services; } } module.exports = ProjectEnvironment;