(node)
| 32 | |
| 33 | return { |
| 34 | Program(node) { |
| 35 | let lastImportDeclaration = null; |
| 36 | node.body.forEach((statement, i) => { |
| 37 | if (statement.type === 'ImportDeclaration') { |
| 38 | const importSpecifiers = statement.specifiers.filter( |
| 39 | specifier => specifier.type === 'ImportSpecifier' |
| 40 | ); |
| 41 | const getSortableName = specifier => specifier.local.name.toLowerCase(); |
| 42 | const firstUnsortedIndex = importSpecifiers |
| 43 | .map(getSortableName) |
| 44 | .findIndex((name, index, array) => array[index - 1] > name); |
| 45 | |
| 46 | if (firstUnsortedIndex !== -1) { |
| 47 | context.report({ |
| 48 | node: importSpecifiers[firstUnsortedIndex], |
| 49 | message: |
| 50 | "Member '{{memberName}}' of the import declaration should be sorted alphabetically.", |
| 51 | data: {memberName: importSpecifiers[firstUnsortedIndex].local.name}, |
| 52 | fix(fixer) { |
| 53 | return fixer.replaceTextRange( |
| 54 | [ |
| 55 | importSpecifiers[0].range[0], |
| 56 | importSpecifiers[importSpecifiers.length - 1].range[1] |
| 57 | ], |
| 58 | importSpecifiers |
| 59 | // Clone the importSpecifiers array to avoid mutating it |
| 60 | .slice() |
| 61 | |
| 62 | // Sort the array into the desired order |
| 63 | .sort((specifierA, specifierB) => { |
| 64 | const aName = getSortableName(specifierA); |
| 65 | const bName = getSortableName(specifierB); |
| 66 | return aName > bName ? 1 : -1; |
| 67 | }) |
| 68 | |
| 69 | // Build a string out of the sorted list of import specifiers and the text between the originals |
| 70 | .reduce((sourceText, specifier, index) => { |
| 71 | const textAfterSpecifier = |
| 72 | index === importSpecifiers.length - 1 |
| 73 | ? '' |
| 74 | : sourceCode |
| 75 | .getText() |
| 76 | .slice( |
| 77 | importSpecifiers[index].range[1], |
| 78 | importSpecifiers[index + 1].range[0] |
| 79 | ); |
| 80 | |
| 81 | return sourceText + sourceCode.getText(specifier) + textAfterSpecifier; |
| 82 | }, '') |
| 83 | ); |
| 84 | } |
| 85 | }); |
| 86 | } else if (lastImportDeclaration) { |
| 87 | let currentLocalMemberName = getFirstLocalMemberName(statement); |
| 88 | let previousLocalMemberName = getFirstLocalMemberName(lastImportDeclaration); |
| 89 | if ( |
| 90 | previousLocalMemberName && |
| 91 | currentLocalMemberName && |
nothing calls this directly
no test coverage detected