|
| 1 | +import debug from 'debug'; |
| 2 | +import path from 'path'; |
| 3 | +import { getProgramsForProjects } from './createWatchProgram'; |
| 4 | +import { firstDefined } from '../node-utils'; |
| 5 | +import { Extra } from '../parser-options'; |
| 6 | +import { ASTAndProgram } from './shared'; |
| 7 | + |
| 8 | +const log = debug('typescript-eslint:typescript-estree:createProjectProgram'); |
| 9 | + |
| 10 | +/** |
| 11 | + * @param code The code of the file being linted |
| 12 | + * @param options The config object |
| 13 | + * @returns If found, returns the source file corresponding to the code and the containing program |
| 14 | + */ |
| 15 | +function createProjectProgram( |
| 16 | + code: string, |
| 17 | + createDefaultProgram: boolean, |
| 18 | + extra: Extra, |
| 19 | +): ASTAndProgram | undefined { |
| 20 | + log('Creating project program for: %s', extra.filePath); |
| 21 | + |
| 22 | + const astAndProgram = firstDefined( |
| 23 | + getProgramsForProjects(code, extra.filePath, extra), |
| 24 | + currentProgram => { |
| 25 | + const ast = currentProgram.getSourceFile(extra.filePath); |
| 26 | + return ast && { ast, program: currentProgram }; |
| 27 | + }, |
| 28 | + ); |
| 29 | + |
| 30 | + if (!astAndProgram && !createDefaultProgram) { |
| 31 | + // the file was either not matched within the tsconfig, or the extension wasn't expected |
| 32 | + const errorLines = [ |
| 33 | + '"parserOptions.project" has been set for @typescript-eslint/parser.', |
| 34 | + `The file does not match your project config: ${path.relative( |
| 35 | + process.cwd(), |
| 36 | + extra.filePath, |
| 37 | + )}.`, |
| 38 | + ]; |
| 39 | + let hasMatchedAnError = false; |
| 40 | + |
| 41 | + const fileExtension = path.extname(extra.filePath); |
| 42 | + if (!['.ts', '.tsx', '.js', '.jsx'].includes(fileExtension)) { |
| 43 | + const nonStandardExt = `The extension for the file (${fileExtension}) is non-standard`; |
| 44 | + if (extra.extraFileExtensions && extra.extraFileExtensions.length > 0) { |
| 45 | + if (!extra.extraFileExtensions.includes(fileExtension)) { |
| 46 | + errorLines.push( |
| 47 | + `${nonStandardExt}. It should be added to your existing "parserOptions.extraFileExtensions".`, |
| 48 | + ); |
| 49 | + hasMatchedAnError = true; |
| 50 | + } |
| 51 | + } else { |
| 52 | + errorLines.push( |
| 53 | + `${nonStandardExt}. You should add "parserOptions.extraFileExtensions" to your config.`, |
| 54 | + ); |
| 55 | + hasMatchedAnError = true; |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + if (!hasMatchedAnError) { |
| 60 | + errorLines.push( |
| 61 | + 'The file must be included in at least one of the projects provided.', |
| 62 | + ); |
| 63 | + hasMatchedAnError = true; |
| 64 | + } |
| 65 | + |
| 66 | + throw new Error(errorLines.join('\n')); |
| 67 | + } |
| 68 | + |
| 69 | + return astAndProgram; |
| 70 | +} |
| 71 | + |
| 72 | +export { createProjectProgram }; |
0 commit comments