gitmail 19.6 KB
Newer Older
1
2
3
4
5
6
#!/usr/bin/perl -w
#
# gitmail - script to send mail for git commits
# Robert Ricci <ricci@cs.utah.edu>
# December 2009
#
7
# To set this script up:
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# 1) Copy or link it to .git/hooks/post-receive in your repository. Make sure
#    it's world-readable and executable.
# 2) Set configuration options by editng the values of variables directly
#    below
#       OR
#    Set the simple values with git options: run
#       git config --add hooks.gitmail.<optname> value
#       (for example:
#           git config --add hooks.gitmail.alwaysmail ricci@cs.utah.edu
# 3) Test it by running it with the -d and -t options, which will not send
#    mail and will give you a chance to make sure everything looks right
#
# TODO:
#    Users can add notifications for themselves
#    Support branch deletion
#    Support commits that remove revisions (ie. are not fast-forwards)
#    Support tag creation/deletion/etc.
#

use strict;
use POSIX 'setsid';
use Getopt::Long;
sub get_config($$);
my $CONFIGBASE = "hooks.gitmail";

######################################################################
# Configuration Options
# Options that use get_config can be set using 'git config' - if not
# set, the second parameter is used as the default
######################################################################

#
# If debugging is enabled, prints a lot of messages and doesn't actually send
# mail.
#
my $debug = get_config("debug",undef);

#
# If set, just picks up the most recent commits instead of reading them from
# stdin. Note that this one doesn't look in the git config; that wouldn't
# make any sense.
#
my $testmode = undef;

#
# Command-line options - have to do this before setting other options, since
# we want to be able to turn on debugging early
#
my %opt;
57
Getopt::Long::Configure("no_ignore_case");
58
if (!GetOptions(\%opt, 'd', 'h', 't', 'T=s') || @ARGV || $opt{h}) {
59
60
61
62
    print STDERR "Usage: gitmail [-h|-d]\n";
    print STDERR "  -h    this message\n";
    print STDERR "  -d    enable debugging output and don't send mail\n";
    print STDERR "  -t    test mode - operate on last 3 commits to master\n";
63
64
    print STDERR "  -T br Like '-t', but use branch 'br' instead of master\n";
    exit 1;
65
66
}

67
my $testbranch = "master";
68
69
if ($opt{d}) { $debug    = 1; }
if ($opt{t}) { $testmode = 1; }
70
if ($opt{T}) { $testmode = 1; $testbranch = $opt{T} }
71
72
73
74
75
76
77
78

#
# Name of this repository - set it to a string to get it included in the
# mail subject line and the X-Git-Repo header
#
my $reponame = get_config("reponame",undef);

#
79
80
81
82
83
84
85
86
# Data structure mapping branch names and path names to email address. Each
# entry is a triple:
#    Branch name
#    File path
#    Mail address
# If *both* the branch and path match for a commit, mail will be sent to the
# associated address. The branch and paths are interpreted as perl regexps,
# with the special value 'undef' matching anything at all. Any of these may
87
# be array references: for the branch and path fields, if *any* of the
88
89
# elements in the array match, the field is considered to match. For the email
# address field, the mail will be sent to all addresses in the array.
90
91
92
#
# *NOTE* This are perl regexps, not shell globs! *NOTE*
#
93
94
95
96
97
98
99
100
101
my @mailto = (
  # Branch              # Path             # Send mail to
# Examples
# [ undef,              undef,             'cvs-testbed@flux.utah.edu' ],
# [ undef,              'snmpit',         ['ricci@flux.utah.edu',
#                                          'sklower@vangogh.cs.berkeley.edu']],
# [ ['^ricci-',
#    '^test-'],         'assign/',         'ricci+assign@flux.utah.edu'],
# [ 'gitmail',          'tools/git',       'ricci+git@flux.utah.edu']
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
);

#
# Default mail address - if none of the more specific regular expressions
# match, send to this address
#
my $defmail = get_config("defmail",undef);

#
# If set, *always* send mail to this address (even if one or more regexps
# match). ($defmail will still be used if no regexps match)
#
my $alwaysmail = get_config("alwaysmail",undef);

#
# If set to true, detach and run in background - the push doesn't return until
# the hook finishes, so doing this means the pusher doesn't have to wait for
# us to finish
# Note: Not well tested!
#
my $detach = get_config("detach",undef);

#
# If set to true, send a separate mail message for every single commit. If
# false, pushes of multiple commits along a branch get included in the same
# mail.
#
129
130
131
132
133
134
135
my $separate_mail = get_config("separatemail",undef);

#
# If set, these arguments will be passed *in addition* to the regular arguments
# to 'git show' to produce descriptions of commits
#
my $showcommit_extra = get_config("showcommitextra",undef);
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191

######################################################################
# Constants
######################################################################

#
# Programs we use
#
my $GIT = "git";
my $SENDMAIL = get_config("sendmail","sendmail");

#
# Magic 'hash' that indicates an empty or non-existant rev
#
my $EMPTYREV = "0"x40;

#
# Types of changes
#
my $CT_CREATE = "create";
my $CT_UPDATE = "update";
my $CT_DELETE = "delete";

#
# Tired of typing this and getting it wrong
#
my $STDERRNULL = " 2> /dev/null";

######################################################################
# Function Prototypes
######################################################################
sub change_type($$);
sub rev_type($);
sub revparse($);
sub changed_files($$);
sub get_mail_addresses($@);
sub uniq(@);
sub flatten_arrayref($);
sub commit_mail($$$@);
sub get_commits($$$);
sub send_mail($$@);
sub short_refname($);
sub debug(@);
sub rev_string($$);

######################################################################
# Main Body
######################################################################

debug("starting");

my @reflines;
if ($testmode) {
    #
    # Provide a simple way to grab some commits - the three most recent ones
    #
192
    @reflines = ("$testbranch~2 $testbranch refs/heads/$testbranch");
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
} else {
    #
    # Get all of the references that are being pushed from stdin - we do this in
    # one slurp so that we can detach below
    #
    @reflines = <STDIN>;
    debug("finished reading stdin");
}


#
# Detach?
#
if ($detach && !$debug) {
    # Stolen from perlipc manpage
    chdir '/'               or die "Can't chdir to /: $!";
    open STDIN, '/dev/null' or die "Can't read /dev/null: $!";
    open STDOUT, '>/dev/null'
                            or die "Can't write to /dev/null: $!";
    defined(my $pid = fork) or die "Can't fork: $!";
    exit if $pid;
    setsid                  or die "Can't start a new session: $!";
    open STDERR, '>&STDOUT' or die "Can't dup stdout: $!";
}

#
# Loop over all of the references we got on stdin
#
foreach my $refline (@reflines) {
    chomp $refline;
    debug("Read line '$refline'");

    #
    # Each line we get on stdin gives us an old revision, a new revision, and
    # a reference (such as the branch name). It's our job to figure out what
    # happened in the middle
    #
    my ($oldrev, $newrev, $refname) = split(/\s+/, $refline);

    #
    # Use rev-parse so that fancy symbolic names, etc. can be used
    # Note: revparse can die if the name given is bogus
    #
    $oldrev = revparse($oldrev);
    $newrev = revparse($newrev);

    #
    # Figure out what type of change occured (update, creation, deletion, etc.)
    # and what type of objects (commit, tree, etc.) we got
    #
    my $ct = change_type($oldrev,$newrev);
    my $old_type = rev_type($oldrev);
    my $new_type = rev_type($newrev);

    debug("Change type: $ct ($old_type,$new_type)");

    #
    # For now, only handle commits that update existing branches or make
    # new ones
    #
    if ($new_type ne "commit") {
        debug("Skipping non-commit");
        next;
    }

    #
    # Get a list of all of the files that changed
    #
    my @changed_files = changed_files($oldrev,$newrev);
    debug("Changed files: ", join(",",@changed_files));

    #
    # Based on the list of files, figure out who to mail
    #
    my @mailaddrs = get_mail_addresses($refname,@changed_files);
    debug("Mailing to: ", join(",",@mailaddrs));

    #
    # Send off the mail!
    #
    if (@mailaddrs) {
        print "Sending email notification to ", join(",",@mailaddrs), "\n";
        commit_mail($oldrev,$newrev,$refname,@mailaddrs);
    }
}

debug("finishing");

######################################################################
# Functions
######################################################################

#
# Does this change represent the creation, deletion, or update of an object?
# Takes old and new revs
#
sub change_type($$) {
    my ($oldrev, $newrev) = @_;
291

292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
    #
    # We can detect creates and deletes by looking for a special 'null'
    # revision
    #
    if ($oldrev eq $EMPTYREV) {
        return $CT_CREATE;
    } elsif ($newrev eq $EMPTYREV) {
        return $CT_DELETE;
    } else {
        return $CT_UPDATE;
    }
}

#
# Find out what type an object has
#
sub rev_type($) {
    my ($rev) = @_;
    my $rev_type = `git cat-file -t '$rev' $STDERRNULL`;
    chomp $rev_type;
    return $rev_type;
}

#
# Parse (possibly) symbolic revision name into hash
# Note: Dies if the revision name is bogus!
#
sub revparse($) {
    my ($rev) = @_;
    open(RP,"$GIT rev-parse $rev $STDERRNULL |");
    my $parsedrev = <RP>;
    my $okay = close(RP);
    if (!$okay) {
        die "gitmail: $rev is not a valid revision\n";
    }
    chomp $parsedrev;
    return $parsedrev;
}

#
# Given two revisions, return an list of the files that were changed between
# them
#
sub changed_files($$) {
    my ($oldrev,$newrev) = @_;

    my $revstring = rev_string($oldrev,$newrev);
    debug("running '$GIT diff-tree -r --name-only '$revstring''");
    my @lines = `$GIT diff-tree -r --name-only '$revstring' $STDERRNULL`;
    chomp @lines;
    return @lines;
}

#
# Given a refname and a list of filenames, return the set of email addresses
# the report should be sent to
#
sub get_mail_addresses($@) {
    my ($refname, @changedfiles) = @_;
    my @addrs;
    my $matched = 0;

    #
    # Note: we use flatten_arrayref so that either individual strings or array
    # references containing lists of addresses can be used
    #

    #
    # If there's an address we're always supposed to send to, include that now
    #
    if (defined($alwaysmail)) {
        push @addrs, flatten_arrayref($alwaysmail);
        debug("Used alwaysmail address $alwaysmail");
    }

    #
368
369
370
    # Find out if this is a branch, and of so, what it's name is. If it's not,
    # set the branch name to be empty, so that only empty regexps will match
    # it
371
    #
372
    my $branchname = "";
373
    if ($refname =~ /^refs\/heads\/(.*)/) {
374
       $branchname = $1;
375
376
377
    }

    #
378
    # Loop through each entry, making sure both branch and path match
379
    #
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
    ENTRY: foreach my $entry (@mailto) {
        my ($branches, $paths, $addresses) = @$entry;
        my @branches = flatten_arrayref($branches);
        my @paths = flatten_arrayref($paths);
        my @addresses = flatten_arrayref($addresses);

        #
        # If the branch doesn't match, go on to the next entry
        #
        my $branch_matched = 0;
        BRANCH: foreach my $branchRE (@branches) {
            if (!defined($branchRE)) {
                debug("Empty branch matched");
                $branch_matched = 1;
                last BRANCH;
            } elsif ($branchname =~ $branchRE) {
                debug("Matched branch regexp /$branchRE/");
                $branch_matched = 1;
                last BRANCH;
399
400
            }
        }
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437

        if (!$branch_matched) {
            next ENTRY;
        }

        #
        # If the path doesn't match, go on to the next entry
        #
        my $paths_matched = 0;
        PATH: foreach my $regexp (@paths) {
            if (!defined($regexp)) {
                debug("  Empty path matched");
                $paths_matched = 1;
                last PATH;
            }
            # Have to check against every file in the changeset
            foreach my $file (@changedfiles) {
                if ($file =~ $regexp) {
                    debug("  Matched path regexp /$regexp/");
                    $paths_matched = 1;
                    last PATH;
                }
            }
        }

        if (!$paths_matched) {
            debug("  Path match failed");
            next ENTRY;
        }

        #
        # Great, made it through - we add all addresses, we'll weed out
        # duplicates later
        #
        debug("  Adding adddresses ", join(",",@addresses));
        $matched = 1;
        push @addrs, @addresses;
438
439
440
441
442
443
444
445
446
447
448
    }

    #
    # Fall back to default if no matches (note that an earlier match with an
    # empty list of addresses will cause this case to not be triggered - this
    # is intentional)
    #
    if (!$matched && defined($defmail)) {
        @addrs = flatten_arrayref($defmail);
        debug("Used default address $alwaysmail");
    }
449

450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
    #
    # Pull out unique values to return
    #
    return uniq(@addrs);
}

#
# Return only the unique elements of the supplied list. Input does not have
# to be sorted, sort order of output is undefined.
#
sub uniq(@) {
    my %uniq;
    map { $uniq{$_} = 1 } @_;
    return keys %uniq;
}

#
# If the parameter is a scalar, just return a one-element array containing the
# scalar. If it's a reference to an array, return the array referenced.
#
sub flatten_arrayref($) {
    my ($ref) = @_;
    if (ref($ref) eq "ARRAY") {
        return @$ref;
    } else {
        return ($ref);
    }
}

#
# Send mail about a regular update commit
#
sub commit_mail($$$@) {
    my ($oldrev,$newrev,$refname,@mailaddrs) = @_;

    #
    # What type of chage was this?
    #
    my $ct = change_type($oldrev,$newrev);

    #
    # Get all commits between these two revisions
    #
    my @revs = get_commits($oldrev,$newrev,$refname);

    debug("commits are: ", join(" ",@revs));

    #
    # Construct the subject line. For now, we just say what repo (if defined)
    # and what branch it happened on
    #
    my $subject = "git commit: ";
    if (defined($reponame)) {
        $subject .= "[$reponame] ";
    }
    $subject .= "branch " . short_refname($refname);

    if ($ct eq $CT_UPDATE) {
        $subject .= " updated";
    } elsif ($ct eq $CT_CREATE) {
        $subject .= " created";
    } elsif ($ct eq $CT_DELETE) {
        $subject .= " deleted";
    }

    my $actionstring = "Branch " . short_refname($refname) .
                       " has been ${ct}d\n\n";
517

518
519
520
521
522
523
    my @fullbody;
    foreach my $rev (@revs) {
        #
        # Just use regular git show command, with purty +/- summary at the
        # bottom (formatted to be narrow enough for email)
        #
524
525
526
527
528
529
530
        my $showcommand = "$GIT show --numstat --shortstat ";
        if (defined($showcommit_extra)) {
            $showcommand .= "$showcommit_extra ";
        }
        $showcommand .= "'$rev'";
        debug("running '$showcommand'");
        my @body = `$showcommand`;
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682

        if ($separate_mail) {
            # Send this message by itself
            send_mail($subject,$actionstring . join("",@body),@mailaddrs);
        } else {
            push @fullbody,\@body;
        }
    }

    #
    # Send all the changes together in one message
    #
    if (!$separate_mail) {
        send_mail($subject,
            $actionstring . join("-"x72 . "\n", map { join "",@$_} @fullbody),
            @mailaddrs);
    }
}

#
# Given two revisions, get a list of the commits that occured between them
# TODO: Consider leaving out already-reachable commits like the contrib script
#       does, or at least making it an option
#
sub get_commits($$$) {
    my ($oldrev,$newrev,$refname) = @_;
    my $ct = change_type($oldrev,$newrev);

    #
    # If this is an update, we can just ask git for the revisions between the
    # two revisions we were given
    #
    if ($ct eq $CT_UPDATE) {
        my $revstring = rev_string($oldrev,$newrev);

        debug("running '$GIT rev-list --reverse --date-order '$revstring'");
        my @revs = `$GIT rev-list --reverse --date-order '$revstring'`;
        chomp @revs;
        return @revs;

    } elsif ($ct eq $CT_CREATE) {
        #
        # If it's a create, we have to be a bit more fancy: we look for all
        # commits reachable from the new branch, but *not* reachable from any
        # other branch (otherwise, we get all of the history back to the dawn
        # of time). I stole this magic from the contrib post-receive-email hook
        # from the git distro.
        #

        #
        # Get the list of all other branch heads
        #
        my @other_branches = `$GIT for-each-ref --format='%(refname)' refs/heads/ | grep -F -v $refname`;
        chomp @other_branches;

        my $other_branches = join(" ",@other_branches);
        debug("other branches are: '$other_branches'");

        #
        # Get a list of commits that are reachable from this branch, and no
        # others.
        #
        debug("running '$GIT rev-parse --not $other_branches | $GIT rev-list --pretty --stdin $newrev'");
        my @commits = `$GIT rev-parse --not $other_branches | $GIT rev-list --reverse --date-order --stdin $newrev`;

        chomp @commits;
        return @commits;
    }

    #
    # The following magic is from the contrib post-receive hook, and it tries
    # to avoid sending the same commit in mail twice, by excluding commits that
    # are reachable from other branches
    #
    #my @other_branches = `$GIT for-each-ref --format='%(refname)' refs/heads/ | grep -F -v $refname`;
    #chomp @other_branches;
    #my $other_branches = join(" ",@other_branches);
    #if ($debug) {
    #    print "other_branches magic: '$other_branches'\n";
    #}
    #my $rev_parse = `$GIT rev-parse --not $other_branches`;
    #if ($debug) {
    #    print "rev_parse magic: \n" . $rev_parse;
    #}
    #my @commits = `$GIT rev-parse --not $other_branches | $GIT rev-list --pretty --stdin $revspec`;

}

#
# Send out some mail (or not, if in debug mode)
#
sub send_mail($$@) {
    my ($subject, $body, @to) = @_;

    if ($debug) {
           open(MAIL,">&STDERR");
           print MAIL "\n\n";
    } else {
           # sendmail args:
           # -oem causes errors in mail to be "mailed back"
           # -odb deliver mail in background
           # -t causes sendmail to look in the message for 'To:' 'Cc:' and
           #    'Bcc:' lines
           open(MAIL, "| $SENDMAIL -odb -oem -t");
    }

    print MAIL "To: " . join(", ",@to) . "\n";
    print MAIL "Subject: $subject\n";

    #
    # Add an X-Git-Repo header to help people procmail
    # TODO: Add branch too!
    #
    if (defined($reponame)) {
        print MAIL "X-Git-Repo: $reponame\n";
    }

    #
    # Marks end of headers
    #
    print MAIL "\n";

    print MAIL $body;

}

#
# Given a full refname, pull off the last part for pretty printing
#
sub short_refname($) {
    my ($refname) = @_;
    $refname =~ /([^\/]+)$/;
    return $1;
}

#
# Print only if in debug mode
#
sub debug(@) {
    if ($debug) {
        print STDERR "*** gitmail: ", @_, "\n";
    }
}

#
# Return either the config value associated with the repo or the second
# argument, which supplies the default.
#
sub get_config($$) {
    my ($var,$default) = @_;
    my $value = `git config $CONFIGBASE.$var`;
    chomp $value;
683
    if ($value ne "") {
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
        debug("Got $value from git config for $var");
        return $value;
    } else {
        debug("Using " , defined($default)?$default : "(undef)" , " for $var");
        return $default;
    }
}

#
# Return an appropriate string to get a revision: if the ref was created or
# deleted, this looks a little different
#
sub rev_string($$) {
    my ($oldrev, $newrev) = @_;
    my $ct = change_type($oldrev,$newrev);
    if ($ct eq $CT_UPDATE) {
        return "$oldrev..$newrev";
    } elsif ($ct eq $CT_CREATE) {
        return $newrev;
    } elsif ($ct eq $CT_DELETE) {
        return $oldrev;
    } else {
        # Shouldn't be able to get here
        return undef;
    }
}