MCPcopy Create free account
hub / github.com/Snapchat/Valdi / checkAndFormatFiles

Function checkAndFormatFiles

npm_modules/cli/src/utils/lintUtils.ts:100–156  ·  view source on GitHub ↗
(
  filePaths: string[],
  prettierOptions: prettier.Options,
  shouldFormat: boolean = false,
)

Source from the content-addressed store, hash-verified

98}
99
100export 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

Callers 2

lintCheckFunction · 0.90
lintFormatFunction · 0.90

Calls 10

isDirectoryFunction · 0.90
hasExtensionFunction · 0.90
readFileSyncMethod · 0.80
getFileInfoMethod · 0.80
writeFileSyncMethod · 0.80
allMethod · 0.65
resolveMethod · 0.65
logMethod · 0.65
mapMethod · 0.45
formatMethod · 0.45

Tested by

no test coverage detected