-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
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
[New]: add rule default-import-match-filename
#1476
Draft
golopot
wants to merge
8
commits into
import-js:main
Choose a base branch
from
golopot:default-import-match-filename
base: main
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.
+558
−0
Draft
Changes from 1 commit
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
830a76b
[New]: add rule `default-import-match-filename`
golopot 5527eff
Rework option ignorePaths to accept glob patterns
golopot 0a914db
Add test cases for absolute paths
golopot 64c6999
Fix cases with scoped packages
golopot d1f0632
Make ignorePaths glob patterns relative to prcoess.cwd
golopot d5701d8
Make option ignorePaths a Set
golopot 029340a
docs add valid example
golopot 678fc02
add a test
golopot 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
This file contains 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
This file contains 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,44 @@ | ||
# import/default-import-match-filename | ||
|
||
Enforces default import name to match filename. Name matching is case-insensitive, and characters `._-` are stripped. | ||
|
||
## Rule Details | ||
|
||
### Options | ||
|
||
#### `ignorePaths` | ||
|
||
Set this option to `['some-dir/', 'bb']` to ignore import statements whose path contains either `some-dir/` or `bb` as a substring. | ||
|
||
### Fail | ||
|
||
```js | ||
import notFoo from './foo'; | ||
import utilsFoo from '../utils/foo'; | ||
import notFoo from '../foo/index.js'; | ||
import notMerge from 'lodash/merge'; | ||
import notPackageName from '..'; // When "../package.json" has name "package-name" | ||
import notDirectoryName from '..'; // When ".." is a directory named "directory-name" | ||
const bar = require('./foo'); | ||
const bar = require('../foo'); | ||
``` | ||
|
||
### Pass | ||
|
||
```js | ||
import foo from './foo'; | ||
import foo from '../foo/index.js'; | ||
import merge from 'lodash/merge'; | ||
import packageName from '..'; // When "../package.json" has name "package-name" | ||
import directoryName from '..'; // When ".." is a directory named "directory-name" | ||
import anything from 'foo'; | ||
import foo_ from './foo'; | ||
import foo from './foo.js'; | ||
import fooBar from './foo-bar'; | ||
import FoObAr from './foo-bar'; | ||
import catModel from './cat.model.js'; | ||
const foo = require('./foo'); | ||
|
||
// Option `{ ignorePaths: ['format/'] }` | ||
import QWERTY from '../format/date'; | ||
``` |
This file contains 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
This file contains 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,199 @@ | ||
import docsUrl from '../docsUrl' | ||
import isStaticRequire from '../core/staticRequire' | ||
import Path from 'path' | ||
|
||
/** | ||
* @param {string} filename | ||
* @returns {string} | ||
*/ | ||
function removeExtension(filename) { | ||
return Path.basename(filename, Path.extname(filename)) | ||
} | ||
|
||
/** | ||
* @param {string} filename | ||
* @returns {string} | ||
*/ | ||
function normalizeFilename(filename) { | ||
return filename.replace(/[-_.]/g, '').toLowerCase() | ||
} | ||
|
||
/** | ||
* Test if local name matches filename. | ||
* @param {string} localName | ||
* @param {string} filename | ||
* @returns {boolean} | ||
*/ | ||
function isCompatible(localName, filename) { | ||
const normalizedLocalName = localName.replace(/_/g, '').toLowerCase() | ||
|
||
return ( | ||
normalizedLocalName === normalizeFilename(filename) || | ||
normalizedLocalName === normalizeFilename(removeExtension(filename)) | ||
) | ||
} | ||
|
||
/** | ||
* Match 'foo' but not 'foo/bar.js' and './foo' | ||
* @param {string} path | ||
* @returns {boolean} | ||
*/ | ||
function isBarePackageImport(path) { | ||
return path !== '.' && path !== '..' && !path.includes('/') | ||
} | ||
|
||
/** | ||
* Match paths consisting of only '.' and '..', like '.', './', '..', '../..'. | ||
* @param {string} path | ||
* @returns {boolean} | ||
*/ | ||
function isAncestorRelativePath(path) { | ||
return ( | ||
path.length > 0 && | ||
!path.startsWith('/') && | ||
path | ||
.split(/[/\\]/) | ||
.every(segment => segment === '..' || segment === '.' || segment === '') | ||
) | ||
} | ||
|
||
/** | ||
* @param {string} packageJsonPath | ||
* @returns {string | undefined} | ||
*/ | ||
function getPackageJsonName(packageJsonPath) { | ||
try { | ||
golopot marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return require(packageJsonPath).name || undefined | ||
} catch (_) { | ||
return undefined | ||
} | ||
} | ||
|
||
function getNameFromPackageJsonOrDirname(path, context) { | ||
const directoryName = Path.join(context.getFilename(), path, '..') | ||
const packageJsonPath = Path.join(directoryName, 'package.json') | ||
const packageJsonName = getPackageJsonName(packageJsonPath) | ||
return packageJsonName || Path.basename(directoryName) | ||
} | ||
|
||
/** | ||
* Get filename from a path. | ||
* @param {string} path | ||
* @param {object} context | ||
* @returns {string | undefined} | ||
*/ | ||
function getFilename(path, context) { | ||
// like require('lodash') | ||
if (isBarePackageImport(path)) { | ||
return undefined | ||
} | ||
|
||
const basename = Path.basename(path) | ||
|
||
const isDir = /^index$|^index\./.test(basename) | ||
const processedPath = isDir ? Path.dirname(path) : path | ||
|
||
// like require('.'), require('..'), require('../..') | ||
if (isAncestorRelativePath(processedPath)) { | ||
return getNameFromPackageJsonOrDirname(processedPath, context) | ||
} | ||
|
||
return Path.basename(processedPath) + (isDir ? '/' : '') | ||
} | ||
|
||
/** | ||
* @param {string[]} ignorePaths | ||
* @param {string} path | ||
* @returns {boolean} | ||
*/ | ||
function isIgnored(ignorePaths, path) { | ||
return ignorePaths.some(pattern => path.includes(pattern)) | ||
} | ||
|
||
module.exports = { | ||
meta: { | ||
type: 'suggestion', | ||
docs: { | ||
url: docsUrl('default-import-match-filename'), | ||
}, | ||
schema: [ | ||
{ | ||
type: 'object', | ||
additionalProperties: false, | ||
properties: { | ||
ignorePaths: { | ||
type: 'array', | ||
items: { | ||
type: 'string', | ||
}, | ||
}, | ||
}, | ||
}, | ||
], | ||
}, | ||
|
||
create(context) { | ||
const ignorePaths = context.options[0] | ||
golopot marked this conversation as resolved.
Show resolved
Hide resolved
|
||
? context.options[0].ignorePaths || [] | ||
: [] | ||
|
||
return { | ||
ImportDeclaration(node) { | ||
const defaultImportSpecifier = node.specifiers.find( | ||
({type}) => type === 'ImportDefaultSpecifier' | ||
) | ||
|
||
const defaultImportName = | ||
defaultImportSpecifier && defaultImportSpecifier.local.name | ||
|
||
if (!defaultImportName) { | ||
return | ||
} | ||
|
||
const filename = getFilename(node.source.value, context) | ||
|
||
if (!filename) { | ||
return | ||
} | ||
|
||
if ( | ||
!isCompatible(defaultImportName, filename) && | ||
!isIgnored(ignorePaths, node.source.value) | ||
) { | ||
context.report({ | ||
node: defaultImportSpecifier, | ||
message: `Default import name does not match filename "${filename}".`, | ||
}) | ||
} | ||
}, | ||
|
||
CallExpression(node) { | ||
if ( | ||
!isStaticRequire(node) || | ||
node.parent.type !== 'VariableDeclarator' || | ||
node.parent.id.type !== 'Identifier' | ||
) { | ||
return | ||
} | ||
|
||
const localName = node.parent.id.name | ||
|
||
const filename = getFilename(node.arguments[0].value, context) | ||
|
||
if (!filename) { | ||
return | ||
} | ||
|
||
if ( | ||
!isCompatible(localName, filename) && | ||
!isIgnored(ignorePaths, node.arguments[0].value) | ||
) { | ||
context.report({ | ||
node: node.parent.id, | ||
message: `Default import name does not match filename "${filename}".`, | ||
}) | ||
} | ||
}, | ||
} | ||
}, | ||
} |
Empty file.
This file contains 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,3 @@ | ||
{ | ||
"name": "package-name" | ||
} |
Empty file.
Empty file.
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.
should this support globs, and that should be in the example?
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.
It seems that globs is not a good tool against relative paths.
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.
can you elaborate? it seems like a good tool to me.
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.
To perform a glob matching a cwd is required, for example:
What should the cwd be in this rule? The first thought is to use the location of
eslintrc
as cwd, but it is problematic when there is anothereslintrc
in a subdirectory, or whenoverrides
is used.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.
the cwd for any eslint rule is always
process.cwd()
, since you can't be sure where the config file is located.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.
Using
process.cwd()
taken as the cwd means that the rule will give different result depending on the cwd of the shell, is that fine?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.
yes, that seems fine to me.