1 | 'use strict';
|
2 |
|
3 | const path = require('node:path');
|
4 | const util = require('../util');
|
5 |
|
6 |
|
7 | const isFileImport = name => path.isAbsolute(name) || name.startsWith('./') || name.startsWith('../');
|
8 |
|
9 | const create = context => {
|
10 | const filename = context.getFilename();
|
11 | const [overrides] = context.options;
|
12 |
|
13 | if (filename === '<input>' || filename === '<text>') {
|
14 | return {};
|
15 | }
|
16 |
|
17 | const resolveFrom = path.dirname(filename);
|
18 |
|
19 | let loadedAvaHelper = false;
|
20 | let avaHelper;
|
21 |
|
22 | const validateImportPath = (node, importPath) => {
|
23 | if (!importPath || typeof importPath !== 'string') {
|
24 | return;
|
25 | }
|
26 |
|
27 | if (!isFileImport(importPath)) {
|
28 | return;
|
29 | }
|
30 |
|
31 | if (!loadedAvaHelper) {
|
32 | avaHelper = util.loadAvaHelper(filename, overrides);
|
33 | loadedAvaHelper = true;
|
34 | }
|
35 |
|
36 | if (!avaHelper) {
|
37 | return {};
|
38 | }
|
39 |
|
40 | const {isTest} = avaHelper.classifyImport(path.resolve(resolveFrom, importPath));
|
41 | if (isTest) {
|
42 | context.report({
|
43 | node,
|
44 | message: 'Test files should not be imported.',
|
45 | });
|
46 | }
|
47 | };
|
48 |
|
49 | return {
|
50 | ImportDeclaration(node) {
|
51 | validateImportPath(node, node.source.value);
|
52 | },
|
53 | CallExpression(node) {
|
54 | if (!(node.callee.type === 'Identifier' && node.callee.name === 'require')) {
|
55 | return;
|
56 | }
|
57 |
|
58 | if (node.arguments[0]) {
|
59 | validateImportPath(node, node.arguments[0].value);
|
60 | }
|
61 | },
|
62 | };
|
63 | };
|
64 |
|
65 | const schema = [{
|
66 | type: 'object',
|
67 | properties: {
|
68 | extensions: {
|
69 | type: 'array',
|
70 | },
|
71 | files: {
|
72 | type: 'array',
|
73 | },
|
74 | },
|
75 | }];
|
76 |
|
77 | module.exports = {
|
78 | create,
|
79 | meta: {
|
80 | type: 'suggestion',
|
81 | docs: {
|
82 | description: 'Ensure no test files are imported anywhere.',
|
83 | url: util.getDocsUrl(__filename),
|
84 | },
|
85 | schema,
|
86 | },
|
87 | };
|