Epoc update
[p5sagit/p5-mst-13.2.git] / lib / Cwd.pm
1 package Cwd;
2 require 5.000;
3
4 =head1 NAME
5
6 getcwd - get pathname of current working directory
7
8 =head1 SYNOPSIS
9
10     use Cwd;
11     $dir = cwd;
12
13     use Cwd;
14     $dir = getcwd;
15
16     use Cwd;
17     $dir = fastgetcwd;
18
19     use Cwd 'chdir';
20     chdir "/tmp";
21     print $ENV{'PWD'};
22
23     use Cwd 'abs_path';     # aka realpath()
24     print abs_path($ENV{'PWD'});
25
26     use Cwd 'fast_abs_path';
27     print fast_abs_path($ENV{'PWD'});
28
29 =head1 DESCRIPTION
30
31 The getcwd() function re-implements the getcwd(3) (or getwd(3)) functions
32 in Perl.
33
34 The abs_path() function takes a single argument and returns the
35 absolute pathname for that argument.  It uses the same algorithm
36 as getcwd().  (Actually, getcwd() is abs_path("."))  Symbolic links
37 and relative-path components ("." and "..") are resolved to return
38 the canonical pathname, just like realpath(3).  Also callable as
39 realpath().
40
41 The fastcwd() function looks the same as getcwd(), but runs faster.
42 It's also more dangerous because it might conceivably chdir() you out
43 of a directory that it can't chdir() you back into.  If fastcwd
44 encounters a problem it will return undef but will probably leave you
45 in a different directory.  For a measure of extra security, if
46 everything appears to have worked, the fastcwd() function will check
47 that it leaves you in the same directory that it started in. If it has
48 changed it will C<die> with the message "Unstable directory path,
49 current directory changed unexpectedly". That should never happen.
50
51 The fast_abs_path() function looks the same as abs_path(), but runs faster.
52 And like fastcwd() is more dangerous.
53
54 The cwd() function looks the same as getcwd and fastgetcwd but is
55 implemented using the most natural and safe form for the current
56 architecture. For most systems it is identical to `pwd` (but without
57 the trailing line terminator).
58
59 It is recommended that cwd (or another *cwd() function) is used in
60 I<all> code to ensure portability.
61
62 If you ask to override your chdir() built-in function, then your PWD
63 environment variable will be kept up to date.  (See
64 L<perlsub/Overriding Builtin Functions>.) Note that it will only be
65 kept up to date if all packages which use chdir import it from Cwd.
66
67 =cut
68
69 use strict;
70
71 use Carp;
72
73 our $VERSION = '2.03';
74
75 use base qw/ Exporter /;
76 our @EXPORT = qw(cwd getcwd fastcwd fastgetcwd);
77 our @EXPORT_OK = qw(chdir abs_path fast_abs_path realpath fast_realpath);
78
79
80 # The 'natural and safe form' for UNIX (pwd may be setuid root)
81
82 sub _backtick_pwd {
83     my $cwd = `pwd`;
84     # `pwd` may fail e.g. if the disk is full
85     chomp($cwd) if defined $cwd;
86     $cwd;
87 }
88
89 # Since some ports may predefine cwd internally (e.g., NT)
90 # we take care not to override an existing definition for cwd().
91
92 *cwd = \&_backtick_pwd unless defined &cwd;
93
94
95 # By Brandon S. Allbery
96 #
97 # Usage: $cwd = getcwd();
98
99 sub getcwd
100 {
101     abs_path('.');
102 }
103
104 # By John Bazik
105 #
106 # Usage: $cwd = &fastcwd;
107 #
108 # This is a faster version of getcwd.  It's also more dangerous because
109 # you might chdir out of a directory that you can't chdir back into.
110     
111 sub fastcwd {
112     my($odev, $oino, $cdev, $cino, $tdev, $tino);
113     my(@path, $path);
114     local(*DIR);
115
116     my($orig_cdev, $orig_cino) = stat('.');
117     ($cdev, $cino) = ($orig_cdev, $orig_cino);
118     for (;;) {
119         my $direntry;
120         ($odev, $oino) = ($cdev, $cino);
121         CORE::chdir('..') || return undef;
122         ($cdev, $cino) = stat('.');
123         last if $odev == $cdev && $oino == $cino;
124         opendir(DIR, '.') || return undef;
125         for (;;) {
126             $direntry = readdir(DIR);
127             last unless defined $direntry;
128             next if $direntry eq '.';
129             next if $direntry eq '..';
130
131             ($tdev, $tino) = lstat($direntry);
132             last unless $tdev != $odev || $tino != $oino;
133         }
134         closedir(DIR);
135         return undef unless defined $direntry; # should never happen
136         unshift(@path, $direntry);
137     }
138     $path = '/' . join('/', @path);
139     if ($^O eq 'apollo') { $path = "/".$path; }
140     # At this point $path may be tainted (if tainting) and chdir would fail.
141     # To be more useful we untaint it then check that we landed where we started.
142     $path = $1 if $path =~ /^(.*)\z/s;  # untaint
143     CORE::chdir($path) || return undef;
144     ($cdev, $cino) = stat('.');
145     die "Unstable directory path, current directory changed unexpectedly"
146         if $cdev != $orig_cdev || $cino != $orig_cino;
147     $path;
148 }
149
150
151 # Keeps track of current working directory in PWD environment var
152 # Usage:
153 #       use Cwd 'chdir';
154 #       chdir $newdir;
155
156 my $chdir_init = 0;
157
158 sub chdir_init {
159     if ($ENV{'PWD'} and $^O ne 'os2' and $^O ne 'dos' and $^O ne 'MSWin32') {
160         my($dd,$di) = stat('.');
161         my($pd,$pi) = stat($ENV{'PWD'});
162         if (!defined $dd or !defined $pd or $di != $pi or $dd != $pd) {
163             $ENV{'PWD'} = cwd();
164         }
165     }
166     else {
167         my $wd = cwd();
168         $wd = Win32::GetFullPathName($wd) if $^O eq 'MSWin32';
169         $ENV{'PWD'} = $wd;
170     }
171     # Strip an automounter prefix (where /tmp_mnt/foo/bar == /foo/bar)
172     if ($^O ne 'MSWin32' and $ENV{'PWD'} =~ m|(/[^/]+(/[^/]+/[^/]+))(.*)|s) {
173         my($pd,$pi) = stat($2);
174         my($dd,$di) = stat($1);
175         if (defined $pd and defined $dd and $di == $pi and $dd == $pd) {
176             $ENV{'PWD'}="$2$3";
177         }
178     }
179     $chdir_init = 1;
180 }
181
182 sub chdir {
183     my $newdir = @? ? shift : '';       # allow for no arg (chdir to HOME dir)
184     $newdir =~ s|///*|/|g unless $^O eq 'MSWin32';
185     chdir_init() unless $chdir_init;
186     return 0 unless CORE::chdir $newdir;
187     if ($^O eq 'VMS') {
188         return $ENV{'PWD'} = $ENV{'DEFAULT'}
189     }
190     elsif ($^O eq 'MSWin32') {
191         $ENV{'PWD'} = Win32::GetFullPathName($newdir);
192         return 1;
193     }
194
195     if ($newdir =~ m#^/#s) {
196         $ENV{'PWD'} = $newdir;
197     } else {
198         my @curdir = split(m#/#,$ENV{'PWD'});
199         @curdir = ('') unless @curdir;
200         my $component;
201         foreach $component (split(m#/#, $newdir)) {
202             next if $component eq '.';
203             pop(@curdir),next if $component eq '..';
204             push(@curdir,$component);
205         }
206         $ENV{'PWD'} = join('/',@curdir) || '/';
207     }
208     1;
209 }
210
211 # Taken from Cwd.pm It is really getcwd with an optional
212 # parameter instead of '.'
213 #
214
215 sub abs_path
216 {
217     my $start = @_ ? shift : '.';
218     my($dotdots, $cwd, @pst, @cst, $dir, @tst);
219
220     unless (@cst = stat( $start ))
221     {
222         carp "stat($start): $!";
223         return '';
224     }
225     $cwd = '';
226     $dotdots = $start;
227     do
228     {
229         $dotdots .= '/..';
230         @pst = @cst;
231         unless (opendir(PARENT, $dotdots))
232         {
233             carp "opendir($dotdots): $!";
234             return '';
235         }
236         unless (@cst = stat($dotdots))
237         {
238             carp "stat($dotdots): $!";
239             closedir(PARENT);
240             return '';
241         }
242         if ($pst[0] == $cst[0] && $pst[1] == $cst[1])
243         {
244             $dir = undef;
245         }
246         else
247         {
248             do
249             {
250                 unless (defined ($dir = readdir(PARENT)))
251                 {
252                     carp "readdir($dotdots): $!";
253                     closedir(PARENT);
254                     return '';
255                 }
256                 $tst[0] = $pst[0]+1 unless (@tst = lstat("$dotdots/$dir"))
257             }
258             while ($dir eq '.' || $dir eq '..' || $tst[0] != $pst[0] ||
259                    $tst[1] != $pst[1]);
260         }
261         $cwd = (defined $dir ? "$dir" : "" ) . "/$cwd" ;
262         closedir(PARENT);
263     } while (defined $dir);
264     chop($cwd) unless $cwd eq '/'; # drop the trailing /
265     $cwd;
266 }
267
268 # added function alias for those of us more
269 # used to the libc function.  --tchrist 27-Jan-00
270 *realpath = \&abs_path;
271
272 sub fast_abs_path {
273     my $cwd = getcwd();
274     my $path = @_ ? shift : '.';
275     CORE::chdir($path) || croak "Cannot chdir to $path:$!";
276     my $realpath = getcwd();
277     CORE::chdir($cwd)  || croak "Cannot chdir back to $cwd:$!";
278     $realpath;
279 }
280
281 # added function alias to follow principle of least surprise
282 # based on previous aliasing.  --tchrist 27-Jan-00
283 *fast_realpath = \&fast_abs_path;
284
285
286 # --- PORTING SECTION ---
287
288 # VMS: $ENV{'DEFAULT'} points to default directory at all times
289 # 06-Mar-1996  Charles Bailey  bailey@newman.upenn.edu
290 # Note: Use of Cwd::chdir() causes the logical name PWD to be defined
291 #   in the process logical name table as the default device and directory
292 #   seen by Perl. This may not be the same as the default device
293 #   and directory seen by DCL after Perl exits, since the effects
294 #   the CRTL chdir() function persist only until Perl exits.
295
296 sub _vms_cwd {
297     return $ENV{'DEFAULT'};
298 }
299
300 sub _vms_abs_path {
301     return $ENV{'DEFAULT'} unless @_;
302     my $path = VMS::Filespec::pathify($_[0]);
303     croak("Invalid path name $_[0]") unless defined $path;
304     return VMS::Filespec::rmsexpand($path);
305 }
306
307 sub _os2_cwd {
308     $ENV{'PWD'} = `cmd /c cd`;
309     chop $ENV{'PWD'};
310     $ENV{'PWD'} =~ s:\\:/:g ;
311     return $ENV{'PWD'};
312 }
313
314 sub _win32_cwd {
315     $ENV{'PWD'} = Win32::GetCwd();
316     $ENV{'PWD'} =~ s:\\:/:g ;
317     return $ENV{'PWD'};
318 }
319
320 *_NT_cwd = \&_win32_cwd if (!defined &_NT_cwd && 
321                             defined &Win32::GetCwd);
322
323 *_NT_cwd = \&_os2_cwd unless defined &_NT_cwd;
324
325 sub _dos_cwd {
326     if (!defined &Dos::GetCwd) {
327         $ENV{'PWD'} = `command /c cd`;
328         chop $ENV{'PWD'};
329         $ENV{'PWD'} =~ s:\\:/:g ;
330     } else {
331         $ENV{'PWD'} = Dos::GetCwd();
332     }
333     return $ENV{'PWD'};
334 }
335
336 sub _qnx_cwd {
337     $ENV{'PWD'} = `/usr/bin/fullpath -t`;
338     chop $ENV{'PWD'};
339     return $ENV{'PWD'};
340 }
341
342 sub _qnx_abs_path {
343     my $path = @_ ? shift : '.';
344     my $realpath=`/usr/bin/fullpath -t $path`;
345     chop $realpath;
346     return $realpath;
347 }
348
349 sub _epoc_cwd {
350     $ENV{'PWD'} = EPOC::getcwd();
351     return $ENV{'PWD'};
352 }
353
354 {
355     no warnings;        # assignments trigger 'subroutine redefined' warning
356
357     if ($^O eq 'VMS') {
358         *cwd            = \&_vms_cwd;
359         *getcwd         = \&_vms_cwd;
360         *fastcwd        = \&_vms_cwd;
361         *fastgetcwd     = \&_vms_cwd;
362         *abs_path       = \&_vms_abs_path;
363         *fast_abs_path  = \&_vms_abs_path;
364     }
365     elsif ($^O eq 'NT' or $^O eq 'MSWin32') {
366         # We assume that &_NT_cwd is defined as an XSUB or in the core.
367         *cwd            = \&_NT_cwd;
368         *getcwd         = \&_NT_cwd;
369         *fastcwd        = \&_NT_cwd;
370         *fastgetcwd     = \&_NT_cwd;
371         *abs_path       = \&fast_abs_path;
372     }
373     elsif ($^O eq 'os2') {
374         # sys_cwd may keep the builtin command
375         *cwd            = defined &sys_cwd ? \&sys_cwd : \&_os2_cwd;
376         *getcwd         = \&cwd;
377         *fastgetcwd     = \&cwd;
378         *fastcwd        = \&cwd;
379         *abs_path       = \&fast_abs_path;
380     }
381     elsif ($^O eq 'dos') {
382         *cwd            = \&_dos_cwd;
383         *getcwd         = \&_dos_cwd;
384         *fastgetcwd     = \&_dos_cwd;
385         *fastcwd        = \&_dos_cwd;
386         *abs_path       = \&fast_abs_path;
387     }
388     elsif ($^O eq 'qnx') {
389         *cwd            = \&_qnx_cwd;
390         *getcwd         = \&_qnx_cwd;
391         *fastgetcwd     = \&_qnx_cwd;
392         *fastcwd        = \&_qnx_cwd;
393         *abs_path       = \&_qnx_abs_path;
394         *fast_abs_path  = \&_qnx_abs_path;
395     }
396     elsif ($^O eq 'cygwin') {
397         *getcwd = \&cwd;
398         *fastgetcwd     = \&cwd;
399         *fastcwd        = \&cwd;
400         *abs_path       = \&fast_abs_path;
401     }
402     elsif ($^O eq 'epoc') {
403         *getcwd = \&_epoc_cwd;
404         *fastgetcwd     = \&_epoc_cwd;
405         *fastcwd        = \&_epoc_cwd;
406         *abs_path       = \&fast_abs_path;
407     }
408 }
409
410 # package main; eval join('',<DATA>) || die $@; # quick test
411
412 1;
413
414 __END__
415 BEGIN { import Cwd qw(:DEFAULT chdir); }
416 print join("\n", cwd, getcwd, fastcwd, "");
417 chdir('..');
418 print join("\n", cwd, getcwd, fastcwd, "");
419 print "$ENV{PWD}\n";