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