This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Create a new local $_ without triggering tie by using local *_ = \my $a
[perl5.git] / lib / Cwd.pm
CommitLineData
a0d0e21e 1package Cwd;
ad78113d 2$VERSION = $VERSION = '2.14';
a0d0e21e 3
f06db76b
AD
4=head1 NAME
5
902bacac 6Cwd - get pathname of current working directory
f06db76b
AD
7
8=head1 SYNOPSIS
9
4633a7c4 10 use Cwd;
04929354 11 my $dir = getcwd;
4633a7c4 12
04929354
MS
13 use Cwd 'abs_path';
14 my $abs_path = abs_path($file);
f06db76b 15
04929354 16=head1 DESCRIPTION
902bacac 17
04929354
MS
18This module provides functions for determining the pathname of the
19current working directory. It is recommended that getcwd (or another
20*cwd() function) be used in I<all> code to ensure portability.
f06db76b 21
04929354
MS
22By default, it exports the functions cwd(), getcwd(), fastcwd(), and
23fastgetcwd() into the caller's namespace.
f06db76b 24
20408e3c 25
04929354 26=head2 getcwd and friends
20408e3c 27
04929354
MS
28Each of these functions are called without arguments and return the
29absolute path of the current working directory.
f06db76b 30
04929354
MS
31=over 4
32
33=item getcwd
34
35 my $cwd = getcwd();
36
37Returns the current working directory.
38
39Re-implements the getcwd(3) (or getwd(3)) functions in Perl.
40
41=item cwd
42
43 my $cwd = cwd();
44
45The cwd() is the most natural form for the current architecture. For
46most systems it is identical to `pwd` (but without the trailing line
47terminator).
48
04929354
MS
49=item fastcwd
50
51 my $cwd = fastcwd();
52
53A more dangerous version of getcwd(), but potentially faster.
54
55It might conceivably chdir() you out of a directory that it can't
56chdir() you back into. If fastcwd encounters a problem it will return
57undef but will probably leave you in a different directory. For a
58measure of extra security, if everything appears to have worked, the
59fastcwd() function will check that it leaves you in the same directory
60that it started in. If it has changed it will C<die> with the message
61"Unstable directory path, current directory changed
62unexpectedly". That should never happen.
63
64=item fastgetcwd
65
66 my $cwd = fastgetcwd();
f06db76b 67
902bacac 68The fastgetcwd() function is provided as a synonym for cwd().
fb73857a 69
04929354
MS
70=back
71
902bacac 72
04929354
MS
73=head2 abs_path and friends
74
75These functions are exported only on request. They each take a single
3ee63918
MS
76argument and return the absolute pathname for it. If no argument is
77given they'll use the current working directory.
04929354
MS
78
79=over 4
80
81=item abs_path
82
83 my $abs_path = abs_path($file);
84
85Uses the same algorithm as getcwd(). Symbolic links and relative-path
86components ("." and "..") are resolved to return the canonical
87pathname, just like realpath(3).
88
89=item realpath
90
91 my $abs_path = realpath($file);
92
93A synonym for abs_path().
94
95=item fast_abs_path
96
510179aa 97 my $abs_path = fast_abs_path($file);
04929354
MS
98
99A more dangerous, but potentially faster version of abs_path.
100
101=back
102
103=head2 $ENV{PWD}
104
105If you ask to override your chdir() built-in function,
106
107 use Cwd qw(chdir);
108
109then your PWD environment variable will be kept up to date. Note that
110it will only be kept up to date if all packages which use chdir import
111it from Cwd.
4633a7c4 112
4633a7c4 113
4d6b4052
JH
114=head1 NOTES
115
116=over 4
117
118=item *
119
04929354
MS
120Since the path seperators are different on some operating systems ('/'
121on Unix, ':' on MacPerl, etc...) we recommend you use the File::Spec
122modules wherever portability is a concern.
123
04929354 124=item *
4d6b4052
JH
125
126Actually, on Mac OS, the C<getcwd()>, C<fastgetcwd()> and C<fastcwd()>
127functions are all aliases for the C<cwd()> function, which, on Mac OS,
128calls `pwd`. Likewise, the C<abs_path()> function is an alias for
129C<fast_abs_path()>.
130
131=back
132
04929354
MS
133=head1 SEE ALSO
134
135L<File::chdir>
136
f06db76b
AD
137=cut
138
b060a406 139use strict;
a9939470 140use Exporter;
ad78113d 141use vars qw(@ISA @EXPORT @EXPORT_OK);
96e4d5b1 142
a9939470
NC
143@ISA = qw/ Exporter /;
144@EXPORT = qw(cwd getcwd fastcwd fastgetcwd);
145@EXPORT_OK = qw(chdir abs_path fast_abs_path realpath fast_realpath);
a0d0e21e 146
f5f423e4
IZ
147# sys_cwd may keep the builtin command
148
149# All the functionality of this module may provided by builtins,
150# there is no sense to process the rest of the file.
151# The best choice may be to have this in BEGIN, but how to return from BEGIN?
152
a9939470 153if ($^O eq 'os2') {
f5f423e4 154 local $^W = 0;
a9939470
NC
155
156 *cwd = defined &sys_cwd ? \&sys_cwd : \&_os2_cwd;
157 *getcwd = \&cwd;
158 *fastgetcwd = \&cwd;
159 *fastcwd = \&cwd;
160
161 *fast_abs_path = \&sys_abspath if defined &sys_abspath;
162 *abs_path = \&fast_abs_path;
163 *realpath = \&fast_abs_path;
164 *fast_realpath = \&fast_abs_path;
165
f5f423e4
IZ
166 return 1;
167}
168
f22d8e4b
DM
169eval {
170 require XSLoader;
46ba3155 171 local $^W = 0;
f22d8e4b
DM
172 XSLoader::load('Cwd');
173};
4633a7c4 174
96e4d5b1 175
3547aa9a
MS
176# Find the pwd command in the expected locations. We assume these
177# are safe. This prevents _backtick_pwd() consulting $ENV{PATH}
178# so everything works under taint mode.
179my $pwd_cmd;
889f7a4f
RGS
180foreach my $try ('/bin/pwd',
181 '/usr/bin/pwd',
182 '/QOpenSys/bin/pwd', # OS/400 PASE.
183 ) {
184
3547aa9a
MS
185 if( -x $try ) {
186 $pwd_cmd = $try;
187 last;
188 }
189}
522b859a 190unless ($pwd_cmd) {
889f7a4f
RGS
191 # Isn't this wrong? _backtick_pwd() will fail if somenone has
192 # pwd in their path but it is not /bin/pwd or /usr/bin/pwd?
193 # See [perl #16774]. --jhi
194 $pwd_cmd = 'pwd';
522b859a 195}
3547aa9a 196
a9939470
NC
197# Lazy-load Carp
198sub _carp { require Carp; Carp::carp(@_) }
199sub _croak { require Carp; Carp::croak(@_) }
200
3547aa9a 201# The 'natural and safe form' for UNIX (pwd may be setuid root)
8b88ae92 202sub _backtick_pwd {
db281859 203 local @ENV{qw(PATH IFS CDPATH ENV BASH_ENV)};
3547aa9a 204 my $cwd = `$pwd_cmd`;
ac3b20cb 205 # Belt-and-suspenders in case someone said "undef $/".
5cf6da5f 206 local $/ = "\n";
ac3b20cb 207 # `pwd` may fail e.g. if the disk is full
7e03f963 208 chomp($cwd) if defined $cwd;
4633a7c4 209 $cwd;
8b88ae92 210}
4633a7c4
LW
211
212# Since some ports may predefine cwd internally (e.g., NT)
213# we take care not to override an existing definition for cwd().
214
ea54c8bd
EC
215unless(defined &cwd) {
216 # The pwd command is not available in some chroot(2)'ed environments
73b801a6
MS
217 if( $^O eq 'MacOS' || (defined $ENV{PATH} &&
218 grep { -x "$_/pwd" } split(':', $ENV{PATH})) )
219 {
ea54c8bd
EC
220 *cwd = \&_backtick_pwd;
221 }
222 else {
223 *cwd = \&getcwd;
224 }
225}
a0d0e21e 226
1f4f94f5
RS
227# set a reasonable (and very safe) default for fastgetcwd, in case it
228# isn't redefined later (20001212 rspier)
229*fastgetcwd = \&cwd;
748a9306 230
a0d0e21e
LW
231# By Brandon S. Allbery
232#
233# Usage: $cwd = getcwd();
234
235sub getcwd
236{
07569ed3 237 abs_path('.');
a0d0e21e
LW
238}
239
a0c9c202
JH
240
241# By John Bazik
242#
243# Usage: $cwd = &fastcwd;
244#
245# This is a faster version of getcwd. It's also more dangerous because
246# you might chdir out of a directory that you can't chdir back into.
247
248sub fastcwd {
249 my($odev, $oino, $cdev, $cino, $tdev, $tino);
250 my(@path, $path);
251 local(*DIR);
252
253 my($orig_cdev, $orig_cino) = stat('.');
254 ($cdev, $cino) = ($orig_cdev, $orig_cino);
255 for (;;) {
256 my $direntry;
257 ($odev, $oino) = ($cdev, $cino);
258 CORE::chdir('..') || return undef;
259 ($cdev, $cino) = stat('.');
260 last if $odev == $cdev && $oino == $cino;
261 opendir(DIR, '.') || return undef;
262 for (;;) {
263 $direntry = readdir(DIR);
264 last unless defined $direntry;
265 next if $direntry eq '.';
266 next if $direntry eq '..';
267
268 ($tdev, $tino) = lstat($direntry);
269 last unless $tdev != $odev || $tino != $oino;
270 }
271 closedir(DIR);
272 return undef unless defined $direntry; # should never happen
273 unshift(@path, $direntry);
274 }
275 $path = '/' . join('/', @path);
276 if ($^O eq 'apollo') { $path = "/".$path; }
277 # At this point $path may be tainted (if tainting) and chdir would fail.
248785eb
RGS
278 # Untaint it then check that we landed where we started.
279 $path =~ /^(.*)\z/s # untaint
280 && CORE::chdir($1) or return undef;
a0c9c202
JH
281 ($cdev, $cino) = stat('.');
282 die "Unstable directory path, current directory changed unexpectedly"
283 if $cdev != $orig_cdev || $cino != $orig_cino;
284 $path;
285}
286
287
4633a7c4 288# Keeps track of current working directory in PWD environment var
a0d0e21e
LW
289# Usage:
290# use Cwd 'chdir';
291# chdir $newdir;
292
4633a7c4 293my $chdir_init = 0;
a0d0e21e 294
4633a7c4 295sub chdir_init {
3b8e3443 296 if ($ENV{'PWD'} and $^O ne 'os2' and $^O ne 'dos' and $^O ne 'MSWin32') {
a0d0e21e
LW
297 my($dd,$di) = stat('.');
298 my($pd,$pi) = stat($ENV{'PWD'});
299 if (!defined $dd or !defined $pd or $di != $pi or $dd != $pd) {
4633a7c4 300 $ENV{'PWD'} = cwd();
a0d0e21e
LW
301 }
302 }
303 else {
3b8e3443
GS
304 my $wd = cwd();
305 $wd = Win32::GetFullPathName($wd) if $^O eq 'MSWin32';
306 $ENV{'PWD'} = $wd;
a0d0e21e 307 }
4633a7c4 308 # Strip an automounter prefix (where /tmp_mnt/foo/bar == /foo/bar)
3b8e3443 309 if ($^O ne 'MSWin32' and $ENV{'PWD'} =~ m|(/[^/]+(/[^/]+/[^/]+))(.*)|s) {
a0d0e21e
LW
310 my($pd,$pi) = stat($2);
311 my($dd,$di) = stat($1);
312 if (defined $pd and defined $dd and $di == $pi and $dd == $pd) {
313 $ENV{'PWD'}="$2$3";
314 }
315 }
316 $chdir_init = 1;
317}
318
319sub chdir {
22978713 320 my $newdir = @_ ? shift : ''; # allow for no arg (chdir to HOME dir)
3b8e3443 321 $newdir =~ s|///*|/|g unless $^O eq 'MSWin32';
a0d0e21e 322 chdir_init() unless $chdir_init;
4ffa1610
JH
323 my $newpwd;
324 if ($^O eq 'MSWin32') {
325 # get the full path name *before* the chdir()
326 $newpwd = Win32::GetFullPathName($newdir);
327 }
328
4633a7c4 329 return 0 unless CORE::chdir $newdir;
4ffa1610 330
3b8e3443
GS
331 if ($^O eq 'VMS') {
332 return $ENV{'PWD'} = $ENV{'DEFAULT'}
333 }
4aecb5b5
JH
334 elsif ($^O eq 'MacOS') {
335 return $ENV{'PWD'} = cwd();
336 }
3b8e3443 337 elsif ($^O eq 'MSWin32') {
4ffa1610 338 $ENV{'PWD'} = $newpwd;
3b8e3443
GS
339 return 1;
340 }
748a9306 341
392d8ab8 342 if ($newdir =~ m#^/#s) {
a0d0e21e 343 $ENV{'PWD'} = $newdir;
4633a7c4
LW
344 } else {
345 my @curdir = split(m#/#,$ENV{'PWD'});
346 @curdir = ('') unless @curdir;
347 my $component;
a0d0e21e
LW
348 foreach $component (split(m#/#, $newdir)) {
349 next if $component eq '.';
350 pop(@curdir),next if $component eq '..';
351 push(@curdir,$component);
352 }
353 $ENV{'PWD'} = join('/',@curdir) || '/';
354 }
4633a7c4 355 1;
a0d0e21e
LW
356}
357
a0c9c202
JH
358
359# In case the XS version doesn't load.
360*abs_path = \&_perl_abs_path unless defined &abs_path;
361sub _perl_abs_path
362{
363 my $start = @_ ? shift : '.';
364 my($dotdots, $cwd, @pst, @cst, $dir, @tst);
365
366 unless (@cst = stat( $start ))
367 {
a9939470 368 _carp("stat($start): $!");
a0c9c202
JH
369 return '';
370 }
371 $cwd = '';
372 $dotdots = $start;
373 do
374 {
375 $dotdots .= '/..';
376 @pst = @cst;
a25ef67d 377 local *PARENT;
a0c9c202
JH
378 unless (opendir(PARENT, $dotdots))
379 {
a9939470 380 _carp("opendir($dotdots): $!");
a0c9c202
JH
381 return '';
382 }
383 unless (@cst = stat($dotdots))
384 {
a9939470 385 _carp("stat($dotdots): $!");
a0c9c202
JH
386 closedir(PARENT);
387 return '';
388 }
389 if ($pst[0] == $cst[0] && $pst[1] == $cst[1])
390 {
391 $dir = undef;
392 }
393 else
394 {
395 do
396 {
397 unless (defined ($dir = readdir(PARENT)))
398 {
a9939470 399 _carp("readdir($dotdots): $!");
a0c9c202
JH
400 closedir(PARENT);
401 return '';
402 }
403 $tst[0] = $pst[0]+1 unless (@tst = lstat("$dotdots/$dir"))
404 }
405 while ($dir eq '.' || $dir eq '..' || $tst[0] != $pst[0] ||
406 $tst[1] != $pst[1]);
407 }
408 $cwd = (defined $dir ? "$dir" : "" ) . "/$cwd" ;
409 closedir(PARENT);
410 } while (defined $dir);
411 chop($cwd) unless $cwd eq '/'; # drop the trailing /
412 $cwd;
413}
414
415
e4c51978
GS
416# added function alias for those of us more
417# used to the libc function. --tchrist 27-Jan-00
418*realpath = \&abs_path;
419
3ee63918 420my $Curdir;
96e4d5b1 421sub fast_abs_path {
422 my $cwd = getcwd();
4d6b4052 423 require File::Spec;
3ee63918
MS
424 my $path = @_ ? shift : ($Curdir ||= File::Spec->curdir);
425
426 # Detaint else we'll explode in taint mode. This is safe because
427 # we're not doing anything dangerous with it.
428 ($path) = $path =~ /(.*)/;
429 ($cwd) = $cwd =~ /(.*)/;
430
e2ba406b 431 if (!CORE::chdir($path)) {
a9939470 432 _croak("Cannot chdir to $path: $!");
e2ba406b 433 }
96e4d5b1 434 my $realpath = getcwd();
e2ba406b 435 if (! ((-d $cwd) && (CORE::chdir($cwd)))) {
a9939470 436 _croak("Cannot chdir back to $cwd: $!");
e2ba406b 437 }
96e4d5b1 438 $realpath;
8b88ae92
NIS
439}
440
e4c51978
GS
441# added function alias to follow principle of least surprise
442# based on previous aliasing. --tchrist 27-Jan-00
443*fast_realpath = \&fast_abs_path;
444
4633a7c4
LW
445
446# --- PORTING SECTION ---
447
448# VMS: $ENV{'DEFAULT'} points to default directory at all times
bd3fa61c 449# 06-Mar-1996 Charles Bailey bailey@newman.upenn.edu
c6538b72 450# Note: Use of Cwd::chdir() causes the logical name PWD to be defined
8b88ae92
NIS
451# in the process logical name table as the default device and directory
452# seen by Perl. This may not be the same as the default device
4633a7c4
LW
453# and directory seen by DCL after Perl exits, since the effects
454# the CRTL chdir() function persist only until Perl exits.
4633a7c4
LW
455
456sub _vms_cwd {
96e4d5b1 457 return $ENV{'DEFAULT'};
458}
459
460sub _vms_abs_path {
461 return $ENV{'DEFAULT'} unless @_;
462 my $path = VMS::Filespec::pathify($_[0]);
e2ba406b
T
463 if (! defined $path)
464 {
a9939470 465 _croak("Invalid path name $_[0]")
e2ba406b 466 }
96e4d5b1 467 return VMS::Filespec::rmsexpand($path);
4633a7c4 468}
68dc0745 469
4633a7c4
LW
470sub _os2_cwd {
471 $ENV{'PWD'} = `cmd /c cd`;
39741d73 472 chomp $ENV{'PWD'};
aa6b7957 473 $ENV{'PWD'} =~ s:\\:/:g ;
4633a7c4
LW
474 return $ENV{'PWD'};
475}
476
96e4d5b1 477sub _win32_cwd {
2d7a9237 478 $ENV{'PWD'} = Win32::GetCwd();
aa6b7957 479 $ENV{'PWD'} =~ s:\\:/:g ;
96e4d5b1 480 return $ENV{'PWD'};
481}
482
483*_NT_cwd = \&_win32_cwd if (!defined &_NT_cwd &&
2d7a9237 484 defined &Win32::GetCwd);
96e4d5b1 485
486*_NT_cwd = \&_os2_cwd unless defined &_NT_cwd;
68dc0745 487
39e571d4
LM
488sub _dos_cwd {
489 if (!defined &Dos::GetCwd) {
490 $ENV{'PWD'} = `command /c cd`;
39741d73 491 chomp $ENV{'PWD'};
aa6b7957 492 $ENV{'PWD'} =~ s:\\:/:g ;
39e571d4
LM
493 } else {
494 $ENV{'PWD'} = Dos::GetCwd();
495 }
55497cff 496 return $ENV{'PWD'};
497}
498
7fbf1995 499sub _qnx_cwd {
35b807ef
NA
500 local $ENV{PATH} = '';
501 local $ENV{CDPATH} = '';
502 local $ENV{ENV} = '';
7fbf1995 503 $ENV{'PWD'} = `/usr/bin/fullpath -t`;
39741d73 504 chomp $ENV{'PWD'};
7fbf1995
NA
505 return $ENV{'PWD'};
506}
507
508sub _qnx_abs_path {
35b807ef
NA
509 local $ENV{PATH} = '';
510 local $ENV{CDPATH} = '';
511 local $ENV{ENV} = '';
fa921dc6 512 my $path = @_ ? shift : '.';
39741d73
MS
513 local *REALPATH;
514
515 open(REALPATH, '-|', '/usr/bin/fullpath', '-t', $path) or
516 die "Can't open /usr/bin/fullpath: $!";
517 my $realpath = <REALPATH>;
518 close REALPATH;
519 chomp $realpath;
7fbf1995
NA
520 return $realpath;
521}
522
ed79a026
OF
523sub _epoc_cwd {
524 $ENV{'PWD'} = EPOC::getcwd();
525 return $ENV{'PWD'};
526}
527
ac1ad7f0 528{
db376a24 529 no warnings; # assignments trigger 'subroutine redefined' warning
4633a7c4 530
ac1ad7f0 531 if ($^O eq 'VMS') {
96e4d5b1 532 *cwd = \&_vms_cwd;
533 *getcwd = \&_vms_cwd;
534 *fastcwd = \&_vms_cwd;
535 *fastgetcwd = \&_vms_cwd;
536 *abs_path = \&_vms_abs_path;
537 *fast_abs_path = \&_vms_abs_path;
ac1ad7f0
PM
538 }
539 elsif ($^O eq 'NT' or $^O eq 'MSWin32') {
540 # We assume that &_NT_cwd is defined as an XSUB or in the core.
96e4d5b1 541 *cwd = \&_NT_cwd;
542 *getcwd = \&_NT_cwd;
543 *fastcwd = \&_NT_cwd;
544 *fastgetcwd = \&_NT_cwd;
545 *abs_path = \&fast_abs_path;
cade0c02 546 *realpath = \&fast_abs_path;
ac1ad7f0 547 }
39e571d4
LM
548 elsif ($^O eq 'dos') {
549 *cwd = \&_dos_cwd;
550 *getcwd = \&_dos_cwd;
551 *fastgetcwd = \&_dos_cwd;
552 *fastcwd = \&_dos_cwd;
96e4d5b1 553 *abs_path = \&fast_abs_path;
ac1ad7f0 554 }
7438b6ad 555 elsif ($^O =~ m/^(?:qnx|nto)$/ ) {
7fbf1995
NA
556 *cwd = \&_qnx_cwd;
557 *getcwd = \&_qnx_cwd;
558 *fastgetcwd = \&_qnx_cwd;
559 *fastcwd = \&_qnx_cwd;
560 *abs_path = \&_qnx_abs_path;
561 *fast_abs_path = \&_qnx_abs_path;
562 }
4fabb596 563 elsif ($^O eq 'cygwin') {
1cab015a
EF
564 *getcwd = \&cwd;
565 *fastgetcwd = \&cwd;
566 *fastcwd = \&cwd;
567 *abs_path = \&fast_abs_path;
a9939470 568 *realpath = \&abs_path;
1cab015a 569 }
ed79a026 570 elsif ($^O eq 'epoc') {
fa6a1c44
OF
571 *cwd = \&_epoc_cwd;
572 *getcwd = \&_epoc_cwd;
ed79a026
OF
573 *fastgetcwd = \&_epoc_cwd;
574 *fastcwd = \&_epoc_cwd;
575 *abs_path = \&fast_abs_path;
576 }
4aecb5b5
JH
577 elsif ($^O eq 'MacOS') {
578 *getcwd = \&cwd;
579 *fastgetcwd = \&cwd;
580 *fastcwd = \&cwd;
581 *abs_path = \&fast_abs_path;
582 }
55497cff 583}
4633a7c4 584
4633a7c4 585
a0d0e21e 5861;