27a3105f3b60bfc8b4ad174b0702256e8de757c8
[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 eval {
89     require XSLoader;
90     XSLoader::load('Cwd');
91 };
92
93 # The 'natural and safe form' for UNIX (pwd may be setuid root)
94
95 sub _backtick_pwd {
96     my $cwd = `pwd`;
97     # `pwd` may fail e.g. if the disk is full
98     chomp($cwd) if defined $cwd;
99     $cwd;
100 }
101
102 # Since some ports may predefine cwd internally (e.g., NT)
103 # we take care not to override an existing definition for cwd().
104
105 unless(defined &cwd) {
106     # The pwd command is not available in some chroot(2)'ed environments
107     if($^O eq 'MacOS' || grep { -x "$_/pwd" } split(':', $ENV{PATH})) {
108         *cwd = \&_backtick_pwd;
109     }
110     else {
111         *cwd = \&getcwd;
112     }
113 }
114
115 # set a reasonable (and very safe) default for fastgetcwd, in case it
116 # isn't redefined later (20001212 rspier)
117 *fastgetcwd = \&cwd;
118
119 # By Brandon S. Allbery
120 #
121 # Usage: $cwd = getcwd();
122
123 sub getcwd
124 {
125     abs_path('.');
126 }
127
128 # Keeps track of current working directory in PWD environment var
129 # Usage:
130 #       use Cwd 'chdir';
131 #       chdir $newdir;
132
133 my $chdir_init = 0;
134
135 sub chdir_init {
136     if ($ENV{'PWD'} and $^O ne 'os2' and $^O ne 'dos' and $^O ne 'MSWin32') {
137         my($dd,$di) = stat('.');
138         my($pd,$pi) = stat($ENV{'PWD'});
139         if (!defined $dd or !defined $pd or $di != $pi or $dd != $pd) {
140             $ENV{'PWD'} = cwd();
141         }
142     }
143     else {
144         my $wd = cwd();
145         $wd = Win32::GetFullPathName($wd) if $^O eq 'MSWin32';
146         $ENV{'PWD'} = $wd;
147     }
148     # Strip an automounter prefix (where /tmp_mnt/foo/bar == /foo/bar)
149     if ($^O ne 'MSWin32' and $ENV{'PWD'} =~ m|(/[^/]+(/[^/]+/[^/]+))(.*)|s) {
150         my($pd,$pi) = stat($2);
151         my($dd,$di) = stat($1);
152         if (defined $pd and defined $dd and $di == $pi and $dd == $pd) {
153             $ENV{'PWD'}="$2$3";
154         }
155     }
156     $chdir_init = 1;
157 }
158
159 sub chdir {
160     my $newdir = @_ ? shift : '';       # allow for no arg (chdir to HOME dir)
161     $newdir =~ s|///*|/|g unless $^O eq 'MSWin32';
162     chdir_init() unless $chdir_init;
163     my $newpwd;
164     if ($^O eq 'MSWin32') {
165         # get the full path name *before* the chdir()
166         $newpwd = Win32::GetFullPathName($newdir);
167     }
168
169     return 0 unless CORE::chdir $newdir;
170
171     if ($^O eq 'VMS') {
172         return $ENV{'PWD'} = $ENV{'DEFAULT'}
173     }
174     elsif ($^O eq 'MacOS') {
175         return $ENV{'PWD'} = cwd();
176     }
177     elsif ($^O eq 'MSWin32') {
178         $ENV{'PWD'} = $newpwd;
179         return 1;
180     }
181
182     if ($newdir =~ m#^/#s) {
183         $ENV{'PWD'} = $newdir;
184     } else {
185         my @curdir = split(m#/#,$ENV{'PWD'});
186         @curdir = ('') unless @curdir;
187         my $component;
188         foreach $component (split(m#/#, $newdir)) {
189             next if $component eq '.';
190             pop(@curdir),next if $component eq '..';
191             push(@curdir,$component);
192         }
193         $ENV{'PWD'} = join('/',@curdir) || '/';
194     }
195     1;
196 }
197
198 # added function alias for those of us more
199 # used to the libc function.  --tchrist 27-Jan-00
200 *realpath = \&abs_path;
201
202 sub fast_abs_path {
203     my $cwd = getcwd();
204     my $path = @_ ? shift : '.';
205     CORE::chdir($path) || croak "Cannot chdir to $path:$!";
206     my $realpath = getcwd();
207     CORE::chdir($cwd)  || croak "Cannot chdir back to $cwd:$!";
208     $realpath;
209 }
210
211 # added function alias to follow principle of least surprise
212 # based on previous aliasing.  --tchrist 27-Jan-00
213 *fast_realpath = \&fast_abs_path;
214
215
216 # --- PORTING SECTION ---
217
218 # VMS: $ENV{'DEFAULT'} points to default directory at all times
219 # 06-Mar-1996  Charles Bailey  bailey@newman.upenn.edu
220 # Note: Use of Cwd::chdir() causes the logical name PWD to be defined
221 #   in the process logical name table as the default device and directory
222 #   seen by Perl. This may not be the same as the default device
223 #   and directory seen by DCL after Perl exits, since the effects
224 #   the CRTL chdir() function persist only until Perl exits.
225
226 sub _vms_cwd {
227     return $ENV{'DEFAULT'};
228 }
229
230 sub _vms_abs_path {
231     return $ENV{'DEFAULT'} unless @_;
232     my $path = VMS::Filespec::pathify($_[0]);
233     croak("Invalid path name $_[0]") unless defined $path;
234     return VMS::Filespec::rmsexpand($path);
235 }
236
237 sub _os2_cwd {
238     $ENV{'PWD'} = `cmd /c cd`;
239     chop $ENV{'PWD'};
240     $ENV{'PWD'} =~ s:\\:/:g ;
241     return $ENV{'PWD'};
242 }
243
244 sub _win32_cwd {
245     $ENV{'PWD'} = Win32::GetCwd();
246     $ENV{'PWD'} =~ s:\\:/:g ;
247     return $ENV{'PWD'};
248 }
249
250 *_NT_cwd = \&_win32_cwd if (!defined &_NT_cwd && 
251                             defined &Win32::GetCwd);
252
253 *_NT_cwd = \&_os2_cwd unless defined &_NT_cwd;
254
255 sub _dos_cwd {
256     if (!defined &Dos::GetCwd) {
257         $ENV{'PWD'} = `command /c cd`;
258         chop $ENV{'PWD'};
259         $ENV{'PWD'} =~ s:\\:/:g ;
260     } else {
261         $ENV{'PWD'} = Dos::GetCwd();
262     }
263     return $ENV{'PWD'};
264 }
265
266 sub _qnx_cwd {
267     $ENV{'PWD'} = `/usr/bin/fullpath -t`;
268     chop $ENV{'PWD'};
269     return $ENV{'PWD'};
270 }
271
272 sub _qnx_abs_path {
273     my $path = @_ ? shift : '.';
274     my $realpath=`/usr/bin/fullpath -t $path`;
275     chop $realpath;
276     return $realpath;
277 }
278
279 sub _epoc_cwd {
280     $ENV{'PWD'} = EPOC::getcwd();
281     return $ENV{'PWD'};
282 }
283
284 {
285     no warnings;        # assignments trigger 'subroutine redefined' warning
286
287     if ($^O eq 'VMS') {
288         *cwd            = \&_vms_cwd;
289         *getcwd         = \&_vms_cwd;
290         *fastcwd        = \&_vms_cwd;
291         *fastgetcwd     = \&_vms_cwd;
292         *abs_path       = \&_vms_abs_path;
293         *fast_abs_path  = \&_vms_abs_path;
294     }
295     elsif ($^O eq 'NT' or $^O eq 'MSWin32') {
296         # We assume that &_NT_cwd is defined as an XSUB or in the core.
297         *cwd            = \&_NT_cwd;
298         *getcwd         = \&_NT_cwd;
299         *fastcwd        = \&_NT_cwd;
300         *fastgetcwd     = \&_NT_cwd;
301         *abs_path       = \&fast_abs_path;
302     }
303     elsif ($^O eq 'os2') {
304         # sys_cwd may keep the builtin command
305         *cwd            = defined &sys_cwd ? \&sys_cwd : \&_os2_cwd;
306         *getcwd         = \&cwd;
307         *fastgetcwd     = \&cwd;
308         *fastcwd        = \&cwd;
309         *abs_path       = \&fast_abs_path;
310     }
311     elsif ($^O eq 'dos') {
312         *cwd            = \&_dos_cwd;
313         *getcwd         = \&_dos_cwd;
314         *fastgetcwd     = \&_dos_cwd;
315         *fastcwd        = \&_dos_cwd;
316         *abs_path       = \&fast_abs_path;
317     }
318     elsif ($^O eq 'qnx') {
319         *cwd            = \&_qnx_cwd;
320         *getcwd         = \&_qnx_cwd;
321         *fastgetcwd     = \&_qnx_cwd;
322         *fastcwd        = \&_qnx_cwd;
323         *abs_path       = \&_qnx_abs_path;
324         *fast_abs_path  = \&_qnx_abs_path;
325     }
326     elsif ($^O eq 'cygwin') {
327         *getcwd = \&cwd;
328         *fastgetcwd     = \&cwd;
329         *fastcwd        = \&cwd;
330         *abs_path       = \&fast_abs_path;
331     }
332     elsif ($^O eq 'epoc') {
333         *cwd            = \&_epoc_cwd;
334         *getcwd         = \&_epoc_cwd;
335         *fastgetcwd     = \&_epoc_cwd;
336         *fastcwd        = \&_epoc_cwd;
337         *abs_path       = \&fast_abs_path;
338     }
339     elsif ($^O eq 'MacOS') {
340         *getcwd     = \&cwd;
341         *fastgetcwd = \&cwd;
342         *fastcwd    = \&cwd;
343         *abs_path   = \&fast_abs_path;
344     }
345 }
346
347 # package main; eval join('',<DATA>) || die $@; # quick test
348
349 1;
350
351 __END__
352 BEGIN { import Cwd qw(:DEFAULT chdir); }
353 print join("\n", cwd, getcwd, fastcwd, "");
354 chdir('..');
355 print join("\n", cwd, getcwd, fastcwd, "");
356 print "$ENV{PWD}\n";