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