"This little thing tests for a file .patch, and if it contains
[p5sagit/p5-mst-13.2.git] / utils / perlbug.PL
1 #!/usr/local/bin/perl
2
3 use Config;
4 use File::Basename qw(&basename &dirname);
5 use Cwd;
6 use File::Spec::Functions;
7
8 # List explicitly here the variables you want Configure to
9 # generate.  Metaconfig only looks for shell variables, so you
10 # have to mention them as if they were shell variables, not
11 # %Config entries.  Thus you write
12 #  $startperl
13 # to ensure Configure will look for $Config{startperl}.
14 #  $perlpath
15
16 # This forces PL files to create target in same directory as PL file.
17 # This is so that make depend always knows where to find PL derivatives.
18 $origdir = cwd;
19 chdir dirname($0);
20 $file = basename($0, '.PL');
21 $file .= '.com' if $^O eq 'VMS';
22
23 open OUT, ">$file" or die "Can't create $file: $!";
24
25 # extract patchlevel.h information
26
27 open PATCH_LEVEL, "<" . catfile(updir, "patchlevel.h")
28     or die "Can't open patchlevel.h: $!";
29
30 my $patchlevel_date = (stat PATCH_LEVEL)[9];
31
32 while (<PATCH_LEVEL>) {
33     last if $_ =~ /^\s*static\s+char.*?local_patches\[\]\s*=\s*{\s*$/;
34 }
35
36 my @patches;
37 while (<PATCH_LEVEL>) {
38     last if /^\s*}/;
39     chomp;
40     s/^\s+,?\s*"?//;
41     s/"?\s*,?$//;
42     s/(['\\])/\\$1/g;
43     push @patches, $_ unless $_ eq 'NULL';
44 }
45 my $patch_desc = "'" . join("',\n    '", @patches) . "'";
46 my $patch_tags = join "", map /(\S+)/ ? "+$1 " : (), @patches;
47
48 close(PATCH_LEVEL) or die "Error closing patchlevel.h: $!";
49
50 # TO DO (prehaps): store/embed $Config::config_sh into perlbug. When perlbug is
51 # used, compare $Config::config_sh with the stored version. If they differ then
52 # append a list of individual differences to the bug report.
53
54
55 print "Extracting $file (with variable substitutions)\n";
56
57 # In this section, perl variables will be expanded during extraction.
58 # You can use $Config{...} to use Configure variables.
59
60 my $extract_version = sprintf("v%vd", $^V);
61
62 print OUT <<"!GROK!THIS!";
63 $Config{startperl}
64     eval 'exec $Config{perlpath} -S \$0 \${1+"\$@"}'
65         if \$running_under_some_shell;
66
67 my \$config_tag1 = '$extract_version - $Config{cf_time}';
68
69 my \$patchlevel_date = $patchlevel_date;
70 my \$patch_tags = '$patch_tags';
71 my \@patches = (
72     $patch_desc
73 );
74 !GROK!THIS!
75
76 # In the following, perl variables are not expanded during extraction.
77
78 print OUT <<'!NO!SUBS!';
79
80 use Config;
81 use File::Spec;         # keep perlbug Perl 5.005 compatible
82 use Getopt::Std;
83 use strict;
84
85 sub paraprint;
86
87 BEGIN {
88     eval "use Mail::Send;";
89     $::HaveSend = ($@ eq "");
90     eval "use Mail::Util;";
91     $::HaveUtil = ($@ eq "");
92 };
93
94 my $Version = "1.31";
95
96 # Changed in 1.06 to skip Mail::Send and Mail::Util if not available.
97 # Changed in 1.07 to see more sendmail execs, and added pipe output.
98 # Changed in 1.08 to use correct address for sendmail.
99 # Changed in 1.09 to close the REP file before calling it up in the editor.
100 #                 Also removed some old comments duplicated elsewhere.
101 # Changed in 1.10 to run under VMS without Mail::Send; also fixed
102 #                 temp filename generation.
103 # Changed in 1.11 to clean up some text and removed Mail::Send deactivator.
104 # Changed in 1.12 to check for editor errors, make save/send distinction
105 #                 clearer and add $ENV{REPLYTO}.
106 # Changed in 1.13 to hopefully make it more difficult to accidentally
107 #                 send mail
108 # Changed in 1.14 to make the prompts a little more clear on providing
109 #                 helpful information. Also let file read fail gracefully.
110 # Changed in 1.15 to add warnings to stop people using perlbug for non-bugs.
111 #                 Also report selected environment variables.
112 # Changed in 1.16 to include @INC, and allow user to re-edit if no changes.
113 # Changed in 1.17 Win32 support added.  GSAR 97-04-12
114 # Changed in 1.18 add '-ok' option for reporting build success. CFR 97-06-18
115 # Changed in 1.19 '-ok' default not '-v'
116 #                 add local patch information
117 #                 warn on '-ok' if this is an old system; add '-okay'
118 # Changed in 1.20 Added patchlevel.h reading and version/config checks
119 # Changed in 1.21 Added '-nok' for reporting build failure DFD 98-05-05
120 # Changed in 1.22 Heavy reformatting & minor bugfixes HVDS 98-05-10
121 # Changed in 1.23 Restore -ok(ay): say 'success'; don't prompt
122 # Changed in 1.24 Added '-F<file>' to save report HVDS 98-07-01
123 # Changed in 1.25 Warn on failure to open save file. HVDS 98-07-12
124 # Changed in 1.26 Don't require -t STDIN for -ok. HVDS 98-07-15
125 # Changed in 1.27 Added Mac OS and File::Spec support CNANDOR 99-07-27
126 # Changed in 1.28 Additional questions for Perlbugtron RFOLEY 20.03.2000
127 # Changed in 1.29 Perlbug(tron): auto(-ok), short prompts RFOLEY 05-05-2000
128 # Changed in 1.30 Added warnings on failure to open files MSTEVENS 13-07-2000
129 # Changed in 1.31 Add checks on close().Fix my $var unless. TJENNESS 26-07-2000
130
131 # TODO: - Allow the user to re-name the file on mail failure, and
132 #       make sure failure (transmission-wise) of Mail::Send is
133 #       accounted for.
134 #       - Test -b option
135
136 my( $file, $usefile, $cc, $address, $perlbug, $testaddress, $filename,
137     $subject, $from, $verbose, $ed, $outfile, $Is_MacOS, $category, $severity, 
138     $fh, $me, $Is_MSWin32, $Is_VMS, $msg, $body, $andcc, %REP, $ok);
139
140 my $perl_version = $^V ? sprintf("v%vd", $^V) : $];
141
142 my $config_tag2 = "$perl_version - $Config{cf_time}";
143
144 Init();
145
146 if ($::opt_h) { Help(); exit; }
147 if ($::opt_d) { Dump(*STDOUT); exit; }
148 if (!-t STDIN && !($ok and not $::opt_n)) {
149     paraprint <<EOF;
150 Please use perlbug interactively. If you want to
151 include a file, you can use the -f switch.
152 EOF
153     die "\n";
154 }
155 if (!-t STDOUT && !$outfile) { Dump(*STDOUT); exit; }
156
157 Query();
158 Edit() unless $usefile || ($ok and not $::opt_n);
159 NowWhat();
160 Send();
161
162 exit;
163
164 sub ask_for_alternatives { # (category|severity)
165     my $name = shift;
166     my %alts = (
167         'category' => {
168             'default' => 'core',
169             'ok'      => 'install',
170             'opts'    => [qw(core docs install library utilities)], # patch, notabug
171         },
172         'severity' => {
173             'default' => 'low',
174             'ok'      => 'none',
175             'opts'    => [qw(critical high medium low wishlist none)], # zero
176         },      
177     );
178     die "Invalid alternative($name) requested\n" unless grep(/^$name$/, keys %alts); 
179     my $alt = "";
180     if ($ok) {
181         $alt = $alts{$name}{'ok'};
182     } else {
183         my @alts = @{$alts{$name}{'opts'}};
184         paraprint <<EOF;
185 Please pick a \u$name from the following:
186
187     @alts
188
189 EOF
190         my $err = 0;
191         do {
192             if ($err++ > 5) {
193                 die "Invalid $name: aborting.\n";
194             }
195             print "Please enter a \u$name [$alts{$name}{'default'}]: ";
196             $alt = <>;
197             chomp $alt;
198             if ($alt =~ /^\s*$/) {
199                 $alt = $alts{$name}{'default'};
200             }
201         } while !((($alt) = grep(/^$alt/i, @alts)));
202     }
203     lc $alt;
204 }
205
206 sub Init {
207     # -------- Setup --------
208
209     $Is_MSWin32 = $^O eq 'MSWin32';
210     $Is_VMS = $^O eq 'VMS';
211     $Is_MacOS = $^O eq 'MacOS';
212
213     @ARGV = split m/\s+/,
214         MacPerl::Ask('Provide command-line args here (-h for help):')
215         if $Is_MacOS && $MacPerl::Version =~ /App/;
216
217     if (!getopts("dhva:s:b:f:F:r:e:SCc:to:n:")) { Help(); exit; };
218
219     # This comment is needed to notify metaconfig that we are
220     # using the $perladmin, $cf_by, and $cf_time definitions.
221
222     # -------- Configuration ---------
223
224     # perlbug address
225     $perlbug = 'perlbug@perl.com';
226
227     # Test address
228     $testaddress = 'perlbug-test@perl.com';
229
230     # Target address
231     $address = $::opt_a || ($::opt_t ? $testaddress : $perlbug);
232
233     # Users address, used in message and in Reply-To header
234     $from = $::opt_r || "";
235
236     # Include verbose configuration information
237     $verbose = $::opt_v || 0;
238
239     # Subject of bug-report message
240     $subject = $::opt_s || "";
241
242     # Send a file
243     $usefile = ($::opt_f || 0);
244
245     # File to send as report
246     $file = $::opt_f || "";
247
248     # File to output to
249     $outfile = $::opt_F || "";
250
251     # Body of report
252     $body = $::opt_b || "";
253
254     # Editor
255     $ed = $::opt_e || $ENV{VISUAL} || $ENV{EDITOR} || $ENV{EDIT}
256         || ($Is_VMS && "edit/tpu")
257         || ($Is_MSWin32 && "notepad")
258         || ($Is_MacOS && '')
259         || "vi";
260
261     # Not OK - provide build failure template by finessing OK report
262     if ($::opt_n) {
263         if (substr($::opt_n, 0, 2) eq 'ok' )    {
264             $::opt_o = substr($::opt_n, 1);
265         } else {
266             Help();
267             exit();
268         }
269     }
270
271     # OK - send "OK" report for build on this system
272     $ok = 0;
273     if ($::opt_o) {
274         if ($::opt_o eq 'k' or $::opt_o eq 'kay') {
275             my $age = time - $patchlevel_date;
276             if ($::opt_o eq 'k' and $age > 60 * 24 * 60 * 60 ) {
277                 my $date = localtime $patchlevel_date;
278                 print <<"EOF";
279 "perlbug -ok" and "perlbug -nok" do not report on Perl versions which
280 are more than 60 days old.  This Perl version was constructed on
281 $date.  If you really want to report this, use
282 "perlbug -okay" or "perlbug -nokay".
283 EOF
284                 exit();
285             }
286             # force these options
287             unless ($::opt_n) {
288                 $::opt_S = 1; # don't prompt for send
289                 $::opt_b = 1; # we have a body
290                 $body = "Perl reported to build OK on this system.\n";
291             }
292             $::opt_C = 1; # don't send a copy to the local admin
293             $::opt_s = 1; # we have a subject line
294             $subject = ($::opt_n ? 'Not ' : '')
295                     . "OK: perl $perl_version ${patch_tags}on"
296                     ." $::Config{'archname'} $::Config{'osvers'} $subject";
297             $ok = 1;
298         } else {
299             Help();
300             exit();
301         }
302     }
303
304     # Possible administrator addresses, in order of confidence
305     # (Note that cf_email is not mentioned to metaconfig, since
306     # we don't really want it. We'll just take it if we have to.)
307     #
308     # This has to be after the $ok stuff above because of the way
309     # that $::opt_C is forced.
310     $cc = $::opt_C ? "" : (
311         $::opt_c || $::Config{'perladmin'}
312         || $::Config{'cf_email'} || $::Config{'cf_by'}
313     );
314
315     # My username
316     $me = $Is_MSWin32 ? $ENV{'USERNAME'}
317             : $^O eq 'os2' ? $ENV{'USER'} || $ENV{'LOGNAME'}
318             : $Is_MacOS ? $ENV{'USER'}
319             : eval { getpwuid($<) };    # May be missing
320
321     $from = $::Config{'cf_email'}
322        if !$from && $::Config{'cf_email'} && $::Config{'cf_by'} && $me &&
323                ($me eq $::Config{'cf_by'});
324 } # sub Init
325
326 sub Query {
327     # Explain what perlbug is
328     unless ($ok) {
329         paraprint <<EOF;
330 This program provides an easy way to create a message reporting a bug
331 in perl, and e-mail it to $address.  It is *NOT* intended for
332 sending test messages or simply verifying that perl works, *NOR* is it
333 intended for reporting bugs in third-party perl modules.  It is *ONLY*
334 a means of reporting verifiable problems with the core perl distribution,
335 and any solutions to such problems, to the people who maintain perl.
336
337 If you're just looking for help with perl, try posting to the Usenet
338 newsgroup comp.lang.perl.misc.  If you're looking for help with using
339 perl with CGI, try posting to comp.infosystems.www.programming.cgi.
340 EOF
341     }
342
343     # Prompt for subject of message, if needed
344     unless ($subject) {
345         paraprint <<EOF;
346 First of all, please provide a subject for the
347 message. It should be a concise description of
348 the bug or problem. "perl bug" or "perl problem"
349 is not a concise description.
350 EOF
351         print "Subject: ";
352         $subject = <>;
353
354         my $err = 0;
355         while ($subject !~ /\S/) {
356             print "\nPlease enter a subject: ";
357             $subject = <>;
358             if ($err++ > 5) {
359                 die "Aborting.\n";
360             }
361         }
362         chop $subject;
363     }
364
365     # Prompt for return address, if needed
366     unless ($from) {
367         # Try and guess return address
368         my $guess;
369
370         $guess = $ENV{'REPLY-TO'} || $ENV{'REPLYTO'} || '';
371         if ($Is_MacOS) {
372             require Mac::InternetConfig;
373             $guess = $Mac::InternetConfig::InternetConfig{
374                 Mac::InternetConfig::kICEmail()
375             };
376         }
377
378         unless ($guess) {
379             my $domain;
380             if ($::HaveUtil) {
381                 $domain = Mail::Util::maildomain();
382             } elsif ($Is_MSWin32) {
383                 $domain = $ENV{'USERDOMAIN'};
384             } else {
385                 require Sys::Hostname;
386                 $domain = Sys::Hostname::hostname();
387             }
388             if ($domain) {
389                 if ($Is_VMS && !$::Config{'d_socket'}) {
390                     $guess = "$domain\:\:$me";
391                 } else {
392                     $guess = "$me\@$domain" if $domain;
393                 }
394             }
395         }
396
397         if ($guess) {
398             unless ($ok) {
399                 paraprint <<EOF;
400 Your e-mail address will be useful if you need to be contacted. If the
401 default shown is not your full internet e-mail address, please correct it.
402 EOF
403             }
404         } else {
405             paraprint <<EOF;
406 So that you may be contacted if necessary, please enter
407 your full internet e-mail address here.
408 EOF
409         }
410
411         if ($ok && $guess) {
412             # use it
413             $from = $guess;
414         } else {
415             # verify it
416             print "Your address [$guess]: ";
417             $from = <>;
418             chop $from;
419             $from = $guess if $from eq '';
420         }
421     }
422
423     if ($from eq $cc or $me eq $cc) {
424         # Try not to copy ourselves
425         $cc = "yourself";
426     }
427
428     # Prompt for administrator address, unless an override was given
429     if( !$::opt_C and !$::opt_c ) {
430         paraprint <<EOF;
431 A copy of this report can be sent to your local
432 perl administrator. If the address is wrong, please
433 correct it, or enter 'none' or 'yourself' to not send
434 a copy.
435 EOF
436         print "Local perl administrator [$cc]: ";
437         my $entry = scalar <>;
438         chop $entry;
439
440         if ($entry ne "") {
441             $cc = $entry;
442             $cc = '' if $me eq $cc;
443         }
444     }
445
446     $cc = '' if $cc =~ /^(none|yourself|me|myself|ourselves)$/i;
447     $andcc = " and $cc" if $cc;
448
449     # Prompt for editor, if no override is given
450 editor:
451     unless ($::opt_e || $::opt_f || $::opt_b) {
452         paraprint <<EOF;
453 Now you need to supply the bug report. Try to make
454 the report concise but descriptive. Include any
455 relevant detail. If you are reporting something
456 that does not work as you think it should, please
457 try to include example of both the actual
458 result, and what you expected.
459
460 Some information about your local
461 perl configuration will automatically be included
462 at the end of the report. If you are using any
463 unusual version of perl, please try and confirm
464 exactly which versions are relevant.
465
466 You will probably want to use an editor to enter
467 the report. If "$ed" is the editor you want
468 to use, then just press Enter, otherwise type in
469 the name of the editor you would like to use.
470
471 If you would like to use a prepared file, type
472 "file", and you will be asked for the filename.
473 EOF
474         print "Editor [$ed]: ";
475         my $entry =scalar <>;
476         chop $entry;
477
478         $usefile = 0;
479         if ($entry eq "file") {
480             $usefile = 1;
481         } elsif ($entry ne "") {
482             $ed = $entry;
483         }
484     }
485
486     # Prompt for category of bug
487     $category ||= ask_for_alternatives('category');
488
489     # Prompt for severity of bug
490     $severity ||= ask_for_alternatives('severity');
491
492     # Generate scratch file to edit report in
493     $filename = filename();
494
495     # Prompt for file to read report from, if needed
496     if ($usefile and !$file) {
497 filename:
498         paraprint <<EOF;
499 What is the name of the file that contains your report?
500 EOF
501         print "Filename: ";
502         my $entry = scalar <>;
503         chop $entry;
504
505         if ($entry eq "") {
506             paraprint <<EOF;
507 No filename? I'll let you go back and choose an editor again.
508 EOF
509             goto editor;
510         }
511
512         unless (-f $entry and -r $entry) {
513             paraprint <<EOF;
514 I'm sorry, but I can't read from `$entry'. Maybe you mistyped the name of
515 the file? If you don't want to send a file, just enter a blank line and you
516 can get back to the editor selection.
517 EOF
518             goto filename;
519         }
520         $file = $entry;
521     }
522
523     # Generate report
524     open(REP,">$filename") or die "Unable to create report file `$filename': $!\n";
525     my $reptype = !$ok ? "bug" : $::opt_n ? "build failure" : "success";
526
527     print REP <<EOF;
528 This is a $reptype report for perl from $from,
529 generated with the help of perlbug $Version running under perl $perl_version.
530
531 EOF
532
533     if ($body) {
534         print REP $body;
535     } elsif ($usefile) {
536         open(F, "<$file")
537                 or die "Unable to read report file from `$file': $!\n";
538         while (<F>) {
539             print REP $_
540         }
541         close(F) or die "Error closing `$file': $!";
542     } else {
543         print REP <<EOF;
544
545 -----------------------------------------------------------------
546 [Please enter your report here]
547
548
549
550 [Please do not change anything below this line]
551 -----------------------------------------------------------------
552 EOF
553     }
554     Dump(*REP);
555     close(REP) or die "Error closing report file: $!";
556
557     # read in the report template once so that
558     # we can track whether the user does any editing.
559     # yes, *all* whitespace is ignored.
560     open(REP, "<$filename") or die "Unable to open report file `$filename': $!\n";
561     while (<REP>) {
562         s/\s+//g;
563         $REP{$_}++;
564     }
565     close(REP) or die "Error closing report file `$filename': $!";
566 } # sub Query
567
568 sub Dump {
569     local(*OUT) = @_;
570
571     print OUT <<EFF;
572 ---
573 Flags:
574     category=$category
575     severity=$severity
576 ---
577 EFF
578     print OUT "This perlbug was built using Perl $config_tag1\n",
579             "It is being executed now by  Perl $config_tag2.\n\n"
580         if $config_tag2 ne $config_tag1;
581
582     print OUT <<EOF;
583 Site configuration information for perl $perl_version:
584
585 EOF
586     if ($::Config{cf_by} and $::Config{cf_time}) {
587         print OUT "Configured by $::Config{cf_by} at $::Config{cf_time}.\n\n";
588     }
589     print OUT Config::myconfig;
590
591     if (@patches) {
592         print OUT join "\n    ", "Locally applied patches:", @patches;
593         print OUT "\n";
594     };
595
596     print OUT <<EOF;
597
598 ---
599 \@INC for perl $perl_version:
600 EOF
601     for my $i (@INC) {
602         print OUT "    $i\n";
603     }
604
605     print OUT <<EOF;
606
607 ---
608 Environment for perl $perl_version:
609 EOF
610     my @env =
611         qw(PATH LD_LIBRARY_PATH LANG PERL_BADLANG SHELL HOME LOGDIR LANGUAGE);
612     push @env, $Config{ldlibpthname} if $Config{ldlibpthname} ne '';
613     push @env, grep /^(?:PERL|LC_|LANG)/, keys %ENV;
614     my %env;
615     @env{@env} = @env;
616     for my $env (sort keys %env) {
617         print OUT "    $env",
618                 exists $ENV{$env} ? "=$ENV{$env}" : ' (unset)',
619                 "\n";
620     }
621     if ($verbose) {
622         print OUT "\nComplete configuration data for perl $perl_version:\n\n";
623         my $value;
624         foreach (sort keys %::Config) {
625             $value = $::Config{$_};
626             $value =~ s/'/\\'/g;
627             print OUT "$_='$value'\n";
628         }
629     }
630 } # sub Dump
631
632 sub Edit {
633     # Edit the report
634     if ($usefile || $body) {
635         paraprint <<EOF;
636 Please make sure that the name of the editor you want to use is correct.
637 EOF
638         print "Editor [$ed]: ";
639         my $entry =scalar <>;
640         chop $entry;
641         $ed = $entry unless $entry eq '';
642     }
643
644 tryagain:
645     my $sts;
646     $sts = system("$ed $filename") unless $Is_MacOS;
647     if ($Is_MacOS) {
648         require ExtUtils::MakeMaker;
649         ExtUtils::MM_MacOS::launch_file($filename);
650         paraprint <<EOF;
651 Press Enter when done.
652 EOF
653         scalar <>;
654     }
655     if ($sts) {
656         paraprint <<EOF;
657 The editor you chose (`$ed') could apparently not be run!
658 Did you mistype the name of your editor? If so, please
659 correct it here, otherwise just press Enter.
660 EOF
661         print "Editor [$ed]: ";
662         my $entry =scalar <>;
663         chop $entry;
664
665         if ($entry ne "") {
666             $ed = $entry;
667             goto tryagain;
668         } else {
669             paraprint <<EOF;
670 You may want to save your report to a file, so you can edit and mail it
671 yourself.
672 EOF
673         }
674     }
675
676     return if ($ok and not $::opt_n) || $body;
677     # Check that we have a report that has some, eh, report in it.
678     my $unseen = 0;
679
680     open(REP, "<$filename") or die "Couldn't open `$filename': $!\n";
681     # a strange way to check whether any significant editing
682     # have been done: check whether any new non-empty lines
683     # have been added. Yes, the below code ignores *any* space
684     # in *any* line.
685     while (<REP>) {
686         s/\s+//g;
687         $unseen++ if $_ ne '' and not exists $REP{$_};
688     }
689
690     while ($unseen == 0) {
691         paraprint <<EOF;
692 I am sorry but it looks like you did not report anything.
693 EOF
694         print "Action (Retry Edit/Cancel) ";
695         my ($action) = scalar(<>);
696         if ($action =~ /^[re]/i) { # <R>etry <E>dit
697             goto tryagain;
698         } elsif ($action =~ /^[cq]/i) { # <C>ancel, <Q>uit
699             Cancel();
700         }
701     }
702 } # sub Edit
703
704 sub Cancel {
705     1 while unlink($filename);  # remove all versions under VMS
706     print "\nCancelling.\n";
707     exit(0);
708 }
709
710 sub NowWhat {
711     # Report is done, prompt for further action
712     if( !$::opt_S ) {
713         while(1) {
714             paraprint <<EOF;
715 Now that you have completed your report, would you like to send
716 the message to $address$andcc, display the message on
717 the screen, re-edit it, or cancel without sending anything?
718 You may also save the message as a file to mail at another time.
719 EOF
720       retry:
721             print "Action (Send/Display/Edit/Cancel/Save to File): ";
722             my $action = scalar <>;
723             chop $action;
724
725             if ($action =~ /^(f|sa)/i) { # <F>ile/<Sa>ve
726                 print "\n\nName of file to save message in [perlbug.rep]: ";
727                 my $file = scalar <>;
728                 chop $file;
729                 $file = "perlbug.rep" if $file eq "";
730
731                 unless (open(FILE, ">$file")) {
732                     print "\nError opening $file: $!\n\n";
733                     goto retry;
734                 }
735                 open(REP, "<$filename") or die "Couldn't open file `$filename': $!\n";
736                 print FILE "To: $address\nSubject: $subject\n";
737                 print FILE "Cc: $cc\n" if $cc;
738                 print FILE "Reply-To: $from\n" if $from;
739                 print FILE "\n";
740                 while (<REP>) { print FILE }
741                 close(REP) or die "Error closing report file `$filename': $!";
742                 close(FILE) or die "Error closing $file: $!";
743
744                 print "\nMessage saved in `$file'.\n";
745                 exit;
746             } elsif ($action =~ /^(d|l|sh)/i ) { # <D>isplay, <L>ist, <Sh>ow
747                 # Display the message
748                 open(REP, "<$filename") or die "Couldn't open file `$filename': $!\n";
749                 while (<REP>) { print $_ }
750                 close(REP) or die "Error closing report file `$filename': $!";
751             } elsif ($action =~ /^se/i) { # <S>end
752                 # Send the message
753                 print "Are you certain you want to send this message?\n"
754                     . 'Please type "yes" if you are: ';
755                 my $reply = scalar <STDIN>;
756                 chop $reply;
757                 if ($reply eq "yes") {
758                     last;
759                 } else {
760                     paraprint <<EOF;
761 That wasn't a clear "yes", so I won't send your message. If you are sure
762 your message should be sent, type in "yes" (without the quotes) at the
763 confirmation prompt.
764 EOF
765                 }
766             } elsif ($action =~ /^[er]/i) { # <E>dit, <R>e-edit
767                 # edit the message
768                 Edit();
769             } elsif ($action =~ /^[qc]/i) { # <C>ancel, <Q>uit
770                 Cancel();
771             } elsif ($action =~ /^s/) {
772                 paraprint <<EOF;
773 I'm sorry, but I didn't understand that. Please type "send" or "save".
774 EOF
775             }
776         }
777     }
778 } # sub NowWhat
779
780 sub Send {
781     # Message has been accepted for transmission -- Send the message
782     if ($outfile) {
783         open SENDMAIL, ">$outfile" or die "Couldn't open '$outfile': $!\n";
784         goto sendout;
785     }
786     if ($::HaveSend) {
787         $msg = new Mail::Send Subject => $subject, To => $address;
788         $msg->cc($cc) if $cc;
789         $msg->add("Reply-To",$from) if $from;
790
791         $fh = $msg->open;
792         open(REP, "<$filename") or die "Couldn't open `$filename': $!\n";
793         while (<REP>) { print $fh $_ }
794         close(REP) or die "Error closing $filename: $!";
795         $fh->close;
796
797         print "\nMessage sent.\n";
798     } elsif ($Is_VMS) {
799         if ( ($address =~ /@/ and $address !~ /^\w+%"/) or
800              ($cc      =~ /@/ and $cc      !~ /^\w+%"/) ) {
801             my $prefix;
802             foreach (qw[ IN MX SMTP UCX PONY WINS ], '') {
803                 $prefix = "$_%", last if $ENV{"MAIL\$PROTOCOL_$_"};
804             }
805             $address = qq[${prefix}"$address"] unless $address =~ /^\w+%"/;
806             $cc = qq[${prefix}"$cc"] unless !$cc || $cc =~ /^\w+%"/;
807         }
808         $subject =~ s/"/""/g; $address =~ s/"/""/g; $cc =~ s/"/""/g;
809         my $sts = system(qq[mail/Subject="$subject" $filename. "$address","$cc"]);
810         if ($sts) {
811             die <<EOF;
812 Can't spawn off mail
813         (leaving bug report in $filename): $sts
814 EOF
815         }
816     } else {
817         my $sendmail = "";
818         for (qw(/usr/lib/sendmail /usr/sbin/sendmail /usr/ucblib/sendmail)) {
819             $sendmail = $_, last if -e $_;
820         }
821         if ($^O eq 'os2' and $sendmail eq "") {
822             my $path = $ENV{PATH};
823             $path =~ s:\\:/: ;
824             my @path = split /$Config{'path_sep'}/, $path;
825             for (@path) {
826                 $sendmail = "$_/sendmail", last if -e "$_/sendmail";
827                 $sendmail = "$_/sendmail.exe", last if -e "$_/sendmail.exe";
828             }
829         }
830
831         paraprint(<<"EOF"), die "\n" if $sendmail eq "";
832 I am terribly sorry, but I cannot find sendmail, or a close equivalent, and
833 the perl package Mail::Send has not been installed, so I can't send your bug
834 report. We apologize for the inconvenience.
835
836 So you may attempt to find some way of sending your message, it has
837 been left in the file `$filename'.
838 EOF
839         open(SENDMAIL, "|$sendmail -t") || die "'|$sendmail -t' failed: $!";
840 sendout:
841         print SENDMAIL "To: $address\n";
842         print SENDMAIL "Subject: $subject\n";
843         print SENDMAIL "Cc: $cc\n" if $cc;
844         print SENDMAIL "Reply-To: $from\n" if $from;
845         print SENDMAIL "\n\n";
846         open(REP, "<$filename") or die "Couldn't open `$filename': $!\n";
847         while (<REP>) { print SENDMAIL $_ }
848         close(REP) or die "Error closing $filename: $!";
849
850         if (close(SENDMAIL)) {
851             printf "\nMessage %s.\n", $outfile ? "saved" : "sent";
852         } else {
853             warn "\nSendmail returned status '", $? >> 8, "'\n";
854         }
855     }
856     1 while unlink($filename);  # remove all versions under VMS
857 } # sub Send
858
859 sub Help {
860     print <<EOF;
861
862 A program to help generate bug reports about perl5, and mail them.
863 It is designed to be used interactively. Normally no arguments will
864 be needed.
865
866 Usage:
867 $0  [-v] [-a address] [-s subject] [-b body | -f inpufile ] [ -F outputfile ]
868     [-r returnaddress] [-e editor] [-c adminaddress | -C] [-S] [-t] [-h]
869 $0  [-v] [-r returnaddress] [-ok | -okay | -nok | -nokay]
870
871 Simplest usage:  run "$0", and follow the prompts.
872
873 Options:
874
875   -v    Include Verbose configuration data in the report
876   -f    File containing the body of the report. Use this to
877         quickly send a prepared message.
878   -F    File to output the resulting mail message to, instead of mailing.
879   -S    Send without asking for confirmation.
880   -a    Address to send the report to. Defaults to `$address'.
881   -c    Address to send copy of report to. Defaults to `$cc'.
882   -C    Don't send copy to administrator.
883   -s    Subject to include with the message. You will be prompted
884         if you don't supply one on the command line.
885   -b    Body of the report. If not included on the command line, or
886         in a file with -f, you will get a chance to edit the message.
887   -r    Your return address. The program will ask you to confirm
888         this if you don't give it here.
889   -e    Editor to use.
890   -t    Test mode. The target address defaults to `$testaddress'.
891   -d    Data mode (the default if you redirect or pipe output.)
892         This prints out your configuration data, without mailing
893         anything. You can use this with -v to get more complete data.
894   -ok   Report successful build on this system to perl porters
895         (use alone or with -v). Only use -ok if *everything* was ok:
896         if there were *any* problems at all, use -nok.
897   -okay As -ok but allow report from old builds.
898   -nok  Report unsuccessful build on this system to perl porters
899         (use alone or with -v). You must describe what went wrong
900         in the body of the report which you will be asked to edit.
901   -nokay As -nok but allow report from old builds.
902   -h    Print this help message.
903
904 EOF
905 }
906
907 sub filename {
908     my $dir = $Is_VMS ? 'sys$scratch:'
909         : ($Is_MSWin32 && $ENV{'TEMP'}) ? $ENV{'TEMP'}
910         : $Is_MacOS ? $ENV{'TMPDIR'}
911         : '/tmp';
912     $filename = "bugrep0$$";
913 #    $dir .= "\\" if $Is_MSWin32 and $dir !~ m|[\\/]$|;
914     $filename++ while -e File::Spec->catfile($dir, $filename);
915     $filename = File::Spec->catfile($dir, $filename);
916 }
917
918 sub paraprint {
919     my @paragraphs = split /\n{2,}/, "@_";
920     print "\n\n";
921     for (@paragraphs) {   # implicit local $_
922         s/(\S)\s*\n/$1 /g;
923         write;
924         print "\n";
925     }
926 }
927
928 format STDOUT =
929 ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~~
930 $_
931 .
932
933 __END__
934
935 =head1 NAME
936
937 perlbug - how to submit bug reports on Perl
938
939 =head1 SYNOPSIS
940
941 B<perlbug> S<[ B<-v> ]> S<[ B<-a> I<address> ]> S<[ B<-s> I<subject> ]>
942 S<[ B<-b> I<body> | B<-f> I<inputfile> ]> S<[ B<-F> I<outputfile> ]>
943 S<[ B<-r> I<returnaddress> ]>
944 S<[ B<-e> I<editor> ]> S<[ B<-c> I<adminaddress> | B<-C> ]>
945 S<[ B<-S> ]> S<[ B<-t> ]>  S<[ B<-d> ]>  S<[ B<-h> ]>
946
947 B<perlbug> S<[ B<-v> ]> S<[ B<-r> I<returnaddress> ]>
948 S<[ B<-ok> | B<-okay> | B<-nok> | B<-nokay> ]>
949
950 =head1 DESCRIPTION
951
952 A program to help generate bug reports about perl or the modules that
953 come with it, and mail them.
954
955 If you have found a bug with a non-standard port (one that was not part
956 of the I<standard distribution>), a binary distribution, or a
957 non-standard module (such as Tk, CGI, etc), then please see the
958 documentation that came with that distribution to determine the correct
959 place to report bugs.
960
961 C<perlbug> is designed to be used interactively. Normally no arguments
962 will be needed.  Simply run it, and follow the prompts.
963
964 If you are unable to run B<perlbug> (most likely because you don't have
965 a working setup to send mail that perlbug recognizes), you may have to
966 compose your own report, and email it to B<perlbug@perl.com>.  You might
967 find the B<-d> option useful to get summary information in that case.
968
969 In any case, when reporting a bug, please make sure you have run through
970 this checklist:
971
972 =over 4
973
974 =item What version of Perl you are running?
975
976 Type C<perl -v> at the command line to find out.
977
978 =item Are you running the latest released version of perl?
979
980 Look at http://www.perl.com/ to find out.  If it is not the latest
981 released version, get that one and see whether your bug has been
982 fixed.  Note that bug reports about old versions of Perl, especially
983 those prior to the 5.0 release, are likely to fall upon deaf ears.
984 You are on your own if you continue to use perl1 .. perl4.
985
986 =item Are you sure what you have is a bug?
987
988 A significant number of the bug reports we get turn out to be documented
989 features in Perl.  Make sure the behavior you are witnessing doesn't fall
990 under that category, by glancing through the documentation that comes
991 with Perl (we'll admit this is no mean task, given the sheer volume of
992 it all, but at least have a look at the sections that I<seem> relevant).
993
994 Be aware of the familiar traps that perl programmers of various hues
995 fall into.  See L<perltrap>.
996
997 Check in L<perldiag> to see what any Perl error message(s) mean.
998 If message isn't in perldiag, it probably isn't generated by Perl.
999 Consult your operating system documentation instead.
1000
1001 If you are on a non-UNIX platform check also L<perlport>, as some
1002 features may be unimplemented or work differently.
1003
1004 Try to study the problem under the Perl debugger, if necessary.
1005 See L<perldebug>.
1006
1007 =item Do you have a proper test case?
1008
1009 The easier it is to reproduce your bug, the more likely it will be
1010 fixed, because if no one can duplicate the problem, no one can fix it.
1011 A good test case has most of these attributes: fewest possible number
1012 of lines; few dependencies on external commands, modules, or
1013 libraries; runs on most platforms unimpeded; and is self-documenting.
1014
1015 A good test case is almost always a good candidate to be on the perl
1016 test suite.  If you have the time, consider making your test case so
1017 that it will readily fit into the standard test suite.
1018
1019 Remember also to include the B<exact> error messages, if any.
1020 "Perl complained something" is not an exact error message.
1021
1022 If you get a core dump (or equivalent), you may use a debugger
1023 (B<dbx>, B<gdb>, etc) to produce a stack trace to include in the bug
1024 report.  NOTE: unless your Perl has been compiled with debug info
1025 (often B<-g>), the stack trace is likely to be somewhat hard to use
1026 because it will most probably contain only the function names and not
1027 their arguments.  If possible, recompile your Perl with debug info and
1028 reproduce the dump and the stack trace.
1029
1030 =item Can you describe the bug in plain English?
1031
1032 The easier it is to understand a reproducible bug, the more likely it
1033 will be fixed.  Anything you can provide by way of insight into the
1034 problem helps a great deal.  In other words, try to analyze the
1035 problem (to the extent you can) and report your discoveries.
1036
1037 =item Can you fix the bug yourself?
1038
1039 A bug report which I<includes a patch to fix it> will almost
1040 definitely be fixed.  Use the C<diff> program to generate your patches
1041 (C<diff> is being maintained by the GNU folks as part of the B<diffutils>
1042 package, so you should be able to get it from any of the GNU software
1043 repositories).  If you do submit a patch, the cool-dude counter at
1044 perlbug@perl.com will register you as a savior of the world.  Your
1045 patch may be returned with requests for changes, or requests for more
1046 detailed explanations about your fix.
1047
1048 Here are some clues for creating quality patches: Use the B<-c> or
1049 B<-u> switches to the diff program (to create a so-called context or
1050 unified diff).  Make sure the patch is not reversed (the first
1051 argument to diff is typically the original file, the second argument
1052 your changed file).  Make sure you test your patch by applying it with
1053 the C<patch> program before you send it on its way.  Try to follow the
1054 same style as the code you are trying to patch.  Make sure your patch
1055 really does work (C<make test>, if the thing you're patching supports
1056 it).
1057
1058 =item Can you use C<perlbug> to submit the report?
1059
1060 B<perlbug> will, amongst other things, ensure your report includes
1061 crucial information about your version of perl.  If C<perlbug> is unable
1062 to mail your report after you have typed it in, you may have to compose
1063 the message yourself, add the output produced by C<perlbug -d> and email
1064 it to B<perlbug@perl.com>.  If, for some reason, you cannot run
1065 C<perlbug> at all on your system, be sure to include the entire output
1066 produced by running C<perl -V> (note the uppercase V).
1067
1068 Whether you use C<perlbug> or send the email manually, please make
1069 your Subject line informative.  "a bug" not informative.  Neither is
1070 "perl crashes" nor "HELP!!!".  These don't help.
1071 A compact description of what's wrong is fine.
1072
1073 =back
1074
1075 Having done your bit, please be prepared to wait, to be told the bug
1076 is in your code, or even to get no reply at all.  The Perl maintainers
1077 are busy folks, so if your problem is a small one or if it is difficult
1078 to understand or already known, they may not respond with a personal reply.
1079 If it is important to you that your bug be fixed, do monitor the
1080 C<Changes> file in any development releases since the time you submitted
1081 the bug, and encourage the maintainers with kind words (but never any
1082 flames!).  Feel free to resend your bug report if the next released
1083 version of perl comes out and your bug is still present.
1084
1085 =head1 OPTIONS
1086
1087 =over 8
1088
1089 =item B<-a>
1090
1091 Address to send the report to.  Defaults to `perlbug@perl.com'.
1092
1093 =item B<-b>
1094
1095 Body of the report.  If not included on the command line, or
1096 in a file with B<-f>, you will get a chance to edit the message.
1097
1098 =item B<-C>
1099
1100 Don't send copy to administrator.
1101
1102 =item B<-c>
1103
1104 Address to send copy of report to.  Defaults to the address of the
1105 local perl administrator (recorded when perl was built).
1106
1107 =item B<-d>
1108
1109 Data mode (the default if you redirect or pipe output).  This prints out
1110 your configuration data, without mailing anything.  You can use this
1111 with B<-v> to get more complete data.
1112
1113 =item B<-e>
1114
1115 Editor to use.
1116
1117 =item B<-f>
1118
1119 File containing the body of the report.  Use this to quickly send a
1120 prepared message.
1121
1122 =item B<-F>
1123
1124 File to output the results to instead of sending as an email. Useful
1125 particularly when running perlbug on a machine with no direct internet
1126 connection.
1127
1128 =item B<-h>
1129
1130 Prints a brief summary of the options.
1131
1132 =item B<-ok>
1133
1134 Report successful build on this system to perl porters. Forces B<-S>
1135 and B<-C>. Forces and supplies values for B<-s> and B<-b>. Only
1136 prompts for a return address if it cannot guess it (for use with
1137 B<make>). Honors return address specified with B<-r>.  You can use this
1138 with B<-v> to get more complete data.   Only makes a report if this
1139 system is less than 60 days old.
1140
1141 =item B<-okay>
1142
1143 As B<-ok> except it will report on older systems.
1144
1145 =item B<-nok>
1146
1147 Report unsuccessful build on this system.  Forces B<-C>.  Forces and
1148 supplies a value for B<-s>, then requires you to edit the report
1149 and say what went wrong.  Alternatively, a prepared report may be
1150 supplied using B<-f>.  Only prompts for a return address if it
1151 cannot guess it (for use with B<make>). Honors return address
1152 specified with B<-r>.  You can use this with B<-v> to get more
1153 complete data.  Only makes a report if this system is less than 60
1154 days old.
1155
1156 =item B<-nokay>
1157
1158 As B<-nok> except it will report on older systems.
1159
1160 =item B<-r>
1161
1162 Your return address.  The program will ask you to confirm its default
1163 if you don't use this option.
1164
1165 =item B<-S>
1166
1167 Send without asking for confirmation.
1168
1169 =item B<-s>
1170
1171 Subject to include with the message.  You will be prompted if you don't
1172 supply one on the command line.
1173
1174 =item B<-t>
1175
1176 Test mode.  The target address defaults to `perlbug-test@perl.com'.
1177
1178 =item B<-v>
1179
1180 Include verbose configuration data in the report.
1181
1182 =back
1183
1184 =head1 AUTHORS
1185
1186 Kenneth Albanowski (E<lt>kjahds@kjahds.comE<gt>), subsequently I<doc>tored
1187 by Gurusamy Sarathy (E<lt>gsar@activestate.comE<gt>), Tom Christiansen
1188 (E<lt>tchrist@perl.comE<gt>), Nathan Torkington (E<lt>gnat@frii.comE<gt>),
1189 Charles F. Randall (E<lt>cfr@pobox.comE<gt>), Mike Guy
1190 (E<lt>mjtg@cam.a.ukE<gt>), Dominic Dunlop (E<lt>domo@computer.orgE<gt>),
1191 Hugo van der Sanden (E<lt>hv@crypt0.demon.co.ukE<gt>),
1192 Jarkko Hietaniemi (E<lt>jhi@iki.fiE<gt>), Chris Nandor
1193 (E<lt>pudge@pobox.comE<gt>), Jon Orwant (E<lt>orwant@media.mit.eduE<gt>,
1194 and Richard Foley (E<lt>richard@rfi.netE<gt>).
1195
1196 =head1 SEE ALSO
1197
1198 perl(1), perldebug(1), perldiag(1), perlport(1), perltrap(1),
1199 diff(1), patch(1), dbx(1), gdb(1)
1200
1201 =head1 BUGS
1202
1203 None known (guess what must have been used to report them?)
1204
1205 =cut
1206
1207 !NO!SUBS!
1208
1209 close OUT or die "Can't close $file: $!";
1210 chmod 0755, $file or die "Can't reset permissions for $file: $!\n";
1211 exec("$Config{'eunicefix'} $file") if $Config{'eunicefix'} ne ':';
1212 chdir $origdir;