Skip to content

Commit

Permalink
add no-useless-path-segments rule Fixes import-js#471
Browse files Browse the repository at this point in the history
  • Loading branch information
graingert committed Aug 16, 2017
1 parent cd77133 commit fb86742
Show file tree
Hide file tree
Showing 3 changed files with 74 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-useless-path-segments': require('./rules/no-useless-path-segments'),

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

import path from 'path'
import resolve from 'eslint-module-utils/resolve'
import moduleVisitor from 'eslint-module-utils/moduleVisitor'

function relative(from, to) {
const rel = path.relative(from, to)
return rel.startsWith('.') ? rel : `.${path.sep}${rel}`
}

module.exports = {
meta: {},

create: function (context) {
const currentDir = path.dirname(context.getFilename())

function checkSourceValue(source) {
const { value } = source
if (!value.startsWith('.')) {
return
}

const resolvedPath = resolve(value, context)
if (resolvedPath === undefined) {
return
}

const expected = path.parse(relative(currentDir, resolvedPath))
const valueParsed = path.parse(value)

if (valueParsed.dir !== expected.dir) {
const proposed = path.format({ dir: expected.dir, base: valueParsed.base })
context.report({
node: source,
message: `Useless path segments for "${value}", should be "${proposed}"`,
})
}
}

return moduleVisitor(checkSourceValue, context.options[0])
},
}
27 changes: 27 additions & 0 deletions tests/src/rules/no-useless-path-segments.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { test } from '../utils'
import { RuleTester } from 'eslint'

const ruleTester = new RuleTester()
const rule = require('rules/no-useless-path-segments')

function runResolverTests(resolver) {
ruleTester.run(`no-useless-path-segments (${resolver})`, rule, {
valid: [
test({ code: 'import "./malformed.js"' }),
test({ code: 'import fs from "fs"' }),
],

invalid: [
test({
code: 'import "./../files/malformed.js"',
errors: [ 'Useless path segments for "./../files/malformed.js", should be "./malformed.js"'],
}),
test({
code: 'import "./../files/malformed"',
errors: [ 'Useless path segments for "./../files/malformed", should be "./malformed"'],
}),
],
})
}

['node', 'webpack'].forEach(runResolverTests)

0 comments on commit fb86742

Please sign in to comment.