Code

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