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