git-send-email.perlon commit gitweb: Filter out commit ID from @difftree in git_commit and git_commitdiff (62fae51)
   1#!/usr/bin/perl -w
   2#
   3# Copyright 2002,2005 Greg Kroah-Hartman <greg@kroah.com>
   4# Copyright 2005 Ryan Anderson <ryan@michonline.com>
   5#
   6# GPL v2 (See COPYING)
   7#
   8# Ported to support git "mbox" format files by Ryan Anderson <ryan@michonline.com>
   9#
  10# Sends a collection of emails to the given email addresses, disturbingly fast.
  11#
  12# Supports two formats:
  13# 1. mbox format files (ignoring most headers and MIME formatting - this is designed for sending patches)
  14# 2. The original format support by Greg's script:
  15#    first line of the message is who to CC,
  16#    and second line is the subject of the message.
  17#
  18
  19use strict;
  20use warnings;
  21use Term::ReadLine;
  22use Getopt::Long;
  23use Data::Dumper;
  24use Git;
  25
  26package FakeTerm;
  27sub new {
  28        my ($class, $reason) = @_;
  29        return bless \$reason, shift;
  30}
  31sub readline {
  32        my $self = shift;
  33        die "Cannot use readline on FakeTerm: $$self";
  34}
  35package main;
  36
  37# most mail servers generate the Date: header, but not all...
  38sub format_2822_time {
  39        my ($time) = @_;
  40        my @localtm = localtime($time);
  41        my @gmttm = gmtime($time);
  42        my $localmin = $localtm[1] + $localtm[2] * 60;
  43        my $gmtmin = $gmttm[1] + $gmttm[2] * 60;
  44        if ($localtm[0] != $gmttm[0]) {
  45                die "local zone differs from GMT by a non-minute interval\n";
  46        }
  47        if ((($gmttm[6] + 1) % 7) == $localtm[6]) {
  48                $localmin += 1440;
  49        } elsif ((($gmttm[6] - 1) % 7) == $localtm[6]) {
  50                $localmin -= 1440;
  51        } elsif ($gmttm[6] != $localtm[6]) {
  52                die "local time offset greater than or equal to 24 hours\n";
  53        }
  54        my $offset = $localmin - $gmtmin;
  55        my $offhour = $offset / 60;
  56        my $offmin = abs($offset % 60);
  57        if (abs($offhour) >= 24) {
  58                die ("local time offset greater than or equal to 24 hours\n");
  59        }
  60
  61        return sprintf("%s, %2d %s %d %02d:%02d:%02d %s%02d%02d",
  62                       qw(Sun Mon Tue Wed Thu Fri Sat)[$localtm[6]],
  63                       $localtm[3],
  64                       qw(Jan Feb Mar Apr May Jun
  65                          Jul Aug Sep Oct Nov Dec)[$localtm[4]],
  66                       $localtm[5]+1900,
  67                       $localtm[2],
  68                       $localtm[1],
  69                       $localtm[0],
  70                       ($offset >= 0) ? '+' : '-',
  71                       abs($offhour),
  72                       $offmin,
  73                       );
  74}
  75
  76my $have_email_valid = eval { require Email::Valid; 1 };
  77my $smtp;
  78
  79sub unique_email_list(@);
  80sub cleanup_compose_files();
  81
  82# Constants (essentially)
  83my $compose_filename = ".msg.$$";
  84
  85# Variables we fill in automatically, or via prompting:
  86my (@to,@cc,@initial_cc,@bcclist,@xh,
  87        $initial_reply_to,$initial_subject,@files,$from,$compose,$time);
  88
  89# Behavior modification variables
  90my ($chain_reply_to, $quiet, $suppress_from, $no_signed_off_cc,
  91        $dry_run) = (1, 0, 0, 0, 0);
  92my $smtp_server;
  93
  94# Example reply to:
  95#$initial_reply_to = ''; #<20050203173208.GA23964@foobar.com>';
  96
  97my $repo = Git->repository();
  98my $term = eval {
  99        new Term::ReadLine 'git-send-email';
 100};
 101if ($@) {
 102        $term = new FakeTerm "$@: going non-interactive";
 103}
 104
 105# Begin by accumulating all the variables (defined above), that we will end up
 106# needing, first, from the command line:
 107
 108my $rc = GetOptions("from=s" => \$from,
 109                    "in-reply-to=s" => \$initial_reply_to,
 110                    "subject=s" => \$initial_subject,
 111                    "to=s" => \@to,
 112                    "cc=s" => \@initial_cc,
 113                    "bcc=s" => \@bcclist,
 114                    "chain-reply-to!" => \$chain_reply_to,
 115                    "smtp-server=s" => \$smtp_server,
 116                    "compose" => \$compose,
 117                    "quiet" => \$quiet,
 118                    "suppress-from" => \$suppress_from,
 119                    "no-signed-off-cc|no-signed-off-by-cc" => \$no_signed_off_cc,
 120                    "dry-run" => \$dry_run,
 121         );
 122
 123# Verify the user input
 124
 125foreach my $entry (@to) {
 126        die "Comma in --to entry: $entry'\n" unless $entry !~ m/,/;
 127}
 128
 129foreach my $entry (@initial_cc) {
 130        die "Comma in --cc entry: $entry'\n" unless $entry !~ m/,/;
 131}
 132
 133foreach my $entry (@bcclist) {
 134        die "Comma in --bcclist entry: $entry'\n" unless $entry !~ m/,/;
 135}
 136
 137# Now, let's fill any that aren't set in with defaults:
 138
 139my ($author) = $repo->ident_person('author');
 140my ($committer) = $repo->ident_person('committer');
 141
 142my %aliases;
 143my @alias_files = $repo->config('sendemail.aliasesfile');
 144my $aliasfiletype = $repo->config('sendemail.aliasfiletype');
 145my %parse_alias = (
 146        # multiline formats can be supported in the future
 147        mutt => sub { my $fh = shift; while (<$fh>) {
 148                if (/^alias\s+(\S+)\s+(.*)$/) {
 149                        my ($alias, $addr) = ($1, $2);
 150                        $addr =~ s/#.*$//; # mutt allows # comments
 151                         # commas delimit multiple addresses
 152                        $aliases{$alias} = [ split(/\s*,\s*/, $addr) ];
 153                }}},
 154        mailrc => sub { my $fh = shift; while (<$fh>) {
 155                if (/^alias\s+(\S+)\s+(.*)$/) {
 156                        # spaces delimit multiple addresses
 157                        $aliases{$1} = [ split(/\s+/, $2) ];
 158                }}},
 159        pine => sub { my $fh = shift; while (<$fh>) {
 160                if (/^(\S+)\s+(.*)$/) {
 161                        $aliases{$1} = [ split(/\s*,\s*/, $2) ];
 162                }}},
 163        gnus => sub { my $fh = shift; while (<$fh>) {
 164                if (/\(define-mail-alias\s+"(\S+?)"\s+"(\S+?)"\)/) {
 165                        $aliases{$1} = [ $2 ];
 166                }}}
 167);
 168
 169if (@alias_files and $aliasfiletype and defined $parse_alias{$aliasfiletype}) {
 170        foreach my $file (@alias_files) {
 171                open my $fh, '<', $file or die "opening $file: $!\n";
 172                $parse_alias{$aliasfiletype}->($fh);
 173                close $fh;
 174        }
 175}
 176
 177my $prompting = 0;
 178if (!defined $from) {
 179        $from = $author || $committer;
 180        do {
 181                $_ = $term->readline("Who should the emails appear to be from? ",
 182                        $from);
 183        } while (!defined $_);
 184
 185        $from = $_;
 186        print "Emails will be sent from: ", $from, "\n";
 187        $prompting++;
 188}
 189
 190if (!@to) {
 191        do {
 192                $_ = $term->readline("Who should the emails be sent to? ",
 193                                "");
 194        } while (!defined $_);
 195        my $to = $_;
 196        push @to, split /,/, $to;
 197        $prompting++;
 198}
 199
 200sub expand_aliases {
 201        my @cur = @_;
 202        my @last;
 203        do {
 204                @last = @cur;
 205                @cur = map { $aliases{$_} ? @{$aliases{$_}} : $_ } @last;
 206        } while (join(',',@cur) ne join(',',@last));
 207        return @cur;
 208}
 209
 210@to = expand_aliases(@to);
 211@initial_cc = expand_aliases(@initial_cc);
 212@bcclist = expand_aliases(@bcclist);
 213
 214if (!defined $initial_subject && $compose) {
 215        do {
 216                $_ = $term->readline("What subject should the emails start with? ",
 217                        $initial_subject);
 218        } while (!defined $_);
 219        $initial_subject = $_;
 220        $prompting++;
 221}
 222
 223if (!defined $initial_reply_to && $prompting) {
 224        do {
 225                $_= $term->readline("Message-ID to be used as In-Reply-To for the first email? ",
 226                        $initial_reply_to);
 227        } while (!defined $_);
 228
 229        $initial_reply_to = $_;
 230        $initial_reply_to =~ s/(^\s+|\s+$)//g;
 231}
 232
 233if (!$smtp_server) {
 234        foreach (qw( /usr/sbin/sendmail /usr/lib/sendmail )) {
 235                if (-x $_) {
 236                        $smtp_server = $_;
 237                        last;
 238                }
 239        }
 240        $smtp_server ||= 'localhost'; # could be 127.0.0.1, too... *shrug*
 241}
 242
 243if ($compose) {
 244        # Note that this does not need to be secure, but we will make a small
 245        # effort to have it be unique
 246        open(C,">",$compose_filename)
 247                or die "Failed to open for writing $compose_filename: $!";
 248        print C "From $from # This line is ignored.\n";
 249        printf C "Subject: %s\n\n", $initial_subject;
 250        printf C <<EOT;
 251GIT: Please enter your email below.
 252GIT: Lines beginning in "GIT: " will be removed.
 253GIT: Consider including an overall diffstat or table of contents
 254GIT: for the patch you are writing.
 255
 256EOT
 257        close(C);
 258
 259        my $editor = $ENV{EDITOR};
 260        $editor = 'vi' unless defined $editor;
 261        system($editor, $compose_filename);
 262
 263        open(C2,">",$compose_filename . ".final")
 264                or die "Failed to open $compose_filename.final : " . $!;
 265
 266        open(C,"<",$compose_filename)
 267                or die "Failed to open $compose_filename : " . $!;
 268
 269        while(<C>) {
 270                next if m/^GIT: /;
 271                print C2 $_;
 272        }
 273        close(C);
 274        close(C2);
 275
 276        do {
 277                $_ = $term->readline("Send this email? (y|n) ");
 278        } while (!defined $_);
 279
 280        if (uc substr($_,0,1) ne 'Y') {
 281                cleanup_compose_files();
 282                exit(0);
 283        }
 284
 285        @files = ($compose_filename . ".final");
 286}
 287
 288
 289# Now that all the defaults are set, process the rest of the command line
 290# arguments and collect up the files that need to be processed.
 291for my $f (@ARGV) {
 292        if (-d $f) {
 293                opendir(DH,$f)
 294                        or die "Failed to opendir $f: $!";
 295
 296                push @files, grep { -f $_ } map { +$f . "/" . $_ }
 297                                sort readdir(DH);
 298
 299        } elsif (-f $f) {
 300                push @files, $f;
 301
 302        } else {
 303                print STDERR "Skipping $f - not found.\n";
 304        }
 305}
 306
 307if (@files) {
 308        unless ($quiet) {
 309                print $_,"\n" for (@files);
 310        }
 311} else {
 312        print <<EOT;
 313git-send-email [options] <file | directory> [... file | directory ]
 314Options:
 315   --from         Specify the "From:" line of the email to be sent.
 316
 317   --to           Specify the primary "To:" line of the email.
 318
 319   --cc           Specify an initial "Cc:" list for the entire series
 320                  of emails.
 321
 322   --bcc          Specify a list of email addresses that should be Bcc:
 323                  on all the emails.
 324
 325   --compose      Use \$EDITOR to edit an introductory message for the
 326                  patch series.
 327
 328   --subject      Specify the initial "Subject:" line.
 329                  Only necessary if --compose is also set.  If --compose
 330                  is not set, this will be prompted for.
 331
 332   --in-reply-to  Specify the first "In-Reply-To:" header line.
 333                  Only used if --compose is also set.  If --compose is not
 334                  set, this will be prompted for.
 335
 336   --chain-reply-to If set, the replies will all be to the previous
 337                  email sent, rather than to the first email sent.
 338                  Defaults to on.
 339
 340   --no-signed-off-cc Suppress the automatic addition of email addresses
 341                 that appear in a Signed-off-by: line, to the cc: list.
 342                 Note: Using this option is not recommended.
 343
 344   --smtp-server  If set, specifies the outgoing SMTP server to use.
 345                  Defaults to localhost.
 346
 347  --suppress-from Suppress sending emails to yourself if your address
 348                  appears in a From: line.
 349
 350   --quiet      Make git-send-email less verbose.  One line per email should be
 351                all that is output.
 352
 353Error: Please specify a file or a directory on the command line.
 354EOT
 355        exit(1);
 356}
 357
 358# Variables we set as part of the loop over files
 359our ($message_id, $cc, %mail, $subject, $reply_to, $references, $message);
 360
 361sub extract_valid_address {
 362        my $address = shift;
 363        my $local_part_regexp = '[^<>"\s@]+';
 364        my $domain_regexp = '[^.<>"\s@]+(?:\.[^.<>"\s@]+)+';
 365
 366        # check for a local address:
 367        return $address if ($address =~ /^($local_part_regexp)$/);
 368
 369        if ($have_email_valid) {
 370                return scalar Email::Valid->address($address);
 371        } else {
 372                # less robust/correct than the monster regexp in Email::Valid,
 373                # but still does a 99% job, and one less dependency
 374                $address =~ /($local_part_regexp\@$domain_regexp)/;
 375                return $1;
 376        }
 377}
 378
 379# Usually don't need to change anything below here.
 380
 381# we make a "fake" message id by taking the current number
 382# of seconds since the beginning of Unix time and tacking on
 383# a random number to the end, in case we are called quicker than
 384# 1 second since the last time we were called.
 385
 386# We'll setup a template for the message id, using the "from" address:
 387my $message_id_from = extract_valid_address($from);
 388my $message_id_template = "<%s-git-send-email-$message_id_from>";
 389
 390sub make_message_id
 391{
 392        my $date = time;
 393        my $pseudo_rand = int (rand(4200));
 394        $message_id = sprintf $message_id_template, "$date$pseudo_rand";
 395        #print "new message id = $message_id\n"; # Was useful for debugging
 396}
 397
 398
 399
 400$cc = "";
 401$time = time - scalar $#files;
 402
 403sub send_message
 404{
 405        my @recipients = unique_email_list(@to);
 406        my $to = join (",\n\t", @recipients);
 407        @recipients = unique_email_list(@recipients,@cc,@bcclist);
 408        my $date = format_2822_time($time++);
 409        my $gitversion = '@@GIT_VERSION@@';
 410        if ($gitversion =~ m/..GIT_VERSION../) {
 411            $gitversion = Git::version();
 412        }
 413
 414        my ($author_name) = ($from =~ /^(.*?)\s+</);
 415        if ($author_name && $author_name =~ /\./ && $author_name !~ /^".*"$/) {
 416                my ($name, $addr) = ($from =~ /^(.*?)(\s+<.*)/);
 417                $from = "\"$name\"$addr";
 418        }
 419        my $header = "From: $from
 420To: $to
 421Cc: $cc
 422Subject: $subject
 423Date: $date
 424Message-Id: $message_id
 425X-Mailer: git-send-email $gitversion
 426";
 427        if ($reply_to) {
 428
 429                $header .= "In-Reply-To: $reply_to\n";
 430                $header .= "References: $references\n";
 431        }
 432        if (@xh) {
 433                $header .= join("\n", @xh) . "\n";
 434        }
 435
 436        if ($dry_run) {
 437                # We don't want to send the email.
 438        } elsif ($smtp_server =~ m#^/#) {
 439                my $pid = open my $sm, '|-';
 440                defined $pid or die $!;
 441                if (!$pid) {
 442                        exec($smtp_server,'-i',
 443                             map { extract_valid_address($_) }
 444                             @recipients) or die $!;
 445                }
 446                print $sm "$header\n$message";
 447                close $sm or die $?;
 448        } else {
 449                require Net::SMTP;
 450                $smtp ||= Net::SMTP->new( $smtp_server );
 451                $smtp->mail( $from ) or die $smtp->message;
 452                $smtp->to( @recipients ) or die $smtp->message;
 453                $smtp->data or die $smtp->message;
 454                $smtp->datasend("$header\n$message") or die $smtp->message;
 455                $smtp->dataend() or die $smtp->message;
 456                $smtp->ok or die "Failed to send $subject\n".$smtp->message;
 457        }
 458        if ($quiet) {
 459                printf "Sent %s\n", $subject;
 460        } else {
 461                print "OK. Log says:\nDate: $date\n";
 462                if ($smtp) {
 463                        print "Server: $smtp_server\n";
 464                } else {
 465                        print "Sendmail: $smtp_server\n";
 466                }
 467                print "From: $from\nSubject: $subject\nCc: $cc\nTo: $to\n\n";
 468                if ($smtp) {
 469                        print "Result: ", $smtp->code, ' ',
 470                                ($smtp->message =~ /\n([^\n]+\n)$/s), "\n";
 471                } else {
 472                        print "Result: OK\n";
 473                }
 474        }
 475}
 476
 477$reply_to = $initial_reply_to;
 478$references = $initial_reply_to || '';
 479make_message_id();
 480$subject = $initial_subject;
 481
 482foreach my $t (@files) {
 483        open(F,"<",$t) or die "can't open file $t";
 484
 485        my $author_not_sender = undef;
 486        @cc = @initial_cc;
 487        @xh = ();
 488        my $input_format = undef;
 489        my $header_done = 0;
 490        $message = "";
 491        while(<F>) {
 492                if (!$header_done) {
 493                        if (/^From /) {
 494                                $input_format = 'mbox';
 495                                next;
 496                        }
 497                        chomp;
 498                        if (!defined $input_format && /^[-A-Za-z]+:\s/) {
 499                                $input_format = 'mbox';
 500                        }
 501
 502                        if (defined $input_format && $input_format eq 'mbox') {
 503                                if (/^Subject:\s+(.*)$/) {
 504                                        $subject = $1;
 505
 506                                } elsif (/^(Cc|From):\s+(.*)$/) {
 507                                        if ($2 eq $from) {
 508                                                next if ($suppress_from);
 509                                        }
 510                                        elsif ($1 eq 'From') {
 511                                                $author_not_sender = $2;
 512                                        }
 513                                        printf("(mbox) Adding cc: %s from line '%s'\n",
 514                                                $2, $_) unless $quiet;
 515                                        push @cc, $2;
 516                                }
 517                                elsif (!/^Date:\s/ && /^[-A-Za-z]+:\s+\S/) {
 518                                        push @xh, $_;
 519                                }
 520
 521                        } else {
 522                                # In the traditional
 523                                # "send lots of email" format,
 524                                # line 1 = cc
 525                                # line 2 = subject
 526                                # So let's support that, too.
 527                                $input_format = 'lots';
 528                                if (@cc == 0) {
 529                                        printf("(non-mbox) Adding cc: %s from line '%s'\n",
 530                                                $_, $_) unless $quiet;
 531
 532                                        push @cc, $_;
 533
 534                                } elsif (!defined $subject) {
 535                                        $subject = $_;
 536                                }
 537                        }
 538
 539                        # A whitespace line will terminate the headers
 540                        if (m/^\s*$/) {
 541                                $header_done = 1;
 542                        }
 543                } else {
 544                        $message .=  $_;
 545                        if (/^Signed-off-by: (.*)$/i && !$no_signed_off_cc) {
 546                                my $c = $1;
 547                                chomp $c;
 548                                push @cc, $c;
 549                                printf("(sob) Adding cc: %s from line '%s'\n",
 550                                        $c, $_) unless $quiet;
 551                        }
 552                }
 553        }
 554        close F;
 555        if (defined $author_not_sender) {
 556                $message = "From: $author_not_sender\n\n$message";
 557        }
 558
 559        $cc = join(", ", unique_email_list(@cc));
 560
 561        send_message();
 562
 563        # set up for the next message
 564        if ($chain_reply_to || !defined $reply_to || length($reply_to) == 0) {
 565                $reply_to = $message_id;
 566                if (length $references > 0) {
 567                        $references .= " $message_id";
 568                } else {
 569                        $references = "$message_id";
 570                }
 571        }
 572        make_message_id();
 573}
 574
 575if ($compose) {
 576        cleanup_compose_files();
 577}
 578
 579sub cleanup_compose_files() {
 580        unlink($compose_filename, $compose_filename . ".final");
 581
 582}
 583
 584$smtp->quit if $smtp;
 585
 586sub unique_email_list(@) {
 587        my %seen;
 588        my @emails;
 589
 590        foreach my $entry (@_) {
 591                if (my $clean = extract_valid_address($entry)) {
 592                        $seen{$clean} ||= 0;
 593                        next if $seen{$clean}++;
 594                        push @emails, $entry;
 595                } else {
 596                        print STDERR "W: unable to extract a valid address",
 597                                        " from: $entry\n";
 598                }
 599        }
 600        return @emails;
 601}