Skip to content

Commit

Permalink
fix: don't apply empty patch files on pre-commit hook (#676)
Browse files Browse the repository at this point in the history
* Don't apply unstaged changes if there were no changes in the patch
  • Loading branch information
mrexox committed Mar 15, 2024
1 parent e9573bb commit 099ab60
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 5 deletions.
27 changes: 23 additions & 4 deletions internal/git/repository.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package git

import (
"fmt"
"os"
"path/filepath"
"regexp"
Expand Down Expand Up @@ -198,7 +199,21 @@ func (r *Repository) RestoreUnstaged() error {
return nil
}

_, err := r.Git.Cmd([]string{
stat, err := r.Fs.Stat(r.unstagedPatchPath)
if err != nil {
return err
}

if stat.Size() == 0 {
err = r.Fs.Remove(r.unstagedPatchPath)
if err != nil {
return fmt.Errorf("couldn't remove the patch %s: %w", r.unstagedPatchPath, err)
}

return nil
}

_, err = r.Git.Cmd([]string{
"git",
"apply",
"-v",
Expand All @@ -207,12 +222,16 @@ func (r *Repository) RestoreUnstaged() error {
"--unidiff-zero",
r.unstagedPatchPath,
})
if err != nil {
return fmt.Errorf("couldn't apply the patch %s: %w", r.unstagedPatchPath, err)
}

if err == nil {
err = r.Fs.Remove(r.unstagedPatchPath)
err = r.Fs.Remove(r.unstagedPatchPath)
if err != nil {
return fmt.Errorf("couldn't remove the patch %s: %w", r.unstagedPatchPath, err)
}

return err
return nil
}

func (r *Repository) StashUnstaged() error {
Expand Down
2 changes: 1 addition & 1 deletion internal/lefthook/run/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ func (r *Runner) postHook() {
}

if err := r.Repo.RestoreUnstaged(); err != nil {
log.Warnf("Couldn't restore hidden unstaged files: %s\n", err)
log.Warnf("Couldn't restore unstaged files: %s\n", err)
return
}

Expand Down

0 comments on commit 099ab60

Please sign in to comment.