refactor(@schematics/angular): use new JSON helpers in codelyzer-5 migration

This commit is contained in:
Charles Lyding 2020-09-23 18:49:22 -04:00 committed by Alan Agius
parent 8facdaee1b
commit 0589a59f15

View File

@ -5,8 +5,6 @@
* Use of this source code is governed by an MIT-style license that can be * Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import { JsonParseMode, parseJsonAst } from '@angular-devkit/core';
import { import {
Rule, Rule,
Tree, Tree,
@ -16,7 +14,7 @@ import {
NodeDependencyType, NodeDependencyType,
addPackageJsonDependency, addPackageJsonDependency,
} from '../../utility/dependencies'; } from '../../utility/dependencies';
import { findPropertyInAstObject } from '../../utility/json-utils'; import { JSONFile } from '../../utility/json-file';
const ruleMapping: {[key: string]: string} = { const ruleMapping: {[key: string]: string} = {
'contextual-life-cycle': 'contextual-lifecycle', 'contextual-life-cycle': 'contextual-lifecycle',
@ -44,34 +42,20 @@ const ruleMapping: {[key: string]: string} = {
export const updateTsLintConfig = (): Rule => { export const updateTsLintConfig = (): Rule => {
return (host: Tree) => { return (host: Tree) => {
const tsLintPath = '/tslint.json'; const tsLintPath = '/tslint.json';
const buffer = host.read(tsLintPath); let tsLintJson;
if (!buffer) { try {
return host; tsLintJson = new JSONFile(host, tsLintPath);
} } catch {
const tsCfgAst = parseJsonAst(buffer.toString(), JsonParseMode.Loose); return;
if (tsCfgAst.kind != 'object') {
return host;
} }
const rulesNode = findPropertyInAstObject(tsCfgAst, 'rules'); for (const [existingRule, newRule] of Object.entries(ruleMapping)) {
if (!rulesNode || rulesNode.kind != 'object') { const ruleValue = tsLintJson.get(['rules', existingRule]);
return host; if (ruleValue !== undefined) {
tsLintJson.remove(['rules', existingRule]);
tsLintJson.modify(['rules', newRule], ruleValue as boolean);
} }
const recorder = host.beginUpdate(tsLintPath);
rulesNode.properties.forEach(prop => {
const mapping = ruleMapping[prop.key.value];
if (mapping) {
recorder.remove(prop.key.start.offset + 1, prop.key.value.length);
recorder.insertLeft(prop.key.start.offset + 1, mapping);
} }
});
host.commitUpdate(recorder);
return host;
}; };
}; };