Skip to content

Commit

Permalink
refactor: extract functions and use filter
Browse files Browse the repository at this point in the history
this makes `checkForRestrictedImportPath` lighter and easier to understand
  • Loading branch information
AdriAt360 committed Jun 2, 2022
1 parent bd987a5 commit 2d8aad5
Showing 1 changed file with 23 additions and 26 deletions.
49 changes: 23 additions & 26 deletions src/rules/no-restricted-paths.js
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,20 @@ module.exports = {
};
}

function reportInvalidExceptions(validators, node) {
validators.forEach(validator => validator.reportInvalidException(node));
}

function reportImportsInRestrictedZone(validators, node, importPath, customMessage) {
validators.forEach(() => {
context.report({
node,
message: `Unexpected path "{{importPath}}" imported in restricted zone.${customMessage ? ` ${customMessage}` : ''}`,
data: { importPath },
});
});
}

const makePathValidators = (zoneFrom, zoneExcept = []) => {
const allZoneFrom = [].concat(zoneFrom);
const areGlobPatterns = allZoneFrom.map(isGlob);
Expand Down Expand Up @@ -209,32 +223,15 @@ module.exports = {
validators[index] = makePathValidators(zone.from, zone.except);
}

validators[index].forEach(({
isPathRestricted,
hasValidExceptions,
isPathException,
reportInvalidException,
}) => {
if (!isPathRestricted(absoluteImportPath)) {
return;
}

if (!hasValidExceptions) {
reportInvalidException(node);
return;
}

const pathIsExcepted = isPathException(absoluteImportPath);
if (pathIsExcepted) {
return;
}

context.report({
node,
message: `Unexpected path "{{importPath}}" imported in restricted zone.${zone.message ? ` ${zone.message}` : ''}`,
data: { importPath },
});
});
const applicableValidatorsForImportPath = validators[index].filter(validator => validator.isPathRestricted(absoluteImportPath));

const validatorsWithInvalidExceptions = applicableValidatorsForImportPath.filter(validator => !validator.hasValidExceptions);
reportInvalidExceptions(validatorsWithInvalidExceptions, node);

const applicableValidatorsForImportPathExcludingExceptions = applicableValidatorsForImportPath
.filter(validator => validator.hasValidExceptions)
.filter(validator => !validator.isPathException(absoluteImportPath));
reportImportsInRestrictedZone(applicableValidatorsForImportPathExcludingExceptions, node, importPath, zone.message);
});
}

Expand Down

0 comments on commit 2d8aad5

Please sign in to comment.