Refactor the pack header reading function out of receive-pack.c
[alt-git.git] / git-send-email.perl
blob8dc2ee0cf7461ace62c5ef7afac6dedc7814ddfb
1 #!/usr/bin/perl -w
3 # Copyright 2002,2005 Greg Kroah-Hartman <greg@kroah.com>
4 # Copyright 2005 Ryan Anderson <ryan@michonline.com>
6 # GPL v2 (See COPYING)
8 # Ported to support git "mbox" format files by Ryan Anderson <ryan@michonline.com>
10 # Sends a collection of emails to the given email addresses, disturbingly fast.
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.
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;
31 sub readline {
32 my $self = shift;
33 die "Cannot use readline on FakeTerm: $$self";
35 package main;
37 # most mail servers generate the Date: header, but not all...
38 sub 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";
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";
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");
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,
76 my $have_email_valid = eval { require Email::Valid; 1 };
77 my $smtp;
79 sub unique_email_list(@);
80 sub cleanup_compose_files();
82 # Constants (essentially)
83 my $compose_filename = ".msg.$$";
85 # Variables we fill in automatically, or via prompting:
86 my (@to,@cc,@initial_cc,@bcclist,@xh,
87 $initial_reply_to,$initial_subject,@files,$from,$compose,$time);
89 # Behavior modification variables
90 my ($chain_reply_to, $quiet, $suppress_from, $no_signed_off_cc,
91 $dry_run) = (1, 0, 0, 0, 0);
92 my $smtp_server;
94 # Example reply to:
95 #$initial_reply_to = ''; #<20050203173208.GA23964@foobar.com>';
97 my $repo = Git->repository();
98 my $term = eval {
99 new Term::ReadLine 'git-send-email';
101 if ($@) {
102 $term = new FakeTerm "$@: going non-interactive";
105 # Begin by accumulating all the variables (defined above), that we will end up
106 # needing, first, from the command line:
108 my $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,
123 # Verify the user input
125 foreach my $entry (@to) {
126 die "Comma in --to entry: $entry'\n" unless $entry !~ m/,/;
129 foreach my $entry (@initial_cc) {
130 die "Comma in --cc entry: $entry'\n" unless $entry !~ m/,/;
133 foreach my $entry (@bcclist) {
134 die "Comma in --bcclist entry: $entry'\n" unless $entry !~ m/,/;
137 # Now, let's fill any that aren't set in with defaults:
139 my ($author) = $repo->ident_person('author');
140 my ($committer) = $repo->ident_person('committer');
142 my %aliases;
143 my @alias_files = $repo->config('sendemail.aliasesfile');
144 my $aliasfiletype = $repo->config('sendemail.aliasfiletype');
145 my %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 ];
169 if (@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;
177 my $prompting = 0;
178 if (!defined $from) {
179 $from = $author || $committer;
180 do {
181 $_ = $term->readline("Who should the emails appear to be from? [$from] ");
182 } while (!defined $_);
184 $from = $_ if ($_);
185 print "Emails will be sent from: ", $from, "\n";
186 $prompting++;
189 if (!@to) {
190 do {
191 $_ = $term->readline("Who should the emails be sent to? ",
192 "");
193 } while (!defined $_);
194 my $to = $_;
195 push @to, split /,/, $to;
196 $prompting++;
199 sub expand_aliases {
200 my @cur = @_;
201 my @last;
202 do {
203 @last = @cur;
204 @cur = map { $aliases{$_} ? @{$aliases{$_}} : $_ } @last;
205 } while (join(',',@cur) ne join(',',@last));
206 return @cur;
209 @to = expand_aliases(@to);
210 @initial_cc = expand_aliases(@initial_cc);
211 @bcclist = expand_aliases(@bcclist);
213 if (!defined $initial_subject && $compose) {
214 do {
215 $_ = $term->readline("What subject should the emails start with? ",
216 $initial_subject);
217 } while (!defined $_);
218 $initial_subject = $_;
219 $prompting++;
222 if (!defined $initial_reply_to && $prompting) {
223 do {
224 $_= $term->readline("Message-ID to be used as In-Reply-To for the first email? ",
225 $initial_reply_to);
226 } while (!defined $_);
228 $initial_reply_to = $_;
229 $initial_reply_to =~ s/(^\s+|\s+$)//g;
232 if (!$smtp_server) {
233 $smtp_server = $repo->config('sendemail.smtpserver');
235 if (!$smtp_server) {
236 foreach (qw( /usr/sbin/sendmail /usr/lib/sendmail )) {
237 if (-x $_) {
238 $smtp_server = $_;
239 last;
242 $smtp_server ||= 'localhost'; # could be 127.0.0.1, too... *shrug*
245 if ($compose) {
246 # Note that this does not need to be secure, but we will make a small
247 # effort to have it be unique
248 open(C,">",$compose_filename)
249 or die "Failed to open for writing $compose_filename: $!";
250 print C "From $from # This line is ignored.\n";
251 printf C "Subject: %s\n\n", $initial_subject;
252 printf C <<EOT;
253 GIT: Please enter your email below.
254 GIT: Lines beginning in "GIT: " will be removed.
255 GIT: Consider including an overall diffstat or table of contents
256 GIT: for the patch you are writing.
259 close(C);
261 my $editor = $ENV{EDITOR};
262 $editor = 'vi' unless defined $editor;
263 system($editor, $compose_filename);
265 open(C2,">",$compose_filename . ".final")
266 or die "Failed to open $compose_filename.final : " . $!;
268 open(C,"<",$compose_filename)
269 or die "Failed to open $compose_filename : " . $!;
271 while(<C>) {
272 next if m/^GIT: /;
273 print C2 $_;
275 close(C);
276 close(C2);
278 do {
279 $_ = $term->readline("Send this email? (y|n) ");
280 } while (!defined $_);
282 if (uc substr($_,0,1) ne 'Y') {
283 cleanup_compose_files();
284 exit(0);
287 @files = ($compose_filename . ".final");
291 # Now that all the defaults are set, process the rest of the command line
292 # arguments and collect up the files that need to be processed.
293 for my $f (@ARGV) {
294 if (-d $f) {
295 opendir(DH,$f)
296 or die "Failed to opendir $f: $!";
298 push @files, grep { -f $_ } map { +$f . "/" . $_ }
299 sort readdir(DH);
301 } elsif (-f $f) {
302 push @files, $f;
304 } else {
305 print STDERR "Skipping $f - not found.\n";
309 if (@files) {
310 unless ($quiet) {
311 print $_,"\n" for (@files);
313 } else {
314 print <<EOT;
315 git-send-email [options] <file | directory> [... file | directory ]
316 Options:
317 --from Specify the "From:" line of the email to be sent.
319 --to Specify the primary "To:" line of the email.
321 --cc Specify an initial "Cc:" list for the entire series
322 of emails.
324 --bcc Specify a list of email addresses that should be Bcc:
325 on all the emails.
327 --compose Use \$EDITOR to edit an introductory message for the
328 patch series.
330 --subject Specify the initial "Subject:" line.
331 Only necessary if --compose is also set. If --compose
332 is not set, this will be prompted for.
334 --in-reply-to Specify the first "In-Reply-To:" header line.
335 Only used if --compose is also set. If --compose is not
336 set, this will be prompted for.
338 --chain-reply-to If set, the replies will all be to the previous
339 email sent, rather than to the first email sent.
340 Defaults to on.
342 --no-signed-off-cc Suppress the automatic addition of email addresses
343 that appear in a Signed-off-by: line, to the cc: list.
344 Note: Using this option is not recommended.
346 --smtp-server If set, specifies the outgoing SMTP server to use.
347 Defaults to localhost.
349 --suppress-from Suppress sending emails to yourself if your address
350 appears in a From: line.
352 --quiet Make git-send-email less verbose. One line per email should be
353 all that is output.
355 Error: Please specify a file or a directory on the command line.
357 exit(1);
360 # Variables we set as part of the loop over files
361 our ($message_id, $cc, %mail, $subject, $reply_to, $references, $message);
363 sub extract_valid_address {
364 my $address = shift;
365 my $local_part_regexp = '[^<>"\s@]+';
366 my $domain_regexp = '[^.<>"\s@]+(?:\.[^.<>"\s@]+)+';
368 # check for a local address:
369 return $address if ($address =~ /^($local_part_regexp)$/);
371 if ($have_email_valid) {
372 return scalar Email::Valid->address($address);
373 } else {
374 # less robust/correct than the monster regexp in Email::Valid,
375 # but still does a 99% job, and one less dependency
376 $address =~ /($local_part_regexp\@$domain_regexp)/;
377 return $1;
381 # Usually don't need to change anything below here.
383 # we make a "fake" message id by taking the current number
384 # of seconds since the beginning of Unix time and tacking on
385 # a random number to the end, in case we are called quicker than
386 # 1 second since the last time we were called.
388 # We'll setup a template for the message id, using the "from" address:
389 my $message_id_from = extract_valid_address($from);
390 my $message_id_template = "<%s-git-send-email-$message_id_from>";
392 sub make_message_id
394 my $date = time;
395 my $pseudo_rand = int (rand(4200));
396 $message_id = sprintf $message_id_template, "$date$pseudo_rand";
397 #print "new message id = $message_id\n"; # Was useful for debugging
402 $cc = "";
403 $time = time - scalar $#files;
405 sub unquote_rfc2047 {
406 local ($_) = @_;
407 if (s/=\?utf-8\?q\?(.*)\?=/$1/g) {
408 s/_/ /g;
409 s/=([0-9A-F]{2})/chr(hex($1))/eg;
411 return "$_ - unquoted";
414 sub send_message
416 my @recipients = unique_email_list(@to);
417 my $to = join (",\n\t", @recipients);
418 @recipients = unique_email_list(@recipients,@cc,@bcclist);
419 my $date = format_2822_time($time++);
420 my $gitversion = '@@GIT_VERSION@@';
421 if ($gitversion =~ m/..GIT_VERSION../) {
422 $gitversion = Git::version();
425 my ($author_name) = ($from =~ /^(.*?)\s+</);
426 if ($author_name && $author_name =~ /\./ && $author_name !~ /^".*"$/) {
427 my ($name, $addr) = ($from =~ /^(.*?)(\s+<.*)/);
428 $from = "\"$name\"$addr";
430 my $header = "From: $from
431 To: $to
432 Cc: $cc
433 Subject: $subject
434 Date: $date
435 Message-Id: $message_id
436 X-Mailer: git-send-email $gitversion
438 if ($reply_to) {
440 $header .= "In-Reply-To: $reply_to\n";
441 $header .= "References: $references\n";
443 if (@xh) {
444 $header .= join("\n", @xh) . "\n";
447 if ($dry_run) {
448 # We don't want to send the email.
449 } elsif ($smtp_server =~ m#^/#) {
450 my $pid = open my $sm, '|-';
451 defined $pid or die $!;
452 if (!$pid) {
453 exec($smtp_server,'-i',
454 map { extract_valid_address($_) }
455 @recipients) or die $!;
457 print $sm "$header\n$message";
458 close $sm or die $?;
459 } else {
460 require Net::SMTP;
461 $smtp ||= Net::SMTP->new( $smtp_server );
462 $smtp->mail( $from ) or die $smtp->message;
463 $smtp->to( @recipients ) or die $smtp->message;
464 $smtp->data or die $smtp->message;
465 $smtp->datasend("$header\n$message") or die $smtp->message;
466 $smtp->dataend() or die $smtp->message;
467 $smtp->ok or die "Failed to send $subject\n".$smtp->message;
469 if ($quiet) {
470 printf "Sent %s\n", $subject;
471 } else {
472 print "OK. Log says:\nDate: $date\n";
473 if ($smtp) {
474 print "Server: $smtp_server\n";
475 } else {
476 print "Sendmail: $smtp_server\n";
478 print "From: $from\nSubject: $subject\nCc: $cc\nTo: $to\n\n";
479 if ($smtp) {
480 print "Result: ", $smtp->code, ' ',
481 ($smtp->message =~ /\n([^\n]+\n)$/s), "\n";
482 } else {
483 print "Result: OK\n";
488 $reply_to = $initial_reply_to;
489 $references = $initial_reply_to || '';
490 make_message_id();
491 $subject = $initial_subject;
493 foreach my $t (@files) {
494 open(F,"<",$t) or die "can't open file $t";
496 my $author_not_sender = undef;
497 @cc = @initial_cc;
498 @xh = ();
499 my $input_format = undef;
500 my $header_done = 0;
501 $message = "";
502 while(<F>) {
503 if (!$header_done) {
504 if (/^From /) {
505 $input_format = 'mbox';
506 next;
508 chomp;
509 if (!defined $input_format && /^[-A-Za-z]+:\s/) {
510 $input_format = 'mbox';
513 if (defined $input_format && $input_format eq 'mbox') {
514 if (/^Subject:\s+(.*)$/) {
515 $subject = $1;
517 } elsif (/^(Cc|From):\s+(.*)$/) {
518 if ($2 eq $from) {
519 next if ($suppress_from);
521 elsif ($1 eq 'From') {
522 $author_not_sender = $2;
524 printf("(mbox) Adding cc: %s from line '%s'\n",
525 $2, $_) unless $quiet;
526 push @cc, $2;
528 elsif (!/^Date:\s/ && /^[-A-Za-z]+:\s+\S/) {
529 push @xh, $_;
532 } else {
533 # In the traditional
534 # "send lots of email" format,
535 # line 1 = cc
536 # line 2 = subject
537 # So let's support that, too.
538 $input_format = 'lots';
539 if (@cc == 0) {
540 printf("(non-mbox) Adding cc: %s from line '%s'\n",
541 $_, $_) unless $quiet;
543 push @cc, $_;
545 } elsif (!defined $subject) {
546 $subject = $_;
550 # A whitespace line will terminate the headers
551 if (m/^\s*$/) {
552 $header_done = 1;
554 } else {
555 $message .= $_;
556 if (/^Signed-off-by: (.*)$/i && !$no_signed_off_cc) {
557 my $c = $1;
558 chomp $c;
559 push @cc, $c;
560 printf("(sob) Adding cc: %s from line '%s'\n",
561 $c, $_) unless $quiet;
565 close F;
566 if (defined $author_not_sender) {
567 $author_not_sender = unquote_rfc2047($author_not_sender);
568 $message = "From: $author_not_sender\n\n$message";
571 $cc = join(", ", unique_email_list(@cc));
573 send_message();
575 # set up for the next message
576 if ($chain_reply_to || !defined $reply_to || length($reply_to) == 0) {
577 $reply_to = $message_id;
578 if (length $references > 0) {
579 $references .= " $message_id";
580 } else {
581 $references = "$message_id";
584 make_message_id();
587 if ($compose) {
588 cleanup_compose_files();
591 sub cleanup_compose_files() {
592 unlink($compose_filename, $compose_filename . ".final");
596 $smtp->quit if $smtp;
598 sub unique_email_list(@) {
599 my %seen;
600 my @emails;
602 foreach my $entry (@_) {
603 if (my $clean = extract_valid_address($entry)) {
604 $seen{$clean} ||= 0;
605 next if $seen{$clean}++;
606 push @emails, $entry;
607 } else {
608 print STDERR "W: unable to extract a valid address",
609 " from: $entry\n";
612 return @emails;