3

I'm trying to create a git hook that is run after a checkout only if a new branch was checked out (i.e. the -b flag was used). I'm using a post-checkout hook and have tried various techniques to get this working like checking oldrev.

Is post-checkout the hook I want? If so what logic should I use in the script so the hook only takes effect when a new branch is checked out?

Thank you!

timo.rieber
  • 3,727
  • 3
  • 32
  • 47
westonkd
  • 96
  • 9
  • As far as I know, once created, a "new" branch is indistinguishable from an "old" branch. – jub0bs Sep 25 '14 at 20:37
  • I don't think git provides a way to do what you want. You might be able to get occasional success by seeing how many reflog entries there are though. – Andrew C Sep 25 '14 at 20:37
  • possible duplicate of [Post-checkout hook with Git](http://stackoverflow.com/questions/1011557/post-checkout-hook-with-git) – jub0bs Sep 25 '14 at 21:04
  • Thanks, previous to asking my question I read the question mentioned above as a possible duplicate. The answers to it address how to use the post-checkout hook, but don't answer the questions of detecting a new branch. – westonkd Sep 25 '14 at 21:16
  • @westonkd I don't think that's possible in a more reliable manner than [that suggested by Andrew](http://stackoverflow.com/questions/26047579/git-post-checkout-hook-on-new-branches-only#comment40805108_26047579). – jub0bs Sep 25 '14 at 21:22
  • Its over a year later, have things changed? – Ashley Coolman Feb 05 '16 at 11:54

1 Answers1

0

The problem is not finding the hook (a post-checkout hook can be used).
It is to detect that a new local branch has just been created.

But "new" compared to which branch? Detecting a "branch point" is tricky, considering you don't know which starting branch to consider.

You can also check the reflog to verify that the branch has been checked out once.

Or, you could also maintain a cache of the local branches: the output of ls .git\refs\heads, saved somewhere as a file being said "cache".
Each time the post-checkout hook is fired up, it would do the ls .git\refs\heads and compare it with its cache. If a new entry is seen (and there is no similar branch in .git\refs\remotes\origin), chances are: this is a new local branch created for the very first time.
Then the hook would update the cache file.

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250