Skip to content

Commit

Permalink
feat: add sort-decorators rule
Browse files Browse the repository at this point in the history
  • Loading branch information
hugop95 authored and azat-io committed Nov 19, 2024
1 parent 97adf51 commit 8fd2c4e
Show file tree
Hide file tree
Showing 7 changed files with 3,957 additions and 0 deletions.
362 changes: 362 additions & 0 deletions docs/content/rules/sort-decorators.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,362 @@
---
title: sort-decorators
description: Enforce sorting of decorators for improved readability and maintainability. Use this ESLint rule to keep your decorators well-organized
shortDescription: Enforce sorted decorators
keywords:
- eslint
- sort decorators
- eslint rule
- coding standards
- code quality
- javascript linting
- typescript decorators sorting
---

import CodeExample from '../../components/CodeExample.svelte'
import Important from '../../components/Important.astro'
import CodeTabs from '../../components/CodeTabs.svelte'
import { dedent } from 'ts-dedent'

Enforce sorted decorators.

Sorting decorators provides a clear and predictable structure to the codebase. This rule detects instances where decorators are not sorted and raises linting errors, encouraging developers to arrange elements in the desired order.

Consistently sorted decorators enhance the overall clarity and organization of your code.

## Try it out

<CodeExample
alphabetical={dedent`
@ApiDescription('Create a new user')
@Authenticated()
@Controller()
@Post('/users')
class CreateUserController {
@AutoInjected()
@NotNull()
userService: UserService;
@IsBoolean()
@NotNull()
accessor disableController: boolean;
@ApiError({ status: 400, description: 'Bad request' })
@ApiResponse({ status: 200, description: 'User created successfully' })
createUser(
@Body()
@IsNotEmpty()
@ValidateNested()
createUserDto: CreateUserDto
): UserDto {
// ...
}
}
`}
lineLength={dedent`
@ApiDescription('Create a new user')
@Authenticated()
@Post('/users')
@Controller()
class CreateUserController {
@AutoInjected()
@NotNull()
userService: UserService;
@IsBoolean()
@NotNull()
accessor disableController: boolean;
@ApiResponse({ status: 200, description: 'User created successfully' })
@ApiError({ status: 400, description: 'Bad request' })
createUser(
@ValidateNested()
@IsNotEmpty()
@Body()
createUserDto: CreateUserDto
): UserDto {
// ...
}
}
`}
initial={dedent`
@Post('/users')
@ApiDescription('Create a new user')
@Authenticated()
@Controller()
class CreateUserController {
@NotNull()
@AutoInjected()
userService: UserService;
@NotNull()
@IsBoolean()
accessor disableController: boolean;
@ApiError({ status: 400, description: 'Bad request' })
@ApiResponse({ status: 200, description: 'User created successfully' })
createUser(
@IsNotEmpty()
@ValidateNested()
@Body()
createUserDto: CreateUserDto
): UserDto {
// ...
}
}
`}
client:load
lang="tsx"
/>

## Options

This rule accepts an options object with the following properties:

### type

<sub>default: `'alphabetical'`</sub>

Specifies the sorting method.

- `'alphabetical'` — Sort items alphabetically (e.g., “a” < “b” < “c”).
- `'natural'` — Sort items in a natural order (e.g., “item2” < “item10”).
- `'line-length'` — Sort items by the length of the code line (shorter lines first).

### order

<sub>default: `'asc'`</sub>

Determines whether the sorted items should be in ascending or descending order.

- `'asc'` — Sort items in ascending order (A to Z, 1 to 9).
- `'desc'` — Sort items in descending order (Z to A, 9 to 1).

### ignoreCase

<sub>default: `true`</sub>

Controls whether sorting should be case-sensitive or not.

- `true` — Ignore case when sorting alphabetically or naturally (e.g., “A” and “a” are the same).
- `false` — Consider case when sorting (e.g., “A” comes before “a”).

### sortOnClasses

<sub>default: `true`</sub>

Controls whether sorting should be enabled for class decorators.

### sortOnMethods

<sub>default: `true`</sub>

Controls whether sorting should be enabled for class method decorators.

### sortOnProperties

<sub>default: `true`</sub>

Controls whether sorting should be enabled for class property decorators.

### sortOnAccessors

<sub>default: `true`</sub>

Controls whether sorting should be enabled for class auto-accessor decorators.

### sortOnParameters

<sub>default: `true`</sub>

Controls whether sorting should be enabled for method parameter decorators.

### specialCharacters

<sub>default: `keep`</sub>

Controls whether special characters should be trimmed, removed or kept before sorting.

- `'keep'` — Keep special characters when sorting (e.g., “_a” comes before “a”).
- `'trim'` — Trim special characters when sorting alphabetically or naturally (e.g., “_a” and “a” are the same).
- `'remove'` — Remove special characters when sorting (e.g., “/a/b” and “ab” are the same).

### partitionByComment

<sub>default: `false`</sub>

Allows you to use comments to separate class decorators into logical groups.

- `true` — All comments will be treated as delimiters, creating partitions.
- `false` — Comments will not be used as delimiters.
- `string` — A glob pattern to specify which comments should act as delimiters.
- `string[]` — An array of glob patterns to specify which comments should act as delimiters.

### groups

<sub>
type: `Array<string | string[]>`
</sub>
<sub>default: `[]`</sub>

Allows you to specify a list of decorator groups for sorting.

Predefined groups:

- `'unknown'` — Decorators that don’t fit into any group specified in the `groups` option.

If the `unknown` group is not specified in the `groups` option, it will automatically be added to the end of the list.

Each decorator will be assigned a single group specified in the `groups` option (or the `unknown` group if no match is found).
The order of items in the `groups` option determines how groups are ordered.

Within a given group, members will be sorted according to the `type`, `order`, `ignoreCase`, etc. options.

Individual groups can be combined together by placing them in an array. The order of groups in that array does not matter.
All members of the groups in the array will be sorted together as if they were part of a single group.

### customGroups

<sub>
type: `{ [groupName: string]: string | string[] }`
</sub>
<sub>default: `{}`</sub>

You can define your own groups and use custom glob patterns or regex to match specific decorators.

Use the `matcher` option to specify the pattern matching method.

Each key of `customGroups` represents a group name which you can then use in the `groups` option. The value for each key can either be of type:
- `string` — A decorator's name matching the value will be marked as part of the group referenced by the key.
- `string[]` — A decorator's name matching any of the values of the array will be marked as part of the group referenced by the key.
The order of values in the array does not matter.

Custom group matching takes precedence over predefined group matching.

#### Example for class decorators (same for the rest of the elements):

```ts

Put all error-related decorators at the bottom:

```ts
@Component()
@Validated()
@AtLeastOneAttributeError()
@NoPublicAttributeError()
class MyClass {
}
```

`groups` and `customGroups` configuration:

```js
{
groups: [
'unknown',
'error' // [!code ++]
],
+ customGroups: { // [!code ++]
+ error: '*Error' // [!code ++]
+ } // [!code ++]
}
```

### matcher

<sub>default: `'minimatch'`</sub>

Determines the matcher used for patterns in the `partitionByComment` and `customGroups` options.

- `'minimatch'`Use the [minimatch](https://github.com/isaacs/minimatch) library for pattern matching.
- `'regex'`Use regular expressions for pattern matching.

## Usage

<CodeTabs
code={[
{
source: dedent`
// eslint.config.js
import perfectionist from 'eslint-plugin-perfectionist'
export default [
{
plugins: {
perfectionist,
},
rules: {
'perfectionist/sort-decorators': [
'error',
{
type: 'alphabetical',
order: 'asc',
ignoreCase: true,
specialCharacters: 'keep',
matcher: 'minimatch',
groups: [],
customGroups: {},
sortOnClasses: true,
sortOnMethods: true,
sortOnAccessors: true,
sortOnProperties: true,
sortOnParameters: true,
},
],
},
},
]
`,
name: 'Flat Config',
value: 'flat',
},
{
source: dedent`
// .eslintrc.js
module.exports = {
plugins: [
'perfectionist',
],
rules: {
'perfectionist/sort-decorators': [
'error',
{
type: 'alphabetical',
order: 'asc',
ignoreCase: true,
specialCharacters: 'keep',
matcher: 'minimatch',
groups: [],
customGroups: {},
sortOnClasses: true,
sortOnMethods: true,
sortOnAccessors: true,
sortOnProperties: true,
sortOnParameters: true,
},
],
},
}
`,
name: 'Legacy Config',
value: 'legacy',
},
]}
type="config-type"
client:load
lang="ts"
/>

## Version

This rule was introduced in [v4.0.0](https://github.com/azat-io/eslint-plugin-perfectionist/releases/tag/v4.0.0).

## Resources

- [Rule source](https://github.com/azat-io/eslint-plugin-perfectionist/blob/main/rules/sort-decorators.ts)
- [Test source](https://github.com/azat-io/eslint-plugin-perfectionist/blob/main/test/sort-decorators.test.ts)
2 changes: 2 additions & 0 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import sortObjectTypes from './rules/sort-object-types'
import sortSwitchCase from './rules/sort-switch-case'
import sortUnionTypes from './rules/sort-union-types'
import sortInterfaces from './rules/sort-interfaces'
import sortDecorators from './rules/sort-decorators'
import sortJsxProps from './rules/sort-jsx-props'
import sortClasses from './rules/sort-classes'
import sortImports from './rules/sort-imports'
Expand Down Expand Up @@ -42,6 +43,7 @@ let plugin = {
'sort-object-types': sortObjectTypes,
'sort-union-types': sortUnionTypes,
'sort-switch-case': sortSwitchCase,
'sort-decorators': sortDecorators,
'sort-interfaces': sortInterfaces,
'sort-jsx-props': sortJsxProps,
'sort-classes': sortClasses,
Expand Down
1 change: 1 addition & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,7 @@ module.exports = {
| :--------------------------------------------------------------------------------------- | :------------------------------------------ | :-- |
| [sort-array-includes](https://perfectionist.dev/rules/sort-array-includes) | Enforce sorted arrays before include method | 🔧 |
| [sort-classes](https://perfectionist.dev/rules/sort-classes) | Enforce sorted classes | 🔧 |
| [sort-decorators](https://perfectionist.dev/rules/sort-decorators) | Enforce sorted decorators | 🔧 |
| [sort-enums](https://perfectionist.dev/rules/sort-enums) | Enforce sorted TypeScript enums | 🔧 |
| [sort-exports](https://perfectionist.dev/rules/sort-exports) | Enforce sorted exports | 🔧 |
| [sort-imports](https://perfectionist.dev/rules/sort-imports) | Enforce sorted imports | 🔧 |
Expand Down
Loading

0 comments on commit 8fd2c4e

Please sign in to comment.