( filePaths: string[], prettierOptions: prettier.Options, shouldFormat: boolean = false, )
| 98 | } |
| 99 | |
| 100 | export async function checkAndFormatFiles( |
| 101 | filePaths: string[], |
| 102 | prettierOptions: prettier.Options, |
| 103 | shouldFormat: boolean = false, |
| 104 | ): Promise<FileLintStatus[]> { |
| 105 | const linter = new eslint.ESLint({fix: true}); |
| 106 | const results: FileLintStatus[] = await Promise.all( |
| 107 | filePaths.map(async fp => { |
| 108 | const filePath = path.resolve(fp); |
| 109 | |
| 110 | if (isDirectory(filePath)) { |
| 111 | return [fp, RESULT_STATUS.DIRECTORY]; |
| 112 | } |
| 113 | |
| 114 | if (hasExtension(filePath, '.json')) { |
| 115 | return [fp, RESULT_STATUS.SKIPPED]; |
| 116 | } |
| 117 | |
| 118 | const fileContent = fs.readFileSync(filePath, 'utf8'); |
| 119 | const prettierFileInfo = await prettier.getFileInfo(filePath); |
| 120 | |
| 121 | if (prettierFileInfo.inferredParser === null) { |
| 122 | return [fp, RESULT_STATUS.SKIPPED]; |
| 123 | } |
| 124 | |
| 125 | const lintResults = await linter.lintFiles([filePath]); |
| 126 | const needsLint = lintResults.length > 0; |
| 127 | let isLintFormatted = false; |
| 128 | |
| 129 | if (shouldFormat && needsLint) { |
| 130 | console.log(lintResults[0]?.messages[0]?.message); |
| 131 | await ESLint.outputFixes(lintResults); |
| 132 | isLintFormatted = true; |
| 133 | } |
| 134 | |
| 135 | const needsPrettier = await prettier.check(fileContent, { ...prettierOptions, filepath: filePath }); |
| 136 | let isPrettierFormatted = false; |
| 137 | |
| 138 | if (shouldFormat && !needsPrettier) { |
| 139 | const formattedContent = await prettier.format(fileContent, { ...prettierOptions, filepath: filePath }); |
| 140 | fs.writeFileSync(filePath, formattedContent, 'utf8'); |
| 141 | |
| 142 | isPrettierFormatted = true; |
| 143 | |
| 144 | } |
| 145 | |
| 146 | if (isPrettierFormatted || isLintFormatted) { |
| 147 | return [fp, RESULT_STATUS.CHANGED]; |
| 148 | } |
| 149 | |
| 150 | const formattedStatus = isPrettierFormatted && isLintFormatted ? RESULT_STATUS.VALID : RESULT_STATUS.NEEDS_FORMAT; |
| 151 | return [fp, formattedStatus]; |
| 152 | }), |
| 153 | ); |
| 154 | |
| 155 | return results; |
| 156 | } |
| 157 |
no test coverage detected