const path = require('path'); const colors = require('colors'); const fs = require('fs'); const docker = require('docker-compose'); 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._loadConfigFile() || !this._loadDockerComposeFile() ) { throw [`Unable to load %s environment`, colors.bold(env)]; } } _loadConfigFile() { const configFilename = `config.${this._env}.json`; const configFilepath = path.join(this._cwd, configFilename); if (!fs.existsSync(configFilepath)) { return false; } try { const config = JSON.parse(fs.readFileSync(configFilepath, 'utf8')); this._config = config; } catch (ex) { return false; } return true; } _loadDockerComposeFile() { const dockerComposeFilename = `docker-compose.${this._env}.yml`; const dockerComposeFilepath = path.join(this._cwd, dockerComposeFilename); if (!fs.existsSync(dockerComposeFilepath)) { return false; } 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; } getHosts() { return this._config['hosts'] || {}; } async getServices() { const data = await docker.configServices({ ...this.getDockerOptions(), ...{ log: false } }); const services = data.out.split('\n'); services.pop(); return services; } } module.exports = ProjectEnvironment;