Skip to content

Commit

Permalink
refactor: migrate bazel, benchpress, elements and misc to prettier fo…
Browse files Browse the repository at this point in the history
…rmatting (angular#53995)

Migrate formatting to prettier for bazel, benchpress, elements and misc from clang-format

PR Close angular#53995
  • Loading branch information
josephperrott authored and ChellappanRajan committed Jan 23, 2024
1 parent 7be1f28 commit fc2bb8f
Show file tree
Hide file tree
Showing 90 changed files with 3,865 additions and 2,950 deletions.
8 changes: 8 additions & 0 deletions .ng-dev/format.mts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ export const format: FormatConfig = {
'modules/**/*.{js,ts}',
'scripts/**/*.{js,ts}',
'packages/animations/**/*.{js,ts}',
'packages/bazel/**/*.{js,ts}',
'packages/benchpress/**/*.{js,ts}',
'packages/elements/**/*.{js,ts}',
'packages/misc/**/*.{js,ts}',
],
},
'clang-format': {
Expand Down Expand Up @@ -45,6 +49,10 @@ export const format: FormatConfig = {
'!modules/**/*.{js,ts}',
'!scripts/**/*.{js,ts}',
'!packages/animations/**/*.{js,ts}',
'!packages/bazel/**/*.{js,ts}',
'!packages/benchpress/**/*.{js,ts}',
'!packages/elements/**/*.{js,ts}',
'!packages/misc/**/*.{js,ts}',
],
},
'buildifier': true,
Expand Down
2 changes: 1 addition & 1 deletion packages/bazel/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ pkg_npm(
) + [
"//packages/bazel/src:package_assets",
"//packages/bazel/src/ng_module:package_assets",
"//packages/bazel/src/types_bundle:package_assets",
"//packages/bazel/src/ng_package:package_assets",
"//packages/bazel/src/ngc-wrapped:package_assets",
"//packages/bazel/src/types_bundle:package_assets",
"//packages/bazel/third_party/github.com/bazelbuild/bazel/src/main/protobuf:package_assets",
],
substitutions = {
Expand Down
34 changes: 21 additions & 13 deletions packages/bazel/src/ng_package/cross_entry_points_imports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@ const skipComment = '// @ng_package: ignore-cross-repo-import';
* forbidden (unless explicitly opted out via comment - {@link skipComment}).
*/
export function analyzeFileAndEnsureNoCrossImports(
file: BazelFileInfo, pkg: PackageMetadata): string[] {
file: BazelFileInfo,
pkg: PackageMetadata,
): string[] {
const content = fs.readFileSync(file.path, 'utf8');
const sf = ts.createSourceFile(file.path, content, ts.ScriptTarget.Latest, true);
const fileDirPath = path.posix.dirname(file.path);
Expand All @@ -57,26 +59,28 @@ export function analyzeFileAndEnsureNoCrossImports(
}
// Skip this import if there is an explicit skip comment.
const leadingComments = ts.getLeadingCommentRanges(sf.text, st.getFullStart());
if (leadingComments !== undefined &&
leadingComments.some(c => sf.text.substring(c.pos, c.end) === skipComment)) {
if (
leadingComments !== undefined &&
leadingComments.some((c) => sf.text.substring(c.pos, c.end) === skipComment)
) {
continue;
}

const destinationPath = path.posix.join(fileDirPath, st.moduleSpecifier.text);
const targetPackage = determineOwningEntryPoint({path: destinationPath}, pkg);
if (targetPackage === null) {
failures.push(
`Could not determine owning entry-point package of: ${destinationPath}. Imported from: ${
fileDebugName}. Is this a relative import to another full package?.\n` +
`You can skip this import by adding a comment: ${skipComment}`);
`Could not determine owning entry-point package of: ${destinationPath}. Imported from: ${fileDebugName}. Is this a relative import to another full package?.\n` +
`You can skip this import by adding a comment: ${skipComment}`,
);
continue;
}

if (targetPackage.path !== owningPkg.path) {
failures.push(
`Found relative cross entry-point import in: ${fileDebugName}. Import to: ${
st.moduleSpecifier.text}\n` +
`You can skip this import by adding a comment: ${skipComment}`);
`Found relative cross entry-point import in: ${fileDebugName}. Import to: ${st.moduleSpecifier.text}\n` +
`You can skip this import by adding a comment: ${skipComment}`,
);
}
}

Expand All @@ -85,8 +89,10 @@ export function analyzeFileAndEnsureNoCrossImports(

/** Determines the owning entry-point for the given JavaScript file. */
function determineOwningEntryPoint(
file: Pick<BazelFileInfo, 'path'>, pkg: PackageMetadata): EntryPointPackage|null {
let owningEntryPoint: EntryPointPackage|null = null;
file: Pick<BazelFileInfo, 'path'>,
pkg: PackageMetadata,
): EntryPointPackage | null {
let owningEntryPoint: EntryPointPackage | null = null;

for (const [name, info] of Object.entries(pkg.entryPoints)) {
// Entry point directory is assumed because technically the entry-point
Expand All @@ -96,8 +102,10 @@ function determineOwningEntryPoint(
// the entry-point.
const assumedEntryPointDir = path.posix.dirname(info.index.path);

if (file.path.startsWith(assumedEntryPointDir) &&
(owningEntryPoint === null || owningEntryPoint.path.length < assumedEntryPointDir.length)) {
if (
file.path.startsWith(assumedEntryPointDir) &&
(owningEntryPoint === null || owningEntryPoint.path.length < assumedEntryPointDir.length)
) {
owningEntryPoint = {name, info, path: assumedEntryPointDir};
}
}
Expand Down
127 changes: 70 additions & 57 deletions packages/bazel/src/ng_package/packager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,10 @@ import {analyzeFileAndEnsureNoCrossImports} from './cross_entry_points_imports';
* List of known `package.json` fields which provide information about
* supported package formats and their associated entry paths.
*/
const knownFormatPackageJsonFormatFields = [
'main',
'esm2022',
'esm',
'typings',
'module',
] as const;
const knownFormatPackageJsonFormatFields = ['main', 'esm2022', 'esm', 'typings', 'module'] as const;

/** Union type matching known `package.json` format fields. */
type KnownPackageJsonFormatFields = typeof knownFormatPackageJsonFormatFields[number];
type KnownPackageJsonFormatFields = (typeof knownFormatPackageJsonFormatFields)[number];

/**
* Type describing the conditional exports descriptor for an entry-point.
Expand All @@ -41,7 +35,7 @@ type ConditionalExport = {
/** Type describing a `package.json` the packager deals with. */
type PackageJson = {
[key in KnownPackageJsonFormatFields]?: string;
}&{
} & {
name: string;
type?: string;
exports?: Record<string, ConditionalExport>;
Expand All @@ -64,29 +58,29 @@ function main(args: string[]): void {
const params = fs.readFileSync(paramFilePath, 'utf-8').split('\n').map(unquoteParameter);

const [
// Output directory for the npm package.
outputDirExecPath,
// Output directory for the npm package.
outputDirExecPath,

// The package segment of the ng_package rule's label (e.g. 'package/common').
owningPackageName,
// The package segment of the ng_package rule's label (e.g. 'package/common').
owningPackageName,

// JSON data capturing metadata of the package being built. See `PackageMetadata`.
metadataArg,
// JSON data capturing metadata of the package being built. See `PackageMetadata`.
metadataArg,

// Path to the package's README.md.
readmeMd,
// Path to the package's README.md.
readmeMd,

// List of rolled-up flat ES2022 modules
fesm2022Arg,
// List of rolled-up flat ES2022 modules
fesm2022Arg,

// List of individual ES2022 modules
esm2022Arg,
// List of individual ES2022 modules
esm2022Arg,

// List of static files that should be copied into the package.
staticFilesArg,
// List of static files that should be copied into the package.
staticFilesArg,

// List of all type definitions that need to packaged into the ng_package.
typeDefinitionsArg,
// List of all type definitions that need to packaged into the ng_package.
typeDefinitionsArg,
] = params;

const fesm2022 = JSON.parse(fesm2022Arg) as BazelFileInfo[];
Expand All @@ -105,7 +99,7 @@ function main(args: string[]): void {
* file is written to.
* @param fileContent Content of the file.
*/
function writeFile(outputRelativePath: string, fileContent: string|Buffer) {
function writeFile(outputRelativePath: string, fileContent: string | Buffer) {
const outputPath = path.join(outputDirExecPath, outputRelativePath);

// Always ensure that the target directory exists.
Expand Down Expand Up @@ -192,7 +186,7 @@ function main(args: string[]): void {

const crossEntryPointFailures: string[] = [];

esm2022.forEach(file => {
esm2022.forEach((file) => {
crossEntryPointFailures.push(...analyzeFileAndEnsureNoCrossImports(file, metadata));
writeEsm2022File(file);
});
Expand All @@ -203,12 +197,12 @@ function main(args: string[]): void {
}

// Copy all FESM files into the package output.
fesm2022.forEach(f => copyFile(f.path, getFlatEsmOutputRelativePath(f)));
fesm2022.forEach((f) => copyFile(f.path, getFlatEsmOutputRelativePath(f)));

// Copy all type definitions into the package, preserving the sub-path from the
// owning package. e.g. a file like `packages/animations/browser/__index.d.ts` will
// end up in `browser/index.d.ts`
typeDefinitions.forEach(f => copyFile(f.path, getTypingOutputRelativePath(f)));
typeDefinitions.forEach((f) => copyFile(f.path, getTypingOutputRelativePath(f)));

for (const file of staticFiles) {
// We copy all files into the package output while preserving the sub-path from
Expand All @@ -226,20 +220,25 @@ function main(args: string[]): void {
// Resolution in the package should only be based on the top-level `package.json`.
if (!isPrimaryPackageJson) {
throw Error(
`Found a nested "package.json" file in the package output: ${file.shortPath}.\n` +
`All information of the package should reside in the primary package file.`);
`Found a nested "package.json" file in the package output: ${file.shortPath}.\n` +
`All information of the package should reside in the primary package file.`,
);
}

// Check if the `name` field of the `package.json` files are matching with
// name of the NPM package. This is an additional safety check.
if (packageName !== metadata.npmPackageName) {
throw Error(
`Primary "package.json" has mismatching package name. Expected the ` +
`package to be named "${metadata.npmPackageName}", but is set to: ${packageName}.`);
`Primary "package.json" has mismatching package name. Expected the ` +
`package to be named "${metadata.npmPackageName}", but is set to: ${packageName}.`,
);
}

let newPackageJson =
insertFormatFieldsIntoPackageJson(outputRelativePath, packageJson, false);
let newPackageJson = insertFormatFieldsIntoPackageJson(
outputRelativePath,
packageJson,
false,
);

newPackageJson = updatePrimaryPackageJson(newPackageJson);

Expand All @@ -260,8 +259,10 @@ function main(args: string[]): void {
* @param isGeneratedPackageJson Whether the passed package.json has been generated.
*/
function insertFormatFieldsIntoPackageJson(
packageJsonOutRelativePath: string, parsedPackage: Readonly<PackageJson>,
isGeneratedPackageJson: boolean): PackageJson {
packageJsonOutRelativePath: string,
parsedPackage: Readonly<PackageJson>,
isGeneratedPackageJson: boolean,
): PackageJson {
const packageJson: PackageJson = {...parsedPackage};
const packageName = packageJson['name'];
const entryPointInfo = metadata.entryPoints[packageName];
Expand All @@ -280,30 +281,37 @@ function main(args: string[]): void {
console.error('WARNING: no module metadata for package', packageName);
console.error(' Not updating the package.json file to point to it');
console.error(
' The ng_module for this package is possibly missing the module_name attribute ');
' The ng_module for this package is possibly missing the module_name attribute ',
);
return packageJson;
}

// If we guessed the index paths for a module, and it contains an explicit `package.json`
// file that already sets format properties, we skip automatic insertion of format
// properties but report a warning in case properties have been set by accident.
if (entryPointInfo.guessedPaths && !isGeneratedPackageJson &&
hasExplicitFormatProperties(packageJson)) {
if (
entryPointInfo.guessedPaths &&
!isGeneratedPackageJson &&
hasExplicitFormatProperties(packageJson)
) {
console.error('WARNING: `package.json` explicitly sets format properties (like `main`).');
console.error(
' Skipping automatic insertion of format properties as explicit ' +
'format properties are set.');
' Skipping automatic insertion of format properties as explicit ' +
'format properties are set.',
);
console.error(' Ignore this warning if explicit properties are set intentionally.');
return packageJson;
}

const fesm2022RelativeOutPath = getFlatEsmOutputRelativePath(entryPointInfo.fesm2022Bundle);
const typingsRelativeOutPath = getTypingOutputRelativePath(entryPointInfo.typings);

packageJson.module =
normalizePath(path.relative(packageJsonContainingDir, fesm2022RelativeOutPath));
packageJson.typings =
normalizePath(path.relative(packageJsonContainingDir, typingsRelativeOutPath));
packageJson.module = normalizePath(
path.relative(packageJsonContainingDir, fesm2022RelativeOutPath),
);
packageJson.typings = normalizePath(
path.relative(packageJsonContainingDir, typingsRelativeOutPath),
);

return packageJson;
}
Expand All @@ -315,8 +323,9 @@ function main(args: string[]): void {
function updatePrimaryPackageJson(packageJson: Readonly<PackageJson>): PackageJson {
if (packageJson.type !== undefined) {
throw Error(
'The primary "package.json" file of the package sets the "type" field ' +
'that is controlled by the packager. Please unset it.');
'The primary "package.json" file of the package sets the "type" field ' +
'that is controlled by the packager. Please unset it.',
);
}

const newPackageJson: PackageJson = {...packageJson};
Expand All @@ -330,8 +339,9 @@ function main(args: string[]): void {
// Capture all entry-points in the `exports` field using the subpath export declarations:
// https://nodejs.org/api/packages.html#packages_subpath_exports.
for (const [moduleName, entryPoint] of Object.entries(metadata.entryPoints)) {
const subpath =
isSecondaryEntryPoint(moduleName) ? `./${getEntryPointSubpath(moduleName)}` : '.';
const subpath = isSecondaryEntryPoint(moduleName)
? `./${getEntryPointSubpath(moduleName)}`
: '.';
const esmIndexOutRelativePath = getEsm2022OutputRelativePath(entryPoint.index);
const fesm2022OutRelativePath = getFlatEsmOutputRelativePath(entryPoint.fesm2022Bundle);
const typesOutRelativePath = getTypingOutputRelativePath(entryPoint.typings);
Expand All @@ -356,7 +366,10 @@ function main(args: string[]): void {
* @throws An error if the mapping is already defined and would conflict.
*/
function insertExportMappingOrError(
packageJson: PackageJson, subpath: string, mapping: ConditionalExport) {
packageJson: PackageJson,
subpath: string,
mapping: ConditionalExport,
) {
if (packageJson.exports === undefined) {
packageJson.exports = {};
}
Expand All @@ -372,8 +385,9 @@ function main(args: string[]): void {
for (const conditionName of Object.keys(mapping) as [keyof ConditionalExport]) {
if (subpathExport[conditionName] !== undefined) {
throw Error(
`Found a conflicting export condition for "${subpath}". The "${conditionName}" ` +
`condition would be overridden by the packager. Please unset it.`);
`Found a conflicting export condition for "${subpath}". The "${conditionName}" ` +
`condition would be overridden by the packager. Please unset it.`,
);
}

// **Note**: The order of the conditions is preserved even though we are setting
Expand All @@ -384,10 +398,9 @@ function main(args: string[]): void {

/** Whether the package explicitly sets any of the format properties (like `main`). */
function hasExplicitFormatProperties(parsedPackage: Readonly<PackageJson>): boolean {
return Object.keys(parsedPackage)
.some(
(fieldName: string) => knownFormatPackageJsonFormatFields.includes(
fieldName as KnownPackageJsonFormatFields));
return Object.keys(parsedPackage).some((fieldName: string) =>
knownFormatPackageJsonFormatFields.includes(fieldName as KnownPackageJsonFormatFields),
);
}

/**
Expand Down
Loading

0 comments on commit fc2bb8f

Please sign in to comment.