-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathconfigCreator.ts
215 lines (183 loc) · 6.75 KB
/
configCreator.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
import { Codacyrc, Parameter, ParameterSpec, Pattern } from "codacy-seed"
import { ESLint, Linter } from "eslint"
import { existsSync } from "fs-extra"
import { cloneDeep, fromPairs, isEmpty, partition } from "lodash"
import path from "path"
import { isBlacklisted } from "./blacklist"
import { DocGenerator } from "./docGenerator"
import { defaultOptions } from "./eslintDefaultOptions"
import { getAllRules, getPluginsName } from "./eslintPlugins"
import { DEBUG, debug } from "./logging"
import { patternIdToEslint } from "./model/patterns"
export async function createEslintConfig (
srcDirPath: string,
codacyrc: Codacyrc
): Promise<[ESLint.Options, string[]]> {
debug("config: creating")
const options = await generateEslintOptions(srcDirPath, codacyrc)
const files = generateFilesToAnalyze(codacyrc)
debug("config: finished")
return [options, files]
}
function generateFilesToAnalyze(codacyrc: Codacyrc): string[] {
debug("files: creating");
const defaultFilesToAnalyze = [
"**/*.ts",
"**/*.tsx",
"**/*.js",
"**/*.jsx",
"**/*.json"
];
const files = codacyrc?.files && codacyrc.files.length
? codacyrc.files
: defaultFilesToAnalyze;
// Files to exclude
const excludedFiles = [
"package.json",
"package-lock.json",
"yarn.lock",
"pnpm-lock.yaml"
];
// Filter out excluded files
const filteredFiles = files.filter(
file => !excludedFiles.some(excluded => file.endsWith(excluded))
);
debug("files: finished");
return filteredFiles;
}
async function generateEslintOptions (
srcDirPath: string,
codacyrc: Codacyrc
): Promise<ESLint.Options> {
debug("options: creating")
let patterns = codacyrc.tools[0].patterns || []
debug(`options: ${patterns.length} patterns in codacyrc`)
const existsEslintConfig = existsEslintConfigInRepoRoot(srcDirPath)
const useCodacyPatterns = patterns.length
const useRepoPatterns = !useCodacyPatterns
const baseOptions: ESLint.Options = {
"cwd": srcDirPath,
"errorOnUnmatchedPattern": false,
"useEslintrc": useRepoPatterns
}
if (!DEBUG && useRepoPatterns) {
debug("options: using eslintrc from repo root")
return baseOptions
}
const options: ESLint.Options = Object.assign({}, baseOptions, cloneDeep(defaultOptions))
if (DEBUG && useRepoPatterns && !existsEslintConfig) {
const patternsSet = "recommended"
patterns = await retrieveCodacyPatterns(patternsSet)
options.baseConfig.rules = convertPatternsToEslintRules(patterns)
debug(`options: setting ${patternsSet} (${patterns.length}) patterns`)
} else if (useCodacyPatterns) {
//TODO: move this logic to a generic (or specific) plugin function
// There are some plugins that their rules should only apply for
// some specific file types / files names. So when those are enabled
// explicitly we need to apply them with a bit of customization.
//
// example: a rule for the storybook should only apply to files with
// "story" or "stories" in the name. If enabled for all files it
// reports false positives on normal files.
// check: conf file @ eslint-plugin-storybook/configs/recommended.js
const [storybookPatterns, otherPatterns] = partition(patterns, (p: Pattern) =>
p.patternId.startsWith("storybook")
)
// configure override in case storybook plugin rules being turned on
if (storybookPatterns.length) {
debug(`options: setting ${storybookPatterns.length} storybook patterns`)
options.baseConfig.overrides.push({
"files": [
"*.stories.@(ts|tsx|js|jsx|mjs|cjs)",
"*.story.@(ts|tsx|js|jsx|mjs|cjs)"
],
"rules": convertPatternsToEslintRules(storybookPatterns)
})
}
// explicitly use only the rules being passed by codacyrc
if (otherPatterns.length) {
debug(`options: setting ${otherPatterns.length} patterns`)
options.baseConfig.rules = convertPatternsToEslintRules(otherPatterns)
}
}
// load only the plugins that are being used in loaded rules
const prefixes = getPatternsUniquePrefixes(patterns)
prefixes
.filter((prefix) => prefix !== "")
.forEach(async (prefix) => {
(await getPluginsName()).includes(prefix)
? options.baseConfig.plugins.push(prefix)
: debug(`options: plugin ${prefix} not found`)
})
debug("options: finished")
return options
}
function getPatternsUniquePrefixes (patterns: Pattern[]) {
const prefixes = patterns.map(item => {
const patternId = patternIdToEslint(item.patternId)
return patternId.substring(0, patternId.lastIndexOf("/"))
})
return [...new Set(prefixes)]
}
function convertPatternsToEslintRules (patterns: Pattern[]): {
[name: string]: Linter.RuleLevel | Linter.RuleLevelAndOptions;
} {
const pairs = patterns.map((pattern: Pattern) => {
const patternId = patternIdToEslint(pattern.patternId)
if (!pattern.parameters) {
return [patternId, "error"]
}
const [unnamedParameters, namedParameters] = partition(
pattern.parameters,
(p) => p.name === "unnamedParam"
)
const namedOptions = fromPairs(namedParameters.map((p) => [p.name, p.value]))
const unnamedOptions = unnamedParameters.map((p) => p.value)
return [
patternId,
isEmpty(namedOptions)
? ["error", ...unnamedOptions]
: ["error", ...unnamedOptions, namedOptions]
]
})
return fromPairs(pairs)
}
function existsEslintConfigInRepoRoot (srcDirPath: string): boolean {
const filenames = [
".eslintrc",
".eslintrc.js",
".eslintrc.cjs",
".eslintrc.yaml",
".eslintrc.yml",
".eslintrc.json"
]
const found = filenames.some(filename => existsSync(srcDirPath + path.sep + filename))
debug(`options: eslintrc config file ${found ? "" : "not "}found`)
return found
}
async function retrieveCodacyPatterns (set: "recommended" | "all" = "recommended"): Promise<Pattern[]> {
const patterns: Pattern[] = [];
(await getAllRules())
.filter(([patternId, rule]) =>
!isBlacklisted(patternId)
&& !(rule?.meta?.deprecated && rule.meta.deprecated === true)
// problems with the path generated (win vs nix) for this specific pattern
&& (!DEBUG || patternId != "spellcheck_spell-checker")
&& (set !== "recommended" || DocGenerator.isDefaultPattern(patternIdToEslint(patternId), rule.meta))
)
.forEach(([patternId, rule]) => {
const pattern = new Pattern(
patternId,
DocGenerator.generateParameters(patternId, rule.meta?.schema)
.map((parameterSpec: ParameterSpec): Parameter => {
return new Parameter(
parameterSpec.name,
parameterSpec.default
)
})
)
patterns.push(pattern)
})
debug(`options: returning ${set} (${patterns.length}) patterns`)
return patterns
}