This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
[inseparable changes from match from perl-5.003_96 to perl-5.003_97]
[perl5.git] / lib / Cwd.pm
1 package Cwd;
2 require 5.000;
3 require Exporter;
4
5 =head1 NAME
6
7 getcwd - get pathname of current working directory
8
9 =head1 SYNOPSIS
10
11     use Cwd;
12     $dir = cwd;
13
14     use Cwd;
15     $dir = getcwd;
16
17     use Cwd;
18     $dir = fastgetcwd;
19
20     use Cwd 'chdir';
21     chdir "/tmp";
22     print $ENV{'PWD'};
23
24 =head1 DESCRIPTION
25
26 The getcwd() function re-implements the getcwd(3) (or getwd(3)) functions
27 in Perl.
28
29 The fastcwd() function looks the same as getcwd(), but runs faster.
30 It's also more dangerous because you might conceivably chdir() out of a
31 directory that you can't chdir() back into.
32
33 The cwd() function looks the same as getcwd and fastgetcwd but is
34 implemented using the most natural and safe form for the current
35 architecture. For most systems it is identical to `pwd` (but without
36 the trailing line terminator). It is recommended that cwd (or another
37 *cwd() function) is used in I<all> code to ensure portability.
38
39 If you ask to override your chdir() built-in function, then your PWD
40 environment variable will be kept up to date.  (See
41 L<perlsub/Overriding Builtin Functions>.) Note that it will only be
42 kept up to date if all packages which use chdir import it from Cwd.
43
44 =cut
45
46 @ISA = qw(Exporter);
47 @EXPORT = qw(cwd getcwd fastcwd fastgetcwd);
48 @EXPORT_OK = qw(chdir);
49
50 # use strict;
51
52 sub _backtick_pwd {  # The 'natural and safe form' for UNIX (pwd may be setuid root)
53     my $cwd;
54     chop($cwd = `pwd`);
55     $cwd;
56
57
58 # Since some ports may predefine cwd internally (e.g., NT)
59 # we take care not to override an existing definition for cwd().
60
61 *cwd = \&_backtick_pwd unless defined &cwd;
62
63
64 # By Brandon S. Allbery
65 #
66 # Usage: $cwd = getcwd();
67
68 sub getcwd
69 {
70     my($dotdots, $cwd, @pst, @cst, $dir, @tst);
71
72     unless (@cst = stat('.'))
73     {
74         warn "stat(.): $!";
75         return '';
76     }
77     $cwd = '';
78     $dotdots = '';
79     do
80     {
81         $dotdots .= '/' if $dotdots;
82         $dotdots .= '..';
83         @pst = @cst;
84         unless (opendir(PARENT, $dotdots))
85         {
86             warn "opendir($dotdots): $!";
87             return '';
88         }
89         unless (@cst = stat($dotdots))
90         {
91             warn "stat($dotdots): $!";
92             closedir(PARENT);
93             return '';
94         }
95         if ($pst[0] == $cst[0] && $pst[1] == $cst[1])
96         {
97             $dir = '';
98         }
99         else
100         {
101             do
102             {
103                 unless (defined ($dir = readdir(PARENT)))
104                 {
105                     warn "readdir($dotdots): $!";
106                     closedir(PARENT);
107                     return '';
108                 }
109                 unless (@tst = lstat("$dotdots/$dir"))
110                 {
111                     # warn "lstat($dotdots/$dir): $!";
112                     # Just because you can't lstat this directory
113                     # doesn't mean you'll never find the right one.
114                     # closedir(PARENT);
115                     # return '';
116                 }
117             }
118             while ($dir eq '.' || $dir eq '..' || $tst[0] != $pst[0] ||
119                    $tst[1] != $pst[1]);
120         }
121         $cwd = "$dir/$cwd";
122         closedir(PARENT);
123     } while ($dir);
124     chop($cwd) unless $cwd eq '/'; # drop the trailing /
125     $cwd;
126 }
127
128
129
130 # By John Bazik
131 #
132 # Usage: $cwd = &fastcwd;
133 #
134 # This is a faster version of getcwd.  It's also more dangerous because
135 # you might chdir out of a directory that you can't chdir back into.
136
137 sub fastcwd {
138     my($odev, $oino, $cdev, $cino, $tdev, $tino);
139     my(@path, $path);
140     local(*DIR);
141
142     ($cdev, $cino) = stat('.');
143     for (;;) {
144         my $direntry;
145         ($odev, $oino) = ($cdev, $cino);
146         chdir('..');
147         ($cdev, $cino) = stat('.');
148         last if $odev == $cdev && $oino == $cino;
149         opendir(DIR, '.');
150         for (;;) {
151             $direntry = readdir(DIR);
152             next if $direntry eq '.';
153             next if $direntry eq '..';
154
155             last unless defined $direntry;
156             ($tdev, $tino) = lstat($direntry);
157             last unless $tdev != $odev || $tino != $oino;
158         }
159         closedir(DIR);
160         unshift(@path, $direntry);
161     }
162     chdir($path = '/' . join('/', @path));
163     $path;
164 }
165
166
167 # Keeps track of current working directory in PWD environment var
168 # Usage:
169 #       use Cwd 'chdir';
170 #       chdir $newdir;
171
172 my $chdir_init = 0;
173
174 sub chdir_init {
175     if ($ENV{'PWD'} and $^O ne 'os2' and $^O ne 'msdos') {
176         my($dd,$di) = stat('.');
177         my($pd,$pi) = stat($ENV{'PWD'});
178         if (!defined $dd or !defined $pd or $di != $pi or $dd != $pd) {
179             $ENV{'PWD'} = cwd();
180         }
181     }
182     else {
183         $ENV{'PWD'} = cwd();
184     }
185     # Strip an automounter prefix (where /tmp_mnt/foo/bar == /foo/bar)
186     if ($ENV{'PWD'} =~ m|(/[^/]+(/[^/]+/[^/]+))(.*)|) {
187         my($pd,$pi) = stat($2);
188         my($dd,$di) = stat($1);
189         if (defined $pd and defined $dd and $di == $pi and $dd == $pd) {
190             $ENV{'PWD'}="$2$3";
191         }
192     }
193     $chdir_init = 1;
194 }
195
196 sub chdir {
197     my $newdir = shift || '';   # allow for no arg (chdir to HOME dir)
198     $newdir =~ s|///*|/|g;
199     chdir_init() unless $chdir_init;
200     return 0 unless CORE::chdir $newdir;
201     if ($^O eq 'VMS') { return $ENV{'PWD'} = $ENV{'DEFAULT'} }
202
203     if ($newdir =~ m#^/#) {
204         $ENV{'PWD'} = $newdir;
205     } else {
206         my @curdir = split(m#/#,$ENV{'PWD'});
207         @curdir = ('') unless @curdir;
208         my $component;
209         foreach $component (split(m#/#, $newdir)) {
210             next if $component eq '.';
211             pop(@curdir),next if $component eq '..';
212             push(@curdir,$component);
213         }
214         $ENV{'PWD'} = join('/',@curdir) || '/';
215     }
216     1;
217 }
218
219
220 # --- PORTING SECTION ---
221
222 # VMS: $ENV{'DEFAULT'} points to default directory at all times
223 # 06-Mar-1996  Charles Bailey  bailey@genetics.upenn.edu
224 # Note: Use of Cwd::chdir() causes the logical name PWD to be defined
225 #   in the process logical name table as the default device and directory 
226 #   seen by Perl. This may not be the same as the default device 
227 #   and directory seen by DCL after Perl exits, since the effects
228 #   the CRTL chdir() function persist only until Perl exits.
229
230 sub _vms_cwd {
231     return $ENV{'DEFAULT'}
232 }
233
234 sub _os2_cwd {
235     $ENV{'PWD'} = `cmd /c cd`;
236     chop $ENV{'PWD'};
237     $ENV{'PWD'} =~ s:\\:/:g ;
238     return $ENV{'PWD'};
239 }
240
241 *_NT_cwd = \&_os2_cwd unless defined &_NT_cwd;
242
243 sub _msdos_cwd {
244     $ENV{'PWD'} = `command /c cd`;
245     chop $ENV{'PWD'};
246     $ENV{'PWD'} =~ s:\\:/:g ;
247     return $ENV{'PWD'};
248 }
249
250 {
251     local $^W = 0;      # assignments trigger 'subroutine redefined' warning
252
253     if ($^O eq 'VMS') {
254         *cwd        = \&_vms_cwd;
255         *getcwd     = \&_vms_cwd;
256         *fastcwd    = \&_vms_cwd;
257         *fastgetcwd = \&_vms_cwd;
258     }
259     elsif ($^O eq 'NT' or $^O eq 'MSWin32') {
260         # We assume that &_NT_cwd is defined as an XSUB or in the core.
261         *cwd        = \&_NT_cwd;
262         *getcwd     = \&_NT_cwd;
263         *fastcwd    = \&_NT_cwd;
264         *fastgetcwd = \&_NT_cwd;
265     }
266     elsif ($^O eq 'os2') {
267         # sys_cwd may keep the builtin command
268         *cwd     = defined &sys_cwd ? \&sys_cwd : \&_os2_cwd;
269         *getcwd  = defined &sys_cwd ? \&sys_cwd : \&_os2_cwd;
270         *fastgetcwd      = defined &sys_cwd ? \&sys_cwd : \&_os2_cwd;
271         *fastcwd         = defined &sys_cwd ? \&sys_cwd : \&_os2_cwd;
272     }
273     elsif ($^O eq 'msdos') {
274         *cwd     = \&_msdos_cwd;
275         *getcwd     = \&_msdos_cwd;
276         *fastgetcwd = \&_msdos_cwd;
277         *fastcwd = \&_msdos_cwd;
278     }
279 }
280
281 # package main; eval join('',<DATA>) || die $@; # quick test
282
283 1;
284
285 __END__
286 BEGIN { import Cwd qw(:DEFAULT chdir); }
287 print join("\n", cwd, getcwd, fastcwd, "");
288 chdir('..');
289 print join("\n", cwd, getcwd, fastcwd, "");
290 print "$ENV{PWD}\n";