-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
no-duplicates: Add autofix #1312
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
Changes from 2 commits
9ac41f3
71a64c6
f47622c
cdb7c37
f74a74e
cca688d
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -2,21 +2,198 @@ import resolve from 'eslint-module-utils/resolve' | |
import docsUrl from '../docsUrl' | ||
|
||
function checkImports(imported, context) { | ||
for (let [module, nodes] of imported.entries()) { | ||
if (nodes.size > 1) { | ||
for (let node of nodes) { | ||
context.report(node, `'${module}' imported multiple times.`) | ||
for (const [module, nodes] of imported.entries()) { | ||
if (nodes.length > 1) { | ||
const message = `'${module}' imported multiple times.` | ||
const [first, ...rest] = nodes | ||
const sourceCode = context.getSourceCode() | ||
const fix = getFix(first, rest, sourceCode) | ||
|
||
context.report({ | ||
node: first.source, | ||
message, | ||
fix, // Attach the autofix (if any) to the first import. | ||
}) | ||
|
||
for (const node of rest) { | ||
context.report({ | ||
node: node.source, | ||
message, | ||
}) | ||
} | ||
} | ||
} | ||
} | ||
|
||
function getFix(first, rest, sourceCode) { | ||
// Sorry ESLint <= 3 users, no autofix for you. | ||
ljharb marked this conversation as resolved.
Show resolved
Hide resolved
|
||
if (typeof sourceCode.getCommentsBefore !== 'function') { | ||
return undefined | ||
} | ||
|
||
const defaultImportNames = new Set( | ||
[first, ...rest].map(getDefaultImportName).filter(Boolean) | ||
) | ||
|
||
// Bail if there are multiple different default import names – it's up to the | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. is there a way we could reduce the ones that are the same? ie, if the list was There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I don't think it's possible to end up with There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. (Also, note that the particular line you commented on isn't about the specifiers inside |
||
// user to choose which one to keep. | ||
if (defaultImportNames.size > 1) { | ||
return undefined | ||
} | ||
|
||
// It's not obvious what the user wants to do with comments associated with | ||
// duplicate imports, so skip imports with comments when autofixing. | ||
const restWithoutComments = rest.filter(node => !( | ||
hasCommentBefore(node, sourceCode) || | ||
hasCommentAfter(node, sourceCode) || | ||
hasCommentInsideNonSpecifiers(node, sourceCode) | ||
)) | ||
|
||
const specifiers = restWithoutComments | ||
.map(node => { | ||
const tokens = sourceCode.getTokens(node) | ||
const openBrace = tokens.find(token => isPunctuator(token, '{')) | ||
const closeBrace = tokens.find(token => isPunctuator(token, '}')) | ||
|
||
if (openBrace == null || closeBrace == null) { | ||
return undefined | ||
} | ||
|
||
return { | ||
importNode: node, | ||
text: sourceCode.text.slice(openBrace.range[1], closeBrace.range[0]), | ||
hasTrailingComma: isPunctuator(sourceCode.getTokenBefore(closeBrace), ','), | ||
isEmpty: !hasSpecifiers(node), | ||
} | ||
}) | ||
.filter(Boolean) | ||
|
||
const unnecessaryImports = restWithoutComments.filter(node => | ||
!hasSpecifiers(node) && | ||
!specifiers.some(specifier => specifier.importNode === node) | ||
) | ||
|
||
const shouldAddDefault = getDefaultImportName(first) == null && defaultImportNames.size === 1 | ||
const shouldAddSpecifiers = specifiers.length > 0 | ||
const shouldRemoveUnnecessary = unnecessaryImports.length > 0 | ||
|
||
if (!(shouldAddDefault || shouldAddSpecifiers || shouldRemoveUnnecessary)) { | ||
return undefined | ||
} | ||
|
||
return function* (fixer) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. does this really need to be a generator? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think it's possible to make an array, There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Confirmed – the array version works, too. Personally I like the generator here, but let me know which way you want it. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'd prefer the array version, I find it easier to understand. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Pushed the array version! |
||
const tokens = sourceCode.getTokens(first) | ||
const openBrace = tokens.find(token => isPunctuator(token, '{')) | ||
const closeBrace = tokens.find(token => isPunctuator(token, '}')) | ||
const firstToken = sourceCode.getFirstToken(first) | ||
const [defaultImportName] = defaultImportNames | ||
|
||
const firstHasTrailingComma = | ||
closeBrace != null && | ||
isPunctuator(sourceCode.getTokenBefore(closeBrace), ',') | ||
const firstIsEmpty = !hasSpecifiers(first) | ||
|
||
const [specifiersText] = specifiers.reduce( | ||
([result, needsComma], specifier) => { | ||
return [ | ||
needsComma && !specifier.isEmpty | ||
? `${result},${specifier.text}` | ||
: `${result}${specifier.text}`, | ||
specifier.isEmpty ? needsComma : true, | ||
] | ||
}, | ||
['', !firstHasTrailingComma && !firstIsEmpty] | ||
) | ||
|
||
if (shouldAddDefault && openBrace == null && shouldAddSpecifiers) { | ||
// `import './foo'` → `import def, {...} from './foo'` | ||
yield fixer.insertTextAfter(firstToken, ` ${defaultImportName}, {${specifiersText}} from`) | ||
} else if (shouldAddDefault && openBrace == null && !shouldAddSpecifiers) { | ||
// `import './foo'` → `import def from './foo'` | ||
yield fixer.insertTextAfter(firstToken, ` ${defaultImportName} from`) | ||
} else if (shouldAddDefault && openBrace != null && closeBrace != null) { | ||
// `import {...} from './foo'` → `import def, {...} from './foo'` | ||
yield fixer.insertTextAfter(firstToken, ` ${defaultImportName},`) | ||
if (shouldAddSpecifiers) { | ||
// `import def, {...} from './foo'` → `import def, {..., ...} from './foo'` | ||
yield fixer.insertTextBefore(closeBrace, specifiersText) | ||
} | ||
} else if (!shouldAddDefault && openBrace == null && shouldAddSpecifiers) { | ||
// `import './foo'` → `import {...} from './foo'` | ||
yield fixer.insertTextAfter(firstToken, ` {${specifiersText}} from`) | ||
} else if (!shouldAddDefault && openBrace != null && closeBrace != null) { | ||
// `import {...} './foo'` → `import {..., ...} from './foo'` | ||
yield fixer.insertTextBefore(closeBrace, specifiersText) | ||
} | ||
|
||
// Remove imports whose specifiers have been moved into the first import. | ||
for (const specifier of specifiers) { | ||
yield fixer.remove(specifier.importNode) | ||
} | ||
|
||
// Remove imports whose default import has been moved to the first import, | ||
// and side-effect-only imports that are unnecessary due to the first | ||
// import. | ||
for (const node of unnecessaryImports) { | ||
yield fixer.remove(node) | ||
} | ||
} | ||
} | ||
|
||
function isPunctuator(node, value) { | ||
return node.type === 'Punctuator' && node.value === value | ||
} | ||
|
||
// Get the name of the default import of `node`, if any. | ||
function getDefaultImportName(node) { | ||
const defaultSpecifier = node.specifiers | ||
.find(specifier => specifier.type === 'ImportDefaultSpecifier') | ||
return defaultSpecifier != null ? defaultSpecifier.local.name : undefined | ||
} | ||
|
||
// Checks whether `node` has any non-default specifiers. | ||
function hasSpecifiers(node) { | ||
const specifiers = node.specifiers | ||
.filter(specifier => specifier.type === 'ImportSpecifier') | ||
return specifiers.length > 0 | ||
} | ||
|
||
// Checks whether `node` has a comment (that ends) on the previous line or on | ||
// the same line as `node` (starts). | ||
function hasCommentBefore(node, sourceCode) { | ||
return sourceCode.getCommentsBefore(node) | ||
.some(comment => comment.loc.end.line >= node.loc.start.line - 1) | ||
} | ||
|
||
// Checks whether `node` has a comment (that starts) on the same line as `node` | ||
// (ends). | ||
function hasCommentAfter(node, sourceCode) { | ||
return sourceCode.getCommentsAfter(node) | ||
.some(comment => comment.loc.start.line === node.loc.end.line) | ||
} | ||
|
||
// Checks whether `node` has any comments _inside,_ except inside the `{...}` | ||
// part (if any). | ||
function hasCommentInsideNonSpecifiers(node, sourceCode) { | ||
const tokens = sourceCode.getTokens(node) | ||
const openBraceIndex = tokens.findIndex(token => isPunctuator(token, '{')) | ||
const closeBraceIndex = tokens.findIndex(token => isPunctuator(token, '}')) | ||
// Slice away the first token, since we're no looking for comments _before_ | ||
// `node` (only inside). If there's a `{...}` part, look for comments before | ||
// the `{`, but not before the `}` (hence the `+1`s). | ||
const someTokens = openBraceIndex >= 0 && closeBraceIndex >= 0 | ||
? tokens.slice(1, openBraceIndex + 1).concat(tokens.slice(closeBraceIndex + 1)) | ||
: tokens.slice(1) | ||
return someTokens.some(token => sourceCode.getCommentsBefore(token).length > 0) | ||
} | ||
|
||
module.exports = { | ||
meta: { | ||
type: 'problem', | ||
docs: { | ||
url: docsUrl('no-duplicates'), | ||
}, | ||
fixable: 'code', | ||
}, | ||
|
||
create: function (context) { | ||
|
@@ -29,9 +206,9 @@ module.exports = { | |
const importMap = n.importKind === 'type' ? typesImported : imported | ||
|
||
if (importMap.has(resolvedPath)) { | ||
importMap.get(resolvedPath).add(n.source) | ||
importMap.get(resolvedPath).push(n) | ||
} else { | ||
importMap.set(resolvedPath, new Set([n.source])) | ||
importMap.set(resolvedPath, [n]) | ||
} | ||
}, | ||
|
||
|
Uh oh!
There was an error while loading. Please reload this page.