12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- 'use strict';var _path = require('path');var _path2 = _interopRequireDefault(_path);
- var _readPkgUp = require('read-pkg-up');var _readPkgUp2 = _interopRequireDefault(_readPkgUp);
- var _resolve = require('eslint-module-utils/resolve');var _resolve2 = _interopRequireDefault(_resolve);
- var _moduleVisitor = require('eslint-module-utils/moduleVisitor');var _moduleVisitor2 = _interopRequireDefault(_moduleVisitor);
- var _importType = require('../core/importType');var _importType2 = _interopRequireDefault(_importType);
- var _docsUrl = require('../docsUrl');var _docsUrl2 = _interopRequireDefault(_docsUrl);function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}
- function findNamedPackage(filePath) {
- const found = _readPkgUp2.default.sync({ cwd: filePath, normalize: false });
- if (found.pkg && !found.pkg.name) {
- return findNamedPackage(_path2.default.join(found.path, '../..'));
- }
- return found;
- }
- function checkImportForRelativePackage(context, importPath, node) {
- const potentialViolationTypes = ['parent', 'index', 'sibling'];
- if (potentialViolationTypes.indexOf((0, _importType2.default)(importPath, context)) === -1) {
- return;
- }
- const resolvedImport = (0, _resolve2.default)(importPath, context);
- const resolvedContext = context.getFilename();
- if (!resolvedImport || !resolvedContext) {
- return;
- }
- const importPkg = findNamedPackage(resolvedImport);
- const contextPkg = findNamedPackage(resolvedContext);
- if (importPkg.pkg && contextPkg.pkg && importPkg.pkg.name !== contextPkg.pkg.name) {
- const importBaseName = _path2.default.basename(importPath);
- const importRoot = _path2.default.dirname(importPkg.path);
- const properPath = _path2.default.relative(importRoot, resolvedImport);
- const properImport = _path2.default.join(
- importPkg.pkg.name,
- _path2.default.dirname(properPath),
- importBaseName === _path2.default.basename(importRoot) ? '' : importBaseName);
- context.report({
- node,
- message: `Relative import from another package is not allowed. Use \`${properImport}\` instead of \`${importPath}\`` });
- }
- }
- module.exports = {
- meta: {
- type: 'suggestion',
- docs: {
- url: (0, _docsUrl2.default)('no-relative-packages') },
- schema: [(0, _moduleVisitor.makeOptionsSchema)()] },
- create(context) {
- return (0, _moduleVisitor2.default)(source => checkImportForRelativePackage(context, source.value, source), context.options[0]);
- } };
|