Doc fix for git-reflog: mention @{...} syntax, and <ref> in synopsys.
[git/platforms.git] / git-send-email.perl
blob2b1f1b598c62ddaed693635adef12e490f49838f
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 Term::ANSIColor;
25 use Git;
27 $SIG{INT} = sub { print color("reset"), "\n"; exit };
29 package FakeTerm;
30 sub new {
31 my ($class, $reason) = @_;
32 return bless \$reason, shift;
34 sub readline {
35 my $self = shift;
36 die "Cannot use readline on FakeTerm: $$self";
38 package main;
41 sub usage {
42 print <<EOT;
43 git-send-email [options] <file | directory>...
44 Options:
45 --from Specify the "From:" line of the email to be sent.
47 --to Specify the primary "To:" line of the email.
49 --cc Specify an initial "Cc:" list for the entire series
50 of emails.
52 --cc-cmd Specify a command to execute per file which adds
53 per file specific cc address entries
55 --bcc Specify a list of email addresses that should be Bcc:
56 on all the emails.
58 --compose Use \$GIT_EDITOR, core.editor, \$EDITOR, or \$VISUAL to edit
59 an introductory message for the patch series.
61 --subject Specify the initial "Subject:" line.
62 Only necessary if --compose is also set. If --compose
63 is not set, this will be prompted for.
65 --in-reply-to Specify the first "In-Reply-To:" header line.
66 Only used if --compose is also set. If --compose is not
67 set, this will be prompted for.
69 --chain-reply-to If set, the replies will all be to the previous
70 email sent, rather than to the first email sent.
71 Defaults to on.
73 --signed-off-cc Automatically add email addresses that appear in
74 Signed-off-by: or Cc: lines to the cc: list. Defaults to on.
76 --smtp-server If set, specifies the outgoing SMTP server to use.
77 Defaults to localhost.
79 --suppress-from Suppress sending emails to yourself if your address
80 appears in a From: line. Defaults to off.
82 --thread Specify that the "In-Reply-To:" header should be set on all
83 emails. Defaults to on.
85 --quiet Make git-send-email less verbose. One line per email
86 should be all that is output.
88 --dry-run Do everything except actually send the emails.
90 --envelope-sender Specify the envelope sender used to send the emails.
92 EOT
93 exit(1);
96 # most mail servers generate the Date: header, but not all...
97 sub format_2822_time {
98 my ($time) = @_;
99 my @localtm = localtime($time);
100 my @gmttm = gmtime($time);
101 my $localmin = $localtm[1] + $localtm[2] * 60;
102 my $gmtmin = $gmttm[1] + $gmttm[2] * 60;
103 if ($localtm[0] != $gmttm[0]) {
104 die "local zone differs from GMT by a non-minute interval\n";
106 if ((($gmttm[6] + 1) % 7) == $localtm[6]) {
107 $localmin += 1440;
108 } elsif ((($gmttm[6] - 1) % 7) == $localtm[6]) {
109 $localmin -= 1440;
110 } elsif ($gmttm[6] != $localtm[6]) {
111 die "local time offset greater than or equal to 24 hours\n";
113 my $offset = $localmin - $gmtmin;
114 my $offhour = $offset / 60;
115 my $offmin = abs($offset % 60);
116 if (abs($offhour) >= 24) {
117 die ("local time offset greater than or equal to 24 hours\n");
120 return sprintf("%s, %2d %s %d %02d:%02d:%02d %s%02d%02d",
121 qw(Sun Mon Tue Wed Thu Fri Sat)[$localtm[6]],
122 $localtm[3],
123 qw(Jan Feb Mar Apr May Jun
124 Jul Aug Sep Oct Nov Dec)[$localtm[4]],
125 $localtm[5]+1900,
126 $localtm[2],
127 $localtm[1],
128 $localtm[0],
129 ($offset >= 0) ? '+' : '-',
130 abs($offhour),
131 $offmin,
135 my $have_email_valid = eval { require Email::Valid; 1 };
136 my $smtp;
138 sub unique_email_list(@);
139 sub cleanup_compose_files();
141 # Constants (essentially)
142 my $compose_filename = ".msg.$$";
144 # Variables we fill in automatically, or via prompting:
145 my (@to,@cc,@initial_cc,@bcclist,@xh,
146 $initial_reply_to,$initial_subject,@files,$author,$sender,$compose,$time);
148 my $smtp_server;
149 my $envelope_sender;
151 # Example reply to:
152 #$initial_reply_to = ''; #<20050203173208.GA23964@foobar.com>';
154 my $repo = Git->repository();
155 my $term = eval {
156 new Term::ReadLine 'git-send-email';
158 if ($@) {
159 $term = new FakeTerm "$@: going non-interactive";
162 # Behavior modification variables
163 my ($quiet, $dry_run) = (0, 0);
165 # Variables with corresponding config settings
166 my ($thread, $chain_reply_to, $suppress_from, $signed_off_cc, $cc_cmd);
168 my %config_settings = (
169 "thread" => [\$thread, 1],
170 "chainreplyto" => [\$chain_reply_to, 1],
171 "suppressfrom" => [\$suppress_from, 0],
172 "signedoffcc" => [\$signed_off_cc, 1],
173 "cccmd" => [\$cc_cmd, ""],
176 foreach my $setting (keys %config_settings) {
177 my $config = $repo->config_bool("sendemail.$setting");
178 ${$config_settings{$setting}->[0]} = (defined $config) ? $config : $config_settings{$setting}->[1];
181 @bcclist = $repo->config('sendemail.bcc');
182 if (!@bcclist or !$bcclist[0]) {
183 @bcclist = ();
186 # Begin by accumulating all the variables (defined above), that we will end up
187 # needing, first, from the command line:
189 my $rc = GetOptions("sender|from=s" => \$sender,
190 "in-reply-to=s" => \$initial_reply_to,
191 "subject=s" => \$initial_subject,
192 "to=s" => \@to,
193 "cc=s" => \@initial_cc,
194 "bcc=s" => \@bcclist,
195 "chain-reply-to!" => \$chain_reply_to,
196 "smtp-server=s" => \$smtp_server,
197 "compose" => \$compose,
198 "quiet" => \$quiet,
199 "cc-cmd=s" => \$cc_cmd,
200 "suppress-from!" => \$suppress_from,
201 "signed-off-cc|signed-off-by-cc!" => \$signed_off_cc,
202 "dry-run" => \$dry_run,
203 "envelope-sender=s" => \$envelope_sender,
204 "thread!" => \$thread,
207 unless ($rc) {
208 usage();
211 # Verify the user input
213 foreach my $entry (@to) {
214 die "Comma in --to entry: $entry'\n" unless $entry !~ m/,/;
217 foreach my $entry (@initial_cc) {
218 die "Comma in --cc entry: $entry'\n" unless $entry !~ m/,/;
221 foreach my $entry (@bcclist) {
222 die "Comma in --bcclist entry: $entry'\n" unless $entry !~ m/,/;
225 # Now, let's fill any that aren't set in with defaults:
227 my ($repoauthor) = $repo->ident_person('author');
228 my ($repocommitter) = $repo->ident_person('committer');
230 my %aliases;
231 my @alias_files = $repo->config('sendemail.aliasesfile');
232 my $aliasfiletype = $repo->config('sendemail.aliasfiletype');
233 my %parse_alias = (
234 # multiline formats can be supported in the future
235 mutt => sub { my $fh = shift; while (<$fh>) {
236 if (/^\s*alias\s+(\S+)\s+(.*)$/) {
237 my ($alias, $addr) = ($1, $2);
238 $addr =~ s/#.*$//; # mutt allows # comments
239 # commas delimit multiple addresses
240 $aliases{$alias} = [ split(/\s*,\s*/, $addr) ];
241 }}},
242 mailrc => sub { my $fh = shift; while (<$fh>) {
243 if (/^alias\s+(\S+)\s+(.*)$/) {
244 # spaces delimit multiple addresses
245 $aliases{$1} = [ split(/\s+/, $2) ];
246 }}},
247 pine => sub { my $fh = shift; while (<$fh>) {
248 if (/^(\S+)\t.*\t(.*)$/) {
249 $aliases{$1} = [ split(/\s*,\s*/, $2) ];
250 }}},
251 gnus => sub { my $fh = shift; while (<$fh>) {
252 if (/\(define-mail-alias\s+"(\S+?)"\s+"(\S+?)"\)/) {
253 $aliases{$1} = [ $2 ];
257 if (@alias_files and $aliasfiletype and defined $parse_alias{$aliasfiletype}) {
258 foreach my $file (@alias_files) {
259 open my $fh, '<', $file or die "opening $file: $!\n";
260 $parse_alias{$aliasfiletype}->($fh);
261 close $fh;
265 ($sender) = expand_aliases($sender) if defined $sender;
267 my $prompting = 0;
268 if (!defined $sender) {
269 $sender = $repoauthor || $repocommitter;
270 do {
271 $_ = $term->readline("Who should the emails appear to be from? [$sender] ");
272 } while (!defined $_);
274 $sender = $_ if ($_);
275 print "Emails will be sent from: ", $sender, "\n";
276 $prompting++;
279 if (!@to) {
280 do {
281 $_ = $term->readline("Who should the emails be sent to? ",
282 "");
283 } while (!defined $_);
284 my $to = $_;
285 push @to, split /,/, $to;
286 $prompting++;
289 sub expand_aliases {
290 my @cur = @_;
291 my @last;
292 do {
293 @last = @cur;
294 @cur = map { $aliases{$_} ? @{$aliases{$_}} : $_ } @last;
295 } while (join(',',@cur) ne join(',',@last));
296 return @cur;
299 @to = expand_aliases(@to);
300 @to = (map { sanitize_address($_) } @to);
301 @initial_cc = expand_aliases(@initial_cc);
302 @bcclist = expand_aliases(@bcclist);
304 if (!defined $initial_subject && $compose) {
305 do {
306 $_ = $term->readline("What subject should the initial email start with? ",
307 $initial_subject);
308 } while (!defined $_);
309 $initial_subject = $_;
310 $prompting++;
313 if ($thread && !defined $initial_reply_to && $prompting) {
314 do {
315 $_= $term->readline("Message-ID to be used as In-Reply-To for the first email? ",
316 $initial_reply_to);
317 } while (!defined $_);
319 $initial_reply_to = $_;
320 $initial_reply_to =~ s/^\s+<?/</;
321 $initial_reply_to =~ s/>?\s+$/>/;
324 if (!$smtp_server) {
325 $smtp_server = $repo->config('sendemail.smtpserver');
327 if (!$smtp_server) {
328 foreach (qw( /usr/sbin/sendmail /usr/lib/sendmail )) {
329 if (-x $_) {
330 $smtp_server = $_;
331 last;
334 $smtp_server ||= 'localhost'; # could be 127.0.0.1, too... *shrug*
337 if ($compose) {
338 # Note that this does not need to be secure, but we will make a small
339 # effort to have it be unique
340 open(C,">",$compose_filename)
341 or die "Failed to open for writing $compose_filename: $!";
342 print C "From $sender # This line is ignored.\n";
343 printf C "Subject: %s\n\n", $initial_subject;
344 printf C <<EOT;
345 GIT: Please enter your email below.
346 GIT: Lines beginning in "GIT: " will be removed.
347 GIT: Consider including an overall diffstat or table of contents
348 GIT: for the patch you are writing.
351 close(C);
353 my $editor = $ENV{GIT_EDITOR} || $repo->config("core.editor") || $ENV{VISUAL} || $ENV{EDITOR} || "vi";
354 system($editor, $compose_filename);
356 open(C2,">",$compose_filename . ".final")
357 or die "Failed to open $compose_filename.final : " . $!;
359 open(C,"<",$compose_filename)
360 or die "Failed to open $compose_filename : " . $!;
362 while(<C>) {
363 next if m/^GIT: /;
364 print C2 $_;
366 close(C);
367 close(C2);
369 do {
370 $_ = $term->readline("Send this email? (y|n) ");
371 } while (!defined $_);
373 if (uc substr($_,0,1) ne 'Y') {
374 cleanup_compose_files();
375 exit(0);
378 @files = ($compose_filename . ".final");
382 # Now that all the defaults are set, process the rest of the command line
383 # arguments and collect up the files that need to be processed.
384 for my $f (@ARGV) {
385 if (-d $f) {
386 opendir(DH,$f)
387 or die "Failed to opendir $f: $!";
389 push @files, grep { -f $_ } map { +$f . "/" . $_ }
390 sort readdir(DH);
392 } elsif (-f $f) {
393 push @files, $f;
395 } else {
396 print STDERR "Skipping $f - not found.\n";
400 if (@files) {
401 unless ($quiet) {
402 print $_,"\n" for (@files);
404 } else {
405 print STDERR "\nNo patch files specified!\n\n";
406 usage();
409 # Variables we set as part of the loop over files
410 our ($message_id, %mail, $subject, $reply_to, $references, $message);
412 sub extract_valid_address {
413 my $address = shift;
414 my $local_part_regexp = '[^<>"\s@]+';
415 my $domain_regexp = '[^.<>"\s@]+(?:\.[^.<>"\s@]+)+';
417 # check for a local address:
418 return $address if ($address =~ /^($local_part_regexp)$/);
420 $address =~ s/^\s*<(.*)>\s*$/$1/;
421 if ($have_email_valid) {
422 return scalar Email::Valid->address($address);
423 } else {
424 # less robust/correct than the monster regexp in Email::Valid,
425 # but still does a 99% job, and one less dependency
426 $address =~ /($local_part_regexp\@$domain_regexp)/;
427 return $1;
431 # Usually don't need to change anything below here.
433 # we make a "fake" message id by taking the current number
434 # of seconds since the beginning of Unix time and tacking on
435 # a random number to the end, in case we are called quicker than
436 # 1 second since the last time we were called.
438 # We'll setup a template for the message id, using the "from" address:
440 my ($message_id_stamp, $message_id_serial);
441 sub make_message_id
443 my $uniq;
444 if (!defined $message_id_stamp) {
445 $message_id_stamp = sprintf("%s-%s", time, $$);
446 $message_id_serial = 0;
448 $message_id_serial++;
449 $uniq = "$message_id_stamp-$message_id_serial";
451 my $du_part;
452 for ($sender, $repocommitter, $repoauthor) {
453 $du_part = extract_valid_address(sanitize_address($_));
454 last if (defined $du_part and $du_part ne '');
456 if (not defined $du_part or $du_part eq '') {
457 use Sys::Hostname qw();
458 $du_part = 'user@' . Sys::Hostname::hostname();
460 my $message_id_template = "<%s-git-send-email-%s>";
461 $message_id = sprintf($message_id_template, $uniq, $du_part);
462 #print "new message id = $message_id\n"; # Was useful for debugging
467 $time = time - scalar $#files;
469 sub unquote_rfc2047 {
470 local ($_) = @_;
471 my $encoding;
472 if (s/=\?([^?]+)\?q\?(.*)\?=/$2/g) {
473 $encoding = $1;
474 s/_/ /g;
475 s/=([0-9A-F]{2})/chr(hex($1))/eg;
477 return wantarray ? ($_, $encoding) : $_;
480 # use the simplest quoting being able to handle the recipient
481 sub sanitize_address
483 my ($recipient) = @_;
484 my ($recipient_name, $recipient_addr) = ($recipient =~ /^(.*?)\s*(<.*)/);
486 if (not $recipient_name) {
487 return "$recipient";
490 # if recipient_name is already quoted, do nothing
491 if ($recipient_name =~ /^(".*"|=\?utf-8\?q\?.*\?=)$/) {
492 return $recipient;
495 # rfc2047 is needed if a non-ascii char is included
496 if ($recipient_name =~ /[^[:ascii:]]/) {
497 $recipient_name =~ s/([^-a-zA-Z0-9!*+\/])/sprintf("=%02X", ord($1))/eg;
498 $recipient_name =~ s/(.*)/=\?utf-8\?q\?$1\?=/;
501 # double quotes are needed if specials or CTLs are included
502 elsif ($recipient_name =~ /[][()<>@,;:\\".\000-\037\177]/) {
503 $recipient_name =~ s/(["\\\r])/\\$1/;
504 $recipient_name = "\"$recipient_name\"";
507 return "$recipient_name $recipient_addr";
511 sub send_message
513 my @recipients = unique_email_list(@to);
514 @cc = (map { sanitize_address($_) } @cc);
515 my $to = join (",\n\t", @recipients);
516 @recipients = unique_email_list(@recipients,@cc,@bcclist);
517 @recipients = (map { extract_valid_address($_) } @recipients);
518 my $date = format_2822_time($time++);
519 my $gitversion = '@@GIT_VERSION@@';
520 if ($gitversion =~ m/..GIT_VERSION../) {
521 $gitversion = Git::version();
524 my $cc = join(", ", unique_email_list(@cc));
525 my $ccline = "";
526 if ($cc ne '') {
527 $ccline = "\nCc: $cc";
529 my $sanitized_sender = sanitize_address($sender);
530 make_message_id();
532 my $header = "From: $sanitized_sender
533 To: $to${ccline}
534 Subject: $subject
535 Date: $date
536 Message-Id: $message_id
537 X-Mailer: git-send-email $gitversion
539 if ($thread && $reply_to) {
541 $header .= "In-Reply-To: $reply_to\n";
542 $header .= "References: $references\n";
544 if (@xh) {
545 $header .= join("\n", @xh) . "\n";
548 my @sendmail_parameters = ('-i', @recipients);
549 my $raw_from = $sanitized_sender;
550 $raw_from = $envelope_sender if (defined $envelope_sender);
551 $raw_from = extract_valid_address($raw_from);
552 unshift (@sendmail_parameters,
553 '-f', $raw_from) if(defined $envelope_sender);
555 if ($dry_run) {
556 # We don't want to send the email.
557 } elsif ($smtp_server =~ m#^/#) {
558 my $pid = open my $sm, '|-';
559 defined $pid or die $!;
560 if (!$pid) {
561 exec($smtp_server, @sendmail_parameters) or die $!;
563 print $sm "$header\n$message";
564 close $sm or die $?;
565 } else {
566 require Net::SMTP;
567 $smtp ||= Net::SMTP->new( $smtp_server );
568 $smtp->mail( $raw_from ) or die $smtp->message;
569 $smtp->to( @recipients ) or die $smtp->message;
570 $smtp->data or die $smtp->message;
571 $smtp->datasend("$header\n$message") or die $smtp->message;
572 $smtp->dataend() or die $smtp->message;
573 $smtp->ok or die "Failed to send $subject\n".$smtp->message;
575 if ($quiet) {
576 printf (($dry_run ? "Dry-" : "")."Sent %s\n", $subject);
577 } else {
578 print (($dry_run ? "Dry-" : "")."OK. Log says:\nDate: $date\n");
579 if ($smtp_server !~ m#^/#) {
580 print "Server: $smtp_server\n";
581 print "MAIL FROM:<$raw_from>\n";
582 print "RCPT TO:".join(',',(map { "<$_>" } @recipients))."\n";
583 } else {
584 print "Sendmail: $smtp_server ".join(' ',@sendmail_parameters)."\n";
586 print "From: $sanitized_sender\nSubject: $subject\nCc: $cc\nTo: $to\n\n";
587 if ($smtp) {
588 print "Result: ", $smtp->code, ' ',
589 ($smtp->message =~ /\n([^\n]+\n)$/s), "\n";
590 } else {
591 print "Result: OK\n";
596 $reply_to = $initial_reply_to;
597 $references = $initial_reply_to || '';
598 $subject = $initial_subject;
600 foreach my $t (@files) {
601 open(F,"<",$t) or die "can't open file $t";
603 my $author = undef;
604 my $author_encoding;
605 my $has_content_type;
606 my $body_encoding;
607 @cc = @initial_cc;
608 @xh = ();
609 my $input_format = undef;
610 my $header_done = 0;
611 $message = "";
612 while(<F>) {
613 if (!$header_done) {
614 if (/^From /) {
615 $input_format = 'mbox';
616 next;
618 chomp;
619 if (!defined $input_format && /^[-A-Za-z]+:\s/) {
620 $input_format = 'mbox';
623 if (defined $input_format && $input_format eq 'mbox') {
624 if (/^Subject:\s+(.*)$/) {
625 $subject = $1;
627 } elsif (/^(Cc|From):\s+(.*)$/) {
628 if (unquote_rfc2047($2) eq $sender) {
629 next if ($suppress_from);
631 elsif ($1 eq 'From') {
632 ($author, $author_encoding)
633 = unquote_rfc2047($2);
635 printf("(mbox) Adding cc: %s from line '%s'\n",
636 $2, $_) unless $quiet;
637 push @cc, $2;
639 elsif (/^Content-type:/i) {
640 $has_content_type = 1;
641 if (/charset="?[^ "]+/) {
642 $body_encoding = $1;
644 push @xh, $_;
646 elsif (!/^Date:\s/ && /^[-A-Za-z]+:\s+\S/) {
647 push @xh, $_;
650 } else {
651 # In the traditional
652 # "send lots of email" format,
653 # line 1 = cc
654 # line 2 = subject
655 # So let's support that, too.
656 $input_format = 'lots';
657 if (@cc == 0) {
658 printf("(non-mbox) Adding cc: %s from line '%s'\n",
659 $_, $_) unless $quiet;
661 push @cc, $_;
663 } elsif (!defined $subject) {
664 $subject = $_;
668 # A whitespace line will terminate the headers
669 if (m/^\s*$/) {
670 $header_done = 1;
672 } else {
673 $message .= $_;
674 if (/^(Signed-off-by|Cc): (.*)$/i && $signed_off_cc) {
675 my $c = $2;
676 chomp $c;
677 push @cc, $c;
678 printf("(sob) Adding cc: %s from line '%s'\n",
679 $c, $_) unless $quiet;
683 close F;
685 if ($cc_cmd ne "") {
686 open(F, "$cc_cmd $t |")
687 or die "(cc-cmd) Could not execute '$cc_cmd'";
688 while(<F>) {
689 my $c = $_;
690 $c =~ s/^\s*//g;
691 $c =~ s/\n$//g;
692 push @cc, $c;
693 printf("(cc-cmd) Adding cc: %s from: '%s'\n",
694 $c, $cc_cmd) unless $quiet;
696 close F
697 or die "(cc-cmd) failed to close pipe to '$cc_cmd'";
700 if (defined $author) {
701 $message = "From: $author\n\n$message";
702 if (defined $author_encoding) {
703 if ($has_content_type) {
704 if ($body_encoding eq $author_encoding) {
705 # ok, we already have the right encoding
707 else {
708 # uh oh, we should re-encode
711 else {
712 push @xh,
713 'MIME-Version: 1.0',
714 "Content-Type: text/plain; charset=$author_encoding";
719 send_message();
721 # set up for the next message
722 if ($chain_reply_to || !defined $reply_to || length($reply_to) == 0) {
723 $reply_to = $message_id;
724 if (length $references > 0) {
725 $references .= "\n $message_id";
726 } else {
727 $references = "$message_id";
732 if ($compose) {
733 cleanup_compose_files();
736 sub cleanup_compose_files() {
737 unlink($compose_filename, $compose_filename . ".final");
741 $smtp->quit if $smtp;
743 sub unique_email_list(@) {
744 my %seen;
745 my @emails;
747 foreach my $entry (@_) {
748 if (my $clean = extract_valid_address($entry)) {
749 $seen{$clean} ||= 0;
750 next if $seen{$clean}++;
751 push @emails, $entry;
752 } else {
753 print STDERR "W: unable to extract a valid address",
754 " from: $entry\n";
757 return @emails;