This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
avoid removing duplicates in user-generated warnings
[perl5.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';
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 as
36 getcwd(). (actually getcwd() is abs_path("."))
37
38 The fastcwd() function looks the same as getcwd(), but runs faster.
39 It's also more dangerous because it might conceivably chdir() you out
40 of a directory that it can't chdir() you back into.  If fastcwd
41 encounters a problem it will return undef but will probably leave you
42 in a different directory.  For a measure of extra security, if
43 everything appears to have worked, the fastcwd() function will check
44 that it leaves you in the same directory that it started in. If it has
45 changed it will C<die> with the message "Unstable directory path,
46 current directory changed unexpectedly". That should never happen.
47
48 The fast_abs_path() function looks the same as abs_path(), but runs faster.
49 And like fastcwd() is more dangerous.
50
51 The cwd() function looks the same as getcwd and fastgetcwd but is
52 implemented using the most natural and safe form for the current
53 architecture. For most systems it is identical to `pwd` (but without
54 the trailing line terminator).
55
56 It is recommended that cwd (or another *cwd() function) is used in
57 I<all> code to ensure portability.
58
59 If you ask to override your chdir() built-in function, then your PWD
60 environment variable will be kept up to date.  (See
61 L<perlsub/Overriding Builtin Functions>.) Note that it will only be
62 kept up to date if all packages which use chdir import it from Cwd.
63
64 =cut
65
66 ## use strict;
67
68 use Carp;
69
70 $VERSION = '2.01';
71
72 require Exporter;
73 @ISA = qw(Exporter);
74 @EXPORT = qw(cwd getcwd fastcwd fastgetcwd);
75 @EXPORT_OK = qw(chdir abs_path fast_abs_path);
76
77
78 # The 'natural and safe form' for UNIX (pwd may be setuid root)
79
80 sub _backtick_pwd {
81     my $cwd;
82     chop($cwd = `pwd`);
83     $cwd;
84 }
85
86 # Since some ports may predefine cwd internally (e.g., NT)
87 # we take care not to override an existing definition for cwd().
88
89 *cwd = \&_backtick_pwd unless defined &cwd;
90
91
92 # By Brandon S. Allbery
93 #
94 # Usage: $cwd = getcwd();
95
96 sub getcwd
97 {
98     abs_path('.');
99 }
100
101 # By John Bazik
102 #
103 # Usage: $cwd = &fastcwd;
104 #
105 # This is a faster version of getcwd.  It's also more dangerous because
106 # you might chdir out of a directory that you can't chdir back into.
107     
108 # List of metachars taken from do_exec() in doio.c
109 my $quoted_shell_meta = quotemeta('$&*(){}[]";\\|?<>~`'."'\n");
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 =~ /^(.*)$/;    # 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') {
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         $ENV{'PWD'} = cwd();
168     }
169     # Strip an automounter prefix (where /tmp_mnt/foo/bar == /foo/bar)
170     if ($ENV{'PWD'} =~ m|(/[^/]+(/[^/]+/[^/]+))(.*)|) {
171         my($pd,$pi) = stat($2);
172         my($dd,$di) = stat($1);
173         if (defined $pd and defined $dd and $di == $pi and $dd == $pd) {
174             $ENV{'PWD'}="$2$3";
175         }
176     }
177     $chdir_init = 1;
178 }
179
180 sub chdir {
181     my $newdir = shift || '';   # allow for no arg (chdir to HOME dir)
182     $newdir =~ s|///*|/|g;
183     chdir_init() unless $chdir_init;
184     return 0 unless CORE::chdir $newdir;
185     if ($^O eq 'VMS') { return $ENV{'PWD'} = $ENV{'DEFAULT'} }
186
187     if ($newdir =~ m#^/#) {
188         $ENV{'PWD'} = $newdir;
189     } else {
190         my @curdir = split(m#/#,$ENV{'PWD'});
191         @curdir = ('') unless @curdir;
192         my $component;
193         foreach $component (split(m#/#, $newdir)) {
194             next if $component eq '.';
195             pop(@curdir),next if $component eq '..';
196             push(@curdir,$component);
197         }
198         $ENV{'PWD'} = join('/',@curdir) || '/';
199     }
200     1;
201 }
202
203 # Taken from Cwd.pm It is really getcwd with an optional
204 # parameter instead of '.'
205 #
206
207 sub abs_path
208 {
209     my $start = @_ ? shift : '.';
210     my($dotdots, $cwd, @pst, @cst, $dir, @tst);
211
212     return cwd() if ( $^O =~ /cygwin/ );
213
214     unless (@cst = stat( $start ))
215     {
216         carp "stat($start): $!";
217         return '';
218     }
219     $cwd = '';
220     $dotdots = $start;
221     do
222     {
223         $dotdots .= '/..';
224         @pst = @cst;
225         unless (opendir(PARENT, $dotdots))
226         {
227             carp "opendir($dotdots): $!";
228             return '';
229         }
230         unless (@cst = stat($dotdots))
231         {
232             carp "stat($dotdots): $!";
233             closedir(PARENT);
234             return '';
235         }
236         if ($pst[0] == $cst[0] && $pst[1] == $cst[1])
237         {
238             $dir = undef;
239         }
240         else
241         {
242             do
243             {
244                 unless (defined ($dir = readdir(PARENT)))
245                 {
246                     carp "readdir($dotdots): $!";
247                     closedir(PARENT);
248                     return '';
249                 }
250                 $tst[0] = $pst[0]+1 unless (@tst = lstat("$dotdots/$dir"))
251             }
252             while ($dir eq '.' || $dir eq '..' || $tst[0] != $pst[0] ||
253                    $tst[1] != $pst[1]);
254         }
255         $cwd = (defined $dir ? "$dir" : "" ) . "/$cwd" ;
256         closedir(PARENT);
257     } while (defined $dir);
258     chop($cwd) unless $cwd eq '/'; # drop the trailing /
259     $cwd;
260 }
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
272 # --- PORTING SECTION ---
273
274 # VMS: $ENV{'DEFAULT'} points to default directory at all times
275 # 06-Mar-1996  Charles Bailey  bailey@newman.upenn.edu
276 # Note: Use of Cwd::chdir() causes the logical name PWD to be defined
277 #   in the process logical name table as the default device and directory
278 #   seen by Perl. This may not be the same as the default device
279 #   and directory seen by DCL after Perl exits, since the effects
280 #   the CRTL chdir() function persist only until Perl exits.
281
282 sub _vms_cwd {
283     return $ENV{'DEFAULT'};
284 }
285
286 sub _vms_abs_path {
287     return $ENV{'DEFAULT'} unless @_;
288     my $path = VMS::Filespec::pathify($_[0]);
289     croak("Invalid path name $_[0]") unless defined $path;
290     return VMS::Filespec::rmsexpand($path);
291 }
292
293 sub _os2_cwd {
294     $ENV{'PWD'} = `cmd /c cd`;
295     chop $ENV{'PWD'};
296     $ENV{'PWD'} =~ s:\\:/:g ;
297     return $ENV{'PWD'};
298 }
299
300 sub _win32_cwd {
301     $ENV{'PWD'} = Win32::GetCwd();
302     $ENV{'PWD'} =~ s:\\:/:g ;
303     return $ENV{'PWD'};
304 }
305
306 *_NT_cwd = \&_win32_cwd if (!defined &_NT_cwd && 
307                             defined &Win32::GetCwd);
308
309 *_NT_cwd = \&_os2_cwd unless defined &_NT_cwd;
310
311 sub _dos_cwd {
312     if (!defined &Dos::GetCwd) {
313         $ENV{'PWD'} = `command /c cd`;
314         chop $ENV{'PWD'};
315         $ENV{'PWD'} =~ s:\\:/:g ;
316     } else {
317         $ENV{'PWD'} = Dos::GetCwd();
318     }
319     return $ENV{'PWD'};
320 }
321
322 sub _qnx_cwd {
323     $ENV{'PWD'} = `/usr/bin/fullpath -t`;
324     chop $ENV{'PWD'};
325     return $ENV{'PWD'};
326 }
327
328 sub _qnx_abs_path {
329     my $path = shift || '.';
330     my $realpath=`/usr/bin/fullpath -t $path`;
331     chop $realpath;
332     return $realpath;
333 }
334
335 {
336     local $^W = 0;      # assignments trigger 'subroutine redefined' warning
337
338     if ($^O eq 'VMS') {
339         *cwd            = \&_vms_cwd;
340         *getcwd         = \&_vms_cwd;
341         *fastcwd        = \&_vms_cwd;
342         *fastgetcwd     = \&_vms_cwd;
343         *abs_path       = \&_vms_abs_path;
344         *fast_abs_path  = \&_vms_abs_path;
345     }
346     elsif ($^O eq 'NT' or $^O eq 'MSWin32') {
347         # We assume that &_NT_cwd is defined as an XSUB or in the core.
348         *cwd            = \&_NT_cwd;
349         *getcwd         = \&_NT_cwd;
350         *fastcwd        = \&_NT_cwd;
351         *fastgetcwd     = \&_NT_cwd;
352         *abs_path       = \&fast_abs_path;
353     }
354     elsif ($^O eq 'os2') {
355         # sys_cwd may keep the builtin command
356         *cwd            = defined &sys_cwd ? \&sys_cwd : \&_os2_cwd;
357         *getcwd         = \&cwd;
358         *fastgetcwd     = \&cwd;
359         *fastcwd        = \&cwd;
360         *abs_path       = \&fast_abs_path;
361     }
362     elsif ($^O eq 'dos') {
363         *cwd            = \&_dos_cwd;
364         *getcwd         = \&_dos_cwd;
365         *fastgetcwd     = \&_dos_cwd;
366         *fastcwd        = \&_dos_cwd;
367         *abs_path       = \&fast_abs_path;
368     }
369     elsif ($^O eq 'qnx') {
370         *cwd            = \&_qnx_cwd;
371         *getcwd         = \&_qnx_cwd;
372         *fastgetcwd     = \&_qnx_cwd;
373         *fastcwd        = \&_qnx_cwd;
374         *abs_path       = \&_qnx_abs_path;
375         *fast_abs_path  = \&_qnx_abs_path;
376     }
377 }
378
379 # package main; eval join('',<DATA>) || die $@; # quick test
380
381 1;
382
383 __END__
384 BEGIN { import Cwd qw(:DEFAULT chdir); }
385 print join("\n", cwd, getcwd, fastcwd, "");
386 chdir('..');
387 print join("\n", cwd, getcwd, fastcwd, "");
388 print "$ENV{PWD}\n";