start.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. const colors = require('colors');
  2. const docker = require('docker-compose/dist/v2');
  3. const path = require('path');
  4. const ProjectEnvironment = require('../classes/ProjectEnvironment');
  5. const log = require('../inc/log');
  6. const runServiceStart = (service, projectEnv) => {
  7. const env = projectEnv.getEnv();
  8. const scripts = [
  9. 'start.before',
  10. `start.before.${env}`,
  11. 'start',
  12. `start.${env}`,
  13. 'start.after',
  14. `start.after.${env}`,
  15. ];
  16. let chain = Promise.resolve();
  17. scripts.forEach(script => {
  18. chain = chain.then(() => {
  19. return new Promise(resolve => {
  20. try {
  21. const start = require(path.join(projectEnv.getCwd(), service, script));
  22. log.log(`\nExecuting %s script for %s...`, colors.bold(script), colors.bold(service));
  23. Promise
  24. .all([start({
  25. exec: (command, options) => {
  26. const opts = { ...projectEnv.getDockerOptions(), ...options };
  27. return docker.exec(service, command, opts);
  28. },
  29. log: (message) => {
  30. log.log('%s - %s', colors.bold(service), message);
  31. },
  32. env: projectEnv.getEnv()
  33. })])
  34. .then(() => {
  35. resolve();
  36. })
  37. .catch(() => {});
  38. } catch (ex) {
  39. resolve();
  40. }
  41. });
  42. });
  43. });
  44. return chain.then(() => {});
  45. };
  46. const runServices = async (projectEnv) => {
  47. let promises = [];
  48. await docker.buildAll(projectEnv.getDockerOptions());
  49. await docker.upAll(projectEnv.getDockerOptions());
  50. const services = await projectEnv.getServices();
  51. services.forEach(service => {
  52. promises.push(runServiceStart(service, projectEnv));
  53. });
  54. await Promise.all(promises);
  55. };
  56. module.exports = (env) => {
  57. try {
  58. const projectEnv = new ProjectEnvironment(process.cwd(), env);
  59. log.log("Starting project (%s environment)...", colors.bold(env));
  60. // Docker up services
  61. runServices(projectEnv);
  62. } catch (ex) {
  63. log.error(JSON.stringify(ex));
  64. }
  65. };