陈帅 7 лет назад
Родитель
Сommit
7b77a0d731
3 измененных файлов с 49 добавлено и 5 удалено
  1. 2 2
      package.json
  2. 43 0
      scripts/lint-prettier.js
  3. 4 3
      scripts/prettier.js

+ 2 - 2
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",

+ 43 - 0
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!');

+ 4 - 3
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!');