packv4: nth_packed_object_sha1() packv4 support
[git/packv4.git] / git-send-email.perl
blobf1a88556824e098ab9594a6018e127c50c7fa51a
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 --bcc Specify a list of email addresses that should be Bcc:
53 on all the emails.
55 --compose Use \$GIT_EDITOR, core.editor, \$EDITOR, or \$VISUAL to edit
56 an introductory message for the patch series.
58 --subject Specify the initial "Subject:" line.
59 Only necessary if --compose is also set. If --compose
60 is not set, this will be prompted for.
62 --in-reply-to Specify the first "In-Reply-To:" header line.
63 Only used if --compose is also set. If --compose is not
64 set, this will be prompted for.
66 --chain-reply-to If set, the replies will all be to the previous
67 email sent, rather than to the first email sent.
68 Defaults to on.
70 --signed-off-cc Automatically add email addresses that appear in
71 Signed-off-by: or Cc: lines to the cc: list. Defaults to on.
73 --smtp-server If set, specifies the outgoing SMTP server to use.
74 Defaults to localhost.
76 --suppress-from Suppress sending emails to yourself if your address
77 appears in a From: line. Defaults to off.
79 --thread Specify that the "In-Reply-To:" header should be set on all
80 emails. Defaults to on.
82 --quiet Make git-send-email less verbose. One line per email
83 should be all that is output.
85 --dry-run Do everything except actually send the emails.
87 --envelope-sender Specify the envelope sender used to send the emails.
89 EOT
90 exit(1);
93 # most mail servers generate the Date: header, but not all...
94 sub format_2822_time {
95 my ($time) = @_;
96 my @localtm = localtime($time);
97 my @gmttm = gmtime($time);
98 my $localmin = $localtm[1] + $localtm[2] * 60;
99 my $gmtmin = $gmttm[1] + $gmttm[2] * 60;
100 if ($localtm[0] != $gmttm[0]) {
101 die "local zone differs from GMT by a non-minute interval\n";
103 if ((($gmttm[6] + 1) % 7) == $localtm[6]) {
104 $localmin += 1440;
105 } elsif ((($gmttm[6] - 1) % 7) == $localtm[6]) {
106 $localmin -= 1440;
107 } elsif ($gmttm[6] != $localtm[6]) {
108 die "local time offset greater than or equal to 24 hours\n";
110 my $offset = $localmin - $gmtmin;
111 my $offhour = $offset / 60;
112 my $offmin = abs($offset % 60);
113 if (abs($offhour) >= 24) {
114 die ("local time offset greater than or equal to 24 hours\n");
117 return sprintf("%s, %2d %s %d %02d:%02d:%02d %s%02d%02d",
118 qw(Sun Mon Tue Wed Thu Fri Sat)[$localtm[6]],
119 $localtm[3],
120 qw(Jan Feb Mar Apr May Jun
121 Jul Aug Sep Oct Nov Dec)[$localtm[4]],
122 $localtm[5]+1900,
123 $localtm[2],
124 $localtm[1],
125 $localtm[0],
126 ($offset >= 0) ? '+' : '-',
127 abs($offhour),
128 $offmin,
132 my $have_email_valid = eval { require Email::Valid; 1 };
133 my $smtp;
135 sub unique_email_list(@);
136 sub cleanup_compose_files();
138 # Constants (essentially)
139 my $compose_filename = ".msg.$$";
141 # Variables we fill in automatically, or via prompting:
142 my (@to,@cc,@initial_cc,@bcclist,@xh,
143 $initial_reply_to,$initial_subject,@files,$author,$sender,$compose,$time);
145 my $smtp_server;
146 my $envelope_sender;
148 # Example reply to:
149 #$initial_reply_to = ''; #<20050203173208.GA23964@foobar.com>';
151 my $repo = Git->repository();
152 my $term = eval {
153 new Term::ReadLine 'git-send-email';
155 if ($@) {
156 $term = new FakeTerm "$@: going non-interactive";
159 # Behavior modification variables
160 my ($quiet, $dry_run) = (0, 0);
162 # Variables with corresponding config settings
163 my ($thread, $chain_reply_to, $suppress_from, $signed_off_cc);
165 my %config_settings = (
166 "thread" => [\$thread, 1],
167 "chainreplyto" => [\$chain_reply_to, 1],
168 "suppressfrom" => [\$suppress_from, 0],
169 "signedoffcc" => [\$signed_off_cc, 1],
172 foreach my $setting (keys %config_settings) {
173 my $config = $repo->config_bool("sendemail.$setting");
174 ${$config_settings{$setting}->[0]} = (defined $config) ? $config : $config_settings{$setting}->[1];
177 @bcclist = $repo->config('sendemail.bcc');
178 if (!@bcclist or !$bcclist[0]) {
179 @bcclist = ();
182 # Begin by accumulating all the variables (defined above), that we will end up
183 # needing, first, from the command line:
185 my $rc = GetOptions("sender|from=s" => \$sender,
186 "in-reply-to=s" => \$initial_reply_to,
187 "subject=s" => \$initial_subject,
188 "to=s" => \@to,
189 "cc=s" => \@initial_cc,
190 "bcc=s" => \@bcclist,
191 "chain-reply-to!" => \$chain_reply_to,
192 "smtp-server=s" => \$smtp_server,
193 "compose" => \$compose,
194 "quiet" => \$quiet,
195 "suppress-from!" => \$suppress_from,
196 "signed-off-cc|signed-off-by-cc!" => \$signed_off_cc,
197 "dry-run" => \$dry_run,
198 "envelope-sender=s" => \$envelope_sender,
199 "thread!" => \$thread,
202 unless ($rc) {
203 usage();
206 # Verify the user input
208 foreach my $entry (@to) {
209 die "Comma in --to entry: $entry'\n" unless $entry !~ m/,/;
212 foreach my $entry (@initial_cc) {
213 die "Comma in --cc entry: $entry'\n" unless $entry !~ m/,/;
216 foreach my $entry (@bcclist) {
217 die "Comma in --bcclist entry: $entry'\n" unless $entry !~ m/,/;
220 # Now, let's fill any that aren't set in with defaults:
222 my ($repoauthor) = $repo->ident_person('author');
223 my ($repocommitter) = $repo->ident_person('committer');
225 my %aliases;
226 my @alias_files = $repo->config('sendemail.aliasesfile');
227 my $aliasfiletype = $repo->config('sendemail.aliasfiletype');
228 my %parse_alias = (
229 # multiline formats can be supported in the future
230 mutt => sub { my $fh = shift; while (<$fh>) {
231 if (/^\s*alias\s+(\S+)\s+(.*)$/) {
232 my ($alias, $addr) = ($1, $2);
233 $addr =~ s/#.*$//; # mutt allows # comments
234 # commas delimit multiple addresses
235 $aliases{$alias} = [ split(/\s*,\s*/, $addr) ];
236 }}},
237 mailrc => sub { my $fh = shift; while (<$fh>) {
238 if (/^alias\s+(\S+)\s+(.*)$/) {
239 # spaces delimit multiple addresses
240 $aliases{$1} = [ split(/\s+/, $2) ];
241 }}},
242 pine => sub { my $fh = shift; while (<$fh>) {
243 if (/^(\S+)\t.*\t(.*)$/) {
244 $aliases{$1} = [ split(/\s*,\s*/, $2) ];
245 }}},
246 gnus => sub { my $fh = shift; while (<$fh>) {
247 if (/\(define-mail-alias\s+"(\S+?)"\s+"(\S+?)"\)/) {
248 $aliases{$1} = [ $2 ];
252 if (@alias_files and $aliasfiletype and defined $parse_alias{$aliasfiletype}) {
253 foreach my $file (@alias_files) {
254 open my $fh, '<', $file or die "opening $file: $!\n";
255 $parse_alias{$aliasfiletype}->($fh);
256 close $fh;
260 ($sender) = expand_aliases($sender) if defined $sender;
262 my $prompting = 0;
263 if (!defined $sender) {
264 $sender = $repoauthor || $repocommitter;
265 do {
266 $_ = $term->readline("Who should the emails appear to be from? [$sender] ");
267 } while (!defined $_);
269 $sender = $_ if ($_);
270 print "Emails will be sent from: ", $sender, "\n";
271 $prompting++;
274 if (!@to) {
275 do {
276 $_ = $term->readline("Who should the emails be sent to? ",
277 "");
278 } while (!defined $_);
279 my $to = $_;
280 push @to, split /,/, $to;
281 $prompting++;
284 sub expand_aliases {
285 my @cur = @_;
286 my @last;
287 do {
288 @last = @cur;
289 @cur = map { $aliases{$_} ? @{$aliases{$_}} : $_ } @last;
290 } while (join(',',@cur) ne join(',',@last));
291 return @cur;
294 @to = expand_aliases(@to);
295 @to = (map { sanitize_address($_) } @to);
296 @initial_cc = expand_aliases(@initial_cc);
297 @bcclist = expand_aliases(@bcclist);
299 if (!defined $initial_subject && $compose) {
300 do {
301 $_ = $term->readline("What subject should the emails start with? ",
302 $initial_subject);
303 } while (!defined $_);
304 $initial_subject = $_;
305 $prompting++;
308 if ($thread && !defined $initial_reply_to && $prompting) {
309 do {
310 $_= $term->readline("Message-ID to be used as In-Reply-To for the first email? ",
311 $initial_reply_to);
312 } while (!defined $_);
314 $initial_reply_to = $_;
315 $initial_reply_to =~ s/(^\s+|\s+$)//g;
318 if (!$smtp_server) {
319 $smtp_server = $repo->config('sendemail.smtpserver');
321 if (!$smtp_server) {
322 foreach (qw( /usr/sbin/sendmail /usr/lib/sendmail )) {
323 if (-x $_) {
324 $smtp_server = $_;
325 last;
328 $smtp_server ||= 'localhost'; # could be 127.0.0.1, too... *shrug*
331 if ($compose) {
332 # Note that this does not need to be secure, but we will make a small
333 # effort to have it be unique
334 open(C,">",$compose_filename)
335 or die "Failed to open for writing $compose_filename: $!";
336 print C "From $sender # This line is ignored.\n";
337 printf C "Subject: %s\n\n", $initial_subject;
338 printf C <<EOT;
339 GIT: Please enter your email below.
340 GIT: Lines beginning in "GIT: " will be removed.
341 GIT: Consider including an overall diffstat or table of contents
342 GIT: for the patch you are writing.
345 close(C);
347 my $editor = $ENV{GIT_EDITOR} || $repo->config("core.editor") || $ENV{VISUAL} || $ENV{EDITOR} || "vi";
348 system($editor, $compose_filename);
350 open(C2,">",$compose_filename . ".final")
351 or die "Failed to open $compose_filename.final : " . $!;
353 open(C,"<",$compose_filename)
354 or die "Failed to open $compose_filename : " . $!;
356 while(<C>) {
357 next if m/^GIT: /;
358 print C2 $_;
360 close(C);
361 close(C2);
363 do {
364 $_ = $term->readline("Send this email? (y|n) ");
365 } while (!defined $_);
367 if (uc substr($_,0,1) ne 'Y') {
368 cleanup_compose_files();
369 exit(0);
372 @files = ($compose_filename . ".final");
376 # Now that all the defaults are set, process the rest of the command line
377 # arguments and collect up the files that need to be processed.
378 for my $f (@ARGV) {
379 if (-d $f) {
380 opendir(DH,$f)
381 or die "Failed to opendir $f: $!";
383 push @files, grep { -f $_ } map { +$f . "/" . $_ }
384 sort readdir(DH);
386 } elsif (-f $f) {
387 push @files, $f;
389 } else {
390 print STDERR "Skipping $f - not found.\n";
394 if (@files) {
395 unless ($quiet) {
396 print $_,"\n" for (@files);
398 } else {
399 print STDERR "\nNo patch files specified!\n\n";
400 usage();
403 # Variables we set as part of the loop over files
404 our ($message_id, %mail, $subject, $reply_to, $references, $message);
406 sub extract_valid_address {
407 my $address = shift;
408 my $local_part_regexp = '[^<>"\s@]+';
409 my $domain_regexp = '[^.<>"\s@]+(?:\.[^.<>"\s@]+)+';
411 # check for a local address:
412 return $address if ($address =~ /^($local_part_regexp)$/);
414 $address =~ s/^\s*<(.*)>\s*$/$1/;
415 if ($have_email_valid) {
416 return scalar Email::Valid->address($address);
417 } else {
418 # less robust/correct than the monster regexp in Email::Valid,
419 # but still does a 99% job, and one less dependency
420 $address =~ /($local_part_regexp\@$domain_regexp)/;
421 return $1;
425 # Usually don't need to change anything below here.
427 # we make a "fake" message id by taking the current number
428 # of seconds since the beginning of Unix time and tacking on
429 # a random number to the end, in case we are called quicker than
430 # 1 second since the last time we were called.
432 # We'll setup a template for the message id, using the "from" address:
434 sub make_message_id
436 my $date = time;
437 my $pseudo_rand = int (rand(4200));
438 my $du_part;
439 for ($sender, $repocommitter, $repoauthor) {
440 $du_part = extract_valid_address(sanitize_address($_));
441 last if (defined $du_part and $du_part ne '');
443 if (not defined $du_part or $du_part eq '') {
444 use Sys::Hostname qw();
445 $du_part = 'user@' . Sys::Hostname::hostname();
447 my $message_id_template = "<%s-git-send-email-$du_part>";
448 $message_id = sprintf $message_id_template, "$date$pseudo_rand";
449 #print "new message id = $message_id\n"; # Was useful for debugging
454 $time = time - scalar $#files;
456 sub unquote_rfc2047 {
457 local ($_) = @_;
458 if (s/=\?utf-8\?q\?(.*)\?=/$1/g) {
459 s/_/ /g;
460 s/=([0-9A-F]{2})/chr(hex($1))/eg;
462 return "$_";
465 # use the simplest quoting being able to handle the recipient
466 sub sanitize_address
468 my ($recipient) = @_;
469 my ($recipient_name, $recipient_addr) = ($recipient =~ /^(.*?)\s*(<.*)/);
471 if (not $recipient_name) {
472 return "$recipient";
475 # if recipient_name is already quoted, do nothing
476 if ($recipient_name =~ /^(".*"|=\?utf-8\?q\?.*\?=)$/) {
477 return $recipient;
480 # rfc2047 is needed if a non-ascii char is included
481 if ($recipient_name =~ /[^[:ascii:]]/) {
482 $recipient_name =~ s/([^-a-zA-Z0-9!*+\/])/sprintf("=%02X", ord($1))/eg;
483 $recipient_name =~ s/(.*)/=\?utf-8\?q\?$1\?=/;
486 # double quotes are needed if specials or CTLs are included
487 elsif ($recipient_name =~ /[][()<>@,;:\\".\000-\037\177]/) {
488 $recipient_name =~ s/(["\\\r])/\\$1/;
489 $recipient_name = "\"$recipient_name\"";
492 return "$recipient_name $recipient_addr";
496 sub send_message
498 my @recipients = unique_email_list(@to);
499 @cc = (map { sanitize_address($_) } @cc);
500 my $to = join (",\n\t", @recipients);
501 @recipients = unique_email_list(@recipients,@cc,@bcclist);
502 @recipients = (map { extract_valid_address($_) } @recipients);
503 my $date = format_2822_time($time++);
504 my $gitversion = '@@GIT_VERSION@@';
505 if ($gitversion =~ m/..GIT_VERSION../) {
506 $gitversion = Git::version();
509 my $cc = join(", ", unique_email_list(@cc));
510 my $ccline = "";
511 if ($cc ne '') {
512 $ccline = "\nCc: $cc";
514 my $sanitized_sender = sanitize_address($sender);
515 make_message_id();
517 my $header = "From: $sanitized_sender
518 To: $to${ccline}
519 Subject: $subject
520 Date: $date
521 Message-Id: $message_id
522 X-Mailer: git-send-email $gitversion
524 if ($thread && $reply_to) {
526 $header .= "In-Reply-To: $reply_to\n";
527 $header .= "References: $references\n";
529 if (@xh) {
530 $header .= join("\n", @xh) . "\n";
533 my @sendmail_parameters = ('-i', @recipients);
534 my $raw_from = $sanitized_sender;
535 $raw_from = $envelope_sender if (defined $envelope_sender);
536 $raw_from = extract_valid_address($raw_from);
537 unshift (@sendmail_parameters,
538 '-f', $raw_from) if(defined $envelope_sender);
540 if ($dry_run) {
541 # We don't want to send the email.
542 } elsif ($smtp_server =~ m#^/#) {
543 my $pid = open my $sm, '|-';
544 defined $pid or die $!;
545 if (!$pid) {
546 exec($smtp_server, @sendmail_parameters) or die $!;
548 print $sm "$header\n$message";
549 close $sm or die $?;
550 } else {
551 require Net::SMTP;
552 $smtp ||= Net::SMTP->new( $smtp_server );
553 $smtp->mail( $raw_from ) or die $smtp->message;
554 $smtp->to( @recipients ) or die $smtp->message;
555 $smtp->data or die $smtp->message;
556 $smtp->datasend("$header\n$message") or die $smtp->message;
557 $smtp->dataend() or die $smtp->message;
558 $smtp->ok or die "Failed to send $subject\n".$smtp->message;
560 if ($quiet) {
561 printf (($dry_run ? "Dry-" : "")."Sent %s\n", $subject);
562 } else {
563 print (($dry_run ? "Dry-" : "")."OK. Log says:\nDate: $date\n");
564 if ($smtp_server !~ m#^/#) {
565 print "Server: $smtp_server\n";
566 print "MAIL FROM:<$raw_from>\n";
567 print "RCPT TO:".join(',',(map { "<$_>" } @recipients))."\n";
568 } else {
569 print "Sendmail: $smtp_server ".join(' ',@sendmail_parameters)."\n";
571 print "From: $sanitized_sender\nSubject: $subject\nCc: $cc\nTo: $to\n\n";
572 if ($smtp) {
573 print "Result: ", $smtp->code, ' ',
574 ($smtp->message =~ /\n([^\n]+\n)$/s), "\n";
575 } else {
576 print "Result: OK\n";
581 $reply_to = $initial_reply_to;
582 $references = $initial_reply_to || '';
583 $subject = $initial_subject;
585 foreach my $t (@files) {
586 open(F,"<",$t) or die "can't open file $t";
588 my $author = undef;
589 @cc = @initial_cc;
590 @xh = ();
591 my $input_format = undef;
592 my $header_done = 0;
593 $message = "";
594 while(<F>) {
595 if (!$header_done) {
596 if (/^From /) {
597 $input_format = 'mbox';
598 next;
600 chomp;
601 if (!defined $input_format && /^[-A-Za-z]+:\s/) {
602 $input_format = 'mbox';
605 if (defined $input_format && $input_format eq 'mbox') {
606 if (/^Subject:\s+(.*)$/) {
607 $subject = $1;
609 } elsif (/^(Cc|From):\s+(.*)$/) {
610 if (unquote_rfc2047($2) eq $sender) {
611 next if ($suppress_from);
613 elsif ($1 eq 'From') {
614 $author = unquote_rfc2047($2);
616 printf("(mbox) Adding cc: %s from line '%s'\n",
617 $2, $_) unless $quiet;
618 push @cc, $2;
620 elsif (!/^Date:\s/ && /^[-A-Za-z]+:\s+\S/) {
621 push @xh, $_;
624 } else {
625 # In the traditional
626 # "send lots of email" format,
627 # line 1 = cc
628 # line 2 = subject
629 # So let's support that, too.
630 $input_format = 'lots';
631 if (@cc == 0) {
632 printf("(non-mbox) Adding cc: %s from line '%s'\n",
633 $_, $_) unless $quiet;
635 push @cc, $_;
637 } elsif (!defined $subject) {
638 $subject = $_;
642 # A whitespace line will terminate the headers
643 if (m/^\s*$/) {
644 $header_done = 1;
646 } else {
647 $message .= $_;
648 if (/^(Signed-off-by|Cc): (.*)$/i && $signed_off_cc) {
649 my $c = $2;
650 chomp $c;
651 push @cc, $c;
652 printf("(sob) Adding cc: %s from line '%s'\n",
653 $c, $_) unless $quiet;
657 close F;
658 if (defined $author) {
659 $message = "From: $author\n\n$message";
663 send_message();
665 # set up for the next message
666 if ($chain_reply_to || !defined $reply_to || length($reply_to) == 0) {
667 $reply_to = $message_id;
668 if (length $references > 0) {
669 $references .= "\n $message_id";
670 } else {
671 $references = "$message_id";
676 if ($compose) {
677 cleanup_compose_files();
680 sub cleanup_compose_files() {
681 unlink($compose_filename, $compose_filename . ".final");
685 $smtp->quit if $smtp;
687 sub unique_email_list(@) {
688 my %seen;
689 my @emails;
691 foreach my $entry (@_) {
692 if (my $clean = extract_valid_address($entry)) {
693 $seen{$clean} ||= 0;
694 next if $seen{$clean}++;
695 push @emails, $entry;
696 } else {
697 print STDERR "W: unable to extract a valid address",
698 " from: $entry\n";
701 return @emails;