Skip to content

Commit

Permalink
add no-redundant-path-segments rule Fixes import-js#471
Browse files Browse the repository at this point in the history
  • Loading branch information
graingert committed Aug 8, 2017
1 parent dd28130 commit 743b51f
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ export const rules = {
'no-dynamic-require': require('./rules/no-dynamic-require'),
'unambiguous': require('./rules/unambiguous'),
'no-unassigned-import': require('./rules/no-unassigned-import'),
'no-redundant-path-segments': require('./rules/no-redundant-path-segments'),

// metadata-based
'no-deprecated': require('./rules/no-deprecated'),
Expand Down
61 changes: 61 additions & 0 deletions src/rules/no-redundant-path-segments.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/**
* @fileOverview Ensures that there are no redundant path segments
* @author Thomas Grainger
*/

import path from 'path';
import _ from 'lodash/fp';
import resolve from 'eslint-module-utils/resolve'
import moduleVisitor from 'eslint-module-utils/moduleVisitor'

function stripExtname(fn) {
const { dir, name } = path.parse(fn);
return path.format({ dir, name });
}

const cartesianProduct =
_.reduce((a, b) =>
_.flatMap(x =>
_.map(y =>
x.concat([y])
)(b)
)(a)
)([[]]);


const anyMatch = _.flow(
cartesianProduct,
_.some(([a, b]) => a === b)
);

module.exports = {
meta: {},

create: function (context) {
const currentPath = context.getFilename();
const currentPathStripped = stripExtname(currentPath);

function checkSourceValue(source) {
const { value } = source;
const resolvedPath = resolve(source, context)
if (resolvedPath === undefined) {
return;
}

const expected = path.relative(currentPath, resolvedPath);
const matched = anyMatch([
[value, stripExtname(value)],
[expected, stripExtname(expected)]
]);

if (!matched) {
context.report({
node: source,
message: `Redundant paths for "${value}", should be ${expected}`
})
}
}

return moduleVisitor(checkSourceValue, context.options[0])
},
}

0 comments on commit 743b51f

Please sign in to comment.