Skip to content

Commit

Permalink
refactor(ngcc): move loadPackageJson() and related types to `utils.…
Browse files Browse the repository at this point in the history
…ts` (#45833)

Move the `loadPackageJson()` helper (and associated generic types, such
as `JsonObject`) from `packages/entry_point.ts` to `utils.ts` and also
rename it to `loadJson()`. This way, they can be used in other places in
future commits, without introducing cyclical dependencies.

PR Close #45833
  • Loading branch information
gkalpak authored and AndrewKushnir committed May 6, 2022
1 parent 06bfcb2 commit 018b917
Show file tree
Hide file tree
Showing 9 changed files with 70 additions and 33 deletions.
2 changes: 1 addition & 1 deletion packages/compiler-cli/ngcc/src/execution/cluster/api.ts
Expand Up @@ -7,7 +7,7 @@
*/

import {AbsoluteFsPath} from '../../../../src/ngtsc/file_system';
import {JsonObject} from '../../packages/entry_point';
import {JsonObject} from '../../utils';
import {PackageJsonChange} from '../../writing/package_json_updater';
import {Task, TaskProcessingOutcome} from '../tasks/api';

Expand Down
Expand Up @@ -11,7 +11,7 @@
import cluster from 'cluster';

import {AbsoluteFsPath} from '../../../../src/ngtsc/file_system';
import {JsonObject} from '../../packages/entry_point';
import {JsonObject} from '../../utils';
import {applyChange, PackageJsonChange, PackageJsonUpdate, PackageJsonUpdater} from '../../writing/package_json_updater';

import {sendMessageToMaster} from './utils';
Expand Down
4 changes: 2 additions & 2 deletions packages/compiler-cli/ngcc/src/execution/tasks/api.ts
Expand Up @@ -5,8 +5,8 @@
* 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
*/
import {EntryPoint, EntryPointJsonProperty, JsonObject} from '../../packages/entry_point';
import {PartiallyOrderedList} from '../../utils';
import {EntryPoint, EntryPointJsonProperty} from '../../packages/entry_point';
import {JsonObject, PartiallyOrderedList} from '../../utils';

/**
* Represents a unit of work to be undertaken by an `Executor`.
Expand Down
27 changes: 3 additions & 24 deletions packages/compiler-cli/ngcc/src/packages/entry_point.ts
Expand Up @@ -10,7 +10,7 @@ import ts from 'typescript';
import {AbsoluteFsPath, PathManipulation, ReadonlyFileSystem} from '../../../src/ngtsc/file_system';
import {Logger} from '../../../src/ngtsc/logging';
import {parseStatementForUmdModule} from '../host/umd_host';
import {resolveFileWithPostfixes} from '../utils';
import {JsonObject, loadJson, resolveFileWithPostfixes} from '../utils';

import {NgccConfiguration, NgccEntryPointConfig} from './configuration';

Expand Down Expand Up @@ -49,13 +49,6 @@ export interface EntryPoint extends JsonObject {
generateDeepReexports: boolean;
}

export type JsonPrimitive = string|number|boolean|null;
export type JsonValue = JsonPrimitive|JsonArray|JsonObject|undefined;
export interface JsonArray extends Array<JsonValue> {}
export interface JsonObject {
[key: string]: JsonValue;
}

export interface PackageJsonFormatPropertiesMap {
browser?: string;
fesm2015?: string;
Expand Down Expand Up @@ -135,10 +128,10 @@ export function getEntryPointInfo(
entryPointPath: AbsoluteFsPath): GetEntryPointResult {
const packagePackageJsonPath = fs.resolve(packagePath, 'package.json');
const entryPointPackageJsonPath = fs.resolve(entryPointPath, 'package.json');
const loadedPackagePackageJson = loadPackageJson(fs, packagePackageJsonPath);
const loadedPackagePackageJson = loadJson<EntryPointPackageJson>(fs, packagePackageJsonPath);
const loadedEntryPointPackageJson = (packagePackageJsonPath === entryPointPackageJsonPath) ?
loadedPackagePackageJson :
loadPackageJson(fs, entryPointPackageJsonPath);
loadJson<EntryPointPackageJson>(fs, entryPointPackageJsonPath);
const {packageName, packageVersion} = getPackageNameAndVersion(
fs, packagePath, loadedPackagePackageJson, loadedEntryPointPackageJson);
const repositoryUrl = getRepositoryUrl(loadedPackagePackageJson);
Expand Down Expand Up @@ -253,20 +246,6 @@ export function getEntryPointFormat(
}
}

/**
* Parse the JSON from a `package.json` file.
* @param packageJsonPath the absolute path to the `package.json` file.
* @returns JSON from the `package.json` file if it is valid, `null` otherwise.
*/
function loadPackageJson(
fs: ReadonlyFileSystem, packageJsonPath: AbsoluteFsPath): EntryPointPackageJson|null {
try {
return JSON.parse(fs.readFile(packageJsonPath)) as EntryPointPackageJson;
} catch {
return null;
}
}

function sniffModuleFormat(
fs: ReadonlyFileSystem, sourceFilePath: AbsoluteFsPath): EntryPointFormat|undefined {
const resolvedPath = resolveFileWithPostfixes(fs, sourceFilePath, ['', '.js', '/index.js']);
Expand Down
22 changes: 22 additions & 0 deletions packages/compiler-cli/ngcc/src/utils.ts
Expand Up @@ -10,6 +10,13 @@ import ts from 'typescript';
import {absoluteFrom, AbsoluteFsPath, isRooted, ReadonlyFileSystem} from '../../src/ngtsc/file_system';
import {DeclarationNode, KnownDeclaration} from '../../src/ngtsc/reflection';

export type JsonPrimitive = string|number|boolean|null;
export type JsonValue = JsonPrimitive|JsonArray|JsonObject|undefined;
export interface JsonArray extends Array<JsonValue> {}
export interface JsonObject {
[key: string]: JsonValue;
}

/**
* A list (`Array`) of partially ordered `T` items.
*
Expand Down Expand Up @@ -164,3 +171,18 @@ export function stripDollarSuffix(value: string): string {
export function stripExtension(fileName: string): string {
return fileName.replace(/\..+$/, '');
}

/**
* Parse the JSON from a `package.json` file.
*
* @param packageJsonPath The absolute path to the `package.json` file.
* @returns JSON from the `package.json` file if it exists and is valid, `null` otherwise.
*/
export function loadJson<T extends JsonObject = JsonObject>(
fs: ReadonlyFileSystem, packageJsonPath: AbsoluteFsPath): T|null {
try {
return JSON.parse(fs.readFile(packageJsonPath)) as T;
} catch {
return null;
}
}
Expand Up @@ -7,7 +7,7 @@
*/

import {AbsoluteFsPath, dirname, FileSystem} from '../../../src/ngtsc/file_system';
import {JsonObject, JsonValue} from '../packages/entry_point';
import {JsonObject, JsonValue} from '../utils';


export type PackageJsonChange = [string[], JsonValue, PackageJsonPropertyPositioning];
Expand Down
Expand Up @@ -13,7 +13,7 @@ import cluster from 'cluster';
import {absoluteFrom as _} from '../../../../src/ngtsc/file_system';
import {runInEachFileSystem} from '../../../../src/ngtsc/file_system/testing';
import {ClusterWorkerPackageJsonUpdater} from '../../../src/execution/cluster/package_json_updater';
import {JsonObject} from '../../../src/packages/entry_point';
import {JsonObject} from '../../../src/utils';
import {PackageJsonPropertyPositioning, PackageJsonUpdate, PackageJsonUpdater} from '../../../src/writing/package_json_updater';
import {mockProperty} from '../../helpers/spy_utils';

Expand Down
40 changes: 38 additions & 2 deletions packages/compiler-cli/ngcc/test/utils_spec.ts
Expand Up @@ -8,10 +8,11 @@

import ts from 'typescript';

import {absoluteFrom as _abs} from '../../src/ngtsc/file_system';
import {absoluteFrom as _abs, FileSystem, getFileSystem} from '../../src/ngtsc/file_system';
import {runInEachFileSystem} from '../../src/ngtsc/file_system/testing';
import {KnownDeclaration} from '../../src/ngtsc/reflection';
import {FactoryMap, getTsHelperFnFromDeclaration, getTsHelperFnFromIdentifier, isRelativePath, stripExtension} from '../src/utils';
import {loadTestFiles} from '../../src/ngtsc/testing';
import {FactoryMap, getTsHelperFnFromDeclaration, getTsHelperFnFromIdentifier, isRelativePath, loadJson, stripExtension} from '../src/utils';

describe('FactoryMap', () => {
it('should return an existing value', () => {
Expand Down Expand Up @@ -240,3 +241,38 @@ describe('stripExtension()', () => {
expect(stripExtension('/fo-o/b_ar')).toBe('/fo-o/b_ar');
});
});

runInEachFileSystem(() => {
let fs: FileSystem;

beforeEach(() => fs = getFileSystem());

describe('loadJson()', () => {
it('should load a `.json` file', () => {
const jsonData = {foo: 'yes', bar: 'sure'};
loadTestFiles([
{
name: _abs('/foo/bar.json'),
contents: `${JSON.stringify(jsonData)}\n`,
},
]);

expect(loadJson(fs, _abs('/foo/bar.json'))).toEqual(jsonData);
});

it('should return `null` if it fails to read the `.json` file', () => {
expect(loadJson(fs, _abs('/does/not/exist.json'))).toBeNull();
});

it('should return `null` if it fails to parse the `.json` file', () => {
loadTestFiles([
{
name: _abs('/foo/bar.txt'),
contents: '{This is not valid JSON.}',
},
]);

expect(loadJson(fs, _abs('/foo/bar.json'))).toBeNull();
});
});
});
Expand Up @@ -8,7 +8,7 @@
import {absoluteFrom, AbsoluteFsPath, FileSystem, getFileSystem} from '../../../src/ngtsc/file_system';
import {runInEachFileSystem} from '../../../src/ngtsc/file_system/testing';
import {loadTestFiles} from '../../../src/ngtsc/testing';
import {JsonObject} from '../../src/packages/entry_point';
import {JsonObject} from '../../src/utils';
import {DirectPackageJsonUpdater, PackageJsonUpdater} from '../../src/writing/package_json_updater';

runInEachFileSystem(() => {
Expand Down

0 comments on commit 018b917

Please sign in to comment.