diff --git a/package.json b/package.json index 1363ec790f8df681c5f7d6394efecf4bb1fba1a4..46eda13d1827f196bd3bda886e832be3a8bad064 100644 --- a/package.json +++ b/package.json @@ -20,7 +20,7 @@ "test": "umi test", "test:component": "umi test ./src/components", "test:all": "node ./tests/run-tests.js", - "prettier": "node node ./scripts/prettier.js", + "prettier": "node ./scripts/prettier.js", "docker:dev": "docker-compose -f ./docker/docker-compose.dev.yml up", "docker:build": "docker-compose -f ./docker/docker-compose.dev.yml build", "docker-prod:dev": "docker-compose -f ./docker/docker-compose.yml up", @@ -100,7 +100,7 @@ }, "lint-staged": { "**/*.{js,jsx,less}": [ - "prettier --write", + "node ./scripts/lint-prettier.js", "git add" ], "**/*.{js,jsx}": "npm run lint-staged:js", diff --git a/scripts/lint-prettier.js b/scripts/lint-prettier.js new file mode 100644 index 0000000000000000000000000000000000000000..ad825a1a3238f49407793138f3a8431e213d2f22 --- /dev/null +++ b/scripts/lint-prettier.js @@ -0,0 +1,43 @@ +/** + * copy to https://github.com/facebook/react/blob/master/scripts/prettier/index.js + * prettier api doc https://prettier.io/docs/en/api.html + *----------*****-------------- + * lint file is prettier + *----------*****-------------- + */ + +const glob = require('glob'); +const prettier = require('prettier'); +const fs = require('fs'); +const prettierConfigPath = require.resolve('../.prettierrc'); + +const files = process.argv.slice(2); + +let didError = false; +let didWarn = false; + +files.forEach(file => { + const options = prettier.resolveConfig.sync(file, { + config: prettierConfigPath, + }); + try { + const fileInfo = prettier.getFileInfo.sync(file); + const input = fs.readFileSync(file, 'utf8'); + const withParserOptions = { + ...options, + parser: fileInfo.inferredParser, + }; + const isPrettier = prettier.check(input, withParserOptions); + if (!isPrettier) { + console.log(`\x1b[31m ${file} is no prettier, please use npm run prettier and git add !`); + didWarn = true; + } + } catch (e) { + didError = true; + } +}); + +if (didWarn || didError) { + process.exit(1); +} +console.log('\x1b[32m lint prettier success!'); diff --git a/scripts/prettier.js b/scripts/prettier.js index 5cbe5c016c6487ce3a1d1b2232decfe83dfb5e3b..b4dbef34ac97fc8ee02b252eb0a5bd9241ff959c 100644 --- a/scripts/prettier.js +++ b/scripts/prettier.js @@ -22,11 +22,11 @@ if (!files.length) { return; } -files.forEach(async file => { +files.forEach(file => { const options = prettier.resolveConfig.sync(file, { config: prettierConfigPath, }); - const fileInfo = await prettier.getFileInfo(file); + const fileInfo = prettier.getFileInfo.sync(file); try { const input = fs.readFileSync(file, 'utf8'); const withParserOptions = { @@ -42,7 +42,8 @@ files.forEach(async file => { didError = true; } }); -console.log('\x1b[32m prettier success!'); + if (didError) { process.exit(1); } +console.log('\x1b[32m prettier success!');