-
Notifications
You must be signed in to change notification settings - Fork 498
/
Copy pathno-imports-in-directory.ts
73 lines (66 loc) · 2.05 KB
/
no-imports-in-directory.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// Copyright 2022 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import path from 'path';
import {createRule} from './utils/ruleCreator.ts';
// Define the structure of the options object
interface Options {
bannedImportPaths?: string[];
}
export default createRule<Options[], 'invalidImport'>({
name: 'no-imports-in-directory',
meta: {
type: 'problem',
docs: {
description: 'Ban files in a directory from importing specific modules',
category: 'Possible Errors',
},
messages: {
invalidImport: 'It is banned to import this module from this file\'s directory',
},
schema: [
{
type: 'object',
properties: {
bannedImportPaths: {
type: 'array',
items: {
type: 'string',
},
},
},
additionalProperties: false,
},
],
},
defaultOptions: [{bannedImportPaths: []}],
create: function(context) {
const filename = context.filename;
// Use ?? [] for safety, although defaultOptions should handle it
const bannedPaths = context.options[0]?.bannedImportPaths ?? [];
const fileNameOfFileBeingChecked = path.resolve(filename);
// No need to proceed if there are no banned paths defined
if (bannedPaths.length === 0) {
return {};
}
return {
ImportDeclaration(node) {
// Ensure node.source is a Literal and has a value (should always be true for imports)
if (typeof node.source.value !== 'string') {
return;
}
const importPath = path.resolve(
path.dirname(fileNameOfFileBeingChecked),
node.source.value,
);
for (const banned of bannedPaths) {
// Ensure 'banned' is a string before calling includes
if (typeof banned === 'string' && importPath.includes(banned)) {
context.report({node, messageId: 'invalidImport'});
break;
}
}
},
};
},
});