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