1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- 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;
|