66a7bd204efd48d61cfeb9029cfa0128daedb98a
[infrastructure.git] / scripts / post-receive-email-with-diffs
1 #!/bin/sh
2 #
3 # Copyright (c) 2007 Andy Parkins
4 #
5 # An example hook script to mail out commit update information.  This hook
6 # sends emails listing new revisions to the repository introduced by the
7 # change being reported.  The rule is that (for branch updates) each commit
8 # will appear on one email and one email only.
9 #
10 # This hook is stored in the contrib/hooks directory.  Your distribution
11 # will have put this somewhere standard.  You should make this script
12 # executable then link to it in the repository you would like to use it in.
13 # For example, on debian the hook is stored in
14 # /usr/share/doc/git-core/contrib/hooks/post-receive-email:
15 #
16 #  chmod a+x post-receive-email
17 #  cd /path/to/your/repository.git
18 #  ln -sf /usr/share/doc/git-core/contrib/hooks/post-receive-email hooks/post-receive
19 #
20 # This hook script assumes it is enabled on the central repository of a
21 # project, with all users pushing only to it and not between each other.  It
22 # will still work if you don't operate in that style, but it would become
23 # possible for the email to be from someone other than the person doing the
24 # push.
25 #
26 # Config
27 # ------
28 # hooks.mailinglist
29 #   This is the list that all pushes will go to; leave it blank to not send
30 #   emails for every ref update.
31 # hooks.announcelist
32 #   This is the list that all pushes of annotated tags will go to.  Leave it
33 #   blank to default to the mailinglist field.  The announce emails lists
34 #   the short log summary of the changes since the last annotated tag.
35 # hooks.envelopesender
36 #   If set then the -f option is passed to sendmail to allow the envelope
37 #   sender address to be set
38 # hooks.emailprefix
39 #   All emails have their subjects prefixed with this prefix, or "[SCM]"
40 #   if emailprefix is unset, to aid filtering
41 #
42 # Notes
43 # -----
44 # All emails include the headers "X-Git-Refname", "X-Git-Oldrev",
45 # "X-Git-Newrev", and "X-Git-Reftype" to enable fine tuned filtering and
46 # give information for debugging.
47 #
48
49 # ---------------------------- Functions
50
51 #
52 # Top level email generation function.  This decides what type of update
53 # this is and calls the appropriate body-generation routine after outputting
54 # the common header
55 #
56 # Note this function doesn't actually generate any email output, that is
57 # taken care of by the functions it calls:
58 #  - generate_email_header
59 #  - generate_create_XXXX_email
60 #  - generate_update_XXXX_email
61 #  - generate_delete_XXXX_email
62 #  - generate_email_footer
63 #
64 generate_email()
65 {
66     # --- Arguments
67     oldrev=$(git rev-parse $1)
68     newrev=$(git rev-parse $2)
69     refname="$3"
70
71     # --- Interpret
72     # 0000->1234 (create)
73     # 1234->2345 (update)
74     # 2345->0000 (delete)
75     if expr "$oldrev" : '0*$' >/dev/null
76     then
77         change_type="create"
78     else
79         if expr "$newrev" : '0*$' >/dev/null
80         then
81             change_type="delete"
82         else
83             change_type="update"
84         fi
85     fi
86
87     # --- Get the revision types
88     newrev_type=$(git cat-file -t $newrev 2> /dev/null)
89     oldrev_type=$(git cat-file -t "$oldrev" 2> /dev/null)
90     case "$change_type" in
91         create|update)
92             rev="$newrev"
93             rev_type="$newrev_type"
94             ;;
95         delete)
96             rev="$oldrev"
97             rev_type="$oldrev_type"
98             ;;
99     esac
100
101     # The revision type tells us what type the commit is, combined with
102     # the location of the ref we can decide between
103     #  - working branch
104     #  - tracking branch
105     #  - unannoted tag
106     #  - annotated tag
107     case "$refname","$rev_type" in
108         refs/tags/*,commit)     # un-annotated tag
109             refname_type="tag"
110             short_refname=${refname##refs/tags/}
111             ;;
112         refs/tags/*,tag)        # annotated tag
113             refname_type="annotated tag"
114             short_refname=${refname##refs/tags/}
115             # change recipients
116             if [ -n "$announcerecipients" ]; then
117                 recipients="$announcerecipients"
118             fi
119             ;;
120         refs/heads/*,commit)    # branch
121             refname_type="branch"
122             short_refname=${refname##refs/heads/}
123             ;;
124         refs/remotes/*,commit)  # tracking branch
125             refname_type="tracking branch"
126             short_refname=${refname##refs/remotes/}
127             echo >&2 "*** Push-update of tracking branch, $refname"
128             echo >&2 "***  - no email generated."
129             exit 0
130             ;;
131         *)                      # Anything else (is there anything else?)
132             echo >&2 "*** Unknown type of update to $refname ($rev_type)"
133             echo >&2 "***  - no email generated"
134             exit 1
135             ;;
136     esac
137
138     # Check if we've got anyone to send to
139     if [ -z "$recipients" ]; then
140         case "$refname_type" in
141             "annotated tag")
142                 config_name="hooks.announcelist"
143                 ;;
144             *)
145                 config_name="hooks.mailinglist"
146                 ;;
147         esac
148         echo >&2 "*** $config_name is not set so no email will be sent"
149         echo >&2 "*** for $refname update $oldrev->$newrev"
150         exit 0
151     fi
152
153     # Email parameters
154     # The email subject will contain the best description of the ref
155     # that we can build from the parameters
156     describe=$(git describe $rev 2>/dev/null)
157     if [ -z "$describe" ]; then
158         describe=$rev
159     fi
160
161     generate_email_header
162
163     # Call the correct body generation function
164     fn_name=general
165     case "$refname_type" in
166         "tracking branch"|branch)
167             fn_name=branch
168             ;;
169         "annotated tag")
170             fn_name=atag
171             ;;
172     esac
173     generate_${change_type}_${fn_name}_email
174
175     generate_email_footer
176 }
177
178 # generate a pattern for testing if a string is a hash
179 hpat="";__=1; while [ $__ -le 40 ] ; do hpat=${hpat}'[0-9a-f]';__=$(($__+1)); done
180 function is_hash () {
181     local hash
182     hash=$1; shift
183     case $hash in $hpat) return 0;; *) return 1;; esac
184 }
185
186 generate_email_header()
187 {
188     # --- Email (all stdout will be the email)
189     # optimize output for branch, master
190     local details
191     if [ "$refname_type" == branch -a "$short_refname" == master ] ; then
192         details=""
193     else
194         details="$refname_type, $short_refname,"
195     fi
196     local shortrev
197     is_hash $describe && shortrev="$(cut -b1-8 <<< $describe).." || shortrev=$describe
198     # Generate header
199     cat <<-EOF
200         To: $recipients
201         Subject: ${emailprefix}$projectdesc ${details}${change_type}d. ${shortrev}
202         X-Git-Refname: $refname
203         X-Git-Reftype: $refname_type
204         X-Git-Oldrev: $oldrev
205         X-Git-Newrev: $newrev
206
207 On $projectdesc, the $refname_type, $short_refname has been ${change_type}d
208         EOF
209 }
210
211 generate_email_footer()
212 {
213     cat <<-EOF
214
215
216         hooks/post-receive
217         --
218         $projectdesc
219         EOF
220 }
221
222 # --------------- Branches
223
224 #
225 # Called for the creation of a branch
226 #
227 generate_create_branch_email()
228 {
229     # This is a new branch and so oldrev is not valid
230     echo "        at  $newrev ($newrev_type)"
231     echo ""
232
233     echo $LOGBEGIN
234     # This shows all log entries that are not already covered by
235     # another ref - i.e. commits that are now accessible from this
236     # ref that were previously not accessible
237     # (see generate_update_branch_email for the explanation of this
238     # command)
239     git rev-parse --not --branches | grep -v $(git rev-parse $refname) |
240     git rev-list --pretty --stdin $newrev
241     echo $LOGEND
242 }
243
244 #
245 # Called for the change of a pre-existing branch
246 #
247 generate_update_branch_email()
248 {
249     # Consider this:
250     #   1 --- 2 --- O --- X --- 3 --- 4 --- N
251     #
252     # O is $oldrev for $refname
253     # N is $newrev for $refname
254     # X is a revision pointed to by some other ref, for which we may
255     #   assume that an email has already been generated.
256     # In this case we want to issue an email containing only revisions
257     # 3, 4, and N.  Given (almost) by
258     #
259     #  git rev-list N ^O --not --all
260     #
261     # The reason for the "almost", is that the "--not --all" will take
262     # precedence over the "N", and effectively will translate to
263     #
264     #  git rev-list N ^O ^X ^N
265     #
266     # So, we need to build up the list more carefully.  git rev-parse
267     # will generate a list of revs that may be fed into git rev-list.
268     # We can get it to make the "--not --all" part and then filter out
269     # the "^N" with:
270     #
271     #  git rev-parse --not --all | grep -v N
272     #
273     # Then, using the --stdin switch to git rev-list we have effectively
274     # manufactured
275     #
276     #  git rev-list N ^O ^X
277     #
278     # This leaves a problem when someone else updates the repository
279     # while this script is running.  Their new value of the ref we're
280     # working on would be included in the "--not --all" output; and as
281     # our $newrev would be an ancestor of that commit, it would exclude
282     # all of our commits.  What we really want is to exclude the current
283     # value of $refname from the --not list, rather than N itself.  So:
284     #
285     #  git rev-parse --not --all | grep -v $(git rev-parse $refname)
286     #
287     # Get's us to something pretty safe (apart from the small time
288     # between refname being read, and git rev-parse running - for that,
289     # I give up)
290     #
291     #
292     # Next problem, consider this:
293     #   * --- B --- * --- O ($oldrev)
294     #          \
295     #           * --- X --- * --- N ($newrev)
296     #
297     # That is to say, there is no guarantee that oldrev is a strict
298     # subset of newrev (it would have required a --force, but that's
299     # allowed).  So, we can't simply say rev-list $oldrev..$newrev.
300     # Instead we find the common base of the two revs and list from
301     # there.
302     #
303     # As above, we need to take into account the presence of X; if
304     # another branch is already in the repository and points at some of
305     # the revisions that we are about to output - we don't want them.
306     # The solution is as before: git rev-parse output filtered.
307     #
308     # Finally, tags: 1 --- 2 --- O --- T --- 3 --- 4 --- N
309     #
310     # Tags pushed into the repository generate nice shortlog emails that
311     # summarise the commits between them and the previous tag.  However,
312     # those emails don't include the full commit messages that we output
313     # for a branch update.  Therefore we still want to output revisions
314     # that have been output on a tag email.
315     #
316     # Luckily, git rev-parse includes just the tool.  Instead of using
317     # "--all" we use "--branches"; this has the added benefit that
318     # "remotes/" will be ignored as well.
319
320     # List all of the revisions that were removed by this update, in a
321     # fast forward update, this list will be empty, because rev-list O
322     # ^N is empty.  For a non fast forward, O ^N is the list of removed
323     # revisions
324     fast_forward=""
325     rev=""
326     for rev in $(git rev-list $newrev..$oldrev)
327     do
328         revtype=$(git cat-file -t "$rev")
329         echo "  discards  $rev ($revtype)"
330     done
331     if [ -z "$rev" ]; then
332         fast_forward=1
333     fi
334
335     # List all the revisions from baserev to newrev in a kind of
336     # "table-of-contents"; note this list can include revisions that
337     # have already had notification emails and is present to show the
338     # full detail of the change from rolling back the old revision to
339     # the base revision and then forward to the new revision
340     for rev in $(git rev-list $oldrev..$newrev)
341     do
342         revtype=$(git cat-file -t "$rev")
343         echo "       via  $rev ($revtype)"
344     done
345
346     if [ "$fast_forward" ]; then
347         echo "      from  $oldrev ($oldrev_type)"
348     else
349         #  1. Existing revisions were removed.  In this case newrev
350         #     is a subset of oldrev - this is the reverse of a
351         #     fast-forward, a rewind
352         #  2. New revisions were added on top of an old revision,
353         #     this is a rewind and addition.
354         # (1) certainly happened, (2) possibly.  When (2) hasn't
355         # happened, we set a flag to indicate that no log printout
356         # is required.
357
358         echo ""
359
360         # Find the common ancestor of the old and new revisions and
361         # compare it with newrev
362         baserev=$(git merge-base $oldrev $newrev)
363         rewind_only=""
364         if [ "$baserev" = "$newrev" ]; then
365             echo "This update discarded existing revisions and left the branch pointing at"
366             echo "a previous point in the repository history."
367             echo ""
368             echo " * -- * -- N ($newrev)"
369             echo "            \\"
370             echo "             O -- O -- O ($oldrev)"
371             echo ""
372             echo "The removed revisions are not necessarilly gone - if another reference"
373             echo "still refers to them they will stay in the repository."
374             rewind_only=1
375         else
376             echo "This update added new revisions after undoing existing revisions.  That is"
377             echo "to say, the old revision is not a strict subset of the new revision.  This"
378             echo "situation occurs when you --force push a change and generate a repository"
379             echo "containing something like this:"
380             echo ""
381             echo " * -- * -- B -- O -- O -- O ($oldrev)"
382             echo "            \\"
383             echo "             N -- N -- N ($newrev)"
384             echo ""
385             echo "When this happens we assume that you've already had alert emails for all"
386             echo "of the O revisions, and so we here report only the revisions in the N"
387             echo "branch from the common base, B."
388         fi
389     fi
390
391     echo ""
392     if [ -z "$rewind_only" ]; then
393         echo ""
394         echo $LOGBEGIN
395         git rev-parse --not --branches | grep -v $(git rev-parse $refname) |
396         git rev-list --pretty --stdin $oldrev..$newrev
397
398         # XXX: Need a way of detecting whether git rev-list actually
399         # outputted anything, so that we can issue a "no new
400         # revisions added by this update" message
401
402         echo $LOGEND
403     else
404         echo "No new revisions were added by this update."
405     fi
406
407     # The diffstat is shown from the old revision to the new revision.
408     # This is to show the truth of what happened in this change.
409     # There's no point showing the stat from the base to the new
410     # revision because the base is effectively a random revision at this
411     # point - the user will be interested in what this revision changed
412     # - including the undoing of previous revisions in the case of
413     # non-fast forward updates.
414     echo ""
415     echo "Summary of changes:"
416     git diff-tree --stat --summary --find-copies-harder $oldrev..$newrev
417     echo
418     echo
419     echo "Changes between commits $(cut -b1-8 <<< $oldrev)..$(cut -b1-8 <<< $newrev)"
420     git diff $oldrev..$newrev
421 }
422
423 #
424 # Called for the deletion of a branch
425 #
426 generate_delete_branch_email()
427 {
428     echo "       was  $oldrev"
429     echo ""
430     echo $LOGEND
431     git show -s --pretty=oneline $oldrev
432     echo $LOGEND
433 }
434
435 # --------------- Annotated tags
436
437 #
438 # Called for the creation of an annotated tag
439 #
440 generate_create_atag_email()
441 {
442     echo "        at  $newrev ($newrev_type)"
443
444     generate_atag_email
445 }
446
447 #
448 # Called for the update of an annotated tag (this is probably a rare event
449 # and may not even be allowed)
450 #
451 generate_update_atag_email()
452 {
453     echo "        to  $newrev ($newrev_type)"
454     echo "      from  $oldrev (which is now obsolete)"
455
456     generate_atag_email
457 }
458
459 #
460 # Called when an annotated tag is created or changed
461 #
462 generate_atag_email()
463 {
464     # Use git for-each-ref to pull out the individual fields from the tag
465     eval $(git for-each-ref --shell --format='
466         tagobject=%(*objectname)
467         tagtype=%(*objecttype)
468         tagger=%(taggername)
469         tagged=%(taggerdate)' $refname
470     )
471
472     echo "   tagging  $tagobject ($tagtype)"
473     case "$tagtype" in
474         commit)
475
476             # If the tagged object is a commit, then we assume this is a
477             # release, and so we calculate which tag this tag is
478             # replacing
479             prevtag=$(git describe --abbrev=0 $newrev^ 2>/dev/null)
480
481             if [ -n "$prevtag" ]; then
482                 echo "  replaces  $prevtag"
483             fi
484             ;;
485         *)
486             echo "    length  $(git cat-file -s $tagobject) bytes"
487             ;;
488     esac
489     echo " tagged by  $tagger"
490     echo "        on  $tagged"
491
492     echo ""
493     echo $LOGBEGIN
494
495     # Show the content of the tag message; this might contain a change
496     # log or release notes so is worth displaying.
497     git cat-file tag $newrev | sed -e '1,/^$/d'
498
499     echo ""
500     case "$tagtype" in
501         commit)
502             # Only commit tags make sense to have rev-list operations
503             # performed on them
504             if [ -n "$prevtag" ]; then
505                 # Show changes since the previous release
506                 git rev-list --pretty=short "$prevtag..$newrev" | git shortlog
507             else
508                 # No previous tag, show all the changes since time began
509                 git rev-list --pretty=short $newrev | git shortlog
510             fi
511             ;;
512         *)
513             # XXX: Is there anything useful we can do for non-commit objects?
514             ;;
515     esac
516
517     echo $LOGEND
518 }
519
520 #
521 # Called for the deletion of an annotated tag
522 #
523 generate_delete_atag_email()
524 {
525     echo "       was  $oldrev"
526     echo ""
527     echo $LOGEND
528     git show -s --pretty=oneline $oldrev
529     echo $LOGEND
530 }
531
532 # --------------- General references
533
534 #
535 # Called when any other type of reference is created (most likely a
536 # non-annotated tag)
537 #
538 generate_create_general_email()
539 {
540     echo "        at  $newrev ($newrev_type)"
541
542     generate_general_email
543 }
544
545 #
546 # Called when any other type of reference is updated (most likely a
547 # non-annotated tag)
548 #
549 generate_update_general_email()
550 {
551     echo "        to  $newrev ($newrev_type)"
552     echo "      from  $oldrev"
553
554     generate_general_email
555 }
556
557 #
558 # Called for creation or update of any other type of reference
559 #
560 generate_general_email()
561 {
562     # Unannotated tags are more about marking a point than releasing a
563     # version; therefore we don't do the shortlog summary that we do for
564     # annotated tags above - we simply show that the point has been
565     # marked, and print the log message for the marked point for
566     # reference purposes
567     #
568     # Note this section also catches any other reference type (although
569     # there aren't any) and deals with them in the same way.
570
571     echo ""
572     if [ "$newrev_type" = "commit" ]; then
573         echo $LOGBEGIN
574         git show --no-color --root -s $newrev
575         echo $LOGEND
576     else
577         # What can we do here?  The tag marks an object that is not
578         # a commit, so there is no log for us to display.  It's
579         # probably not wise to output git cat-file as it could be a
580         # binary blob.  We'll just say how big it is
581         echo "$newrev is a $newrev_type, and is $(git cat-file -s $newrev) bytes long."
582     fi
583 }
584
585 #
586 # Called for the deletion of any other type of reference
587 #
588 generate_delete_general_email()
589 {
590     echo "       was  $oldrev"
591     echo ""
592     echo $LOGEND
593     git show -s --pretty=oneline $oldrev
594     echo $LOGEND
595 }
596
597 send_mail()
598 {
599     COMMITTER=$(git-for-each-ref --format='%(committer)' --sort=-committerdate count=1 refs/heads)
600     COMMITTERNAME=$(cut -d'<' -f1 <<< $COMMITTER)
601     if [ -n "$envelopesender" ] ; then
602         COMMITTERMAIL=$envelopesender
603     else
604         COMMITTERMAIL=$(cut -d'<' -f2 <<< $COMMITTER |cut -d'>' -f1)
605     fi
606     /usr/sbin/sendmail -t -f "$COMMITTERMAIL" -F "$COMMITTERNAME"
607 }
608
609 # ---------------------------- main()
610
611 # --- Constants
612 LOGBEGIN="-----------------------------------------------------------------------"
613 LOGEND="-----------------------------------------------------------------------"
614
615 # --- Config
616 # Set GIT_DIR either from the working directory, or from the environment
617 # variable.
618 GIT_DIR=$(git rev-parse --git-dir 2>/dev/null)
619 if [ -z "$GIT_DIR" ]; then
620     echo >&2 "fatal: post-receive: GIT_DIR not set"
621     exit 1
622 fi
623
624 if [ -f "$GIT_DIR/description" ]; then
625     projectdesc=$(sed -ne '1p' "$GIT_DIR/description")
626 else
627     projectdesc=$(git-config gitweb.description)
628 fi
629 # Check if the description is unchanged from it's default, and shorten it to
630 # a more manageable length if it is
631 if expr "$projectdesc" : "Unnamed repository.*$" >/dev/null
632 then
633     projectdesc="UNNAMED PROJECT"
634 fi
635
636 recipients=$(git config hooks.mailinglist)
637 announcerecipients=$(git config hooks.announcelist)
638 envelopesender=$(git config hooks.envelopesender)
639 emailprefix=$(git config hooks.emailprefix || echo '[SCM] ')
640
641 # --- Main loop
642 # Allow dual mode: run from the command line just like the update hook, or
643 # if no arguments are given then run as a hook script
644 if [ -n "$1" -a -n "$2" -a -n "$3" ]; then
645     # Output to the terminal in command line mode - if someone wanted to
646     # resend an email; they could redirect the output to sendmail
647     # themselves
648     PAGER= generate_email $2 $3 $1
649 else
650     while read oldrev newrev refname
651     do
652         generate_email $oldrev $newrev $refname | send_mail
653     done
654 fi