salix/gulpfile.js

515 lines
14 KiB
JavaScript
Raw Normal View History

require('require-yaml');
const gulp = require('gulp');
const fs = require('fs-extra');
const exec = require('child_process').exec;
const PluginError = require('plugin-error');
const argv = require('minimist')(process.argv.slice(2));
const log = require('fancy-log');
2017-10-18 04:41:17 +00:00
// Configuration
let isWindows = /^win/.test(process.platform);
if (argv.NODE_ENV)
process.env.NODE_ENV = argv.NODE_ENV;
let env = process.env.NODE_ENV ? process.env.NODE_ENV : 'development';
let langs = ['es', 'en'];
let srcDir = './front';
2018-12-27 11:54:16 +00:00
let modulesDir = './modules';
let servicesDir = './services';
let modules = require('./modules.yml');
let wpConfig = require('./webpack.config.yml');
let buildDir = wpConfig.buildDir;
let devServerPort = wpConfig.devServerPort;
let nginxDir = `${servicesDir}/nginx`;
let proxyConf = require(`${nginxDir}/config.yml`);
let proxyEnvFile = `${nginxDir}/config.${env}.yml`;
2018-02-03 21:53:02 +00:00
if (fs.existsSync(proxyEnvFile))
Object.assign(proxyConf, require(proxyEnvFile));
let defaultService = proxyConf.main;
let defaultPort = proxyConf.defaultPort;
2018-02-03 21:53:02 +00:00
// Development
2017-05-16 10:37:48 +00:00
const nginx = gulp.series(nginxStart);
nginx.description = `Starts/restarts the nginx process`;
2018-03-13 10:15:39 +00:00
const localesRoutes = gulp.parallel(locales, routes);
localesRoutes.description = `Builds locales and routes`;
const front = gulp.series(buildClean, gulp.parallel(localesRoutes, watch, webpackDevServer));
front.description = `Starts frontend service`;
2018-01-31 11:17:17 +00:00
const back = gulp.series(dockerStart, backOnly, nginx);
back.description = `Starts backend and database service`;
const defaultTask = gulp.parallel(front, back);
defaultTask.description = `Starts all application services`;
function backOnly(done) {
2018-12-27 11:54:16 +00:00
let app = require(`./loopback/server/server`);
app.start(defaultPort);
app.on('started', done);
}
backOnly.description = `Starts backend service`;
// backend tests
2019-01-24 11:01:35 +00:00
function backendUnitTest() {
let app = require(`./loopback/server/server`);
let specFiles = [
2019-01-24 11:01:35 +00:00
'back/**/*.spec.js',
'loopback/**/*.spec.js',
'modules/*/back/**/*.spec.js'
];
const jasmine = require('gulp-jasmine');
let options = {errorOnFail: false};
if (argv.junit || argv.j) {
const reporters = require('jasmine-reporters');
options.reporter = new reporters.JUnitXmlReporter();
}
return gulp.src(specFiles)
.pipe(jasmine(options))
.on('jasmineDone', function() {
app.disconnect();
});
}
2019-01-24 11:01:35 +00:00
backendUnitTest.description = `Runs the backend tests only, can receive args --junit or -j to save reports on a xml file`;
2019-01-24 11:01:35 +00:00
const dockerAndBackTest = gulp.series(docker, backendUnitTest);
dockerAndBackTest.description = `Restarts database and runs the backend tests`;
2019-01-24 11:01:35 +00:00
function backTest(done) {
const nodemon = require('gulp-nodemon');
2019-01-25 15:26:07 +00:00
let gulpBin = isWindows
? 'node_modules/.bin/gulp.cmd'
: 'node_modules/.bin/gulp';
2019-01-24 11:01:35 +00:00
nodemon({
2019-01-25 15:26:07 +00:00
exec: gulpBin,
2019-01-24 11:01:35 +00:00
args: ['dockerAndBackTest'],
watch: ['loopback', 'modules/*/back/**', 'back'],
done: done
});
}
backTest.description = `Watches for changes in modules to execute backTest task`;
// end to end tests
function e2eOnly() {
const jasmine = require('gulp-jasmine');
2018-09-05 11:01:21 +00:00
if (argv.show || argv.s)
process.env.E2E_SHOW = true;
2019-01-04 14:51:03 +00:00
return gulp.src('./e2e/tests.js')
.pipe(jasmine({reporter: 'none'}));
}
e2eOnly.description = `Runs the e2e tests only`;
2018-02-01 07:48:54 +00:00
e2e = gulp.series(docker, e2eOnly);
e2e.description = `Restarts database and runs the e2e tests`;
function smokesOnly() {
2018-03-09 19:04:03 +00:00
const jasmine = require('gulp-jasmine');
2019-01-04 14:51:03 +00:00
return gulp.src('./e2e/smokes-tests.js')
.pipe(jasmine({reporter: 'none'}));
}
smokesOnly.description = `Runs the smokes tests only`;
2018-03-09 19:04:03 +00:00
smokes = gulp.series(docker, smokesOnly);
smokes.description = `Restarts database and runs the smokes tests`;
const clean = gulp.parallel(buildClean, nginxClean);
clean.description = 'Cleans all generated project files';
2018-02-07 12:24:46 +00:00
function install() {
const install = require('gulp-install');
const print = require('gulp-print');
2019-01-22 10:16:14 +00:00
let packageFiles = ['front/package.json', 'print/package.json'];
return gulp.src(packageFiles)
.pipe(print(filepath => {
return `Installing packages in ${filepath}`;
}))
.pipe(install({
npm: ['--no-package-lock']
}));
}
install.description = `Installs node dependencies in all directories`;
2018-06-12 09:24:43 +00:00
const i = gulp.series(install);
i.description = `Alias for the 'install' task`;
// Deployment
2018-06-12 09:24:43 +00:00
const build = gulp.series(clean, gulp.parallel(localesRoutes, webpack, nginxConf));
build.description = `Generates binaries and configuration files`;
function buildClean() {
const del = require('del');
const files = [
2018-12-27 15:10:55 +00:00
`${buildDir}/*`
];
return del(files, {force: true});
}
buildClean.description = `Cleans all files generated by the 'build' task`;
// Webpack
function webpack(done) {
const webpackCompile = require('webpack');
const merge = require('webpack-merge');
let wpConfig = require('./webpack.config.js');
wpConfig = merge(wpConfig, {});
let compiler = webpackCompile(wpConfig);
compiler.run(function(err, stats) {
if (err) throw new PluginError('webpack', err);
log('[webpack]', stats.toString(wpConfig.stats));
done();
});
}
webpack.description = `Transpiles application into files`;
function webpackDevServer(done) {
const webpack = require('webpack');
const merge = require('webpack-merge');
const WebpackDevServer = require('webpack-dev-server');
let wpConfig = require('./webpack.config.js');
wpConfig = merge(wpConfig, {});
let devServer = wpConfig.devServer;
for (let entryName in wpConfig.entry) {
let entry = wpConfig.entry[entryName];
let wdsAssets = [`webpack-dev-server/client?http://127.0.0.1:${devServer.port}/`];
if (Array.isArray(entry))
wdsAssets = wdsAssets.concat(entry);
else
wdsAssets.push(entry);
wpConfig.entry[entryName] = wdsAssets;
}
let compiler = webpack(wpConfig);
new WebpackDevServer(compiler, wpConfig.devServer)
.listen(devServer.port, devServer.host, function(err) {
if (err) throw new PluginError('webpack-dev-server', err);
// TODO: Keep the server alive or continue?
done();
});
}
webpackDevServer.description = `Transpiles application into memory`;
// Locale
2018-12-27 11:54:16 +00:00
let localeFiles = [
`${srcDir}/**/locale/*.yml`,
`${modulesDir}/*/front/**/locale/*.yml`
];
/**
* Mixes all locale files into one JSON file per module and language. It looks
* recursively in all project directories for locale folders with per language
* yaml translation files.
*
* @return {Stream} The merged gulp streams
*/
function locales() {
const mergeJson = require('gulp-merge-json');
2018-02-04 14:46:46 +00:00
const yaml = require('gulp-yaml');
2018-02-05 18:34:04 +00:00
const merge = require('merge-stream');
let streams = [];
2018-12-27 11:54:16 +00:00
let localePaths = [];
for (let mod of modules)
2018-12-27 11:54:16 +00:00
localePaths[mod] = `${modulesDir}/${mod}`;
let baseMods = ['core', 'auth', 'salix'];
for (let mod of baseMods)
localePaths[mod] = `${srcDir}/${mod}`;
for (let mod in localePaths) {
let path = localePaths[mod];
for (let lang of langs) {
2018-12-27 11:54:16 +00:00
let localeFiles = `${path}/**/locale/${lang}.yml`;
2017-03-01 08:55:17 +00:00
streams.push(gulp.src(localeFiles)
2018-02-04 14:46:46 +00:00
.pipe(yaml())
.pipe(mergeJson({fileName: `${lang}.json`}))
2017-03-01 08:55:17 +00:00
.pipe(gulp.dest(`${buildDir}/locale/${mod}`)));
}
}
return merge(streams);
}
locales.description = `Generates client locale files`;
// Routes
2018-12-27 11:54:16 +00:00
let routeFiles = `${modulesDir}/*/front/routes.json`;
function routes() {
2018-02-05 18:34:04 +00:00
const concat = require('gulp-concat');
const wrap = require('gulp-wrap');
return gulp.src(routeFiles)
.pipe(concat('routes.js', {newLine: ','}))
.pipe(wrap('var routes = [<%=contents%>\n];'))
.pipe(gulp.dest(buildDir));
}
routes.description = 'Merges all module routes file into one file';
// Watch
function watch(done) {
gulp.watch(routeFiles, gulp.series(routes));
gulp.watch(localeFiles, gulp.series(locales));
done();
}
watch.description = `Watches for changes in routes and locale files`;
2017-10-18 04:41:17 +00:00
2018-02-01 15:01:49 +00:00
// Docker
/**
* Builds the database image and runs a container. It only rebuilds the
* image when fixtures have been modified or when the day on which the
* image was built is different to today. Some workarounds have been used
* to avoid a bug with OverlayFS driver on MacOS.
*/
async function docker() {
try {
2019-01-04 12:32:04 +00:00
await execP('docker rm -fv salix-db');
} catch (e) {}
let d = new Date();
let pad = v => v < 10 ? '0' + v : v;
let stamp = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
await execP(`docker build --build-arg STAMP=${stamp} -t salix-db ./services/db`);
2019-01-09 12:04:49 +00:00
let runChown = process.platform != 'linux';
await execP(`docker run --env RUN_CHOWN=${runChown} -d --name salix-db -p 3306:3306 salix-db`);
if (runChown) await dockerWait();
}
docker.description = `Builds the database image and runs a container`;
/**
* Does the minium effort to start the database container, if it doesn't exists
* calls the 'docker' task, if it is started does nothing. Keep in mind that when
* you do not rebuild the docker you may be using an outdated version of it.
* See the 'docker' task for more info.
*/
async function dockerStart() {
let state;
try {
2019-01-04 12:32:04 +00:00
let result = await execP('docker container inspect -f "{{json .State}}" salix-db');
state = JSON.parse(result.stdout);
} catch (err) {
return await docker();
}
switch (state.Status) {
case 'running':
return;
case 'exited':
2019-01-04 12:32:04 +00:00
await execP('docker start salix-db');
await dockerWait();
2019-01-04 12:32:04 +00:00
return;
default:
throw new Error(`Unknown docker status: ${state.Status}`);
}
}
dockerStart.description = `Starts the database container`;
function dockerWait() {
return new Promise((resolve, reject) => {
const mysql = require('mysql2');
let interval = 100;
let elapsedTime = 0;
let maxInterval = 30 * 60 * 1000;
log('Waiting for MySQL init process...');
checker();
async function checker() {
elapsedTime += interval;
let state;
try {
let result = await execP('docker container inspect -f "{{json .State}}" salix-db');
state = JSON.parse(result.stdout);
} catch (err) {
return reject(new Error(err.message));
}
if (state.Status === 'exited')
return reject(new Error('Docker exited, please see the docker logs for more info'));
let conn = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root'
});
conn.on('error', () => {});
conn.connect(err => {
conn.destroy();
if (!err) return resolve();
if (elapsedTime >= maxInterval)
reject(new Error(`MySQL not initialized whithin ${elapsedTime} secs`));
else
setTimeout(checker, interval);
});
}
});
}
dockerWait.description = `Waits until database service is ready`;
// Nginx
let nginxConfFile = 'temp/nginx.conf';
let nginxTemp = `${nginxDir}/temp`;
async function nginxStart() {
await nginxConf();
let nginxBin = await nginxGetBin();
if (isWindows)
nginxBin = `start /B ${nginxBin}`;
log(`Application available at http://${proxyConf.host}:${proxyConf.port}/`);
await execP(`${nginxBin} -c "${nginxConfFile}" -p "${nginxDir}"`);
}
nginxStart.description = `Starts the nginx process`;
async function nginxStop() {
try {
let nginxBin = await nginxGetBin();
await fs.stat(`${nginxTemp}/nginx.pid`);
await execP(`${nginxBin} -c "${nginxConfFile}" -p "${nginxDir}" -s stop`);
} catch (e) {}
}
nginxStop.description = `Stops the nginx process`;
/**
* Generates the nginx configuration file. If NODE_ENV is defined and the
* 'nginx.[environment].mst' file exists, it is used as a template, otherwise,
* the 'nginx.mst' template file is used.
*/
async function nginxConf() {
await nginxStop();
const mustache = require('mustache');
if (!await fs.exists(nginxTemp))
await fs.mkdir(nginxTemp);
let params = {
services: modules,
defaultService: defaultService,
defaultPort: defaultPort,
devServerPort: devServerPort,
port: proxyConf.port,
host: proxyConf.host
};
let confFile = `${nginxDir}/nginx.${env}.mst`;
if (!await fs.exists(confFile))
confFile = `${nginxDir}/nginx.mst`;
let template = await fs.readFile(confFile, 'utf8');
let nginxConfData = mustache.render(template, params);
await fs.writeFile(`${nginxTemp}/nginx.conf`, nginxConfData);
}
nginxConf.description = `Generates the nginx configuration file`;
async function nginxClean() {
await nginxStop();
const del = require('del');
return del([`${nginxTemp}/*`], {force: true});
}
nginxClean.description = `Cleans all files generated by nginx`;
async function nginxGetBin() {
if (isWindows)
return 'nginx';
try {
let nginxBin = '/usr/sbin/nginx';
await fs.stat(nginxBin);
return nginxBin;
} catch (e) {
return 'nginx';
}
}
2018-02-01 11:52:58 +00:00
// Helpers
2018-02-01 11:52:58 +00:00
/**
* Promisified version of exec().
*
* @param {String} command The exec command
* @return {Promise} The promise
*/
function execP(command) {
return new Promise((resolve, reject) => {
exec(command, (err, stdout, stderr) => {
if (err)
reject(err);
else {
resolve({
stdout: stdout,
stderr: stderr
});
}
});
2018-02-01 11:52:58 +00:00
});
}
2018-02-01 11:52:58 +00:00
module.exports = {
default: defaultTask,
front,
back,
backOnly,
2019-01-24 11:01:35 +00:00
backendUnitTest,
dockerAndBackTest,
backTest,
e2eOnly,
e2e,
smokesOnly,
smokes,
clean,
2019-01-09 09:05:18 +00:00
install,
2019-01-09 14:41:15 +00:00
i,
build,
buildClean,
nginxStart,
nginx,
nginxStop,
nginxConf,
nginxClean,
webpack,
webpackDevServer,
locales,
routes,
localesRoutes,
watch,
docker,
dockerStart,
dockerWait
};