prettier.js 1.17 KB
Newer Older
陈帅's avatar
陈帅 committed
1 2 3 4 5 6 7 8 9 10 11
/**
 * copy to https://github.com/facebook/react/blob/master/scripts/prettier/index.js
 * prettier api doc https://prettier.io/docs/en/api.html
 *----------*****--------------
 *  prettier all js and all ts.
 *----------*****--------------
 */

const glob = require('glob');
const prettier = require('prettier');
const fs = require('fs');
陈帅's avatar
陈帅 committed
12
const getPrettierFiles = require('./getPrettierFiles');
陈帅's avatar
陈帅 committed
13 14 15 16
const prettierConfigPath = require.resolve('../.prettierrc');

let didError = false;

陈帅's avatar
陈帅 committed
17
const files = getPrettierFiles();
陈帅's avatar
陈帅 committed
18

陈帅's avatar
陈帅 committed
19
files.forEach(file => {
陈帅's avatar
陈帅 committed
20 21 22
  const options = prettier.resolveConfig.sync(file, {
    config: prettierConfigPath,
  });
陈帅's avatar
陈帅 committed
23
  const fileInfo = prettier.getFileInfo.sync(file);
陈帅's avatar
陈帅 committed
24 25 26
  if (fileInfo.ignored) {
    return;
  }
陈帅's avatar
陈帅 committed
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
  try {
    const input = fs.readFileSync(file, 'utf8');
    const withParserOptions = {
      ...options,
      parser: fileInfo.inferredParser,
    };
    const output = prettier.format(input, withParserOptions);
    if (output !== input) {
      fs.writeFileSync(file, output, 'utf8');
      console.log(`\x1b[34m ${file} is prettier`);
    }
  } catch (e) {
    didError = true;
  }
});
陈帅's avatar
陈帅 committed
42

陈帅's avatar
陈帅 committed
43 44 45
if (didError) {
  process.exit(1);
}
陈帅's avatar
陈帅 committed
46
console.log('\x1b[32m prettier success!');