fix(dev-infra): update type castings for JSON.parse usage (#40710)

Update usages of JSON.parse to be cast as specific types.

PR Close #40710
This commit is contained in:
Joey Perrott 2021-02-04 14:42:42 -08:00 committed by Alex Rickabaugh
parent 2c90391d4b
commit cbdb5e208e
14 changed files with 27 additions and 17 deletions

View File

@ -28,7 +28,7 @@ export class Buildifier extends Formatter {
commandFlags: `${BAZEL_WARNING_FLAG} --lint=warn --mode=check --format=json`,
callback:
(_: string, code: number, stdout: string) => {
return code !== 0 || !JSON.parse(stdout)['success'];
return code !== 0 || !(JSON.parse(stdout) as {success: string}).success;
},
},
format: {

View File

@ -2391,7 +2391,7 @@ class Buildifier extends Formatter {
check: {
commandFlags: `${BAZEL_WARNING_FLAG} --lint=warn --mode=check --format=json`,
callback: (_, code, stdout) => {
return code !== 0 || !JSON.parse(stdout)['success'];
return code !== 0 || !JSON.parse(stdout).success;
},
},
format: {

View File

@ -50,7 +50,7 @@ describe('ng-dev release build', () => {
expect(writeSpy).toHaveBeenCalledTimes(1);
const jsonText = writeSpy.calls.mostRecent().args[0] as string;
const parsed = JSON.parse(jsonText);
const parsed = JSON.parse(jsonText) as releaseConfig.BuiltPackage[];
expect(parsed).toEqual([
{name: '@angular/pkg1', outputPath: 'dist/pkg1'},

View File

@ -82,7 +82,8 @@ export abstract class ReleaseAction {
/** Updates the version in the project top-level `package.json` file. */
protected async updateProjectVersion(newVersion: semver.SemVer) {
const pkgJsonPath = join(this.projectDir, packageJsonPath);
const pkgJson = JSON.parse(await fs.readFile(pkgJsonPath, 'utf8'));
const pkgJson =
JSON.parse(await fs.readFile(pkgJsonPath, 'utf8')) as {version: string, [key: string]: any};
pkgJson.version = newVersion.format();
// Write the `package.json` file. Note that we add a trailing new line
// to avoid unnecessary diff. IDEs usually add a trailing new line.
@ -558,7 +559,8 @@ export abstract class ReleaseAction {
private async _verifyPackageVersions(version: semver.SemVer, packages: BuiltPackage[]) {
for (const pkg of packages) {
const {version: packageJsonVersion} =
JSON.parse(await fs.readFile(join(pkg.outputPath, 'package.json'), 'utf8'));
JSON.parse(await fs.readFile(join(pkg.outputPath, 'package.json'), 'utf8')) as
{version: string, [key: string]: any};
if (version.compare(packageJsonVersion) !== 0) {
error(red('The built package version does not match the version being released.'));
error(` Release Version: ${version.version}`);

View File

@ -64,7 +64,7 @@ export async function invokeReleaseBuildCommand(): Promise<BuiltPackage[]> {
info(green(' ✓ Built release output for all packages.'));
// The `ng-dev release build` command prints a JSON array to stdout
// that represents the built release packages and their output paths.
return JSON.parse(stdout.trim());
return JSON.parse(stdout.trim()) as BuiltPackage[];
} catch (e) {
spinner.stop();
error(e);

View File

@ -49,7 +49,7 @@ describe('cut next pre-release action', () => {
await expectStagingAndPublishWithoutCherryPick(action, 'master', '10.2.0-next.0', 'next');
const pkgJsonContents = readFileSync(join(action.testTmpDir, packageJsonPath), 'utf8');
const pkgJson = JSON.parse(pkgJsonContents);
const pkgJson = JSON.parse(pkgJsonContents) as {version: string, [key: string]: any};
expect(pkgJson.version).toBe('10.2.0-next.0', 'Expected version to not have changed.');
});

View File

@ -35,7 +35,8 @@ export async function getVersionOfBranch(
repo: GithubRepoWithApi, branchName: string): Promise<semver.SemVer> {
const {data} = await repo.api.repos.getContents(
{owner: repo.owner, repo: repo.name, path: '/package.json', ref: branchName});
const {version} = JSON.parse(Buffer.from(data.content, 'base64').toString());
const {version} = JSON.parse(Buffer.from(data.content, 'base64').toString()) as
{version: string, [key: string]: any};
const parsedVersion = semver.parse(version);
if (parsedVersion === null) {
throw Error(`Invalid version detected in following branch: ${branchName}.`);

View File

@ -93,7 +93,7 @@ export function main(
info(yellow(` Please rerun with "--warnings" to inspect unresolved imports.`));
}
const expected: Golden = JSON.parse(readFileSync(goldenFile, 'utf8'));
const expected = JSON.parse(readFileSync(goldenFile, 'utf8')) as Golden;
const {fixedCircularDeps, newCircularDeps} = compareGoldens(actual, expected);
const isMatching = fixedCircularDeps.length === 0 && newCircularDeps.length === 0;

View File

@ -42,7 +42,6 @@ describe('sourcemaps', function() {
Buffer.from(content.substring(index + marker.length), 'base64').toString('utf8');
const decoder = new SourceMapConsumer(JSON.parse(sourceMapData) as RawSourceMap);
const originalPosition = decoder.originalPositionFor({line: errorLine, column: errorColumn});
const sourceCodeLines = readFileSync(require.resolve('../../src/sourcemap/index.ts'), {
encoding: 'UTF-8'

View File

@ -112,12 +112,14 @@ describe('@angular/common ng_package', () => {
}
// https://github.com/angular/common-builds/blob/master/package.json
it('/', () => {
const actual = JSON.parse(fs.readFileSync('package.json', {encoding: 'utf-8'})) as PackageJson;
const actual =
JSON.parse(fs.readFileSync('package.json', {encoding: 'utf-8'})) as PackageJson;
expect(actual['main']).toEqual('./bundles/common.umd.js');
});
// https://github.com/angular/common-builds/blob/master/http/package.json
it('/http', () => {
const actual = JSON.parse(fs.readFileSync('http/package.json', {encoding: 'utf-8'})) as PackageJson;
const actual =
JSON.parse(fs.readFileSync('http/package.json', {encoding: 'utf-8'})) as PackageJson;
expect(actual['main']).toEqual('../bundles/common-http.umd.js');
expect(actual['es2015']).toEqual('../fesm2015/http.js');
expect(actual['module']).toEqual('../fesm2015/http.js');
@ -132,7 +134,8 @@ describe('@angular/common ng_package', () => {
// https://github.com/angular/common-builds/blob/master/http/testing/package.json
it('/http/testing', () => {
const actual =
JSON.parse(fs.readFileSync('http/testing/package.json', {encoding: 'utf-8'})) as PackageJson;
JSON.parse(fs.readFileSync('http/testing/package.json', {encoding: 'utf-8'})) as
PackageJson;
expect(actual['main']).toEqual('../../bundles/common-http-testing.umd.js');
expect(actual['es2015']).toEqual('../../fesm2015/http/testing.js');
expect(actual['module']).toEqual('../../fesm2015/http/testing.js');

View File

@ -86,7 +86,9 @@ export class ChromeDriverExtension extends WebDriverExtension {
.then((entries) => {
const events: PerfLogEvent[] = [];
entries.forEach((entry: any) => {
const message = (JSON.parse(entry['message']) as {message: any})['message'];
const message =
(JSON.parse(entry['message']) as
{message: {method: string, params: PerfLogEvent}})['message'];
if (message['method'] === 'Tracing.dataCollected') {
events.push(message['params']);
}

View File

@ -44,7 +44,9 @@ export class IOsDriverExtension extends WebDriverExtension {
.then((entries) => {
const records: any[] = [];
entries.forEach((entry: any) => {
const message = (JSON.parse(entry['message']) as {message: any})['message'];
const message =
(JSON.parse(entry['message']) as
{message: {method: string, params: PerfLogEvent}})['message'];
if (message['method'] === 'Timeline.eventRecorded') {
records.push(message['params']['record']);
}

View File

@ -50,7 +50,7 @@ import {Injector, JsonFileReporter, MeasureValues, Options, SampleDescription} f
[mv(0, 0, {'a': 3, 'b': 6}), mv(1, 1, {'a': 5, 'b': 9})]);
const regExp = /somePath\/someId_\d+\.json/;
expect(loggedFile['filename'].match(regExp) != null).toBe(true);
const parsedContent = JSON.parse(loggedFile['content']) as any;
const parsedContent = JSON.parse(loggedFile['content']) as {[key: string]: any};
expect(parsedContent).toEqual({
'description': {
'id': 'someId',

View File

@ -86,7 +86,8 @@ export function discoverAllEntrypoints(dirPath: string) {
// Get all typings file locations from package.json files
for (const packageJson of packageJsons) {
const packageJsonObj = JSON.parse(fs.readFileSync(packageJson, {encoding: 'utf8'})) as any;
const packageJsonObj =
JSON.parse(fs.readFileSync(packageJson, {encoding: 'utf8'})) as {typings: string};
const typings = packageJsonObj.typings;
if (typings) {
entryPoints.push(path.join(path.dirname(packageJson), typings));