All files / util helpers.ts

88.98% Statements 105/118
87.8% Branches 36/41
92.85% Functions 13/14
88.07% Lines 96/109

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    5x 5x 5x   5x 5x   5x   5x       5x   5x               5x     5x         5x   5x 5x         5x 1x   1x   1x                   5x 11x   11x 20x 7x     20x 2x       11x           5x         5x 29x 24x     5x 1x     4x           5x 16x 2x     14x 4x     10x 4x     6x 1x     5x           5x 8x 8x   8x 4x 8x     4x     4x           5x   46x 4x     42x           5x 8x   8x 27x 15x   12x                 5x 4x 1x     3x       3x   3x 26x     3x             5x 4x   4x 2x     2x 2x   2x 1x     1x           5x       2x 2x 2x 2x 2x 2x   2x 1x     1x   1x                   5x                                         5x 2x 2x         2x 2x   2x            
 
/* eslint-disable no-process-exit */
import {createInterface} from 'node:readline/promises';
import {exec} from 'node:child_process';
import {promisify} from 'node:util';
 
import * as fs from 'fs/promises';
import * as path from 'path';
 
import {ERRORS} from '@grnsft/if-core/utils';
 
import {STRINGS, CONFIG} from '../config';
 
import {Difference} from '../types/lib/compare';
 
import {load} from '../lib/load';
 
import {
  installDependencies,
  initPackageJsonIfNotExists,
  updatePackageJsonDependencies,
  extractPathsWithVersion,
  updatePackageJsonProperties,
} from './npm';
 
import {logger} from './logger';
import {EnvironmentOptions} from '../types/if-env';
 
const {IF_ENV} = CONFIG;
const {
  FAILURE_MESSAGE,
  FAILURE_MESSAGE_TEMPLATE,
  FAILURE_MESSAGE_DEPENDENCIES,
} = IF_ENV;
 
const {UNSUPPORTED_ERROR} = STRINGS;
const {MissingPluginDependenciesError} = ERRORS;
 
/**
 * Impact engine error handler. Logs errors and appends issue template if error is unknown.
 */
export const andHandle = (error: Error) => {
  const knownErrors = Object.keys(ERRORS);
 
  logger.error(error);
 
  Iif (!knownErrors.includes(error.name)) {
    logger.error(UNSUPPORTED_ERROR(error.name));
    // eslint-disable-next-line no-process-exit
    process.exit(2);
  }
};
 
/**
 * Append entries from defaults which are missing from inputs.
 */
export const mergeObjects = (defaults: any, input: any) => {
  const merged: Record<string, any> = structuredClone(input);
 
  for (const key in defaults) {
    if (!(key in input)) {
      merged[key] = defaults[key];
    }
 
    if (merged[key] === undefined || merged[key] === null) {
      merged[key] = defaults[key];
    }
  }
 
  return merged;
};
 
/**
 * Promise version of Node's `exec` from `child-process`.
 */
export const execPromise = promisify(exec);
 
/**
 * `If-diff` equality checker.
 */
export const checkIfEqual = (source: any, target: any) => {
  if (source === target) {
    return true;
  }
 
  if (source === '*' || target === '*') {
    return true;
  }
 
  return false;
};
 
/**
 * Converts given `value` to either `1` or `0`.
 */
const convertToXorable = (value: any) => {
  if (typeof value === 'number') {
    return value !== 0 ? 1 : 0;
  }
 
  if (typeof value === 'boolean') {
    return value ? 1 : 0;
  }
 
  if (typeof value === 'string') {
    return value.length > 0 ? 1 : 0;
  }
 
  if (typeof value === 'object') {
    return 1;
  }
 
  return 0;
};
 
/**
 * If one of the `valuesToCheck` values is undefined, then set `missing`, otherwise `exists`.
 */
const setValuesIfMissing = (response: Difference) => {
  const source = convertToXorable(response.source);
  const target = convertToXorable(response.target);
 
  if (source ^ target) {
    ['source', 'target'].forEach(value => {
      response[value] = response[value] ? 'exists' : 'missing';
    });
 
    return response;
  }
 
  return response;
};
 
/**
 * Checks if objects are primitive types.
 */
export const oneIsPrimitive = (source: any, target: any) => {
  // eslint-disable-next-line eqeqeq
  if (source == null || target == null) {
    return true;
  }
 
  return source !== Object(source) && target !== Object(target);
};
 
/**
 * Format not matching message for CLI logging.
 */
export const formatNotMatchingLog = (message: Difference) => {
  const flattenMessage = setValuesIfMissing(message);
 
  Object.keys(flattenMessage).forEach(key => {
    if (key === 'message' || key === 'path') {
      console.log(message[key]);
    } else {
      console.log(`${key}: ${message[key]}`);
    }
  });
};
 
/**
 * 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];
};
 
/**
 * Gets the folder path of the manifest file, dependencies from manifest file and install argument from the given arguments.
 */
export const getOptionsFromArgs = async (commandArgs: {
  manifest: string;
  install: boolean | undefined;
}) => {
  const {manifest, install} = commandArgs;
  const folderPath = path.dirname(manifest);
  const loadedManifest = await load(manifest);
  const rawManifest = loadedManifest.rawManifest;
  const plugins = rawManifest?.initialize?.plugins || {};
  const dependencies = rawManifest?.execution?.environment.dependencies || [];
 
  if (!dependencies.length) {
    throw new MissingPluginDependenciesError(FAILURE_MESSAGE_DEPENDENCIES);
  }
 
  const pathsWithVersion = extractPathsWithVersion(plugins, dependencies);
 
  return {
    folderPath,
    dependencies: pathsWithVersion,
    install,
  };
};
 
/**
 * Creates folder if not exists, installs dependencies if required, update depenedencies.
 */
export const initializeAndInstallLibs = async (options: EnvironmentOptions) => {
  try {
    const {folderPath, install, cwd, dependencies} = options;
    const packageJsonPath = await initPackageJsonIfNotExists(folderPath);
 
    await updatePackageJsonProperties(packageJsonPath, cwd);
 
    if (install) {
      await installDependencies(folderPath, dependencies);
    } else {
      await updatePackageJsonDependencies(packageJsonPath, dependencies, cwd);
    }
  } catch (error) {
    console.log(FAILURE_MESSAGE);
    process.exit(2);
  }
};
 
/**
 * Adds a manifest template to the folder where the if-env CLI command runs.
 */
export const addTemplateManifest = async (destinationDir: string) => {
  try {
    const templateManifest = path.resolve(
      __dirname,
      '../config/env-template.yml'
    );
 
    const destinationPath = path.resolve(destinationDir, 'manifest.yml');
    const data = await fs.readFile(templateManifest, 'utf-8');
 
    await fs.writeFile(destinationPath, data, 'utf-8');
  } catch (error) {
    console.log(FAILURE_MESSAGE_TEMPLATE);
    process.exit(1);
  }
};