Allow INSTALL, bindir, mandir to be set in main Makefile
[git/jnareb-git.git] / git-send-email.perl
blob6e1a3a157f9aeda806c94e779df12492caf6576a
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;
25 # most mail servers generate the Date: header, but not all...
26 $ENV{LC_ALL} = 'C';
27 use POSIX qw/strftime setlocale LC_ALL/;
28 setlocale( &LC_ALL, 'C' );
30 my $have_email_valid = eval { require Email::Valid; 1 };
31 my $smtp;
33 sub unique_email_list(@);
34 sub cleanup_compose_files();
36 # Constants (essentially)
37 my $compose_filename = ".msg.$$";
39 # Variables we fill in automatically, or via prompting:
40 my (@to,@cc,@initial_cc,@bcclist,
41 $initial_reply_to,$initial_subject,@files,$from,$compose,$time);
43 # Behavior modification variables
44 my ($chain_reply_to, $quiet, $suppress_from, $no_signed_off_cc) = (1, 0, 0, 0);
45 my $smtp_server;
47 # Example reply to:
48 #$initial_reply_to = ''; #<20050203173208.GA23964@foobar.com>';
50 my $term = new Term::ReadLine 'git-send-email';
52 # Begin by accumulating all the variables (defined above), that we will end up
53 # needing, first, from the command line:
55 my $rc = GetOptions("from=s" => \$from,
56 "in-reply-to=s" => \$initial_reply_to,
57 "subject=s" => \$initial_subject,
58 "to=s" => \@to,
59 "cc=s" => \@initial_cc,
60 "bcc=s" => \@bcclist,
61 "chain-reply-to!" => \$chain_reply_to,
62 "smtp-server=s" => \$smtp_server,
63 "compose" => \$compose,
64 "quiet" => \$quiet,
65 "suppress-from" => \$suppress_from,
66 "no-signed-off-cc|no-signed-off-by-cc" => \$no_signed_off_cc,
69 # Verify the user input
71 foreach my $entry (@to) {
72 die "Comma in --to entry: $entry'\n" unless $entry !~ m/,/;
75 foreach my $entry (@initial_cc) {
76 die "Comma in --cc entry: $entry'\n" unless $entry !~ m/,/;
79 foreach my $entry (@bcclist) {
80 die "Comma in --bcclist entry: $entry'\n" unless $entry !~ m/,/;
83 # Now, let's fill any that aren't set in with defaults:
85 sub gitvar {
86 my ($var) = @_;
87 my $fh;
88 my $pid = open($fh, '-|');
89 die "$!" unless defined $pid;
90 if (!$pid) {
91 exec('git-var', $var) or die "$!";
93 my ($val) = <$fh>;
94 close $fh or die "$!";
95 chomp($val);
96 return $val;
99 sub gitvar_ident {
100 my ($name) = @_;
101 my $val = gitvar($name);
102 my @field = split(/\s+/, $val);
103 return join(' ', @field[0...(@field-3)]);
106 my ($author) = gitvar_ident('GIT_AUTHOR_IDENT');
107 my ($committer) = gitvar_ident('GIT_COMMITTER_IDENT');
109 my %aliases;
110 chomp(my @alias_files = `git-repo-config --get-all sendemail.aliasesfile`);
111 chomp(my $aliasfiletype = `git-repo-config sendemail.aliasfiletype`);
112 my %parse_alias = (
113 # multiline formats can be supported in the future
114 mutt => sub { my $fh = shift; while (<$fh>) {
115 if (/^alias\s+(\S+)\s+(.*)$/) {
116 my ($alias, $addr) = ($1, $2);
117 $addr =~ s/#.*$//; # mutt allows # comments
118 # commas delimit multiple addresses
119 $aliases{$alias} = [ split(/\s*,\s*/, $addr) ];
120 }}},
121 mailrc => sub { my $fh = shift; while (<$fh>) {
122 if (/^alias\s+(\S+)\s+(.*)$/) {
123 # spaces delimit multiple addresses
124 $aliases{$1} = [ split(/\s+/, $2) ];
125 }}},
126 pine => sub { my $fh = shift; while (<$fh>) {
127 if (/^(\S+)\s+(.*)$/) {
128 $aliases{$1} = [ split(/\s*,\s*/, $2) ];
129 }}},
130 gnus => sub { my $fh = shift; while (<$fh>) {
131 if (/\(define-mail-alias\s+"(\S+?)"\s+"(\S+?)"\)/) {
132 $aliases{$1} = [ $2 ];
136 if (@alias_files && defined $parse_alias{$aliasfiletype}) {
137 foreach my $file (@alias_files) {
138 open my $fh, '<', $file or die "opening $file: $!\n";
139 $parse_alias{$aliasfiletype}->($fh);
140 close $fh;
144 my $prompting = 0;
145 if (!defined $from) {
146 $from = $author || $committer;
147 do {
148 $_ = $term->readline("Who should the emails appear to be from? ",
149 $from);
150 } while (!defined $_);
152 $from = $_;
153 print "Emails will be sent from: ", $from, "\n";
154 $prompting++;
157 if (!@to) {
158 do {
159 $_ = $term->readline("Who should the emails be sent to? ",
160 "");
161 } while (!defined $_);
162 my $to = $_;
163 push @to, split /,/, $to;
164 $prompting++;
167 sub expand_aliases {
168 my @cur = @_;
169 my @last;
170 do {
171 @last = @cur;
172 @cur = map { $aliases{$_} ? @{$aliases{$_}} : $_ } @last;
173 } while (join(',',@cur) ne join(',',@last));
174 return @cur;
177 @to = expand_aliases(@to);
178 @initial_cc = expand_aliases(@initial_cc);
179 @bcclist = expand_aliases(@bcclist);
181 if (!defined $initial_subject && $compose) {
182 do {
183 $_ = $term->readline("What subject should the emails start with? ",
184 $initial_subject);
185 } while (!defined $_);
186 $initial_subject = $_;
187 $prompting++;
190 if (!defined $initial_reply_to && $prompting) {
191 do {
192 $_= $term->readline("Message-ID to be used as In-Reply-To for the first email? ",
193 $initial_reply_to);
194 } while (!defined $_);
196 $initial_reply_to = $_;
197 $initial_reply_to =~ s/(^\s+|\s+$)//g;
200 if (!$smtp_server) {
201 foreach (qw( /usr/sbin/sendmail /usr/lib/sendmail )) {
202 if (-x $_) {
203 $smtp_server = $_;
204 last;
207 $smtp_server ||= 'localhost'; # could be 127.0.0.1, too... *shrug*
210 if ($compose) {
211 # Note that this does not need to be secure, but we will make a small
212 # effort to have it be unique
213 open(C,">",$compose_filename)
214 or die "Failed to open for writing $compose_filename: $!";
215 print C "From $from # This line is ignored.\n";
216 printf C "Subject: %s\n\n", $initial_subject;
217 printf C <<EOT;
218 GIT: Please enter your email below.
219 GIT: Lines beginning in "GIT: " will be removed.
220 GIT: Consider including an overall diffstat or table of contents
221 GIT: for the patch you are writing.
224 close(C);
226 my $editor = $ENV{EDITOR};
227 $editor = 'vi' unless defined $editor;
228 system($editor, $compose_filename);
230 open(C2,">",$compose_filename . ".final")
231 or die "Failed to open $compose_filename.final : " . $!;
233 open(C,"<",$compose_filename)
234 or die "Failed to open $compose_filename : " . $!;
236 while(<C>) {
237 next if m/^GIT: /;
238 print C2 $_;
240 close(C);
241 close(C2);
243 do {
244 $_ = $term->readline("Send this email? (y|n) ");
245 } while (!defined $_);
247 if (uc substr($_,0,1) ne 'Y') {
248 cleanup_compose_files();
249 exit(0);
252 @files = ($compose_filename . ".final");
256 # Now that all the defaults are set, process the rest of the command line
257 # arguments and collect up the files that need to be processed.
258 for my $f (@ARGV) {
259 if (-d $f) {
260 opendir(DH,$f)
261 or die "Failed to opendir $f: $!";
263 push @files, grep { -f $_ } map { +$f . "/" . $_ }
264 sort readdir(DH);
266 } elsif (-f $f) {
267 push @files, $f;
269 } else {
270 print STDERR "Skipping $f - not found.\n";
274 if (@files) {
275 unless ($quiet) {
276 print $_,"\n" for (@files);
278 } else {
279 print <<EOT;
280 git-send-email [options] <file | directory> [... file | directory ]
281 Options:
282 --from Specify the "From:" line of the email to be sent.
284 --to Specify the primary "To:" line of the email.
286 --cc Specify an initial "Cc:" list for the entire series
287 of emails.
289 --bcc Specify a list of email addresses that should be Bcc:
290 on all the emails.
292 --compose Use \$EDITOR to edit an introductory message for the
293 patch series.
295 --subject Specify the initial "Subject:" line.
296 Only necessary if --compose is also set. If --compose
297 is not set, this will be prompted for.
299 --in-reply-to Specify the first "In-Reply-To:" header line.
300 Only used if --compose is also set. If --compose is not
301 set, this will be prompted for.
303 --chain-reply-to If set, the replies will all be to the previous
304 email sent, rather than to the first email sent.
305 Defaults to on.
307 --no-signed-off-cc Suppress the automatic addition of email addresses
308 that appear in a Signed-off-by: line, to the cc: list.
309 Note: Using this option is not recommended.
311 --smtp-server If set, specifies the outgoing SMTP server to use.
312 Defaults to localhost.
314 --suppress-from Supress sending emails to yourself if your address
315 appears in a From: line.
317 --quiet Make git-send-email less verbose. One line per email should be
318 all that is output.
320 Error: Please specify a file or a directory on the command line.
322 exit(1);
325 # Variables we set as part of the loop over files
326 our ($message_id, $cc, %mail, $subject, $reply_to, $references, $message);
328 sub extract_valid_address {
329 my $address = shift;
330 my $local_part_regexp = '[^<>"\s@]+';
331 my $domain_regexp = '[^.<>"\s@]+(?:\.[^.<>"\s@]+)+';
333 # check for a local address:
334 return $address if ($address =~ /^($local_part_regexp)$/);
336 if ($have_email_valid) {
337 return scalar Email::Valid->address($address);
338 } else {
339 # less robust/correct than the monster regexp in Email::Valid,
340 # but still does a 99% job, and one less dependency
341 $address =~ /($local_part_regexp\@$domain_regexp)/;
342 return $1;
346 # Usually don't need to change anything below here.
348 # we make a "fake" message id by taking the current number
349 # of seconds since the beginning of Unix time and tacking on
350 # a random number to the end, in case we are called quicker than
351 # 1 second since the last time we were called.
353 # We'll setup a template for the message id, using the "from" address:
354 my $message_id_from = extract_valid_address($from);
355 my $message_id_template = "<%s-git-send-email-$message_id_from>";
357 sub make_message_id
359 my $date = time;
360 my $pseudo_rand = int (rand(4200));
361 $message_id = sprintf $message_id_template, "$date$pseudo_rand";
362 #print "new message id = $message_id\n"; # Was useful for debugging
367 $cc = "";
368 $time = time - scalar $#files;
370 sub send_message
372 my @recipients = unique_email_list(@to);
373 my $to = join (",\n\t", @recipients);
374 @recipients = unique_email_list(@recipients,@cc,@bcclist);
375 my $date = strftime('%a, %d %b %Y %H:%M:%S %z', localtime($time++));
376 my $gitversion = '@@GIT_VERSION@@';
377 if ($gitversion =~ m/..GIT_VERSION../) {
378 $gitversion = `git --version`;
379 chomp $gitversion;
380 # keep only what's after the last space
381 $gitversion =~ s/^.* //;
384 my $header = "From: $from
385 To: $to
386 Cc: $cc
387 Subject: $subject
388 Reply-To: $from
389 Date: $date
390 Message-Id: $message_id
391 X-Mailer: git-send-email $gitversion
393 if ($reply_to) {
395 $header .= "In-Reply-To: $reply_to\n";
396 $header .= "References: $references\n";
399 if ($smtp_server =~ m#^/#) {
400 my $pid = open my $sm, '|-';
401 defined $pid or die $!;
402 if (!$pid) {
403 exec($smtp_server,'-i',
404 map { extract_valid_address($_) }
405 @recipients) or die $!;
407 print $sm "$header\n$message";
408 close $sm or die $?;
409 } else {
410 require Net::SMTP;
411 $smtp ||= Net::SMTP->new( $smtp_server );
412 $smtp->mail( $from ) or die $smtp->message;
413 $smtp->to( @recipients ) or die $smtp->message;
414 $smtp->data or die $smtp->message;
415 $smtp->datasend("$header\n$message") or die $smtp->message;
416 $smtp->dataend() or die $smtp->message;
417 $smtp->ok or die "Failed to send $subject\n".$smtp->message;
419 if ($quiet) {
420 printf "Sent %s\n", $subject;
421 } else {
422 print "OK. Log says:\nDate: $date\n";
423 if ($smtp) {
424 print "Server: $smtp_server\n";
425 } else {
426 print "Sendmail: $smtp_server\n";
428 print "From: $from\nSubject: $subject\nCc: $cc\nTo: $to\n\n";
429 if ($smtp) {
430 print "Result: ", $smtp->code, ' ',
431 ($smtp->message =~ /\n([^\n]+\n)$/s), "\n";
432 } else {
433 print "Result: OK\n";
438 $reply_to = $initial_reply_to;
439 $references = $initial_reply_to || '';
440 make_message_id();
441 $subject = $initial_subject;
443 foreach my $t (@files) {
444 open(F,"<",$t) or die "can't open file $t";
446 my $author_not_sender = undef;
447 @cc = @initial_cc;
448 my $found_mbox = 0;
449 my $header_done = 0;
450 $message = "";
451 while(<F>) {
452 if (!$header_done) {
453 $found_mbox = 1, next if (/^From /);
454 chomp;
456 if ($found_mbox) {
457 if (/^Subject:\s+(.*)$/) {
458 $subject = $1;
460 } elsif (/^(Cc|From):\s+(.*)$/) {
461 if ($2 eq $from) {
462 next if ($suppress_from);
464 else {
465 $author_not_sender = $2;
467 printf("(mbox) Adding cc: %s from line '%s'\n",
468 $2, $_) unless $quiet;
469 push @cc, $2;
472 } else {
473 # In the traditional
474 # "send lots of email" format,
475 # line 1 = cc
476 # line 2 = subject
477 # So let's support that, too.
478 if (@cc == 0) {
479 printf("(non-mbox) Adding cc: %s from line '%s'\n",
480 $_, $_) unless $quiet;
482 push @cc, $_;
484 } elsif (!defined $subject) {
485 $subject = $_;
489 # A whitespace line will terminate the headers
490 if (m/^\s*$/) {
491 $header_done = 1;
493 } else {
494 $message .= $_;
495 if (/^Signed-off-by: (.*)$/i && !$no_signed_off_cc) {
496 my $c = $1;
497 chomp $c;
498 push @cc, $c;
499 printf("(sob) Adding cc: %s from line '%s'\n",
500 $c, $_) unless $quiet;
504 close F;
505 if (defined $author_not_sender) {
506 $message = "From: $author_not_sender\n\n$message";
509 $cc = join(", ", unique_email_list(@cc));
511 send_message();
513 # set up for the next message
514 if ($chain_reply_to || length($reply_to) == 0) {
515 $reply_to = $message_id;
516 if (length $references > 0) {
517 $references .= " $message_id";
518 } else {
519 $references = "$message_id";
522 make_message_id();
525 if ($compose) {
526 cleanup_compose_files();
529 sub cleanup_compose_files() {
530 unlink($compose_filename, $compose_filename . ".final");
534 $smtp->quit if $smtp;
536 sub unique_email_list(@) {
537 my %seen;
538 my @emails;
540 foreach my $entry (@_) {
541 if (my $clean = extract_valid_address($entry)) {
542 $seen{$clean} ||= 0;
543 next if $seen{$clean}++;
544 push @emails, $entry;
545 } else {
546 print STDERR "W: unable to extract a valid address",
547 " from: $entry\n";
550 return @emails;