All files / build-tools patch-set.ts

54.23% Statements 64/118
37.25% Branches 19/51
55% Functions 11/20
55.85% Lines 62/111

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            1x 1x 1x     1x                           1x                                               1x 8x   8x 16x   16x   12x 12x 11x   3x 3x   1x 1x 1x 1x       7x     16x                   1x               1x         1x                   13x 13x       13x 17x   17x 2x 2x 2x       2x 1x   1x   1x       15x           3x   3x 3x 3x   3x 3x                                                       3x 3x 3x     5x   5x 3x 3x     3x   3x   2x                             2x 2x     2x           3x                         6x     6x 1x   5x                                                                     1x              
 
/**
 * Apply a JSON patch set into the given target file
 *
 * The sources can be taken from one or more directories.
 */
import * as path from 'path';
import * as fastJsonPatch from 'fast-json-patch';
import * as fs from 'fs-extra';
 
// eslint-disable-next-line @typescript-eslint/no-require-imports
const sortJson = require('sort-json');
 
export interface PatchOptions {
  readonly quiet?: boolean;
}
 
export type PatchSet = Record<string, PatchSetElement>;
 
export type PatchSetElement =
  | { readonly type: 'fragment'; readonly data: any }
  | { readonly type: 'patch'; readonly data: any }
  | { readonly type: 'set'; readonly sources: PatchSet }
  ;
 
export async function loadPatchSet(sourceDirectory: string, relativeTo = process.cwd()): Promise<PatchSet> {
  const ret: PatchSet = {};
 
  const files = await fs.readdir(sourceDirectory);
  for (const file of files) {
    const fullFile = path.join(sourceDirectory, file);
    const relName = path.relative(relativeTo, fullFile);
 
    if ((await fs.stat(fullFile)).isDirectory()) {
      ret[relName] = {
        type: 'set',
        sources: await loadPatchSet(fullFile, sourceDirectory),
      };
    } else Iif (file.endsWith('.json')) {
      ret[relName] = {
        type: file.indexOf('patch') === -1 ? 'fragment' : 'patch',
        data: await fs.readJson(fullFile),
      };
    }
  }
 
  return ret;
}
 
export function evaluatePatchSet(sources: PatchSet, options: PatchOptions = {}) {
  const targetObject: any = {};
 
  for (const key of Object.keys(sources).sort()) {
    const value = sources[key];
 
    switch (value.type) {
      case 'fragment':
        log(key);
        merge(targetObject, value.data, []);
        break;
      case 'patch':
        patch(targetObject, value.data, (m) => log(`${key}: ${m}`));
        break;
      case 'set':
        const evaluated = evaluatePatchSet(value.sources, options);
        log(key);
        merge(targetObject, evaluated, []);
        break;
    }
  }
 
  return targetObject;
 
  function log(x: string) {
    Iif (!options.quiet) {
      // eslint-disable-next-line no-console
      console.log(x);
    }
  }
}
 
/**
 * Load a patch set from a directory
 */
export async function applyPatchSet(sourceDirectory: string, options: PatchOptions = {}) {
  const patches = await loadPatchSet(sourceDirectory);
  return evaluatePatchSet(patches, options);
}
 
/**
 * Load a patch set and write it out to a file
 */
export async function applyAndWrite(targetFile: string, sourceDirectory: string, options: PatchOptions = {}) {
  const model = await applyPatchSet(sourceDirectory, options);
  await writeSorted(targetFile, model);
}
 
export async function writeSorted(targetFile: string, data: any) {
  await fs.mkdirp(path.dirname(targetFile));
  await fs.writeJson(targetFile, sortJson(data), { spaces: 2 });
}
 
function printSorted(data: any) {
  process.stdout.write(JSON.stringify(sortJson(data), undefined, 2));
}
 
function merge(target: any, fragment: any, jsonPath: string[]) {
  Iif (!fragment) { return; }
  Iif (!target || typeof target !== 'object' || Array.isArray(target)) {
    throw new Error(`Expected object, found: '${target}' at '$.${jsonPath.join('.')}'`);
  }
 
  for (const key of Object.keys(fragment)) {
    Iif (key.startsWith('$')) { continue; }
 
    if (key in target) {
      const specVal = target[key];
      const fragVal = fragment[key];
      Iif (typeof specVal !== typeof fragVal) {
        // eslint-disable-next-line max-len
        throw new Error(`Attempted to merge ${JSON.stringify(fragVal)} into incompatible ${JSON.stringify(specVal)} at path ${jsonPath.join('/')}/${key}`);
      }
      if (specVal == fragVal) {
        continue;
      }
      if (typeof specVal !== 'object') {
        // eslint-disable-next-line max-len
        throw new Error(`Conflict when attempting to merge ${JSON.stringify(fragVal)} into ${JSON.stringify(specVal)} at path ${jsonPath.join('/')}/${key}`);
      }
      merge(specVal, fragVal, [...jsonPath, key]);
    } else {
      target[key] = fragment[key];
    }
  }
}
 
function patch(target: any, fragment: any, log: (x: string) => void) {
  Iif (!fragment) { return; }
 
  const patches = findPatches(target, fragment);
  for (const p of patches) {
    log(p.description ?? '');
 
    try {
      fastJsonPatch.applyPatch(target, p.operations);
    } catch (e) {
      throw new Error(`error applying patch: ${JSON.stringify(p, undefined, 2)}: ${e.message}`);
    }
  }
}
 
interface Patch {
  readonly description?: string;
  readonly operations: Operation[];
}
 
type Operation =
  | { readonly op: 'add'; readonly path: string; readonly value: any }
  | { readonly op: 'remove'; readonly path: string }
  | { readonly op: 'replace'; readonly path: string; readonly value: any }
  | { readonly op: 'copy'; readonly path: string; readonly from: string }
  | { readonly op: 'move'; readonly path: string; readonly from: string }
  | { readonly op: 'test'; readonly path: string; readonly value: any }
  ;
 
/**
 * Find the sets of patches to apply in a document
 *
 * Adjusts paths to be root-relative, which makes it possible to have paths
 * point outside the patch scope.
 */
function findPatches(data: any, patchSource: any): Patch[] {
  const ret: Patch[] = [];
  recurse(data, patchSource, []);
  return ret;
 
  function recurse(actualData: any, fragment: any, jsonPath: string[]) {
    Iif (!fragment) { return; }
 
    if ('patch' in fragment) {
      const p = fragment.patch;
      Iif (!p.operations) {
        throw new Error(`Patch needs 'operations' key, got: ${JSON.stringify(p)}`);
      }
      ret.push({
        description: p.description,
        operations: p.operations.map((op: any) => adjustPaths(op, jsonPath)),
      });
    } else Iif ('patch:each' in fragment) {
      const p = fragment['patch:each'];
      Iif (typeof actualData !== 'object') {
        throw new Error(`Patch ${p.description}: expecting object in data, found '${actualData}'`);
      }
      Iif (!p.operations) {
        throw new Error(`Patch needs 'operations' key, got: ${JSON.stringify(p)}`);
      }
      for (const key in actualData) {
        ret.push({
          description: `${key}: ${p.description}`,
          operations: p.operations.map((op: any) => adjustPaths(op, [...jsonPath, key])),
        });
      }
    } else {
      for (const key of Object.keys(fragment)) {
        Iif (!(key in actualData)) {
          actualData[key] = {};
        }
        recurse(actualData[key], fragment[key], [...jsonPath, key]);
      }
    }
  }
 
  function adjustPaths(op: any, jsonPath: string[]): Operation {
    return {
      ...op,
      ...op.path ? { path: adjustPath(op.path, jsonPath) } : undefined,
      ...op.from ? { from: adjustPath(op.from, jsonPath) } : undefined,
    };
  }
 
  /**
   * Adjust path
   *
   * '$/' means from the root, otherwise interpret as relative path.
   */
  function adjustPath(originalPath: string, jsonPath: string[]): string {
    Iif (typeof originalPath !== 'string') {
      throw new Error(`adjustPath: expected string, got ${JSON.stringify(originalPath)}`);
    }
    if (originalPath.startsWith('$/')) {
      return originalPath.substr(1);
    }
    return jsonPath.map(p => `/${p}`).join('') + originalPath;
  }
}
 
 
/**
 * Run this file as a CLI tool, to apply a patch set from the command line
 */
async function main(args: string[]) {
  const quiet = eatArg('-q', args) || eatArg('--quiet', args);
 
  Iif (args.length < 1) {
    throw new Error('Usage: patch-set <DIR> [<FILE>]');
  }
 
  const [dir, targetFile] = args;
 
  const model = await applyPatchSet(dir, { quiet });
  if (targetFile) {
    await writeSorted(targetFile, model);
  } else {
    printSorted(model);
  }
}
 
function eatArg(arg: string, args: string[]) {
  for (let i = 0; i < args.length; i++) {
    Iif (args[i] === arg) {
      args.splice(i, 1);
      return true;
    }
  }
  return false;
}
 
Iif (require.main === module) {
  main(process.argv.slice(2)).catch(e => {
    process.exitCode = 1;
    // eslint-disable-next-line no-console
    console.error(e.message);
  });
}