git-pre-push-hook.pl 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #!/usr/bin/perl -w
  2. # To use this script: symlink it to .git/hooks/pre-push, then "git push"
  3. #
  4. # This script is called by "git push" after it has checked the remote status,
  5. # but before anything has been pushed. If this script exits with a non-zero
  6. # status nothing will be pushed.
  7. #
  8. # This hook is called with the following parameters:
  9. #
  10. # $1 -- Name of the remote to which the push is being done
  11. # $2 -- URL to which the push is being done
  12. #
  13. # If pushing without using a named remote those arguments will be equal.
  14. #
  15. # Information about the commits which are being pushed is supplied as lines to
  16. # the standard input in the form:
  17. #
  18. # <local ref> <local sha1> <remote ref> <remote sha1>
  19. use warnings;
  20. use strict;
  21. my $remote = $ARGV[0];
  22. my $url = $ARGV[1];
  23. #print("remote: $remote\n");
  24. #print("url: $url\n");
  25. $url =~ s#^git\@github\.com\:#https://github.com/#i;
  26. my $commiturl = $url =~ /\Ahttps?:\/\/github.com\// ? "$url/commit/" : '';
  27. my $z40 = '0000000000000000000000000000000000000000';
  28. my $reported = 0;
  29. while (<STDIN>) {
  30. chomp;
  31. my ($local_ref, $local_sha, $remote_ref, $remote_sha) = split / /;
  32. #print("local_ref: $local_ref\n");
  33. #print("local_sha: $local_sha\n");
  34. #print("remote_ref: $remote_ref\n");
  35. #print("remote_sha: $remote_sha\n");
  36. my $range = '';
  37. if ($remote_sha eq $z40) { # New branch, examine all commits
  38. $range = $local_sha;
  39. } else { # Update to existing branch, examine new commits
  40. $range = "$remote_sha..$local_sha";
  41. }
  42. my $gitcmd = "git log --reverse --oneline --no-abbrev-commit '$range'";
  43. open(GITPIPE, '-|', $gitcmd) or die("\n\n$0: Failed to run '$gitcmd': $!\n\nAbort push!\n\n");
  44. while (<GITPIPE>) {
  45. chomp;
  46. if (/\A([a-fA-F0-9]+)\s+(.*?)\Z/) {
  47. my $hash = $1;
  48. my $msg = $2;
  49. if (!$reported) {
  50. print("\nCommits expected to be pushed:\n");
  51. $reported = 1;
  52. }
  53. #print("hash: $hash\n");
  54. #print("msg: $msg\n");
  55. print("$commiturl$hash -- $msg\n");
  56. } else {
  57. die("$0: Unexpected output from '$gitcmd'!\n\nAbort push!\n\n");
  58. }
  59. }
  60. die("\n\n$0: Failing exit code from running '$gitcmd'!\n\nAbort push!\n\n") if !close(GITPIPE);
  61. }
  62. print("\n") if $reported;
  63. exit(0); # Let the push go forward.
  64. # end of git-pre-push-hook.pl ...