All files / common/util helpers.ts

100% Statements 36/36
100% Branches 10/10
100% Functions 4/4
100% Lines 33/33

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    8x 8x 8x 8x         8x         8x 25x   25x 2x     23x             8x 4x 1x     3x       3x   3x 26x     3x             8x 4x   4x 2x     2x 2x   2x 1x     1x           8x 8x   8x 8x             8x           8x    
 
/* eslint-disable no-process-exit */
import {createInterface} from 'node:readline/promises';
import {exec, execFileSync} from 'child_process';
import * as path from 'path';
import {promisify} from 'util';
 
/**
 * Promise version of Node's `exec` from `child-process`.
 */
export const execPromise = promisify(exec);
 
/**
 * Prepends process path to given `filePath`.
 */
export const prependFullFilePath = (filePath: string) => {
  const processRunningPath = process.cwd();
 
  if (path.isAbsolute(filePath)) {
    return filePath;
  }
 
  return path.normalize(`${processRunningPath}/${filePath}`);
};
 
/**
 * Checks if there is data piped, then collects it.
 * Otherwise returns empty string.
 */
const collectPipedData = async () => {
  if (process.stdin.isTTY) {
    return '';
  }
 
  const readline = createInterface({
    input: process.stdin,
  });
 
  const data: string[] = [];
 
  for await (const line of readline) {
    data.push(line);
  }
 
  return data.join('\n');
};
 
/**
 * Checks if there is piped data, tries to parse yaml from it.
 * Returns empty string if haven't found anything.
 */
export const parseManifestFromStdin = async () => {
  const pipedSourceManifest = await collectPipedData();
 
  if (!pipedSourceManifest) {
    return '';
  }
 
  const regex = /# start((?:.*\n)+?)# end/;
  const match = regex.exec(pipedSourceManifest);
 
  if (!match) {
    return '';
  }
 
  return match![1];
};
 
/**
 * Runs the --help command when the entered command is incorrect.
 */
export const runHelpCommand = (command: string) => {
  console.log(`Here are the supported flags for the \`${command}\` command:`);
 
  const isGlobal = !!process.env.npm_config_global;
  const ifCommand = [
    isGlobal ? command : 'npm',
    ...(isGlobal ? ['--silent'] : ['run', command, '--silent']),
    '--',
    '-h',
  ];
 
  execFileSync(ifCommand[0], ifCommand.slice(1), {
    cwd: process.env.CURRENT_DIR || process.cwd(),
    stdio: 'inherit',
    shell: false,
  });
 
  process.exit(1);
};