-
-
Notifications
You must be signed in to change notification settings - Fork 85
/
format-files.js
256 lines (236 loc) · 6.87 KB
/
format-files.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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
/* eslint no-console:0 */
import path from 'path'
import fs from 'fs'
import glob from 'glob'
import Rx from 'rxjs/Rx'
import format from 'prettier-eslint'
import chalk from 'chalk'
import getStdin from 'get-stdin'
import nodeIgnore from 'ignore'
import findUp from 'find-up'
import memoize from 'lodash.memoize'
import indentString from 'indent-string'
import getLogger from 'loglevel-colored-level-prefix'
import * as messages from './messages'
const LINE_SEPERATOR_REGEX = /(\r|\n|\r\n)/
const rxGlob = Rx.Observable.bindNodeCallback(glob)
const rxReadFile = Rx.Observable.bindNodeCallback(fs.readFile)
const rxWriteFile = Rx.Observable.bindNodeCallback(fs.writeFile)
const findUpSyncMemoized = memoize(findUpSync, function resolver(...args) {
return args.join('::')
})
const getIsIgnoredMemoized = memoize(getIsIgnored)
const logger = getLogger({prefix: 'prettier-eslint-cli'})
export default formatFilesFromArgv
function formatFilesFromArgv({
_: fileGlobs,
logLevel = logger.getLevel(),
listDifferent,
stdin,
write,
eslintPath,
prettierPath,
ignore: ignoreGlobs = [],
eslintIgnore: applyEslintIgnore = true,
prettierLast,
...prettierOptions
}) {
logger.setLevel(logLevel)
const prettierESLintOptions = {
logLevel,
eslintPath,
prettierPath,
prettierLast,
prettierOptions,
}
const cliOptions = {write, listDifferent}
if (stdin) {
return formatStdin(prettierESLintOptions)
} else {
return formatFilesFromGlobs(
fileGlobs,
[...ignoreGlobs], // make a copy to avoid manipulation
cliOptions,
prettierESLintOptions,
applyEslintIgnore,
)
}
}
async function formatStdin(prettierESLintOptions) {
const stdinValue = (await getStdin()).trim()
try {
const formatted = format({text: stdinValue, ...prettierESLintOptions})
process.stdout.write(formatted)
return Promise.resolve(formatted)
} catch (error) {
logger.error(
'There was a problem trying to format the stdin text',
`\n${indentString(error.stack, 4)}`,
)
process.exitCode = 1
return Promise.resolve(stdinValue)
}
}
function formatFilesFromGlobs(
fileGlobs,
ignoreGlobs,
cliOptions,
prettierESLintOptions,
applyEslintIgnore,
) {
const concurrentGlobs = 3
const concurrentFormats = 10
return new Promise(resolve => {
const successes = []
const failures = []
const unchanged = []
Rx.Observable
.from(fileGlobs)
.mergeMap(
getFilesFromGlob.bind(null, ignoreGlobs, applyEslintIgnore),
null,
concurrentGlobs,
)
.concatAll()
.distinct()
.mergeMap(filePathToFormatted, null, concurrentFormats)
.subscribe(onNext, onError, onComplete)
function filePathToFormatted(filePath) {
return formatFile(filePath, prettierESLintOptions, cliOptions)
}
function onNext(info) {
if (info.error) {
failures.push(info)
} else if (info.unchanged) {
unchanged.push(info)
} else {
successes.push(info)
}
}
function onError(error) {
logger.error(
'There was an unhandled error while formatting the files',
`\n${indentString(error.stack, 4)}`,
)
process.exitCode = 1
resolve({error, successes, failures})
}
function onComplete() {
const isNotSilent = logger.getLevel() !== logger.levels.SILENT
/* use console.error directly here because
* - we don't want these messages prefixed
* - we want them to go to stderr, not stdout
*/
if (successes.length && isNotSilent) {
console.error(
messages.success({
success: chalk.green('success'),
count: successes.length,
countString: chalk.bold(successes.length),
}),
)
}
if (failures.length && isNotSilent) {
process.exitCode = 1
console.error(
messages.failure({
failure: chalk.red('failure'),
count: failures.length,
countString: chalk.bold(failures.length),
}),
)
}
if (unchanged.length && isNotSilent) {
console.error(
messages.unchanged({
unchanged: chalk.gray('unchanged'),
count: unchanged.length,
countString: chalk.bold(unchanged.length),
}),
)
}
resolve({successes, failures})
}
})
}
function getFilesFromGlob(ignoreGlobs, applyEslintIgnore, fileGlob) {
const globOptions = {ignore: ignoreGlobs}
if (!fileGlob.includes('node_modules')) {
// basically, we're going to protect you from doing something
// not smart unless you explicitly include it in your glob
globOptions.ignore.push('**/node_modules/**')
}
return rxGlob(fileGlob, globOptions).map(filePaths => {
return filePaths.filter(filePath => {
return applyEslintIgnore ?
!isFilePathMatchedByEslintignore(filePath) :
true
})
})
}
function formatFile(filePath, prettierESLintOptions, cliOptions) {
const fileInfo = {filePath}
let format$ = rxReadFile(filePath, 'utf8').map(text => {
fileInfo.text = text
fileInfo.formatted = format({text, filePath, ...prettierESLintOptions})
fileInfo.unchanged = fileInfo.text === fileInfo.formatted
return fileInfo
})
if (cliOptions.write) {
format$ = format$.mergeMap(info => {
if (info.unchanged) {
return Rx.Observable.of(info)
} else {
return rxWriteFile(filePath, info.formatted).map(() => info)
}
})
} else if (cliOptions.listDifferent) {
format$ = format$.map(info => {
if (!info.unchanged) {
console.log(info.filePath)
}
return info
})
} else {
format$ = format$.map(info => {
process.stdout.write(info.formatted)
return info
})
}
return format$.catch(error => {
logger.error(
`There was an error formatting "${fileInfo.filePath}":`,
`\n${indentString(error.stack, 4)}`,
)
return Rx.Observable.of(Object.assign(fileInfo, {error}))
})
}
function getNearestEslintignorePath(filePath) {
const {dir} = path.parse(filePath)
return findUpSyncMemoized('.eslintignore', dir)
}
function isFilePathMatchedByEslintignore(filePath) {
const eslintignorePath = getNearestEslintignorePath(filePath)
if (!eslintignorePath) {
return false
}
const eslintignoreDir = path.parse(eslintignorePath).dir
const filePathRelativeToEslintignoreDir = path.relative(
eslintignoreDir,
filePath,
)
const isIgnored = getIsIgnoredMemoized(eslintignorePath)
return isIgnored(filePathRelativeToEslintignoreDir)
}
function findUpSync(filename, cwd) {
return findUp.sync('.eslintignore', {cwd})
}
function getIsIgnored(filename) {
const ignoreLines = fs
.readFileSync(filename, 'utf8')
.split(LINE_SEPERATOR_REGEX)
.filter(line => Boolean(line.trim()))
const instance = nodeIgnore()
instance.add(ignoreLines)
return instance.ignores.bind(instance)
}