diff --git a/README.md b/README.md index cc9d1d789b..04b179601c 100644 --- a/README.md +++ b/README.md @@ -94,6 +94,7 @@ This plugin intends to support linting of ES2015+ (ES6+) import/export syntax, a * Forbid anonymous values as default exports ([`no-anonymous-default-export`]) * Prefer named exports to be grouped together in a single export declaration ([`group-exports`]) * Enforce a leading comment with the webpackChunkName for dynamic imports ([`dynamic-import-chunkname`]) +* Enforce default import name to match filename ([`default-import-match-filename`]) [`first`]: ./docs/rules/first.md [`exports-last`]: ./docs/rules/exports-last.md @@ -111,6 +112,7 @@ This plugin intends to support linting of ES2015+ (ES6+) import/export syntax, a [`no-default-export`]: ./docs/rules/no-default-export.md [`no-named-export`]: ./docs/rules/no-named-export.md [`dynamic-import-chunkname`]: ./docs/rules/dynamic-import-chunkname.md +[`default-import-match-filename`]: ./docs/rules/default-import-match-filename.md ## `eslint-plugin-import` for enterprise diff --git a/docs/rules/default-import-match-filename.md b/docs/rules/default-import-match-filename.md new file mode 100644 index 0000000000..55c2c11e8b --- /dev/null +++ b/docs/rules/default-import-match-filename.md @@ -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` + +This option accepts an array of glob patterns. An import statement will be ignored if the import source path matches some of the glob patterns, where the glob patterns are relative to the current working directory where the linter is launched. For example, with the option `{ignorePaths: ['**/foo.js']}`, the statement `import whatever from './foo.js'` will be ignored. + +### 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: ['**/models/*.js'] }` +import whatever from '../models/foo.js'; +``` diff --git a/src/index.js b/src/index.js index d0a98b7cb9..19688707d8 100644 --- a/src/index.js +++ b/src/index.js @@ -38,6 +38,7 @@ export const rules = { 'unambiguous': require('./rules/unambiguous'), 'no-unassigned-import': require('./rules/no-unassigned-import'), 'no-useless-path-segments': require('./rules/no-useless-path-segments'), + 'default-import-match-filename': require('./rules/default-import-match-filename'), 'dynamic-import-chunkname': require('./rules/dynamic-import-chunkname'), // export diff --git a/src/rules/default-import-match-filename.js b/src/rules/default-import-match-filename.js new file mode 100644 index 0000000000..b9720e7252 --- /dev/null +++ b/src/rules/default-import-match-filename.js @@ -0,0 +1,207 @@ +import docsUrl from '../docsUrl' +import isStaticRequire from '../core/staticRequire' +import Path from 'path' +import minimatch from 'minimatch' +import resolve from 'eslint-module-utils/resolve' + +/** + * @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' and '@foo/bar' but not 'foo/bar.js', './foo', or '@foo/bar/a.js' + * @param {string} path + * @returns {boolean} + */ +function isBarePackageImport(path) { + return (path !== '.' && path !== '..' && !path.includes('/') && !path.startsWith('@')) || + /@[^/]+\/[^/]+$/.test(path) +} + +/** + * 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 { + 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 {object} context + * @param {string[]} ignorePaths + * @param {string} path + * @returns {boolean} + */ +function isIgnored(context, ignorePaths, path) { + const resolvedPath = resolve(path, context) + return resolvedPath != null && + ignorePaths.some(pattern => + minimatch(Path.relative(process.cwd(), resolvedPath), 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] + ? 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(context, 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(context, ignorePaths, node.arguments[0].value) + ) { + context.report({ + node: node.parent.id, + message: `Default import name does not match filename "${filename}".`, + }) + } + }, + } + }, +} diff --git a/tests/files/default-import-match-filename/ignored/foo.js b/tests/files/default-import-match-filename/ignored/foo.js new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/files/default-import-match-filename/main.js b/tests/files/default-import-match-filename/main.js new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/files/default-import-match-filename/package.json b/tests/files/default-import-match-filename/package.json new file mode 100644 index 0000000000..a2508f8479 --- /dev/null +++ b/tests/files/default-import-match-filename/package.json @@ -0,0 +1,3 @@ +{ + "name": "package-name" +} diff --git a/tests/files/default-import-match-filename/some-directory/a.js b/tests/files/default-import-match-filename/some-directory/a.js new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/files/default-import-match-filename/some-directory/index.js b/tests/files/default-import-match-filename/some-directory/index.js new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/src/rules/default-import-match-filename.js b/tests/src/rules/default-import-match-filename.js new file mode 100644 index 0000000000..1a5281cb4d --- /dev/null +++ b/tests/src/rules/default-import-match-filename.js @@ -0,0 +1,290 @@ +import {RuleTester} from 'eslint' +import {testFilePath} from '../utils' + +import rule from '../../../src/rules/default-import-match-filename' // eslint-disable-line import/default + +const ruleTester = new RuleTester({ + parserOptions: { + sourceType: 'module', + ecmaVersion: 6, + }, +}) + +function getMessage(filename) { + return `Default import name does not match filename "${filename}".` +} + +/** + * @param {string} code + * @param {string} expectedFilename + * @param {string} [filename] + */ +function fail(code, expectedFilename, filename) { + return { + code, + errors: [ + { + message: getMessage(expectedFilename), + }, + ], + filename, + } +} + +const parserOptions = { + ecmaVersion: 6, + sourceType: 'module', +} + +ruleTester.run('default-import-match-filename', rule, { + valid: [ + 'import Cat from "./cat"', + 'import cat from "./cat"', + 'import cat from "./Cat"', + 'import Cat from "./Cat"', + 'import cat from "./cat.js"', + 'import cat from "./cat.ts"', + 'import cat from "./cat.jpeg"', + 'import cat from ".cat"', + 'import cat_ from "./cat"', + 'import cat from "./cat/index"', + 'import cat from "./cat/index.js"', + 'import cat from "./cat/index.css"', + 'import cat from "../cat/index.js"', + 'import merge from "lodash/merge"', + 'import cat from "/cat.js"', // absolute path + 'import cat from "C:\\cat.js"', + 'import cat from "C:/cat.js"', + 'import loudCat from "./loud-cat"', + 'import LOUDCAT from "./loud-cat"', + 'import loud_cat from "./loud-cat"', + 'import loudcat from "./loud_cat"', + 'import loud_cat from "./loud_cat"', + 'import loudCat from "./loud_cat"', + 'import catModel from "./cat.model"', + 'import catModel from "./cat.model.js"', + 'import doge from "cat"', + 'import doge from "loud-cat"', + 'import doge from ".cat"', + 'import doge from ""', + 'import whatever from "@foo/bar"', + 'import {doge} from "./cat"', + 'import cat, {doge} from "./cat"', + 'const cat = require("./cat")', + 'const cat = require("../cat")', + 'const cat = require("./cat/index")', + 'const cat = require("./cat/index.js")', + 'const doge = require("cat")', + 'const {f, g} = require("./cat")', + { + code: `import whatever from './ignored/foo.js'`, + filename: testFilePath('default-import-match-filename/main.js'), + options: [{ignorePaths: ['**/ignored/*.js']}], + }, + { + code: `import whatever from '../ignored/foo.js'`, + filename: testFilePath('default-import-match-filename/some-directory/a.js'), + options: [{ignorePaths: ['**/ignored/*.js']}], + }, + { + code: `import whatever from './ignored/foo.js'`, + filename: testFilePath('default-import-match-filename/main.js'), + options: [{ignorePaths: ['**/foo.js']}], + }, + { + code: ` + import someDirectory from "."; + import someDirectory_ from "./"; + const someDirectory__ = require('.'); + `, + filename: testFilePath( + 'default-import-match-filename/some-directory/a.js', + ), + }, + { + code: ` + import packageName from ".."; + import packageName_ from "../"; + import packageName__ from "./.."; + import packageName___ from "./../"; + const packageName____ = require('..'); + `, + filename: testFilePath( + 'default-import-match-filename/some-directory/a.js', + ), + }, + { + code: 'import doge from "../index.js"', + filename: 'doge/a/a.js', + }, + { + code: 'import JordanHarband from "./JordanHarband";', + parserOptions, + }, + { + code: 'import JordanHarband from "./JordanHarband.js";', + parserOptions, + }, + { + code: 'import JordanHarband from "./JordanHarband.jsx";', + parserOptions, + }, + { + code: 'import JordanHarband from "/some/path/to/JordanHarband.js";', + parserOptions, + }, + { + code: 'import JordanHarband from "/another/path/to/JordanHarband.js";', + parserOptions, + }, + { + code: 'import JordanHarband from "/another/path/to/jordanHarband.js";', + parserOptions, + }, + { + code: 'import JordanHarband from "/another/path/to/jordanHarband.jsx";', + parserOptions, + }, + { + code: 'import JordanHarband from "./JordanHarband/index.js";', + parserOptions, + }, + { + code: 'import JordanHarband from "./JordanHarband/index.jsx";', + parserOptions, + }, + { + code: 'import TaeKim from "./TaeKim.ts";', + parserOptions, + settings: { + 'import/extensions': ['.ts'], + }, + }, + { + code: 'import TaeKim from "./TaeKim.tsx";', + parserOptions, + settings: { + 'import/extensions': ['.ts'], + }, + }, + { + code: 'import TaeKim from "./TaeKim.js";', + parserOptions, + settings: { + 'import/extensions': ['.js', '.jsx', '.ts', '.tsx'], + }, + }, + { + code: 'import TaeKim from "./TaeKim.jsx";', + parserOptions, + settings: { + 'import/extensions': ['.js', '.jsx', '.ts', '.tsx'], + }, + }, + { + code: 'import TaeKim from "./TaeKim.ts";', + parserOptions, + settings: { + 'import/extensions': ['.js', '.jsx', '.ts', '.tsx'], + }, + }, + { + code: 'import TaeKim from "./TaeKim.tsx";', + parserOptions, + settings: { + 'import/extensions': ['.js', '.jsx', '.ts', '.tsx'], + }, + }, + { + code: 'import JordanHarband from "path/to/something/JoRdAnHaRbAnD.jsx";', + parserOptions, + }, + ], + invalid: [ + fail('import cat0 from "./cat"', 'cat'), + fail('import catfish from "./cat"', 'cat'), + fail('import catfish, {cat} from "./cat"', 'cat'), + fail('import catModel from "./models/cat"', 'cat'), + fail('import cat from "./cat.model.js"', 'cat.model.js'), + fail('import doge from "./cat/index"', 'cat/'), + fail('import doge from "./cat/index.js"', 'cat/'), + fail('import doge from "../cat/index.js"', 'cat/'), + fail('import doge from "../cat/index.css"', 'cat/'), + fail('import doge from "lodash/merge"', 'merge'), + fail('import doge from "lodash/a/b/c"', 'c'), + fail('import doge from "@foo/bar/a"', 'a'), + fail('import doge from "/cat"', 'cat'), + fail('import cat7 from "./cat8"', 'cat8'), + fail('const catfish = require("./cat")', 'cat'), + fail('const doge = require("./cat/index")', 'cat/'), + fail('const doge = require("./cat/index.js")', 'cat/'), + fail('const doge = require("../models/cat")', 'cat'), + fail( + 'import nope from "."', + 'some-directory', + testFilePath('default-import-match-filename/some-directory/a.js'), + ), + fail( + 'import nope from ".."', + 'package-name', + testFilePath('default-import-match-filename/some-directory/a.js'), + ), + fail( + 'import nope from "../../index.js"', + 'package-name', + testFilePath('default-import-match-filename/some-directory/foo/a.js'), + ), + { + code: `import wrongName from './some-directory/a.js';`, + output: `import wrongName from './some-directory/a.js';`, + filename: testFilePath('default-import-match-filename/main.js'), + options: [{ignorePaths: ['**/b.js', 'a.js', './a.js']}], + errors: [{message: getMessage('a.js')}], + }, + { + code: 'import JordanHarband from "./NotJordanHarband.js";', + output: 'import JordanHarband from "./NotJordanHarband.js";', + parserOptions, + errors: [{ + message: getMessage('NotJordanHarband.js'), + type: 'ImportDefaultSpecifier', + }], + }, + { + code: 'import JordanHarband from "./NotJordanHarband.jsx";', + output: 'import JordanHarband from "./NotJordanHarband.jsx";', + parserOptions, + errors: [{ + message: getMessage('NotJordanHarband.jsx'), + type: 'ImportDefaultSpecifier', + }], + }, + { + code: 'import JordanHarband from "./NotJordanHarband/index.js";', + output: 'import JordanHarband from "./NotJordanHarband/index.js";', + parserOptions, + errors: [{ + message: getMessage('NotJordanHarband/'), + type: 'ImportDefaultSpecifier', + }], + }, + { + code: 'import JordanHarband from "./JordanHarband/foobar.js";', + output: 'import JordanHarband from "./JordanHarband/foobar.js";', + parserOptions, + errors: [{ + message: getMessage('foobar.js'), + type: 'ImportDefaultSpecifier', + }], + }, + { + code: 'import JordanHarband from "/path/to/JordanHarbandReducer.js";', + output: 'import JordanHarband from "/path/to/JordanHarbandReducer.js";', + parserOptions, + errors: [{ + message: getMessage('JordanHarbandReducer.js'), + type: 'ImportDefaultSpecifier', + }], + }, + ], +})