gitmail 24.8 KB
Newer Older
1
2
#!/usr/bin/perl -w
#
3
4
5
# EMULAB-COPYRIGHT
# Copyright (c) 2009-2010 University of Utah and the Flux Group.
# All rights reserved.
6
#
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', 'o=s@') || @ARGV || $opt{h}) {
59
    print STDERR "Usage: gitmail [-h|-d]\n";
60
61
62
63
64
65
    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";
    print STDERR "  -T br  like '-t', but use branch 'br' instead of master\n";
    print STDERR "  -o o=v give option o the value v (may be given multiple\n";
    print STDERR "         times)\n";
66
    exit 1;
67
68
}

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

#
# 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);

#
81
82
83
84
85
86
87
88
# 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
89
# be array references: for the branch and path fields, if *any* of the
90
91
# 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.
92
93
#
# *NOTE* This are perl regexps, not shell globs! *NOTE*
94
# *NOTE* This can also be read from a file - see below *NOTE*
95
#
96
97
98
99
100
101
102
103
104
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']
105
106
);

107
108
109
110
111
112
113
114
115
116
#
# If set, look in a file for the @mailto structure.  This file should be
# executable perl code that returns an array following the same format as the
# @mailto array below. For example, the file could contain:
# ( [ undef, undef, 'me@example.com'] )
#
# *NOTE* If this is set, overrides the @mailto setting above *NOTE*
#
my $mailconfigfile = get_config("mailconfigfile",undef);

117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
#
# 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.
#
142
143
144
145
146
147
148
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);
149

Ryan Jackson's avatar
Ryan Jackson committed
150
151
152
153
#
# If set, check all commit objects to see if they exist in the repository
# at the specified path.  If a commit object exists in this repository,
# do not include its log in the email message.
154
155
156
# Note: This should point at the .git directory - for a 'bare' repository,
# this is just the path the repository. For a 'reglar' repository, this is the
# .git/ directory *inside* the repositry.
Ryan Jackson's avatar
Ryan Jackson committed
157
158
159
#
my $exclude_repo = get_config("excluderepo",undef);

160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
######################################################################
# 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";
181
my $CT_FORCED_UPDATE = "force-update";
182
183
184
185
186
187
188
189
190
191
192
193
194

#
# 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($$);
Ryan Jackson's avatar
Ryan Jackson committed
195
sub changed_files_single_revision($);
196
sub get_mail_addresses($@);
197
sub get_merge_base($$);
198
199
sub uniq(@);
sub flatten_arrayref($);
Ryan Jackson's avatar
Ryan Jackson committed
200
sub commit_mail($\@$@);
201
202
203
204
205
sub get_commits($$$);
sub send_mail($$@);
sub short_refname($);
sub debug(@);
sub rev_string($$);
206
207
sub object_exists($$);
sub filter_out_objects_in_repo($@);
208
209
210
211
212
213
214

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

debug("starting");

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
#
# Read from the mail config file, if requested. We do this before detaching
# so that we can report an error if one occurs.
#
if ($mailconfigfile) {
    #
    # We open the file, read the contents, then eval them. If we didn't get any
    # errors, the result becomes the new contents of the @mailto array
    #
    if (!open(MCF,"<$mailconfigfile")) {
        warn "gitmail: Unable to open config file $mailconfigfile - $!\n";
    } else {
        my @mailcode = <MCF>;
        close MCF;

        #
        # Have to turn array back into a single string before we can call
        # eval on it. Put the result in a temp. variable so that we don't
        # overwrite @mailto if there is an error
        #
        my @mailconfig = eval join("\n",@mailcode);

        #
        # If there were any errors in the eval, they will be found in the magic
        # variable $@ - however, they will also have been printed to stderr, so
        # don't print again
        #
        if ($@) {
243
            warn "gitmail: Error in $mailconfigfile: $@\n";
244
245
246
247
248
249
250
251
252
        } else {
            @mailto = @mailconfig;
        }
    }
}

#
# Get the actual references
#
253
254
255
256
257
my @reflines;
if ($testmode) {
    #
    # Provide a simple way to grab some commits - the three most recent ones
    #
258
    @reflines = ("$testbranch~2 $testbranch refs/heads/$testbranch");
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
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
} 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;
    }

    #
Ryan Jackson's avatar
Ryan Jackson committed
324
325
    # Get all commits between these two revisions
    # and all files that changed
326
    #
Ryan Jackson's avatar
Ryan Jackson committed
327
328
329
330
    my @commits = get_commits($oldrev,$newrev,$refname);
    debug("commits are: ", join(" ",@commits));

    my @changed_files;
331
332
333
334
335
    if (defined $exclude_repo || $ct eq $CT_FORCED_UPDATE) {
	if (defined $exclude_repo) {
	    @commits = filter_out_objects_in_repo($exclude_repo, @commits);
	    next unless (@commits);
        }
Ryan Jackson's avatar
Ryan Jackson committed
336
337
338
339
        @changed_files = map { changed_files_single_revision($_) } @commits;
    } else {
    	@changed_files = changed_files($oldrev,$newrev);
    }
340
341
342
343
344
345
346
347
348
349
350
351
352
    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";
Ryan Jackson's avatar
Ryan Jackson committed
353
        commit_mail($ct,@commits,$refname,@mailaddrs);
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
    }
}

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) = @_;
369

370
371
372
373
374
375
376
377
378
    #
    # 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 {
379
380
381
382
383
384
385
        my $merge_base = get_merge_base($oldrev,$newrev);
	my $oldrev = revparse($oldrev);
	if ($merge_base eq $oldrev) {
            return $CT_UPDATE;
	} else {
            return $CT_FORCED_UPDATE;
	}
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
    }
}

#
# 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;
}

#
Ryan Jackson's avatar
Ryan Jackson committed
416
# Given two revisions, return a list of the files that were changed between
417
418
419
420
421
422
423
424
425
426
427
428
# 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;
}

Ryan Jackson's avatar
Ryan Jackson committed
429
430
431
432
433
434
435
436
437
438
439
440
441
#
# Given one revision, return a list of the files that were changed between
# it and its parents
#
sub changed_files_single_revision($) {
    my ($rev) = @_;

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

442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
#
# 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");
    }

    #
465
466
467
    # 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
468
    #
469
    my $branchname = "";
470
    if ($refname =~ /^refs\/heads\/(.*)/) {
471
       $branchname = $1;
472
473
474
    }

    #
475
    # Loop through each entry, making sure both branch and path match
476
    #
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
    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;
496
497
            }
        }
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534

        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;
535
536
537
538
539
540
541
542
543
544
545
    }

    #
    # 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");
    }
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
    #
    # 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
#
Ryan Jackson's avatar
Ryan Jackson committed
579
580
sub commit_mail($\@$@) {
    my ($ct,$commits,$refname,@mailaddrs) = @_;
581
582
583
584
585
586
587
588
589
590
591
592
593

    #
    # 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";
594
595
    } elsif ($ct eq $CT_FORCED_UPDATE) {
        $subject .= " force-updated";
596
597
598
599
600
601
602
603
    } 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";
604

605
606
607
608
    if ($ct eq $CT_FORCED_UPDATE) {
        $actionstring .= "New and/or modified commits shown below\n\n";
    }

609
    my @fullbody;
Ryan Jackson's avatar
Ryan Jackson committed
610
    foreach my $rev (@$commits) {
611
612
613
614
        #
        # Just use regular git show command, with purty +/- summary at the
        # bottom (formatted to be narrow enough for email)
        #
615
616
617
618
619
620
621
        my $showcommand = "$GIT show --numstat --shortstat ";
        if (defined($showcommit_extra)) {
            $showcommand .= "$showcommit_extra ";
        }
        $showcommand .= "'$rev'";
        debug("running '$showcommand'");
        my @body = `$showcommand`;
622
623
624
625
626
627
628
629
630
631
632
633
634
635

        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,
636
637
            $actionstring . join("\n" . "-"x72 . "\n\n",
                                 map { join "",@$_} @fullbody),
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
            @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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
    # two revisions we were given.  We call git-cherry for this information
    # so that we can identify if a particular commit already exists in the
    # repository with a different commit hash (for the rebase case).
    #
    if ($ct eq $CT_UPDATE || $ct eq $CT_FORCED_UPDATE) {
        debug("running '$GIT cherry '$oldrev' '$newrev'");
	# Only return revs prefixed with a '+' since commits prefixed with a
	# '-' are already in the repository with a different commit hash.  We
	# should have seen those already, so we don't want to see them here.
	# Note that '+' commits may not be "new" per-se, but they are not the
	# same as the existing commit with the same commit message due to
	# rebasing.
	my @revs;
	for (`$GIT cherry '$oldrev' '$newrev'`) {
		chomp;
		unshift @revs, $1 if (/^\+\s+(.*)$/);
	}
670
671
672
673
674
675
676
677
678
679
680
681
682
683
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
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
        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($) {
762
763
764
765
766
767
768
769
    my ($ref) = @_;
    my $refname = `git rev-parse --abbrev-ref $ref $STDERRNULL`;
    chomp $refname;

    # This shouldn't be necessary, but return the full ref if
    # rev-parse doesn't return anything.
    $refname = $ref if (!$refname);
    return $refname;
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
}

#
# 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) = @_;
Ryan Jackson's avatar
Ryan Jackson committed
787

788
789
790
791
792
793
794
795
796
797
798
799
800
    #
    # Allow the user to override on command line
    #
    if ($opt{o}) {
        foreach my $pair (@{$opt{o}}) {
            my ($name,$value) = split /=/, $pair;
            if ($name eq $var) {
                debug("Using config value $value for $name from command line");
                return $value;
            }
        }
    }

801
802
    my $value = `git config $CONFIGBASE.$var`;
    chomp $value;
803
    if ($value ne "") {
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
        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;
    }
}
830

831
832
833
834
835
836
837
838
839
840
841
842
843
#
# Returns the merge base (i.e., common ancestor) of
# the two supplied revisions.
#
sub get_merge_base($$)
{
	my ($rev_a, $rev_b) = @_;
	my $mb = `git merge-base '$rev_a' '$rev_b'`;
	chomp $mb;

	return $mb
}

844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
#
# Returns 1 if the given object (identified by hash) exists in the given
# repository (identified by path); 0 if it does not .
#
sub object_exists($$) {
    my ($obj, $repo) = @_;

    #
    # 'cat-file -e' is like 'test -e', and don't be fooled by the name, it
    # works on non-files too
    #
    debug("running $GIT --git-dir='$repo' cat-file -e $obj");
    my $rv = system "$GIT --git-dir='$repo' cat-file -e $obj";
    if ($rv) {
        return 0;
    } else {
        return 1;
    }
}

#
# Return a list of all objects from the input list that do *not* exist in
# the given repo
#
sub filter_out_objects_in_repo($@) {
    my $repo = shift @_;
    return grep { !object_exists($_,$repo)} @_;
}