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