Custom eslint rules
Valeriy Kuzmin
Moonfare, Berlin, 2022
Plan
- Custom eslint rules
- No-v3-DI-smuggling
- ast-tools helper
- Everything together
Intro
Problem
- Code review works with a diff, not the whole project
- People can miss things in complex projects
- We have a ton of custom conventions
- Architectural errors
- Too tight coupling
- Minor annoying errors
Solution
- Linting to the rescue!
- Run in CI
- Run in IDE
- Limited to the pre-defined rules
- Cannot cover custom conventions
But...
What is a custom eslint rule?
Rule
Walker
Meta
docs + messages
Loader
eslint-local-rules.js
Loader
eslint-local-rules.js
eslint-plugin-local-rules
Node type => analyzer
Loader
eslint-local-rules.js
Tests
valid cases
invalid cases
Welcome back to AST
No-v3-DI-smuggling
Problem
Non-v3
V3
TOKEN_V2
Impl v2
TOKEN_V3
Impl v3
Examples (from tests)
// ok
bind<DocumentAccessValidatorInterface>(PROFESSIONALISATION_DOCUMENT_ACCESS_VALIDATOR_INTERNAL)
.to(ProfessionalisationDocumentAccessValidatorImpl)
// ok
container.bind<DocumentAccessValidatorInterface>(PROFESSIONALISATION_DOCUMENT_ACCESS_VALIDATOR_INTERNAL)
.to(ProfessionalisationDocumentAccessValidatorImpl)
// not ok
bind<AuthorizationService>(AUTHORIZATION_SERVICE).to(AuthorizationService)
context.report({
node,
messageId: 'noSmuggling',
data: {
token: bindArgument,
implementation: toArgument,
},
});
Demo 1
ast-tools helper
Idea
1. Analyze the whole codebase first with TS
2. Save data to files
3. Synchronously read in the rule
What we want from the helper
- What is a v3 file vs non-v3 file vs ignored file?
- What is token declaration?
- What is implementation?
- Where does the token come from?
- What about uniqueness?
Demo 2
Everything together
Validation
Unique?
Yes
Import path doesn't matter
No
v2 binds to v3 = error
v3 token and v2 class?
Yes
No or unclear
assume no error
Drawbacks
1. Reexports are not followed - you can fool the rule
2. Impls are only properly checked if all non-unique are in v2
Demo 3
Done! Questions?
Custom eslint rules
By Valeriy Kuzmin
Custom eslint rules
- 156