Skip to content

Commit

Permalink
Merge bef8b4c into b4789dd
Browse files Browse the repository at this point in the history
  • Loading branch information
gastonpereyra committed Jun 27, 2019
2 parents b4789dd + bef8b4c commit 7a13b26
Show file tree
Hide file tree
Showing 13 changed files with 4,177 additions and 11 deletions.
122 changes: 122 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
'use strict';

module.exports = {
extends: 'airbnb-base',

env: {
node: true,
es6: true,
mocha: true
},

globals: {
__rootpath: true,
coreRequire: true,
mainRequire: true,
JANIS_CORE: true,
JANIS_ENV: true,
JANIS_ENV_ALIAS: true
},

parserOptions: {
sourceType: 'script'
},

settings: {
'import/core-modules': ['aws-sdk', 'lodash', 'yamljs', 'openapi-schema-validator']
},

rules: {
'operator-linebreak': 0,
'no-continue': 0,
'no-plusplus': 0,
'prefer-spread': 0,
'prefer-rest-params': 0,
'class-methods-use-this': 0,
'consistent-return': 0,
'prefer-template': 0,
'import/no-unresolved': 0,
'import/no-extraneous-dependencies': ['error', { devDependencies: ['**/tests/**/*.js'] }],

'no-bitwise': 0,

curly: ['error', 'multi-or-nest'],

'no-underscore-dangle': ['warn', {
allowAfterThis: true,
allowAfterSuper: true,
allow: ['_call', '__rootpath', '_where']
}],

'no-tabs': 0,

'no-new': 0,

'func-names': 0,

'space-before-function-paren': ['error', {
'anonymous': 'never',
'named': 'never',
'asyncArrow': 'always'
}],

'arrow-parens': ['error', 'as-needed'],
'arrow-body-style': 0,

indent: ['error', 'tab', {
SwitchCase: 1
}],

'comma-dangle': ['error', 'never'],

'padded-blocks': 0,

'max-len': ['error', {
code: 150,
tabWidth: 1,
comments: 200
}],

'spaced-comment': ['error', 'always', {
exceptions: ['*']
}],

'newline-per-chained-call': ['error', {
ignoreChainWithDepth: 2
}],

'no-param-reassign': 0,

'no-prototype-builtins': 0,

'keyword-spacing': ['error', {
overrides: {
if: {
after: false
},
for: {
after: false
},
while: {
after: false
},
switch: {
after: false
},
catch: {
after: false
}
}
}],

'no-restricted-syntax': ['error', 'ForInStatement', 'LabeledStatement', 'WithStatement'],
'function-paren-newline': 0,
'no-await-in-loop': 0,

'object-curly-newline': ['error', {
ObjectExpression: { minProperties: 5, multiline: true, consistent: true },
ObjectPattern: { minProperties: 5, multiline: true, consistent: true }
}],
'nonblock-statement-body-position': ['error', 'below', { overrides: { else: 'any' } }]
}
};
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules/
.nyc_output/
5 changes: 5 additions & 0 deletions .huskyrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"hooks": {
"pre-commit": "npm run lint && npm t"
}
}
20 changes: 20 additions & 0 deletions .nycrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"exclude": [
"coverages/",
"tests/",
"mocks/",
".eslintrc.js",
".travis.yml"
],
"extension": [
".js"
],
"cache": true,
"all": true,
"default-excludes": true,
"check-coverage": true,
"statements": 95,
"branches": 95,
"functions": 95,
"lines": 95
}
15 changes: 15 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
language: node_js
node_js:
- "lts/*"
cache: npm
script:
- |
# Run test script
npm run test-ci
after_script:
- |
# Upload coverage to coveralls
if [[ -d .nyc_output ]]; then
npm install --save-dev coveralls@2
nyc report --reporter=text-lcov | coveralls
fi
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Changelog

All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).

## [Unreleased]
### Added
- `EnviromentBuilder` added
- *Unit Test* added
- `npx` added
26 changes: 15 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,19 +1,23 @@
# environment-builder

Build the exclusive files of each environment in the right folder.

## Installation
```sh
npm install @janiscommerce/environment-builder
```

## API
[![Build Status](https://travis-ci.org/janis-commerce/environment-builder.svg?branch=JCN-94-environment-builder)](https://travis-ci.org/janis-commerce/environment-builder)
[![Coverage Status](https://coveralls.io/repos/github/janis-commerce/environment-builder/badge.svg?branch=JCN-94-environment-builder)](https://coveralls.io/github/janis-commerce/environment-builder?branch=JCN-94-environment-builder)

Build the exclusive files of each environment in the right config folder.

## Usage
```js
const EnvironmentBuilder = require('@janiscommerce/environment-builder');

In the console

```sh
npx @janiscommerce/environment-builder [ENVIRONMENT]
```
* `[ENVIRONMENT]` name of the *environment* you want to build. If it's empty will be *'local'*.
* The files will be copy in `/root/config/`.
* If there are files in `/root/config/` will be removed, and replace with the new ones.

## Configuration

The environments should be located in the folder `/root/environments/[ENVIRONMENT]`. It mustn't be empty.

## Examples
8 changes: 8 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
'use strict';

const { EnvironmentBuilder } = require('./lib');

(async () => {
const envBuilder = new EnvironmentBuilder();
await envBuilder.execute(process.argv[2]);
})();
134 changes: 134 additions & 0 deletions lib/environment-builder.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
'use strict';

/* eslint-disable no-console */

const fs = require('fs');
const path = require('path');
const { promisify } = require('util');

const rmdir = promisify(require('rimraf'));
const ncp = promisify(require('ncp').ncp);

const readDir = promisify(fs.readdir);
const stat = promisify(fs.stat);

const ENVIRONMENTS_DIR = path.join(process.cwd(), 'environments');
const CONFIG_DIR = path.join(process.cwd(), 'config');
const DEFAULT_ENVIRONMENT = 'local';

/**
* Simple Console Log
* @param {string} message DEFAULT = 'Something happened'
* @param {string} prefix DEFAULT = 'BUILDING'
* @param {boolean} error if it's an error message
*/
/* istanbul ignore next */
const logger = (message = 'Something happened', prefix = 'BUILDING', error = false) => {
const time = new Date().toLocaleTimeString();

/*
/x1b[**m -> text editor codes
/x1b[35m = Magenta
/x1b[32m = Green
/x1b[31m = Red
/x1b[1m = Bright
/x1b[0m = Reset, back to normal
*/

if(error) {
console.error(`[\x1b[35m \x1b[1mENV-BUILDER\x1b[0m | ${time} ] | \x1b[31m${prefix}\x1b[0m | ${message}`);
console.error(`[\x1b[35m \x1b[1mENV-BUILDER\x1b[0m | ${time} ] | \x1b[31mERROR\x1b[0m | Abort. Can't create ENVIRONMENT.\n`);
} else
console.log(`[\x1b[35m \x1b[1mENV-BUILDER\x1b[0m | ${time} ] | \x1b[32m${prefix}\x1b[0m | ${message}`);
};

class EnvironmentBuilder {
static get envDir() {
return ENVIRONMENTS_DIR;
}

static get configDir() {
return CONFIG_DIR;
}

static get defaultEnv() {
return DEFAULT_ENVIRONMENT;
}

/**
* Execute de Builder
*/
async execute(environment = this.constructor.defaultEnv) {
// Capture of Parametre or assign Default Value and build the path
const environmentDir = path.join(this.constructor.envDir, environment);

logger(`Building Environment - '${environment}'`, 'START');
try {
// Checks if path exist
if(!(await this.exists(this.constructor.envDir)) || !(await this.exists(environmentDir))) {
logger(`Directory: '${environmentDir}' doesn't exist.`, 'ERROR', true);
return;
}

// checks if source folde is empty
if(await this.isEmptyFolder(environmentDir)) {
logger(`Directory: '${environmentDir}' is empty.`, 'ERROR', true);
return;
}

logger(`Environment '${environment}' directory found.`);

// If CONFIG has files
if(await this.exists(this.constructor.configDir) && !(await this.isEmptyFolder(this.constructor.configDir))) {
// Delete if have it
logger('Previous Enviromment\'s Config folder found. Deleting.');
await rmdir(this.constructor.configDir);
logger('Delete previous Enviromment\'s Config.');
}

// try to copy files
logger(`Copying '${environment}' files to '${this.constructor.configDir}'.`);
await ncp(environmentDir, this.constructor.configDir);
logger(`'${environment}' files copied to '${this.constructor.configDir}'.`);

logger(`Environment '${environment}' created.\n`, 'SUCCESS');
} catch(error) {
logger(`${error.message}.`, 'ERROR', true);
}

}

/**
* Returns if folder is empty asynchronously
* @param {string} filePath Path to folder
* @returns {Promise<boolean>}
*/
async isEmptyFolder(filePath) {

try {
const files = await readDir(filePath);
return !files.length;
} catch(error) {
// if file not exist or have permission problems
throw error;
}
}

/**
* Return if exist or not a File or directory asynchronously
* @param {string} filePath Path of File
* @returns {Promise<boolean>}
*/
async exists(filePath) {

try {
await stat(filePath);
return true;
} catch(error) {
return false;
}
}

}

module.exports = EnvironmentBuilder;
7 changes: 7 additions & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
'use strict';

const EnvironmentBuilder = require('./environment-builder');

module.exports = {
EnvironmentBuilder
};
Loading

0 comments on commit 7a13b26

Please sign in to comment.