Home > Blockchain >  git add same files in precommit after formatting, cannot add deleted files
git add same files in precommit after formatting, cannot add deleted files

Time:04-08

I have a react project where we have been manually formatting our code before every push. So logically I setup the precommit hook using husky.

This is the precommit hook

#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

added_files=$(git diff --name-only --cached)

yarn fix
git add ${added_files}

I want to "re-add" the same files, as it was intended by the author of commit (yarn fix runs over the whole project).

Now this hook works perfectly, until I have some deleted files.

output of git status:

Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
        new file:   .babelrc
        modified:   .gitignore
        modified:   package.json
        modified:   public/index.html
        deleted:    src/App.css

Output of git diff --name-only --cached:

.babelrc
.gitignore
package.json
public/index.html
src/App.css

Output of pre-commit hook:

yarn run v1.22.10
$ semistandard --fix
Done in 1.23s.
fatal: pathspec 'src/App.css' did not match any files
husky - pre-commit hook exited with code 128 (error)

Seems like deleted files cannot be "re-added". What would be a better solution?

CodePudding user response:

Turns out it was too simple. Fixed by adding --diff-filter, which would filter out deleted files.

#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

added_files=$(git diff --name-only --cached --diff-filter=d)

yarn fix
git add ${added_files}
  • Related