Skip to content

feat(eslint-plugin): add rule 'sort-ngmodule-metadata-arrays' for array sort order of modules #386

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Apr 11, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions packages/eslint-plugin/docs/rules/sort-ngmodule-metadata-arrays.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Enforces sorting of values within NgModule metadata arrays (`sort-ngmodule-metadata-arrays`)

This rule enforces that NgModule metadata arrays have a sorted list of identifiers. Objects such as provider definitions, call expressions and computed members will be ignored for sorting purposes. Sorting is based on simple string localeCompare.

## Rule Details

Examples of **incorrect** code for this rule:

```ts
@NgModule({
providers: [_Provider, BProvider, AProvider, CProvider],
})
export class AppModule {}
```

Example of **correct** code for this rule:

```ts
@Component({
providers: [_Provider, AProvider, BProvider, CProvider],
})
export class AppComponent {}
```

## Options

There are no additional options for this rule

```json
{
"@angular-eslint/sort-ngmodule-metadata-arrays": ["error"]
}
```
1 change: 1 addition & 0 deletions packages/eslint-plugin/src/configs/all.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
"@angular-eslint/prefer-on-push-component-change-detection": "error",
"@angular-eslint/prefer-output-readonly": "error",
"@angular-eslint/relative-url-prefix": "error",
"@angular-eslint/sort-ngmodule-metadata-arrays": "error",
"@angular-eslint/use-component-selector": "error",
"@angular-eslint/use-component-view-encapsulation": "error",
"@angular-eslint/use-injectable-provided-in": "error",
Expand Down
4 changes: 4 additions & 0 deletions packages/eslint-plugin/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,9 @@ import preferOutputReadonly, {
import relativeUrlPrefix, {
RULE_NAME as relativeUrlPrefixRuleName,
} from './rules/relative-url-prefix';
import sortNgmoduleMetadataArrays, {
RULE_NAME as sortNgmoduleMetadataArraysName,
} from './rules/sort-ngmodule-metadata-arrays';
import useComponentSelector, {
RULE_NAME as useComponentSelectorRuleName,
} from './rules/use-component-selector';
Expand Down Expand Up @@ -132,6 +135,7 @@ export default {
[preferOnPushComponentChangeDetectionRuleName]: preferOnPushComponentChangeDetection,
[preferOutputReadonlyRuleName]: preferOutputReadonly,
[relativeUrlPrefixRuleName]: relativeUrlPrefix,
[sortNgmoduleMetadataArraysName]: sortNgmoduleMetadataArrays,
[useComponentSelectorRuleName]: useComponentSelector,
[useComponentViewEncapsulationRuleName]: useComponentViewEncapsulation,
[useInjectableProvidedInRuleName]: useInjectableProvidedIn,
Expand Down
69 changes: 69 additions & 0 deletions packages/eslint-plugin/src/rules/sort-ngmodule-metadata-arrays.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { TSESTree } from '@typescript-eslint/experimental-utils';
import { createESLintRule } from '../utils/create-eslint-rule';
import { MODULE_CLASS_DECORATOR } from '../utils/selectors';
import {
getDecoratorPropertyValue,
isArrayExpression,
isIdentifier,
} from '../utils/utils';

import type { NgModule } from '@angular/compiler/src/core';

type Options = [];
export const RULE_NAME = 'sort-ngmodule-metadata-arrays';
export type MessageIds = 'sortNgmoduleMetadataArrays';
const validProperties: (keyof NgModule)[] = [
'bootstrap',
'declarations',
'entryComponents',
'exports',
'imports',
'providers',
'schemas',
];

export default createESLintRule<Options, MessageIds>({
name: RULE_NAME,
meta: {
type: 'suggestion',
docs: {
description:
'Enforces ASC alphabetical order for NgModule metadata arrays for easy visual scanning',
category: 'Best Practices',
recommended: false,
},
schema: [],
messages: {
sortNgmoduleMetadataArrays:
'NgModule metadata arrays should be sorted in ASC alphabetical order',
},
},
defaultOptions: [],
create(context) {
return {
[MODULE_CLASS_DECORATOR](node: TSESTree.Decorator) {
validProperties.forEach((prop: keyof NgModule) => {
const initializer = getDecoratorPropertyValue(node, prop);
if (
!initializer ||
!isArrayExpression(initializer) ||
initializer.elements.length < 2
) {
return;
}
const unorderedNode = initializer.elements
.filter(isIdentifier)
.find(
({ name }, index, list) =>
name.localeCompare(list[index + 1]?.name) === 1,
);
if (!unorderedNode) return;
context.report({
messageId: 'sortNgmoduleMetadataArrays',
node: unorderedNode,
});
});
},
};
},
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
import {
convertAnnotatedSourceToFailureCase,
RuleTester,
} from '@angular-eslint/utils';
import rule, {
MessageIds,
RULE_NAME,
} from '../../src/rules/sort-ngmodule-metadata-arrays';

//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------

const ruleTester = new RuleTester({
parser: '@typescript-eslint/parser',
});

const messageIdSortFailure: MessageIds = 'sortNgmoduleMetadataArrays';

ruleTester.run(RULE_NAME, rule, {
valid: [
{
code: `
@NgModule({
imports: [
_foo,
AModule,
bModule,
cModule,
DModule,
],
bootstrap: [
AppModule1,
AppModule2,
AppModule3,
],
declarations: [
AComponent,
bDirective,
cPipe,
DComponent
],
providers: [
AProvider,
{
provide: 'myprovider',
useClass: MyProvider,
},
bProvider,
cProvider,
DProvider,
],
})
class Test {}
`,
},
],
invalid: [
convertAnnotatedSourceToFailureCase({
description: 'it should fail if imports array is not sorted ASC',
annotatedSource: `
@NgModule({
imports: [
aModule,
bModule,
DModule,
~~~~~~~
cModule,
]
})
class Test {}
`,
messageId: messageIdSortFailure,
}),
convertAnnotatedSourceToFailureCase({
description: 'it should fail if declarations array is not sorted ASC',
annotatedSource: `
@NgModule({
declarations: [
AComponent,
cPipe,
~~~~~
bDirective,
DComponent
],
})
class Test {}
`,
messageId: messageIdSortFailure,
}),
convertAnnotatedSourceToFailureCase({
description: 'it should fail if exports array is not sorted ASC',
annotatedSource: `
@NgModule({
exports: [
AComponent,
cPipe,
~~~~~
bDirective,
DComponent
],
})
class Test {}
`,
messageId: messageIdSortFailure,
}),
convertAnnotatedSourceToFailureCase({
description: 'it should fail if bootstrap array is not sorted ASC',
annotatedSource: `
@NgModule({
bootstrap: [
AppModule2,
AppModule3,
~~~~~~~~~~
AppModule1,
]
})
class Test {}
`,
messageId: messageIdSortFailure,
}),
convertAnnotatedSourceToFailureCase({
description: 'it should fail if schemas array is not sorted ASC',
annotatedSource: `
@NgModule({
schemas: [
A_SCHEMA,
C_SCHEMA,
~~~~~~~~
B_SCHEMA,
]
})
class Test {}
`,
messageId: messageIdSortFailure,
}),
convertAnnotatedSourceToFailureCase({
description:
'it should fail if providers array is not sorted ASC, but ignore objects',
annotatedSource: `
@NgModule({
imports: [
AProvider,
{
provide: 'myprovider',
useClass: MyProvider,
},
cProvider,
~~~~~~~~~
bProvider,
DProvider,
]
})
class Test {}
`,
messageId: messageIdSortFailure,
}),
],
});