UNPKG

eslint-plugin-ferramentas

Version:
82 lines (81 loc) 3.44 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.rule = void 0; const utils_1 = require("../../utils"); const Base_1 = require("../Base"); const Debug_1 = require("../Debug"); const Input_1 = require("./Input"); const Metadata_1 = require("./Metadata"); /** * Auxiliar class to calculate the group of a given import */ class ImportGroupHelper { constructor(groups) { this.groups = groups; this.cache = new Map(); } calculateType(declaration) { if (!(0, utils_1.isPathRelative)(declaration.rawPath)) { return 'ABSOLUTE'; } const position = this.groups.findIndex((pattern) => pattern.test(declaration.pathFromWorkingDirectory)); if (position < 0) { return 'GROUP_NOT_FOUND'; } return `GROUP_${position}`; } mapType(declaration) { const value = this.cache.get(declaration) ?? this.calculateType(declaration); if (!this.cache.has(declaration)) { this.cache.set(declaration, value); } return value; } } const rule = (0, Base_1.createRule)({ name: Metadata_1.name, type: 'layout', fixable: 'whitespace', hasSuggestions: true, docs: { description: [ 'Enforces consistency of spacing between relative imports according to the folder each imports reference.', 'Imports are grouped as defined in the configuration, spaces are only allowed between the groups.', 'Non relative imports, and relative imports without a specified group will be considered to be each in their own group, thus having spaces between them as well.', ].join('\n'), }, schema: Metadata_1.schema, messages: { noEmpty: 'There should be no empty lines in a import group', oneEmpty: 'There should be one empty line between import groups', }, }, (input) => ({ ...(0, Input_1.mapGroups)(input), ...(0, Debug_1.mapDebugRuleOptionInput)(input) }), (context) => { const groups = context.getOption('groups'); context.debug('groups', ...groups); const helper = new ImportGroupHelper(groups); return { 'ImportDeclaration + ImportDeclaration': (node) => { const declaration = context.getImportDeclaration(node); context.debug('declaration', declaration); const previous = declaration.getPreviousSiblingWithSameTypeOrThrow(); context.debug('previous', previous); const needsSpace = helper.mapType(declaration) !== helper.mapType(previous); context.debug('needsSpace', needsSpace); const wantedLineBreaks = needsSpace ? 2 : 1; context.debug('wantedLines', wantedLineBreaks); const actualLineBreaks = declaration.getLocation(true).start.line - previous.getLocation(false).end.line; context.debug('actualLines', actualLineBreaks); if (wantedLineBreaks === actualLineBreaks) { return; } const range = declaration.getRangeBetween(previous, true); context.debug('range', range); context.report({ loc: declaration.getLocation(false), messageId: needsSpace ? 'oneEmpty' : 'noEmpty', fix: (fixer) => [fixer.replaceTextRange(range, Array(wantedLineBreaks).fill('\n').join(''))], }); }, }; }); exports.rule = rule;