All files / piscosour/lib sour.js

0% Statements 0/122
0% Branches 0/56
0% Functions 0/13
0% Lines 0/118
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212                                                                                                                                                                                                                                                                                                                                                                                                                                       
'use strict';
 
const path = require('path');
const moment = require('moment');
 
const params = require('./params');
const config = require('./config').setOptions({isGlobal: !params.onlyLocal});
 
const analytics = require('./analytics');
const bus = require('./bus');
const context = require('./context');
const docs = require('./docs');
const execution = require('./execution');
const logger = require('./logger');
const scullion = require('./globalScullion');
const sipper = require('./sipper');
const stepper = require('./stepper');
 
/**
 * Sour is the commands line interface
 * @returns gush : execute the commands.
 * @constructor Sour
 */
module.exports = function() {
 
  const _config = config.get();
 
  /**
   * Normalize commands getting context
   *
   * @returns {{name: *, context: *, orig: *, recipe: *, isStep: *}}
   * @private
   */
  const normalize = function(command) {
    logger.trace('#green', 'sour:normalize:', 'commands:', command);
 
    if (Object.prototype.toString.call(command) === '[object Array]') {
      command = command[0];
      if (!command) {
        command = '';
      }
    }
 
    const normal = {};
 
    normal.orig = normal.name = command;
 
    if (command.indexOf(':') >= 0) {
      const names = command.split(':');
      normal.context = names[0];
      if (names.length === 3) {
        normal.isStep = true;
        normal.name = names[2];
      } else {
        normal.name = names[1];
      }
    }
 
    if (normal.context) {
      const exists = Object.getOwnPropertyNames(_config.contexts).find(name => name === normal.context);
      normal.context = [ normal.context ];
      normal.contextFixed = true;
      if (!exists) {
        logger.error('#red', 'ERROR:', '#cyan', normal.context, 'is not a software unit in the configuration');
        normal.context = undefined;
      }
    } else {
      normal.context = context.whoami();
      normal.context = normal.context.length > 0 ? normal.context : undefined;
    }
 
    if (params.all) {
      normal.context = config.allContexts();
    }
 
    if (!normal.isStep) {
      normal.flowName = normal.name;
    }
 
    params.normal = JSON.parse(JSON.stringify(normal));
 
    return normal;
  };
 
  /**
   * checks if the params is available and compatible with configurations
   * @param reject : callback function
   * @private
   */
  const check = function(reject, cb) {
    logger.trace('#green', 'sour:check:', 'commands:', params.commands);
    const normal = normalize(params.commands);
 
    if (normal.orig === '') {
      return docs.help(normal, cb);
    }
 
    if (!normal.context) {
      logger.error('#red', 'ERROR:', 'command', '#cyan', normal.orig, 'needs a context of execution');
      return reject();
    }
    if (config.isAvailable(normal)) {
      return normal;
    }
    if (normal.name) {
      const type = normal.isStep ? 'step' : 'flow';
      logger.error(type, '#green', normal.orig, '#red', 'doesn\'t exist!');
      logger.txt('\n', _config.cmd, '-la for help.', '\n');
      return reject('command not available');
    }
    return docs.help(normal, cb);
  };
 
  /**
   * Execute all the commands of the utility
   * @returns {Promise}
   */
  const gush = function(init) {
    return docs.showDisclaimer().then(() => new Promise((resolve, reject) => {
      logger.trace('#green', 'sour:gush', 'commands:', params.commands);
 
      const _resolve = function() {
        const lastFinished = execution.lastFinished('flow') || execution.lastFinished('step');
        if (lastFinished.stats.hardOk()) {
          bus.emit('command:end', { status: 0 });
          resolve.apply(this, arguments);
        } else {
          bus.emit('command:end', { status: 1 });
          reject.apply(this, arguments);
        }
      };
 
      const _reject = function() {
        if (arguments[0].notBuilt) {
          logger.info('Execution', '#green', 'NOT BUILT');
          bus.emit('command:end', {status: 2});
          resolve.apply(this, arguments);
        } else {
          bus.emit('command:end', {status: 1});
          reject.apply(this, arguments);
        }
      };
 
      const execute = function(normal) {
        logger.info('Execution contexts:', '[', '#bold', normal.context.join(', '), ']');
        bus.emit('command:start', normal);
        if (normal.isStep) {
          normal.params = config.getStepParams(normal);
          normal.context.map(ctx => analytics.hit(`/steps/${ctx}::${normal.name}`, `step: ${ctx}::${normal.name}`));
          stepper.execute(normal, _resolve, _reject);
        } else {
          normal.context.map(ctx => analytics.hit(`/flows/${ctx}:${normal.name}`, `flow: ${ctx}:${normal.name}`));
          sipper.execute(normal, params.initStep, params.endStep, _resolve, _reject);
        }
      };
 
      const executeAnswers = function(answers) {
        try {
          const command = answers.command && !answers.step ? answers.command : answers.step;
          params.commands.push(command);
          execute(normalize([ command ]));
        } catch (e) {
          console.error(e.stack);
          reject(e);
        }
      };
 
      try {
        if (params.version) {
          docs.version();
          resolve();
        } else if (params.functionalTests) {
          require('./functionalTests').run(resolve, reject);
        } else if (params.saveRequirements && params.commands.length === 0) {
          config.saveRequirements().then(resolve, reject);
        } else if (params.writeCache) {
          scullion.writeCache();
          resolve();
        } else if (params.showContext) {
          logger.txt(context.whoami());
          resolve();
        } else {
          const normal = check(reject, executeAnswers);
          if (normal) {
            normal.init = init;
            if (params.help) {
              docs.help(normal);
              resolve();
            } else {
              execute(normal);
            }
          }
        }
 
        // Commented until domain implementation were undone
        //if (!params.writeCache) {
        //  const spawn = require('child_process').spawn;
        //  spawn(process.execPath, [path.join(config.getDir('module'), 'bin', 'pisco.js'), '-w'], {stdio: ['ignore', process.stdout, process.stderr]});
        //}
 
      } catch (e) {
        console.error(e.stack);
        reject(e);
      }
    }));
  };
 
  return {
    gush: gush
  };
};