prettier.js 1.21 KB
Newer Older
陈帅's avatar
陈帅 committed
1 2 3 4 5 6 7 8 9 10
/**
 * 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 prettier = require('prettier');
const fs = require('fs');
陈帅's avatar
陈帅 committed
11
const getPrettierFiles = require('./getPrettierFiles');
陈帅's avatar
陈帅 committed
12
const prettierConfigPath = require.resolve('../.prettierrc');
13
const chalk = require('chalk');
陈帅's avatar
陈帅 committed
14 15 16

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
  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');
36
      console.log(chalk.green(`${file} is prettier`));
陈帅's avatar
陈帅 committed
37 38
    }
  } catch (e) {
陈帅's avatar
陈帅 committed
39
    console.log(e);
陈帅's avatar
陈帅 committed
40 41 42
    didError = true;
  }
});
陈帅's avatar
陈帅 committed
43

陈帅's avatar
陈帅 committed
44 45 46
if (didError) {
  process.exit(1);
}
47
console.log(chalk.hex('#1890FF')('prettier success!'));