setup-hooks 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #!/usr/bin/env bash
  2. #=============================================================================
  3. # Copyright 2010-2012 Kitware, Inc.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. #=============================================================================
  17. # Run this script to set up local Git hooks for this project.
  18. # Project configuration instructions:
  19. #
  20. # - Publish a "hooks" branch in the project repository such that
  21. # clones will have "refs/remotes/origin/hooks".
  22. #
  23. # - Populate adjacent "config" file with:
  24. # hooks.url = Repository URL publishing "hooks" branch
  25. # hooks.branch = Repository branch instead of "hooks"
  26. egrep_q() {
  27. egrep "$@" >/dev/null 2>/dev/null
  28. }
  29. die() {
  30. echo 1>&2 "$@" ; exit 1
  31. }
  32. # Make sure we are inside the repository.
  33. cd "${BASH_SOURCE%/*}" &&
  34. # Select a hooks branch.
  35. if url=$(git config --get hooks.url); then
  36. # Fetch hooks from locally configured repository.
  37. branch=$(git config hooks.branch || echo hooks)
  38. elif git for-each-ref refs/remotes/origin/hooks 2>/dev/null |
  39. egrep_q 'refs/remotes/origin/hooks$'; then
  40. # Use hooks cloned from origin.
  41. url=.. && branch=remotes/origin/hooks
  42. elif url=$(git config -f config --get hooks.url); then
  43. # Fetch hooks from project-configured repository.
  44. branch=$(git config -f config hooks.branch || echo hooks)
  45. else
  46. die 'This project is not configured to install local hooks.'
  47. fi &&
  48. # Populate ".git/hooks".
  49. echo 'Setting up git hooks...' &&
  50. git_dir=$(git rev-parse --git-dir) &&
  51. mkdir -p "$git_dir/hooks" &&
  52. cd "$git_dir/hooks" &&
  53. if ! test -e .git; then
  54. git init -q || die 'Could not run git init for hooks.'
  55. fi &&
  56. git fetch -q "$url" "$branch" &&
  57. git reset -q --hard FETCH_HEAD || die 'Failed to install hooks'