Question

I'm new to git hooks. I'm not able to understand below pre-commit hook. Can anyone tell me how this works please.Here my doubt is how grep will be happened in committed files as we are not taking those files anywhere. Sorry if am asking wrong question but please help me in understanding git hooks..

#!/usr/bin/env ruby
if `grep -rls "require 'ruby-debug'; raise" *` != ""
  puts "You twit, you've left a debugger in!"
  exit(1)
end
Était-ce utile?

La solution

You should rather grep on indexed (cached) files, instead of your working tree.
Otherwise, your grep could find debug instructions in files (or part of files) which aren't part of the next commit.

See "Git pre-commit hook : changed/added files":

git diff --cached --name-only --diff-filter=ACM

As explained in "Why You Need a Git Pre-Commit Hook and Why Most Are Wrong":

Most test against whatever files are currently on disk, not what is in the staging area (the files actually being committed).

The approach if that hook is a bit different: it stashes every work in progress before searching the files.

def main(all_files):
    # Stash any changes to the working tree that are not going to be committed
    subprocess.call(['git', 'stash', '-u', '--keep-index'], stdout=subprocess.PIPE)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top