-
Notifications
You must be signed in to change notification settings - Fork 2.8k
[ZEPPELIN-6372] Reimplement custom TSLint rules as ESLint rules #5279
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
Open
voidmatcha
wants to merge
1
commit into
apache:master
Choose a base branch
from
voidmatcha:ZEPPELIN-6372
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
173 changes: 173 additions & 0 deletions
173
zeppelin-web-angular/eslint-rules/constructor-params-order.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,173 @@ | ||
| /* | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| // ESLint reimplementation of the former custom TSLint `constructor-params-order` | ||
| // rule (ZEPPELIN-6301). Enforces the constructor parameter order | ||
| // public -> protected -> private (-> none -> optional) for a consistent New UI | ||
| // constructor style. ESLint replaces TSLint under ZEPPELIN-6372. | ||
|
|
||
| 'use strict'; | ||
|
|
||
| const RANK = { public: 0, protected: 1, private: 2, none: 3, optional: 4 }; | ||
|
|
||
| /** | ||
| * Collect decorators attached to a (possibly parameter-property) parameter node. | ||
| * @param {any} param | ||
| * @returns {any[]} | ||
| */ | ||
| function getDecorators(param) { | ||
| if (Array.isArray(param.decorators) && param.decorators.length > 0) { | ||
| return param.decorators; | ||
| } | ||
| // TSParameterProperty wraps the real parameter in `.parameter`. | ||
| if (param.parameter && Array.isArray(param.parameter.decorators)) { | ||
| return param.parameter.decorators; | ||
| } | ||
| return []; | ||
| } | ||
|
|
||
| /** | ||
| * True when the parameter is optional -- either annotated with `@Optional()` | ||
| * (Angular DI) or declared with a `?` question token. | ||
| * @param {any} param | ||
| * @returns {boolean} | ||
| */ | ||
| function isOptional(param) { | ||
| const hasOptionalDecorator = getDecorators(param).some(decorator => { | ||
| let expr = decorator.expression; | ||
| if (expr && expr.type === 'CallExpression') { | ||
| expr = expr.callee; | ||
| } | ||
| return expr && expr.type === 'Identifier' && expr.name === 'Optional'; | ||
| }); | ||
| if (hasOptionalDecorator) { | ||
| return true; | ||
| } | ||
| const inner = param.type === 'TSParameterProperty' ? param.parameter : param; | ||
| return !!(inner && inner.optional); | ||
| } | ||
|
|
||
| /** | ||
| * Map a constructor parameter to its accessibility rank. | ||
| * @param {any} param | ||
| * @returns {number} | ||
| */ | ||
| function getRank(param) { | ||
| if (isOptional(param)) { | ||
| return RANK.optional; | ||
| } | ||
| if (param.type === 'TSParameterProperty') { | ||
| // A parameter property with no explicit accessibility (e.g. `readonly x`) | ||
| // is implicitly public. | ||
| return RANK[param.accessibility || 'public']; | ||
| } | ||
| return RANK.none; | ||
| } | ||
|
|
||
| /** | ||
| * Source range of a parameter's "content": the parameter itself plus its | ||
| * leading decorators/comments and any trailing comment that sits before the | ||
| * following comma. Reordering moves these content ranges between fixed slots | ||
| * (keeping the original commas and whitespace in place), so comments travel | ||
| * with their parameter -- the same guarantee the original TSLint fixer gave by | ||
| * slicing from getFullStart() to getFullStart(). | ||
| * @param {any} param | ||
| * @param {import('eslint').SourceCode} sourceCode | ||
| * @returns {[number, number]} | ||
| */ | ||
| function getContentRange(param, sourceCode) { | ||
| let start = param.range[0]; | ||
| let headNode = param; | ||
| for (const decorator of getDecorators(param)) { | ||
| if (decorator.range[0] < start) { | ||
| start = decorator.range[0]; | ||
| headNode = decorator; | ||
| } | ||
| } | ||
| const leading = sourceCode.getCommentsBefore(headNode); | ||
| if (leading.length > 0 && leading[0].range[0] < start) { | ||
| start = leading[0].range[0]; | ||
| } | ||
| let end = param.range[1]; | ||
| const nextToken = sourceCode.getTokenAfter(param); | ||
| for (const comment of sourceCode.getCommentsAfter(param)) { | ||
| if (!nextToken || comment.range[1] <= nextToken.range[0]) { | ||
| end = Math.max(end, comment.range[1]); | ||
| } | ||
| } | ||
| return [start, end]; | ||
| } | ||
|
|
||
| /** @type {import('eslint').Rule.RuleModule} */ | ||
| module.exports = { | ||
| meta: { | ||
| type: 'suggestion', | ||
| docs: { | ||
| description: 'Enforce constructor parameter order: public, protected, private' | ||
| }, | ||
| fixable: 'code', | ||
| schema: [], | ||
| messages: { | ||
| order: 'Constructor parameters should be ordered: public, protected, private' | ||
| } | ||
| }, | ||
|
|
||
| create(context) { | ||
| const sourceCode = context.sourceCode || context.getSourceCode(); | ||
|
|
||
| /** | ||
| * @param {any} node MethodDefinition with kind === 'constructor' | ||
| */ | ||
| function checkConstructor(node) { | ||
| const params = node.value.params; | ||
| if (!params || params.length <= 1) { | ||
| return; | ||
| } | ||
|
|
||
| const ranks = params.map(getRank); | ||
| const inOrder = ranks.every((rank, i) => i === 0 || ranks[i - 1] <= rank); | ||
| if (inOrder) { | ||
| return; | ||
| } | ||
|
|
||
| context.report({ | ||
| node, | ||
| messageId: 'order', | ||
| fix(fixer) { | ||
| const text = sourceCode.getText(); | ||
| const ranges = params.map(p => getContentRange(p, sourceCode)); | ||
| // Stable sort by rank preserves the original relative order within a | ||
| // group, matching the previous TSLint behaviour. | ||
| const order = params.map((_, i) => i).sort((a, b) => ranks[a] - ranks[b]); | ||
|
|
||
| // Drop the sorted parameter content into the fixed slots, keeping the | ||
| // original separators (commas, whitespace, indentation) between slots | ||
| // untouched. Only the parameter text moves, so formatting and inter- | ||
| // parameter comments are preserved. | ||
| let out = ''; | ||
| for (let slot = 0; slot < params.length; slot++) { | ||
| const src = ranges[order[slot]]; | ||
| out += text.slice(src[0], src[1]); | ||
| if (slot < params.length - 1) { | ||
| out += text.slice(ranges[slot][1], ranges[slot + 1][0]); | ||
| } | ||
| } | ||
| return fixer.replaceTextRange([ranges[0][0], ranges[params.length - 1][1]], out); | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| return { | ||
| 'MethodDefinition[kind="constructor"]': checkConstructor | ||
| }; | ||
| } | ||
| }; | ||
84 changes: 84 additions & 0 deletions
84
zeppelin-web-angular/eslint-rules/constructor-params-order.test.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,84 @@ | ||
| /* | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| // Regression suite for the constructor-params-order fixer. It rewrites source | ||
| // files unattended via lint-staged on every commit, so the tricky reordering | ||
| // cases (comments, multi-line) are locked down here. Run with | ||
| // `npm run test:eslint-rules` (Node's built-in runner, no extra deps). | ||
|
|
||
| 'use strict'; | ||
|
|
||
| const test = require('node:test'); | ||
| const { RuleTester } = require('eslint'); | ||
| const tsParser = require('@typescript-eslint/parser'); | ||
| const rule = require('./constructor-params-order'); | ||
|
|
||
| const ruleTester = new RuleTester({ | ||
| languageOptions: { parser: tsParser, ecmaVersion: 2022, sourceType: 'module' } | ||
| }); | ||
|
|
||
| test('constructor-params-order', () => { | ||
| ruleTester.run('constructor-params-order', rule, { | ||
| valid: [ | ||
| 'class A { constructor(public a: X, protected b: Y, private c: Z) {} }', | ||
| 'class A { constructor(private a: X) {} }', | ||
| 'class A { constructor() {} }', | ||
| // optional (@Optional() / question token) ranks last, so these are ordered | ||
| 'class A { constructor(public a: X, private c: Z, @Optional() private d: W) {} }', | ||
| 'class A { constructor(private a: X, @Optional() @Inject(T) public b: Y) {} }', | ||
| 'class A { constructor(private a: X, b?: Y) {} }', | ||
| // a `readonly`-only parameter property is implicitly public, so it ranks first | ||
| 'class A { constructor(readonly a: X, private b: Y) {} }' | ||
| ], | ||
| invalid: [ | ||
| { | ||
| code: 'class A { constructor(private c: Z, public a: X) {} }', | ||
| output: 'class A { constructor(public a: X, private c: Z) {} }', | ||
| errors: [{ messageId: 'order' }] | ||
| }, | ||
| { | ||
| code: 'class A { constructor(private c: Z, protected b: Y, public a: X) {} }', | ||
| output: 'class A { constructor(public a: X, protected b: Y, private c: Z) {} }', | ||
| errors: [{ messageId: 'order' }] | ||
| }, | ||
| { | ||
| code: 'class A { constructor(@Optional() private a: X, public b: Y) {} }', | ||
| output: 'class A { constructor(public b: Y, @Optional() private a: X) {} }', | ||
| errors: [{ messageId: 'order' }] | ||
| }, | ||
| // a trailing comment before the comma must travel with its parameter | ||
| { | ||
| code: 'class A { constructor(private b: B /* injected lazily */, public a: A) {} }', | ||
| output: 'class A { constructor(public a: A, private b: B /* injected lazily */) {} }', | ||
| errors: [{ messageId: 'order' }] | ||
| }, | ||
| // multi-line: original commas / indentation are preserved | ||
| { | ||
| code: 'class A {\n constructor(\n private c: Z,\n public a: X\n ) {}\n}', | ||
| output: 'class A {\n constructor(\n public a: X,\n private c: Z\n ) {}\n}', | ||
| errors: [{ messageId: 'order' }] | ||
| }, | ||
| // a leading block comment stays attached to its parameter | ||
| { | ||
| code: 'class A {\n constructor(\n private a: A,\n /* keep */ public b: B\n ) {}\n}', | ||
| output: 'class A {\n constructor(\n /* keep */ public b: B,\n private a: A\n ) {}\n}', | ||
| errors: [{ messageId: 'order' }] | ||
| }, | ||
| // a `readonly`-only parameter property is public and must precede private | ||
| { | ||
| code: 'class A { constructor(private a: A, readonly b: B) {} }', | ||
| output: 'class A { constructor(readonly b: B, private a: A) {} }', | ||
| errors: [{ messageId: 'order' }] | ||
| } | ||
| ] | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| /* | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| // Local ESLint plugin for the project's Angular-specific constructor parameter | ||
| // ordering rule, reimplemented from the former custom TSLint rule | ||
| // (ZEPPELIN-6301 / ZEPPELIN-6372). The alphabetical public-api.ts export sort | ||
| // (ZEPPELIN-6325) is delegated to eslint-plugin-perfectionist instead. | ||
|
|
||
| 'use strict'; | ||
|
|
||
| module.exports = { | ||
| rules: { | ||
| 'constructor-params-order': require('./constructor-params-order') | ||
| } | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Could you add a
RuleTestersuite for this rule (valid/invalid/outputcases, including the comment and multi-line scenarios noted in the other comments)? It runs under plain Node with the already-installed deps, and since this fixer rewrites source files unattended on every commit, having regression coverage for the tricky cases would make future changes to it much safer.