All files start.ts

100% Statements 102/102
100% Branches 44/44
100% Functions 15/15
100% Lines 101/101

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 2881x 1x 1x 1x   1x 1x   1x             1x 1x 1x 1x                               1x       1x   1x 1x       1x 1x               1x 1x       1x                       4x 4x   4x   4x               4x 3x 3x     4x 4x   4x                     4x 4x   4x 12x 12x     4x 8x     4x         4x         4x     1x                     4x 3x 2x 1x 1x     1x                           1x                         1x             6x 6x 6x 6x   6x   6x 6x   6x   9x 9x   9x         6x         6x   9x 8x 6x   6x 6x   6x                         8x         1x 4x 4x 4x 4x   4x   4x 4x   4x     1x 5x   5x 1x     5x 1x   1x     5x 1x       1x 5x 5x   5x 5x   5x 5x   5x   5x 1x 1x     4x   4x     1x  
import * as childProcess from 'child_process';
import * as colors from 'colors/safe';
import * as es from 'event-stream';
import * as fs from 'fs';
import { Tree } from 'jargs';
import * as path from 'path';
import * as WebSocket from 'ws';
import * as constants from './constants';
import {
  Colors,
  COLORS,
  DEFAULT_ENV,
  SOCKET_PORT,
  UTF8,
} from './constants';
import * as logger from './logger';
import * as procfile from './procfile';
import router, { ACTIONS, Routes } from './router';
import {
  getAvailablePort,
  getConfigPath,
  getDisplayName,
  getEnvVariables,
  getIn,
  getProjectName,
  getTimeNow,
  handleShebang,
  injectEnvVars,
  loadWtfJson,
  onClose,
  PortError,
  wrapDisplayName,
} from './utils';
 
const routes: Routes = {};
 
let ws: WebSocket;
 
export const applyRoutes = (routesToApply: Routes) => {
  /* istanbul ignore else */
  if (ws.readyState === WebSocket.OPEN) {
    ws.send(JSON.stringify({type: ACTIONS.ADD_ROUTES, payload: routesToApply}));
  }
};
 
export const addRoute = (processName: string, color: Colors, url: string, port: number) => {
  routes[url] = {
    processName,
    url,
    port,
    color,
  };
 
  /* istanbul ignore else */
  if (ws.readyState === WebSocket.OPEN) {
    ws.send(JSON.stringify({type: ACTIONS.ADD_ROUTE, payload: {processName, color, url, port}}));
  }
};
 
export const startProcessWithMaybePort = (
  item: procfile.Command,
  processName: string,
  longestName: number,
  env: string,
  color: Colors,
  tree: Tree,
  envVariables: {[i: string]: string},
  configEnvVariables: {[i: string]: string},
  url?: string,
  port?: number
) => {
  const { time } = tree.flags;
  const displayName = getDisplayName(processName, env);
 
  logger.log(colors[color](`Starting ${displayName} process...`));
 
  const environment: {[i: string]: string} = {
    ...envVariables,
    ...configEnvVariables,
    ...process.env,
    PORT: process.env.PORT || '',
    PYTHONUNBUFFERED: 'true',
  };
 
  if (url && port) {
    environment.PORT = port.toString();
    addRoute(displayName, color, url, port);
  }
 
  const resolvedCommand = handleShebang(item.command);
  const commandOptions = injectEnvVars(item.options, environment);
 
  const subProcess = childProcess.spawn(
    resolvedCommand,
    commandOptions,
    {
      cwd: process.cwd(),
      shell: true,
      env: environment,
      stdio: 'pipe',
    }
  );
 
  logger.log(colors[color](`Running ${resolvedCommand} ${commandOptions.join(' ')}`));
  logger.log(colors[color](`PID: ${subProcess.pid}, Parent PID: ${process.pid}\n`));
 
  const getPrefix = () => {
    const timeNow = time ? getTimeNow() + ' ' : '';
    return colors[color](wrapDisplayName(timeNow + displayName, longestName + timeNow.length));
  };
 
  const mapOutput = (message: any, cb: any) => {
    cb(null, `${getPrefix()}${message}\n`);
  };
 
  subProcess.stdout
    .pipe(es.split('\n'))
    .pipe(es.map(mapOutput))
    .pipe(process.stderr);
 
  subProcess.stderr
    .pipe(es.split('\n'))
    .pipe(es.map(mapOutput))
    .pipe(process.stderr);
 
  subProcess.on('close', (code) => onClose(getPrefix(), code));
};
 
export const startProcess = (
  item: procfile.Command,
  processName: string,
  longestName: number,
  env: string,
  color: Colors,
  tree: Tree,
  envVariables: {[i: string]: string},
  configEnvVariables: {[i: string]: string},
  url?: string
) => {
  if (url) {
    getAvailablePort((error: PortError | undefined, port?: number) => {
      if (error) {
        logger.log(error.message);
        return process.exit(1);
      }
 
      startProcessWithMaybePort(
        item,
        processName,
        longestName,
        env,
        color,
        tree,
        envVariables,
        configEnvVariables,
        url,
        port
      );
    });
  } else {
    startProcessWithMaybePort(
      item,
      processName,
      longestName,
      env,
      color,
      tree,
      envVariables,
      configEnvVariables
    );
  }
};
 
export const startProcesses = (
  procfileData: string,
  wtfJson: constants.ConfigProject,
  env: string,
  tree: Tree,
  envVariables: {[i: string]: string}
) => {
  let { processes } = tree.args;
  let { exclude } = tree.kwargs;
  processes = Array.isArray(processes) ? processes : [];
  exclude = Array.isArray(exclude) ? exclude : [];
 
  const procfileConfig = procfile.parse(procfileData.toString());
 
  let longestName: number = 0;
  let index = 0;
 
  for (const processName in procfileConfig) {
    /* istanbul ignore else */
    if (procfileConfig.hasOwnProperty(processName)) {
      const displayName = getDisplayName(processName, env);
 
      if (
        (!processes.length || processes.indexOf(processName) >= 0) &&
        (!longestName || displayName.length > longestName) &&
        exclude.indexOf(processName) < 0
      ) {
        longestName = displayName.length;
      }
    }
  }
 
  for (const processName in procfileConfig) {
    /* istanbul ignore else */
    if (exclude.indexOf(processName) < 0 && procfileConfig.hasOwnProperty(processName)) {
      if ((!processes.length || processes.indexOf(processName) >= 0) && exclude.indexOf(processName) < 0) {
        const item = procfileConfig[processName];
 
        const url = getIn(wtfJson, ['routes', processName]);
        const configEnvVariables = getIn(wtfJson, ['env', env]) || {};
 
        startProcess(
          item,
          processName,
          longestName,
          env,
          COLORS[index % (COLORS.length)],
          tree,
          envVariables,
          configEnvVariables,
          url
        );
      }
 
      index += 1;
    }
  }
};
 
export const readWtfJsonAndEnv = (procfileData: string, tree: Tree) => {
  const configPath = getConfigPath();
  const projectName = getProjectName();
  let { env } = tree.kwargs;
  env = typeof env === 'string' ? env : DEFAULT_ENV;
 
  const config = loadWtfJson(configPath, projectName, env);
 
  const envPath = path.join(process.cwd(), 'etc/environments', env, 'env');
  const envVariables = getEnvVariables(envPath);
 
  startProcesses(procfileData, getIn(config, [projectName]) || {}, env, tree, envVariables);
};
 
export const startRouterCommunication = () => {
  ws = new WebSocket(`ws://localhost:${SOCKET_PORT}`);
 
  ws.on('open', () => {
    applyRoutes(routes);
  });
 
  ws.on('close', () => {
    router();
 
    setTimeout(startRouterCommunication, 1000);
  });
 
  ws.on('message', (data) => {
    logger.log(data.toString());
  });
};
 
const start = (tree: Tree) => {
  router();
  startRouterCommunication();
 
  process.stdout.setMaxListeners(20);
  process.stderr.setMaxListeners(20);
 
  let { env } = tree.kwargs;
  env = typeof env === 'string' ? env : DEFAULT_ENV;
 
  const procfilePath = path.join(process.cwd(), 'etc/environments', env, 'procfile');
 
  if (!fs.existsSync(procfilePath)) {
    logger.log(`No procfile found at ${procfilePath}`);
    return process.exit(1);
  }
 
  const procfileContent = fs.readFileSync(procfilePath, UTF8);
 
  readWtfJsonAndEnv(procfileContent, tree);
};
 
export default start;