From 830a76b2209af44cb5477e7cd6efa00a123e9e72 Mon Sep 17 00:00:00 2001 From: Chiawen Chen Date: Sat, 14 Sep 2019 20:28:20 +0800 Subject: [PATCH 1/5] [New]: add rule `default-import-match-filename` Co-Authored-By: Chiawen Chen Co-Authored-By: Armano Co-Authored-By: Sharmila --- README.md | 2 + docs/rules/default-import-match-filename.md | 44 +++ src/index.js | 1 + src/rules/default-import-match-filename.js | 199 +++++++++++++ .../default-import-match-filename/main.js | 0 .../package.json | 3 + .../some-directory/a.js | 0 .../some-directory/index.js | 0 .../rules/default-import-match-filename.js | 276 ++++++++++++++++++ 9 files changed, 525 insertions(+) create mode 100644 docs/rules/default-import-match-filename.md create mode 100644 src/rules/default-import-match-filename.js create mode 100644 tests/files/default-import-match-filename/main.js create mode 100644 tests/files/default-import-match-filename/package.json create mode 100644 tests/files/default-import-match-filename/some-directory/a.js create mode 100644 tests/files/default-import-match-filename/some-directory/index.js create mode 100644 tests/src/rules/default-import-match-filename.js 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..32cc3cb86c --- /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` + +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'; +``` 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..6fef5ed0dd --- /dev/null +++ b/src/rules/default-import-match-filename.js @@ -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 { + 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] + ? 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}".`, + }) + } + }, + } + }, +} 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..7cdf6557ef --- /dev/null +++ b/tests/src/rules/default-import-match-filename.js @@ -0,0 +1,276 @@ +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 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 {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 QWER from './ignore-dir/a'; + import WRYYY from '../models/mmm'; + `, + options: [{ignorePaths: ['ignore-dir/', 'mmm']}], + }, + { + 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 "/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 QWERTY from '../bbb/ccc';`, + output: `import QWERTY from '../bbb/ccc';`, + options: [{ignorePaths: ['aaa']}], + errors: [{message: getMessage('ccc')}], + }, + { + 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', + }], + }, + ], +}) From 5527eff8139375bd7b2f1500eab1d4ca72f5a5cf Mon Sep 17 00:00:00 2001 From: Chiawen Chen Date: Wed, 19 Feb 2020 18:44:27 +0800 Subject: [PATCH 2/5] Rework option ignorePaths to accept glob patterns --- docs/rules/default-import-match-filename.md | 6 ++--- src/rules/default-import-match-filename.js | 13 ++++++--- .../ignored/foo.js | 0 .../rules/default-import-match-filename.js | 27 ++++++++++++------- 4 files changed, 30 insertions(+), 16 deletions(-) create mode 100644 tests/files/default-import-match-filename/ignored/foo.js diff --git a/docs/rules/default-import-match-filename.md b/docs/rules/default-import-match-filename.md index 32cc3cb86c..68903dca32 100644 --- a/docs/rules/default-import-match-filename.md +++ b/docs/rules/default-import-match-filename.md @@ -8,7 +8,7 @@ Enforces default import name to match filename. Name matching is case-insensitiv #### `ignorePaths` -Set this option to `['some-dir/', 'bb']` to ignore import statements whose path contains either `some-dir/` or `bb` as a substring. +This option accepts an array of glob patterns. The glob patterns are to be matched against the resolved **abosolute** path of import statements. As an example, with the option `{ignorePaths: ['**/foo.js']}`, the statement `import whatever from './foo.js'` is ignored, since `./foo.js` resolves to, say, `/home/me/thing/foo.js`, which matches the glob pattern `**/foo.js`. ### Fail @@ -39,6 +39,6 @@ import FoObAr from './foo-bar'; import catModel from './cat.model.js'; const foo = require('./foo'); -// Option `{ ignorePaths: ['format/'] }` -import QWERTY from '../format/date'; +// Option `{ ignorePaths: ['**/models/*.js'] }` +import whatever from '../models/foo.js'; ``` diff --git a/src/rules/default-import-match-filename.js b/src/rules/default-import-match-filename.js index 6fef5ed0dd..66e43f6c49 100644 --- a/src/rules/default-import-match-filename.js +++ b/src/rules/default-import-match-filename.js @@ -1,6 +1,8 @@ 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 @@ -102,12 +104,15 @@ function getFilename(path, context) { } /** + * @param {object} context * @param {string[]} ignorePaths * @param {string} path * @returns {boolean} */ -function isIgnored(ignorePaths, path) { - return ignorePaths.some(pattern => path.includes(pattern)) +function isIgnored(context, ignorePaths, path) { + const resolvedPath = resolve(path, context) + return resolvedPath != null && + ignorePaths.some(pattern => minimatch(resolvedPath, pattern)) } module.exports = { @@ -158,7 +163,7 @@ module.exports = { if ( !isCompatible(defaultImportName, filename) && - !isIgnored(ignorePaths, node.source.value) + !isIgnored(context, ignorePaths, node.source.value) ) { context.report({ node: defaultImportSpecifier, @@ -186,7 +191,7 @@ module.exports = { if ( !isCompatible(localName, filename) && - !isIgnored(ignorePaths, node.arguments[0].value) + !isIgnored(context, ignorePaths, node.arguments[0].value) ) { context.report({ node: node.parent.id, 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/src/rules/default-import-match-filename.js b/tests/src/rules/default-import-match-filename.js index 7cdf6557ef..60aac378dd 100644 --- a/tests/src/rules/default-import-match-filename.js +++ b/tests/src/rules/default-import-match-filename.js @@ -73,11 +73,19 @@ ruleTester.run('default-import-match-filename', rule, { 'const doge = require("cat")', 'const {f, g} = require("./cat")', { - code: ` - import QWER from './ignore-dir/a'; - import WRYYY from '../models/mmm'; - `, - options: [{ignorePaths: ['ignore-dir/', 'mmm']}], + 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: ` @@ -222,10 +230,11 @@ ruleTester.run('default-import-match-filename', rule, { testFilePath('default-import-match-filename/some-directory/foo/a.js'), ), { - code: `import QWERTY from '../bbb/ccc';`, - output: `import QWERTY from '../bbb/ccc';`, - options: [{ignorePaths: ['aaa']}], - errors: [{message: getMessage('ccc')}], + 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";', From 0a914db6ed4551ba71fa1221409dd16c80c463a9 Mon Sep 17 00:00:00 2001 From: Chiawen Chen Date: Wed, 19 Feb 2020 19:03:35 +0800 Subject: [PATCH 3/5] Add test cases for absolute paths --- tests/src/rules/default-import-match-filename.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/src/rules/default-import-match-filename.js b/tests/src/rules/default-import-match-filename.js index 60aac378dd..abfa5a3a26 100644 --- a/tests/src/rules/default-import-match-filename.js +++ b/tests/src/rules/default-import-match-filename.js @@ -52,6 +52,9 @@ ruleTester.run('default-import-match-filename', rule, { '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"', From 64c6999a4627d2ea70fbb174194d66fc8b6af699 Mon Sep 17 00:00:00 2001 From: Chiawen Chen Date: Wed, 19 Feb 2020 19:27:00 +0800 Subject: [PATCH 4/5] Fix cases with scoped packages --- src/rules/default-import-match-filename.js | 5 +++-- tests/src/rules/default-import-match-filename.js | 2 ++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/rules/default-import-match-filename.js b/src/rules/default-import-match-filename.js index 66e43f6c49..290f9789b9 100644 --- a/src/rules/default-import-match-filename.js +++ b/src/rules/default-import-match-filename.js @@ -36,12 +36,13 @@ function isCompatible(localName, filename) { } /** - * Match 'foo' but not 'foo/bar.js' and './foo' + * 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('/') + return (path !== '.' && path !== '..' && !path.includes('/') && !path.startsWith('@')) || + /@[^/]+\/[^/]+$/.test(path) } /** diff --git a/tests/src/rules/default-import-match-filename.js b/tests/src/rules/default-import-match-filename.js index abfa5a3a26..1a5281cb4d 100644 --- a/tests/src/rules/default-import-match-filename.js +++ b/tests/src/rules/default-import-match-filename.js @@ -67,6 +67,7 @@ ruleTester.run('default-import-match-filename', rule, { '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")', @@ -211,6 +212,7 @@ ruleTester.run('default-import-match-filename', rule, { 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'), From d1f0632ff7b31b24103cd64d66571a2123f958c2 Mon Sep 17 00:00:00 2001 From: Chiawen Chen Date: Fri, 13 Mar 2020 11:06:47 +0800 Subject: [PATCH 5/5] Make ignorePaths glob patterns relative to prcoess.cwd --- docs/rules/default-import-match-filename.md | 2 +- src/rules/default-import-match-filename.js | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/rules/default-import-match-filename.md b/docs/rules/default-import-match-filename.md index 68903dca32..55c2c11e8b 100644 --- a/docs/rules/default-import-match-filename.md +++ b/docs/rules/default-import-match-filename.md @@ -8,7 +8,7 @@ Enforces default import name to match filename. Name matching is case-insensitiv #### `ignorePaths` -This option accepts an array of glob patterns. The glob patterns are to be matched against the resolved **abosolute** path of import statements. As an example, with the option `{ignorePaths: ['**/foo.js']}`, the statement `import whatever from './foo.js'` is ignored, since `./foo.js` resolves to, say, `/home/me/thing/foo.js`, which matches the glob pattern `**/foo.js`. +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 diff --git a/src/rules/default-import-match-filename.js b/src/rules/default-import-match-filename.js index 290f9789b9..b9720e7252 100644 --- a/src/rules/default-import-match-filename.js +++ b/src/rules/default-import-match-filename.js @@ -113,7 +113,9 @@ function getFilename(path, context) { function isIgnored(context, ignorePaths, path) { const resolvedPath = resolve(path, context) return resolvedPath != null && - ignorePaths.some(pattern => minimatch(resolvedPath, pattern)) + ignorePaths.some(pattern => + minimatch(Path.relative(process.cwd(), resolvedPath), pattern) + ) } module.exports = {