-
-
Notifications
You must be signed in to change notification settings - Fork 82
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: use "prettier-tslint" and "prettier-eslint" when they exist
When the scm root has "./node_modules/prettier-tslint" and/or "./node_modules/prettier-eslint", we use them on applicable modules.
- Loading branch information
1 parent
3ae5e08
commit 132b173
Showing
1 changed file
with
32 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,27 +1,51 @@ | ||
import { readFileSync, writeFileSync } from 'fs'; | ||
import { resolveConfig, format } from 'prettier'; | ||
import { resolveConfig, format as prettierFormat } from 'prettier'; | ||
import { join } from 'path'; | ||
|
||
export default ( | ||
rootDirectory, | ||
files, | ||
{ config, onWriteFile, onExamineFile } = {} | ||
) => { | ||
// Use local "prettier-tslint" if possible. | ||
const tslintFormat = loadFormat(rootDirectory, 'prettier-tslint', 'format'); | ||
// Use local "prettier-eslint" if possible. | ||
const eslintFormat = loadFormat(rootDirectory, 'prettier-eslint'); | ||
|
||
for (const relative of files) { | ||
onExamineFile && onExamineFile(relative); | ||
const file = join(rootDirectory, relative); | ||
const options = resolveConfig.sync(file, { config, editorconfig: true }); | ||
const input = readFileSync(file, 'utf8'); | ||
const output = format( | ||
input, | ||
Object.assign({}, options, { | ||
filepath: file, | ||
}) | ||
); | ||
|
||
const format = | ||
(/\.(mjs|jsx?)$/.test(file) && (eslintFormat || tslintFormat)) || | ||
(/\.tsx?$/.test(file) && (tslintFormat || eslintFormat)) || | ||
prettierFormat; | ||
|
||
const options = resolveConfig.sync(file, { config, editorconfig: true }); | ||
const output = | ||
format === prettierFormat | ||
? format(input, ((options.filepath = file), options)) | ||
: format({ | ||
text: input, | ||
filePath: file, | ||
prettierOptions: options, | ||
}); | ||
|
||
if (output !== input) { | ||
writeFileSync(file, output); | ||
onWriteFile && onWriteFile(relative); | ||
} | ||
} | ||
}; | ||
|
||
function loadFormat(rootDirectory, formatName, exportName) { | ||
let entry; | ||
try { | ||
entry = require.resolve(join(rootDirectory, 'node_modules', formatName)); | ||
} catch (e) { | ||
return; | ||
} | ||
const exports = require(entry); | ||
return exportName ? exports[exportName] : exports; | ||
} |