Skip to content
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

feat(eslint): rules for customization #1055

Merged
merged 1 commit into from
Mar 22, 2022
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
2 changes: 2 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,7 @@
]
],
"ish-custom-rules/component-creation-test": "error",
"ish-custom-rules/do-not-use-theme-identifier": "warn",
"ish-custom-rules/newline-before-root-members": "warn",
"ish-custom-rules/no-assignment-to-inputs": "error",
"ish-custom-rules/no-collapsible-if": "warn",
Expand Down Expand Up @@ -639,6 +640,7 @@
"ish-custom-rules/use-async-synchronization-in-tests": "warn",
"ish-custom-rules/use-camel-case-environment-properties": "error",
"ish-custom-rules/use-component-change-detection": "warn",
"ish-custom-rules/use-correct-component-overrides": "warn",
"ish-custom-rules/use-jest-extended-matchers-in-tests": "warn",
"ish-custom-rules/require-formly-code-documentation": "warn",
"jest/no-commented-out-tests": "warn",
Expand Down
4 changes: 4 additions & 0 deletions eslint-rules/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { banImportsFilePatternRule } from './rules/ban-imports-file-pattern';
import { componentCreationTestRule } from './rules/component-creation-test';
import { doNotUseThemeIdentifierRule } from './rules/do-not-use-theme-identifier';
import { newlineBeforeRootMembersRule } from './rules/newline-before-root-members';
import { noAssignmentToInputsRule } from './rules/no-assignment-to-inputs';
import { noCollapsibleIfRule } from './rules/no-collapsible-if';
Expand All @@ -19,6 +20,7 @@ import { useAliasImportsRule } from './rules/use-alias-imports';
import { useAsyncSynchronizationInTestsRule } from './rules/use-async-synchronization-in-tests';
import { useCamelCaseEnvironmentPropertiesRule } from './rules/use-camel-case-environment-properties';
import { useComponentChangeDetectionRule } from './rules/use-component-change-detection';
import { useCorrectComponentOverridesRule } from './rules/use-correct-component-overrides';
import { useJestExtendedMatchersInTestsRule } from './rules/use-jest-extended-matchers-in-tests';

const rules = {
Expand All @@ -44,6 +46,8 @@ const rules = {
'no-var-before-return': noVarBeforeReturnRule,
'require-formly-code-documentation': requireFormlyCodeDocumentationRule,
'sort-testbed-metadata-arrays': sortTestbedMetadataArraysRule,
'do-not-use-theme-identifier': doNotUseThemeIdentifierRule,
'use-correct-component-overrides': useCorrectComponentOverridesRule,
};

module.exports = {
Expand Down
41 changes: 41 additions & 0 deletions eslint-rules/src/rules/do-not-use-theme-identifier.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { TSESLint } from '@typescript-eslint/experimental-utils';

import { normalizePath } from '../helpers';

const DEFAULT_FILE_PATTERN = '.*\\.(component|directive|pipe)\\.ts';

export const doNotUseThemeIdentifierRule: TSESLint.RuleModule<string, [string]> = {
dhhyi marked this conversation as resolved.
Show resolved Hide resolved
meta: {
docs: {
description: `Using the THEME variable in Angular artifacts directly bypasses the concept of component overrides and leads to bad practice. This rule warns about the use. The pattern for files can be configured. Default is "${DEFAULT_FILE_PATTERN}"`,
recommended: 'warn',
url: '',
},
messages: {
doNotUseThemeIdentifier: 'Do not use THEME variable here. Instead use correctly named overrides.',
},
type: 'problem',
schema: [
{
type: 'string',
additionalProperties: false,
},
],
},
create(context) {
const config = context.options[0] ?? DEFAULT_FILE_PATTERN;

if (!new RegExp(config).test(normalizePath(context.getFilename()))) {
return {};
}

return {
'Identifier[name="THEME"]'(node) {
context.report({
node,
messageId: 'doNotUseThemeIdentifier',
});
},
};
},
};
142 changes: 142 additions & 0 deletions eslint-rules/src/rules/use-correct-component-overrides.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
import { strings } from '@angular-devkit/core';
import { Selectors } from '@angular-eslint/utils';
import { ASTUtils, TSESLint, TSESTree } from '@typescript-eslint/experimental-utils';
import * as fs from 'fs';
import * as path from 'path';

import { normalizePath } from '../helpers';

export const useCorrectComponentOverridesRule: TSESLint.RuleModule<string, []> = {
dhhyi marked this conversation as resolved.
Show resolved Hide resolved
meta: {
docs: {
description:
'For component overrides to work correctly, every Component decorator has to point its URLs to the component base files for HTML and SCSS. This rule checks if this is the case. Additionally, if a test is composed for a component override, this rule checks if the correct component files are used (because the override mechanism does not work with jest).',
recommended: 'warn',
url: '',
suggestion: true,
},
messages: {
shouldPointToBasicFile: 'Override should point to basic component file.',
testOverrideTemplateMissing:
'Did not find template override ({{ expectedTemplate }}) this spec is supposed to test.',
testOverrideTSMissing: 'Did not find TS import ({{ expectedTS }}) this spec is supposed to test.',
pointToBasicFile: 'Replace with basic component file.',
},
type: 'problem',
schema: [],
hasSuggestions: true,
},
create(context) {
const fileName = path.basename(normalizePath(context.getFilename()));
const fileBaseName = fileName.replace(/component.*/, 'component');
if (/\.component\.(?!spec)([a-z]+\.)?ts$/.test(fileName)) {
return {
[`${Selectors.COMPONENT_CLASS_DECORATOR} ObjectExpression > Property[key.name="templateUrl"] > Literal`](
node: TSESTree.Literal
) {
const expected = `./${fileBaseName}.html`;
if (node.value !== expected) {
context.report({
node,
messageId: 'shouldPointToBasicFile',
suggest: [{ fix: fixer => fixer.replaceText(node, `'${expected}'`), messageId: 'pointToBasicFile' }],
});
}
},

[`${Selectors.COMPONENT_CLASS_DECORATOR} ObjectExpression > Property[key.name="styleUrls"] > ArrayExpression`](
node: TSESTree.ArrayExpression
) {
const expected = `./${fileBaseName}.scss`;
if (!node.elements.some(el => el.type === TSESTree.AST_NODE_TYPES.Literal && el.value === expected)) {
const suggest = [];
if (node.elements.length <= 1) {
suggest.push({
fix: fixer => fixer.replaceText(node, `['${expected}']`),
messageId: 'pointToBasicFile',
});
}

context.report({
node,
messageId: 'shouldPointToBasicFile',
suggest,
});
}
},
};
} else if (/\.component\.[a-z]+\.spec\.ts$/.test(fileName)) {
function getText(node) {
return context.getSourceCode().getText(node);
}

const expectTemplateOverride = fs.existsSync(context.getFilename().replace(/\.spec\.ts$/, '.html'));
let hasCorrectTemplateOverride = false;
const expectedTemplate = fileName.replace('.spec.ts', '.html');

const expectTSOverride = fs.existsSync(context.getFilename().replace(/\.spec\.ts$/, '.ts'));
let hasCorrectTSOverride = false;
const expectedTS = fileName.replace('.spec.ts', '');

const classifiedBaseName = strings.classify(fileBaseName.replace(/\W/g, '-'));

if (expectTSOverride || expectTemplateOverride) {
const methods = {
'Program:exit'(node: TSESTree.Program) {
if (expectTemplateOverride && !hasCorrectTemplateOverride) {
context.report({
node,
messageId: 'testOverrideTemplateMissing',
data: {
expectedTemplate,
},
});
}
if (expectTSOverride && !hasCorrectTSOverride) {
context.report({
node,
messageId: 'testOverrideTSMissing',
data: {
expectedTS,
},
});
}
},
};

if (expectTemplateOverride) {
methods['CallExpression[callee.property.name="overrideComponent"]'] = (node: TSESTree.CallExpression) => {
if (node.arguments.length === 2) {
const arg1 = node.arguments[0];
const isCorrectOverrideKey = ASTUtils.isIdentifier(arg1) && arg1.name === classifiedBaseName;

const arg2 = node.arguments[1];
const isCorrectTemplateReplace =
arg2.type === TSESTree.AST_NODE_TYPES.ObjectExpression &&
arg2.properties[0].type === TSESTree.AST_NODE_TYPES.Property &&
ASTUtils.isIdentifier(arg2.properties[0].key) &&
arg2.properties[0].key.name === 'set' &&
getText(arg2.properties[0].value)
.replace(/\s*/g, '')
.includes(`template:require('./${expectedTemplate}')`);

hasCorrectTemplateOverride = isCorrectOverrideKey && isCorrectTemplateReplace;
}
};
}

if (expectTSOverride) {
methods[`ImportDeclaration[source.value="./${expectedTS}"] > ImportSpecifier`] = (
node: TSESTree.ImportSpecifier
) => {
hasCorrectTSOverride = node.imported.name === classifiedBaseName;
};
}

return methods;
}
}

return {};
},
};
57 changes: 57 additions & 0 deletions eslint-rules/tests/do-not-use-theme-identifier.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { doNotUseThemeIdentifierRule } from '../src/rules/do-not-use-theme-identifier';

import { RuleTestConfig } from './_execute-tests';

const config: RuleTestConfig<[string]> = {
ruleName: 'do-not-use-theme-identifier',
rule: doNotUseThemeIdentifierRule,
tests: {
valid: [
{
filename: 'test.component.spec.ts',
code: `const theme = THEME;`,
},
],
invalid: [
{
filename: 'test.component.ts',
code: `const theme = THEME;`,
errors: [
{
messageId: 'doNotUseThemeIdentifier',
},
],
},
{
filename: 'test.pipe.ts',
code: `const theme = THEME;`,
errors: [
{
messageId: 'doNotUseThemeIdentifier',
},
],
},
{
filename: 'test.directive.ts',
code: `const theme = THEME;`,
errors: [
{
messageId: 'doNotUseThemeIdentifier',
},
],
},
{
filename: 'test.component.spec.ts',
options: ['.*\\.ts'],
code: `const theme = THEME;`,
errors: [
{
messageId: 'doNotUseThemeIdentifier',
},
],
},
],
},
};

export default config;
Loading