All files utils.ts

100% Statements 141/141
100% Branches 54/54
100% Functions 31/31
100% Lines 137/137

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 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 3167x 7x 7x 7x 7x 7x 7x 7x                     7x                 7x 21x   21x 7x   14x 3x     14x       7x 52x   52x 17x   35x 19x     16x       7x 9x   9x 3x   6x 1x   5x         7x 7x   7x   4x 2x     4x     3x 3x                 216x 210x   210x   206x 2x     206x 2x 2x     204x   2x   2x               2x   2x   2x             7x 13x 13x     13x   5x 1x     4x       8x   8x 1x     7x   7x 6x   6x   6x     6x 1x       5x     1x     7x 7x 1x 1x     6x   6x   6x   6x     7x 24x     7x       8x     19x 2x   2x 1x     1x         7x 9x 9x 9x 9x 9x     7x 12x     7x 20x     7x 15x     7x 15x   15x   15x     7x 3x                                   7x 4x     7x 23x 23x   23x 23x   7x 7x 7x     16x     7x 7x 1x 1x   6x   6x   6x   6x   6x       7x 8x   8x     7x 21x             7x 6x 1x 1x     5x   5x    
import * as colors from 'colors/safe';
import * as dotenv from 'dotenv';
import * as fs from 'fs';
import * as moment from 'moment';
import * as net from 'net';
import * as os from 'os';
import * as path from 'path';
import {
  Config,
  DEFAULT_ENV,
  ENV_BIN,
  MATCHES_ENV_VAR,
  MATCHES_SHEBANG,
  PADDING,
  TABLE_FLIP,
  UTF8,
  WAT,
} from './constants';
import * as logger from './logger';
 
export interface PortError extends Error {
  message: string;
  code: string;
}
 
export type PortCallback = (error: PortError | undefined, inUse?: boolean) => any;
 
export const setIn = (obj: {[i: string]: any}, setPath: ReadonlyArray<string>, value: any) => {
  const [first, ...rest] = setPath;
 
  if (!rest.length) {
    obj[first] = value;
  } else {
    if (!(first in obj)) {
      obj[first] = {};
    }
 
    setIn(obj[first], rest, value);
  }
};
 
export const getIn = (obj: Readonly<{[i: string]: any}>, setPath: ReadonlyArray<string>): any => {
  const [first, ...rest] = setPath;
 
  if (!rest.length) {
    return obj[first];
  } else {
    if (!(first in obj)) {
      return;
    }
 
    return getIn(obj[first], rest);
  }
};
 
export const delIn = (obj: {[i: string]: any}, setPath: ReadonlyArray<string>) => {
  const [first, ...rest] = setPath;
 
  if (!rest.length) {
    delete obj[first];
  } else {
    if (!(first in obj)) {
      return;
    } else {
      delIn(obj[first], rest);
    }
  }
};
 
export const isPortTaken = (port: number, callback: PortCallback) => {
  const tester = net.createServer();
 
  tester
    .once('error', (error: PortError) => {
      if (error.code !== 'EADDRINUSE') {
        callback(error);
      }
 
      callback(undefined, true);
    })
    .once('listening', () => {
      tester.once('close', () => {
        callback(undefined, false) ;
      })
      .close();
    })
    .listen(port);
};
 
export type ServerCallback = (error: PortError | undefined, port?: number) => any;
 
export const getAvailablePort = (callback: ServerCallback, attempt = 0) => {
  const server = net.createServer();
 
  server
    .once('error', (error: PortError) => {
      if (error.code !== 'EADDRINUSE') {
        callback(error);
      }
 
      if (attempt >= 100) {
        logger.log('Could not find an available port');
        return process.exit(1);
      }
 
      getAvailablePort(
        (portError: PortError | undefined, port?: number) => {
          server
            .once('close', () => {
              callback(portError, port);
            })
            .close();
        },
        attempt + 1
      );
    })
    .once('listening', () => {
      const { port } = server.address();
 
      server
        .once('close', () => {
          callback(undefined, port);
        })
        .close();
    })
    .listen(0);
};
 
export const handleShebang = (command: string): string => {
  const filePath = path.join(process.cwd(), command);
  const envFilePath = path.join(process.cwd(), ENV_BIN, command);
 
  // In root of project
  if (!fs.existsSync(filePath)) {
    // In env
    if (fs.existsSync(envFilePath)) {
      return envFilePath;
    // Global command
    } else {
      return command;
    }
  }
 
  const firstLine = fs.readFileSync(filePath, UTF8).split('\n')[0];
 
  if (!firstLine) {
    return command;
  }
 
  const shebang = MATCHES_SHEBANG.exec(firstLine);
 
  if (shebang) {
    const shebangCommand = shebang[2].trim();
 
    const shebangCommandPath = path.join(process.cwd(), ENV_BIN, shebangCommand);
 
    const envExists = fs.existsSync(shebangCommandPath);
 
    // Shebang in env
    if (envExists) {
      return `${shebangCommandPath} ${command}`;
    }
 
    // Global command
    return `${shebangCommand} ${command}`;
  }
 
  return command;
};
 
export const getEnvVariables = (envPath: string): {[i: string]: string} => {
  if (!fs.existsSync(envPath)) {
    logger.log(`No environment file at ${envPath}\n`);
    return {};
  }
 
  const envFile = fs.readFileSync(envPath, UTF8);
 
  const envVariables = dotenv.parse(envFile);
 
  logger.log(`Found ${Object.keys(envVariables).length} variables in ${envPath}\n`);
 
  return envVariables;
};
 
export const isTruthyString = (value: any): value is string => {
  return Boolean(value && typeof value === 'string');
};
 
export const injectEnvVars = (
  commandOptions: ReadonlyArray<string | undefined>,
  environment: Readonly<{[i: string]: string}>
) => {
  return commandOptions
    .filter(isTruthyString)
    .map((option) => {
      return option.replace(MATCHES_ENV_VAR, (match: string): string => {
        const varName = match.substring(1);
 
        if (varName in environment) {
          return environment[varName];
        }
 
        return match;
      });
    });
};
 
export const onClose = (prefix: string, code: number) => {
  const exitColor = code ? 'red' : 'green';
  const wat = code ? colors.red(WAT) : '';
  const tableFlip = code ? ' ' + TABLE_FLIP : '';
  const message = `${wat}${prefix}${colors[exitColor](`Process exited with code ${code}${tableFlip}`)}`;
  logger.log(message);
};
 
export const getConfigPath = () => {
  return path.join(os.homedir(), 'wtf.json');
};
 
export const getProjectName = () => {
  return path.basename(process.cwd());
};
 
export const getDisplayName = (processName: string, env: string): string => {
  return `${env === DEFAULT_ENV ? '' : `${env}:`}${processName}`;
};
 
export const wrapDisplayName = (displayName: string, longestName: number): string => {
  const diff = longestName - displayName.length;
 
  const padding = diff >= 0 ? PADDING.substring(0, diff) : '';
 
  return `[ ${displayName}${padding} ] `;
};
 
export const constructHTMLMessage = (message: string) => {
  return (
    `<html>
      <head>
        <title>WAT</title>
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
      </head>
      <body>
        <div style="font-family: arial, helvetica, sans-serif; color: #333; text-align: center;">
          <pre style="display: inline-block; color: red; font-size: 10px; line-height: 1; text-align: left;">
            ${WAT}
          </pre>
          <p style="font-size: 16px;">${message}</p>
        </div>
      </body>
    </html>`
  );
};
 
export const getTimeNow = () => {
  return moment().format('HH:mm:ss.SS');
};
 
export const readWtfJson = (configPath: string): Config => {
  let config: Config = {};
  const configContent = fs.readFileSync(configPath, UTF8);
 
  try {
    config = JSON.parse(configContent);
  } catch (error) {
    logger.log(colors.red(`Invalid wtf.json at ${configPath}`));
    logger.log(colors.red(`${error.message}`));
    return {};
  }
 
  return config;
};
 
export const loadWtfJson = (configPath: string, projectName: string, env: string): Config => {
  if (!fs.existsSync(configPath)) {
    logger.log(`No wtf.json found at ${configPath} - run "wtf init" to begin setup\n`);
    return {};
  } else {
    logger.log(`Loading wtf.json from ${configPath}`);
 
    const config = readWtfJson(configPath);
 
    const configEnvVariables = getIn(config, [projectName, 'env', env]) || {};
 
    logger.log(`Found ${Object.keys(configEnvVariables).length} variables in wtf.json\n`);
 
    return config;
  }
};
 
export const getRouterPort = () => {
  const { PORT } = process.env;
 
  return PORT ? parseInt(PORT, 10) : 8080;
};
 
export const createStringFromConfig = (createdConfig: {} | undefined): string => {
  return JSON.stringify(
    createdConfig,
    undefined,
    2
  ) + '\n';
};
 
export const writeConfigCallback = (error?: NodeJS.ErrnoException) => {
  if (error) {
    logger.log(error.message);
    return process.exit(1);
  }
 
  const configPath = getConfigPath();
 
  logger.log(`wtf.json written to ${configPath}`);
};