-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathcreate-eslint-config.js
240 lines (211 loc) · 6.7 KB
/
create-eslint-config.js
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
#!/usr/bin/env node
import { existsSync, readFileSync, writeFileSync, unlinkSync } from 'node:fs'
import { createRequire } from 'node:module'
import path from 'node:path'
import process from 'node:process'
import { bold, blue, yellow, red, green, dim } from 'kolorist'
import createConfig, { deepMerge } from '../index.js'
const require = createRequire(import.meta.url)
const Enquirer = require('enquirer')
const enquirer = new Enquirer()
function abort() {
console.error(red('✖') + ' Operation cancelled')
process.exit(1)
}
function prompt(questions) {
return enquirer.prompt(questions).catch(abort)
}
const cwd = process.cwd()
const requireInCwd = createRequire(path.resolve(cwd, 'index.cjs'))
// Only works in directories that has a `package.json`
const pkgJsonPath = path.resolve(cwd, 'package.json')
if (!existsSync(pkgJsonPath)) {
console.error(
`${bold(yellow('package.json'))} not found in the current directory.`,
)
abort()
}
const rawPkgJson = readFileSync(pkgJsonPath, 'utf-8')
function inferIndent(rawJson) {
const lines = rawJson.split('\n')
const firstLineWithIndent = lines.find(
l => l.startsWith(' ') || l.startsWith('\t'),
)
if (!firstLineWithIndent) {
return ''
}
return /^\s+/.exec(firstLineWithIndent)[0]
}
const indent = inferIndent(rawPkgJson)
const pkg = JSON.parse(rawPkgJson)
// 1. check for existing config files
// `.eslintrc.*`, `eslintConfig` in `package.json`
// FIXME: `eslint.config.*`
// ask if wanna overwrite?
// https://eslint.org/docs/latest/user-guide/configuring/configuration-files#configuration-file-formats
// The experimental `eslint.config.js` isn't supported yet
const eslintConfigFormats = ['js', 'cjs', 'yaml', 'yml', 'json']
for (const fmt of eslintConfigFormats) {
const configFileName = `.eslintrc.${fmt}`
const fullConfigPath = path.resolve(cwd, configFileName)
if (existsSync(fullConfigPath)) {
const { shouldRemove } = await prompt({
type: 'toggle',
disabled: 'No',
enabled: 'Yes',
name: 'shouldRemove',
message:
`Found existing ESLint config file: ${bold(blue(configFileName))}.\n` +
'Do you want to remove the config file and continue?',
initial: false,
})
if (shouldRemove) {
unlinkSync(fullConfigPath)
} else {
abort()
}
}
}
if (pkg.eslintConfig) {
const { shouldRemoveConfigField } = await prompt({
type: 'toggle',
disabled: 'No',
enabled: 'Yes',
name: 'shouldRemoveConfigField',
message:
`Found existing ${bold(blue('eslintConfig'))} field in ${bold(yellow('package.json'))}.\n` +
'Do you want to remove the config field and continue?',
initial: false,
})
if (shouldRemoveConfigField) {
delete pkg.eslintConfig
}
}
// 2. Check Vue
let vueVersion
// Not detected? Abort
// Vue 2? Abort because this tool only supports Vue 3
try {
vueVersion = requireInCwd('vue/package.json').version
console.info(dim(`Detected Vue.js version: ${vueVersion}`))
} catch {}
if (!vueVersion || !/^3/.test(vueVersion)) {
const { continueAnyway } = await prompt({
type: 'toggle',
disabled: 'No',
enabled: 'Yes',
name: 'continueAnyway',
message: 'Vue 3.x is required but not detected. Continue anyway?',
initial: false,
})
if (!continueAnyway) {
abort()
}
}
// 4. Check TypeScript
// 4.1 Allow JS?
// 4.2 Allow JS in Vue? Allow JSX (TSX, if answered no in 4.1) in Vue?
let detectedTypeScript = false
try {
const tsVersion = requireInCwd('typescript/package.json').version
console.info(dim(`Detected TypeScript version: ${tsVersion}`))
detectedTypeScript = true
} catch {}
const { hasTypeScript } = await prompt({
type: 'toggle',
disabled: 'No',
enabled: 'Yes',
name: 'hasTypeScript',
message: 'Does your project use TypeScript?',
initial: detectedTypeScript,
})
const supportedScriptLangs = {}
// FIXME: Use a multi-select prompt
// if (hasTypeScript) {
// const { allowJsInVue } = await prompt({
// type: 'toggle',
// disabled: 'No',
// enabled: 'Yes',
// name: 'allowJsInVue',
// message: `Do you use plain ${yellow('<script>')}s (without ${blue('lang="ts"')}) in ${green('.vue')} files?`,
// initial: false
// })
// if (allowJsInVue) {
// const { allowJsxInVue } = await prompt({
// type: 'toggle',
// disabled: 'No',
// enabled: 'Yes',
// name: 'allowJsxInVue',
// message: `Do you use ${yellow('<script lang="jsx">')}s in ${green('.vue')} files (not recommended)?`,
// initial: false
// })
// additionalConfig.extends = [
// `@vue/eslint-config-${styleGuide}-with-typescript/${
// allowJsxInVue
// ? 'allow-jsx-in-vue'
// : 'allow-js-in-vue'
// }`
// ]
// } else {
// const { allowTsxInVue } = await prompt({
// type: 'toggle',
// disabled: 'No',
// enabled: 'Yes',
// name: 'allowTsxInVue',
// message: `Do you use ${yellow('<script lang="tsx">')}s in ${green('.vue')} files (not recommended)?`,
// initial: false
// })
// if (allowTsxInVue) {
// additionalConfig.extends = [
// `@vue/eslint-config-${styleGuide}-with-typescript/allow-tsx-in-vue`
// ]
// }
// }
// }
// 5. Do you need Prettier to format your codebase?
const { needsPrettier } = await prompt({
type: 'toggle',
disabled: 'No',
enabled: 'Yes',
name: 'needsPrettier',
message: 'Do you need Prettier to format your code?',
})
const { needsOxlint } = await prompt({
type: 'toggle',
disabled: 'No',
enabled: 'Yes',
name: 'needsOxlint',
message:
'Would you like to supplement ESLint with Oxlint for faster linting (experimental)?',
})
const { pkg: pkgToExtend, files } = createConfig({
hasTypeScript,
supportedScriptLangs,
needsPrettier,
needsOxlint,
})
deepMerge(pkg, pkgToExtend)
// Write `package.json` back
writeFileSync(pkgJsonPath, JSON.stringify(pkg, null, indent) + '\n', 'utf8')
// Write files back
for (const [name, content] of Object.entries(files)) {
const fullPath = path.resolve(cwd, name)
writeFileSync(fullPath, content, 'utf8')
}
// Prompt: Run `npm install` or `yarn` or `pnpm install`
const userAgent = process.env.npm_config_user_agent ?? ''
const packageManager = /pnpm/.test(userAgent)
? 'pnpm'
: /yarn/.test(userAgent)
? 'yarn'
: 'npm'
const installCommand =
packageManager === 'yarn' ? 'yarn' : `${packageManager} install`
const lintCommand =
packageManager === 'npm' ? 'npm run lint' : `${packageManager} lint`
console.info(
'\n' +
`${bold(yellow('package.json'))} and ${bold(blue(`eslint.config.${hasTypeScript ? 'ts' : 'js'}`))} have been updated.\n` +
`Now please run ${bold(green(installCommand))} to re-install the dependencies.\n` +
`Then you can run ${bold(green(lintCommand))} to lint your files.`,
)