Drag autodoc.pl and overload.pl into the age of safer_open().
[p5sagit/p5-mst-13.2.git] / regen_lib.pl
1 #!/usr/bin/perl -w
2 use strict;
3 use vars qw($Is_W32 $Is_OS2 $Is_Cygwin $Is_NetWare $Needs_Write);
4 use Config; # Remember, this is running using an existing perl
5 use File::Compare;
6 use Symbol;
7
8 # Common functions needed by the regen scripts
9
10 $Is_W32 = $^O eq 'MSWin32';
11 $Is_OS2 = $^O eq 'os2';
12 $Is_Cygwin = $^O eq 'cygwin';
13 $Is_NetWare = $Config{osname} eq 'NetWare';
14 if ($Is_NetWare) {
15   $Is_W32 = 0;
16 }
17
18 $Needs_Write = $Is_OS2 || $Is_W32 || $Is_Cygwin || $Is_NetWare;
19
20 sub safer_unlink {
21   my @names = @_;
22   my $cnt = 0;
23
24   my $name;
25   foreach $name (@names) {
26     next unless -e $name;
27     chmod 0777, $name if $Needs_Write;
28     ( CORE::unlink($name) and ++$cnt
29       or warn "Couldn't unlink $name: $!\n" );
30   }
31   return $cnt;
32 }
33
34 sub safer_rename_silent {
35   my ($from, $to) = @_;
36
37   # Some dosish systems can't rename over an existing file:
38   safer_unlink $to;
39   chmod 0600, $from if $Needs_Write;
40   rename $from, $to;
41 }
42
43 sub rename_if_different {
44   my ($from, $to) = @_;
45
46   if (compare($from, $to) == 0) {
47       warn "no changes between '$from' & '$to'\n";
48       safer_unlink($from);
49       return;
50   }
51   warn "changed '$from' to '$to'\n";
52   safer_rename_silent($from, $to) or die "renaming $from to $to: $!";
53 }
54
55 # Saf*er*, but not totally safe. And assumes always open for output.
56 sub safer_open {
57     my $name = shift;
58     my $fh = gensym;
59     open $fh, ">$name" or die "Can't create $name: $!";
60     *{$fh}->{SCALAR} = $name;
61     binmode $fh;
62     $fh;
63 }
64
65 sub safer_close {
66     my $fh = shift;
67     close $fh or die 'Error closing ' . *{$fh}->{SCALAR} . ": $!";
68 }
69
70 1;