All files / if-merge/util helpers.ts

100% Statements 30/30
100% Branches 6/6
100% Functions 4/4
100% Lines 29/29

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 771x   1x   1x   1x           1x 5x 5x   5x 1x   5x           5x   5x           1x 5x   5x 10x 10x 10x 10x   10x 10x         10x 10x           5x           1x         5x 1x     5x       5x    
import * as path from 'path';
 
import {getFileName, getYamlFiles} from '../../common/util/fs';
import {Context} from '../../common/types/manifest';
import {load} from '../../common/lib/load';
 
import {exhaust} from '../../if-run/lib/exhaust';
import {IFMergeArgs} from '../types/process-args';
 
/**
 * Merges the given manifests in the one file.
 */
export const mergeManifests = async (mergeArgs: IFMergeArgs) => {
  const {manifests: commandManifests, output, name, description} = mergeArgs;
  let manifests = commandManifests;
 
  if (commandManifests.length === 1) {
    manifests = await getYamlFiles(commandManifests[0]);
  }
  const context = {
    name: name || 'if-merge',
    description: description || 'merged manifest',
    tags: null,
    initialize: {plugins: {}},
  };
  const tree = await mergeManifestsData(manifests, context);
 
  await saveMergedManifest(tree, context, output);
};
 
/**
 * Merges manifests data.
 */
const mergeManifestsData = async (manifests: string[], context: Context) => {
  const tree: any = {children: {}};
 
  for await (const manifest of manifests) {
    const manifestName = getFileName(manifest);
    const {rawManifest} = await load(manifest);
    const parentDir = path.basename(path.dirname(manifest));
    const uniqueName = `${parentDir}-${manifestName}`;
 
    context.tags = Object.assign({}, context.tags, rawManifest.tags);
    context.initialize.plugins = {
      ...context.initialize.plugins,
      ...rawManifest.initialize.plugins,
    };
 
    Object.keys(rawManifest.tree.children).forEach(child => {
      tree.children[`${child}-${uniqueName}`] = {
        ...rawManifest.tree.children[child],
      };
    });
  }
 
  return tree;
};
 
/**
 * Saves the merged manifest in the `merged-manifest.yaml` file.
 */
const saveMergedManifest = async (
  tree: any,
  context: Context,
  outputPath: string | undefined
) => {
  if (outputPath?.endsWith('/')) {
    outputPath += 'merged-manifest';
  }
 
  const output = {
    outputPath,
    noOutput: false,
  };
  await exhaust(tree, context, output);
};