All files / src/utils/angular json-utils.ts

58.33% Statements 21/36
26.31% Branches 5/19
75% Functions 3/4
57.14% Lines 20/35

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 6745x   7x 7x   7x                 7x                             7x 1x 1x 1x   1x   1x                   1x   1x 1x 1x 1x                   7x 1x 1x 1x    
export { JSONFile } from '@schematics/angular/utility/json-file';
 
import { JsonAstObject, parseJsonAst, JsonParseMode, JsonValue } from '@angular-devkit/core';
import { SchematicsException } from '@angular-devkit/schematics';
import { Tree } from '@angular-devkit/schematics/src/tree/interface';
import { JSONFile } from '@schematics/angular/utility/json-file';
 
export interface ModuleAndTargetReplamenent {
  oldModule?: string;
  newModule?: string | false;
  oldTarget?: string;
  newTarget?: string;
}
 
export function readJsonFileAsAstObject(host: Tree, path: string): JsonAstObject | undefined {
  const configBuffer = host.read(path);
  Iif (!configBuffer) {
    return undefined;
  }
 
  const content = configBuffer.toString();
  const astContent = parseJsonAst(content, JsonParseMode.Loose);
  Iif (!astContent || astContent.kind !== 'object') {
    throw new SchematicsException(`Invalid JSON AST Object (${path})`);
  }
 
  return astContent;
}
 
export function updateModuleAndTarget(host: Tree, tsConfigPath: string, replacements: ModuleAndTargetReplamenent) {
  const tslint = new JSONFile(host, tsConfigPath);
  const targetPath = ['compilerOptions', 'target'];
  const modulePath = ['compilerOptions', 'module'];
 
  const { oldTarget, newTarget, newModule, oldModule } = replacements;
 
  Iif (newTarget) {
    const targetValue = tslint.get(targetPath);
    tslint.get([]);
    if (!targetValue && !oldTarget) {
      tslint.modify(targetPath, newTarget);
    } else Iif (typeof targetValue === 'string' && (!oldTarget || oldTarget === targetValue.toLowerCase())) {
      tslint.modify(targetPath, newTarget);
    }
  }
 
  Iif (newModule === false) {
    tslint.remove(modulePath);
  } else if (newModule) {
    const moduleValue = tslint.get(modulePath);
    if (typeof moduleValue === 'string' && oldModule === moduleValue.toLowerCase()) {
      tslint.modify(modulePath, newModule);
    }
  }
}
 
export interface TSLintRule {
  name: string;
  value: JsonValue;
}
 
export function addTslintRule(host: Tree, tsLintConfigPath: string, replacements: TSLintRule) {
  const tslint = new JSONFile(host, tsLintConfigPath);
  const { name, value } = replacements;
  tslint.modify(['rules', name], value);
}