Skip to content

Commit

Permalink
feat: use "prettier-tslint" and "prettier-eslint" when they exist
Browse files Browse the repository at this point in the history
When the scm root has "./node_modules/prettier-tslint" and/or
"./node_modules/prettier-eslint", we use them on applicable modules.
  • Loading branch information
aleclarson committed Dec 13, 2018
1 parent 3ae5e08 commit 132b173
Showing 1 changed file with 32 additions and 8 deletions.
40 changes: 32 additions & 8 deletions src/formatFiles.js
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;
}

0 comments on commit 132b173

Please sign in to comment.