Pre commit hook checks for source lint (not staged)

1.4k Views Asked by At

The idea of git hooks is for preventing the wrong source code from being committed. I use husky for this purpose. Here is my setting:

"husky": {
  "hooks": {
    "pre-commit": "ng lint --fix=true"
  }
}

If there is a lint error, it prevents from being committed. Here is the scenario:

  1. Developer writes wrong code (e.g. x==y which should be x===y from lint point of view)
  2. He uses these commands: git add . and git commit -m "msg here" which fails. Because lint fails.
  3. He corrects the source code. But instead of doing git add . again, he uses this command: git commit -m "msg here". This time lint doesn't fail, because in source code everything is fine, and ng lint succeeds. But actually, he is committing the previous version which has been added before.

Any idea how to prevent this?

1

There are 1 best solutions below

4
On BEST ANSWER

lint-staged is what you are looking for.

It will only lint the staged files, which is really efficient.

That means that it would force the developer in your example to stage the fix before lint-staged will accept it.

Put this in your package.json file:

{ 
   ...
   "devDependencies": {
       "lint-staged": "^10.5.1",
       ...
   }
   ...
   "husky": {
       "hooks": {
           "pre-commit": "lint-staged"
        }
    }
   ...
}