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