Mention File::Spec in File::Basename
[p5sagit/p5-mst-13.2.git] / lib / File / Basename.pm
1 =head1 NAME
2
3 File::Basename - Parse file paths into directory, filename and suffix.
4
5 =head1 SYNOPSIS
6
7     use File::Basename;
8
9     ($name,$path,$suffix) = fileparse($fullname,@suffixlist);
10     $name = fileparse($fullname,@suffixlist);
11
12     $basename = basename($fullname,@suffixlist);
13     $dirname  = dirname($fullname);
14
15
16 =head1 DESCRIPTION
17
18 These routines allow you to parse file paths into their directory, filename
19 and suffix.
20
21 B<NOTE>: C<dirname()> and C<basename()> emulate the behaviours, and
22 quirks, of the shell and C functions of the same name.  See each
23 function's documention for details.  If your concern is just parsing
24 paths it is safer to use L<File::Spec>'s C<splitpath()> and
25 C<splitdir()> methods.
26
27 It is guaranteed that
28
29     # Where $path_separator is / for Unix, \ for Windows, etc...
30     dirname($path) . $path_separator . basename($path);
31
32 is equivalent to the original path for all systems but VMS.
33
34
35 =cut
36
37
38 package File::Basename;
39
40 # A bit of juggling to insure that C<use re 'taint';> always works, since
41 # File::Basename is used during the Perl build, when the re extension may
42 # not be available.
43 BEGIN {
44   unless (eval { require re; })
45     { eval ' sub re::import { $^H |= 0x00100000; } ' } # HINT_RE_TAINT
46   import re 'taint';
47 }
48
49
50 use strict;
51 use 5.006;
52 use warnings;
53 our(@ISA, @EXPORT, $VERSION, $Fileparse_fstype, $Fileparse_igncase);
54 require Exporter;
55 @ISA = qw(Exporter);
56 @EXPORT = qw(fileparse fileparse_set_fstype basename dirname);
57 $VERSION = "2.74";
58
59 fileparse_set_fstype($^O);
60
61
62 =over 4
63
64 =item C<fileparse>
65
66     my($filename, $directories, $suffix) = fileparse($path);
67     my($filename, $directories, $suffix) = fileparse($path, @suffixes);
68     my $filename                         = fileparse($path, @suffixes);
69
70 The C<fileparse()> routine divides a file path into its $directories, $filename
71 and (optionally) the filename $suffix.
72
73 $directories contains everything up to and including the last
74 directory separator in the $path including the volume (if applicable).
75 The remainder of the $path is the $filename.
76
77      # On Unix returns ("baz", "/foo/bar/", "")
78      fileparse("/foo/bar/baz");
79
80      # On Windows returns ("baz", "C:\foo\bar\", "")
81      fileparse("C:\foo\bar\baz");
82
83      # On Unix returns ("", "/foo/bar/baz/", "")
84      fileparse("/foo/bar/baz/");
85
86 If @suffixes are given each element is a pattern (either a string or a
87 C<qr//>) matched against the end of the $filename.  The matching
88 portion is removed and becomes the $suffix.
89
90      # On Unix returns ("baz", "/foo/bar", ".txt")
91      fileparse("/foo/bar/baz", qr/\.[^.]*/);
92
93 If type is non-Unix (see C<fileparse_set_fstype()>) then the pattern
94 matching for suffix removal is performed case-insensitively, since
95 those systems are not case-sensitive when opening existing files.
96
97 You are guaranteed that C<$directories . $filename . $suffix> will
98 denote the same location as the original $path.
99
100 =cut
101
102
103 sub fileparse {
104   my($fullname,@suffices) = @_;
105
106   unless (defined $fullname) {
107       require Carp;
108       Carp::croak("fileparse(): need a valid pathname");
109   }
110
111   my $orig_type = '';
112   my($type,$igncase) = ($Fileparse_fstype, $Fileparse_igncase);
113
114   my($taint) = substr($fullname,0,0);  # Is $fullname tainted?
115
116   if ($type eq "VMS" and $fullname =~ m{/} ) {
117     # We're doing Unix emulation
118     $orig_type = $type;
119     $type = 'Unix';
120   }
121
122   my($dirpath, $basename);
123
124   if (grep { $type eq $_ } qw(MSDOS DOS MSWin32 Epoc)) {
125     ($dirpath,$basename) = ($fullname =~ /^((?:.*[:\\\/])?)(.*)/s);
126     $dirpath .= '.\\' unless $dirpath =~ /[\\\/]\z/;
127   }
128   elsif ($type eq "OS2") {
129     ($dirpath,$basename) = ($fullname =~ m#^((?:.*[:\\/])?)(.*)#s);
130     $dirpath = './' unless $dirpath;    # Can't be 0
131     $dirpath .= '/' unless $dirpath =~ m#[\\/]\z#;
132   }
133   elsif ($type eq "MacOS") {
134     ($dirpath,$basename) = ($fullname =~ /^(.*:)?(.*)/s);
135     $dirpath = ':' unless $dirpath;
136   }
137   elsif ($type eq "AmigaOS") {
138     ($dirpath,$basename) = ($fullname =~ /(.*[:\/])?(.*)/s);
139     $dirpath = './' unless $dirpath;
140   }
141   elsif ($type eq 'VMS' ) {
142     ($dirpath,$basename) = ($fullname =~ /^(.*[:>\]])?(.*)/s);
143     $dirpath ||= '';  # should always be defined
144   }
145   else { # Default to Unix semantics.
146     ($dirpath,$basename) = ($fullname =~ m#^(.*/)?(.*)#s);
147     if ($orig_type eq 'VMS' and $fullname =~ m:^(/[^/]+/000000(/|$))(.*):) {
148       # dev:[000000] is top of VMS tree, similar to Unix '/'
149       # so strip it off and treat the rest as "normal"
150       my $devspec  = $1;
151       my $remainder = $3;
152       ($dirpath,$basename) = ($remainder =~ m#^(.*/)?(.*)#s);
153       $dirpath ||= '';  # should always be defined
154       $dirpath = $devspec.$dirpath;
155     }
156     $dirpath = './' unless $dirpath;
157   }
158       
159
160   my($tail, $suffix);
161   if (@suffices) {
162     $tail = '';
163     foreach $suffix (@suffices) {
164       my $pat = ($igncase ? '(?i)' : '') . "($suffix)\$";
165       if ($basename =~ s/$pat//s) {
166         $taint .= substr($suffix,0,0);
167         $tail = $1 . $tail;
168       }
169     }
170   }
171
172   # Ensure taint is propgated from the path to its pieces.
173   $tail .= $taint if defined $tail; # avoid warning if $tail == undef
174   wantarray ? ($basename .= $taint, $dirpath .= $taint, $tail)
175             : ($basename .= $taint);
176 }
177
178
179
180 =item C<basename>
181
182     my $filename = basename($path);
183     my $filename = basename($path, @suffixes);
184
185 This function is provided for compatibility with the Unix shell command 
186 C<basename(1)>.  It does B<NOT> always return the file name portion of a
187 path as you might expect.  To be safe, if you want the file name portion of
188 a path use C<fileparse()>.
189
190 C<basename()> returns the last level of a filepath even if the last
191 level is clearly directory.  In effect, it is acting like C<pop()> for
192 paths.  This differs from C<fileparse()>'s behaviour.
193
194     # Both return "bar"
195     basename("/foo/bar");
196     basename("/foo/bar/");
197
198 @suffixes work as in C<fileparse()> except all regex metacharacters are
199 quoted.
200
201     # These two function calls are equivalent.
202     my $filename = basename("/foo/bar/baz.txt",  ".txt");
203     my $filename = fileparse("/foo/bar/baz.txt", qr/\Q.txt\E/);
204
205 =cut
206
207
208 sub basename {
209   my($name) = shift;
210   _strip_trailing_sep($name);
211   (fileparse($name, map("\Q$_\E",@_)))[0];
212 }
213
214
215
216 =item C<dirname>
217
218 This function is provided for compatibility with the Unix shell
219 command C<dirname(1)> and has inherited some of its quirks.  In spite of
220 its name it does B<NOT> always return the directory name as you might
221 expect.  To be safe, if you want the directory name of a path use
222 C<fileparse()>.
223
224 Only on VMS (where there is no ambiguity between the file and directory
225 portions of a path) and AmigaOS (possibly due to an implementation quirk in
226 this module) does C<dirname()> work like C<fileparse($path)>, returning just the
227 $directories.
228
229     # On VMS and AmigaOS
230     my $directories = dirname($path);
231
232 When using Unix or MSDOS syntax this emulates the C<dirname(1)> shell function
233 which is subtly different from how C<fileparse()> works.  It returns all but
234 the last level of a file path even if the last level is clearly a directory.
235 In effect, it is not returning the directory portion but simply the path one
236 level up acting like C<chop()> for file paths.
237
238 Also unlike C<fileparse()>, C<dirname()> does not include a trailing slash on
239 its returned path.
240
241     # returns /foo/bar.  fileparse() would return /foo/bar/
242     dirname("/foo/bar/baz");
243
244     # also returns /foo/bar despite the fact that baz is clearly a 
245     # directory.  fileparse() would return /foo/bar/baz/
246     dirname("/foo/bar/baz/");
247
248     # returns '.'.  fileparse() would return 'foo/'
249     dirname("foo/");
250
251 Under VMS, if there is no directory information in the $path, then the
252 current default device and directory is used.
253
254 =cut
255
256
257 sub dirname {
258     my $path = shift;
259
260     my($type) = $Fileparse_fstype;
261
262     if( $type eq 'VMS' and $path =~ m{/} ) {
263         # Parse as Unix
264         local($File::Basename::Fileparse_fstype) = '';
265         return dirname($path);
266     }
267
268     my($basename, $dirname) = fileparse($path);
269
270     if ($type eq 'VMS') { 
271         $dirname ||= $ENV{DEFAULT};
272     }
273     elsif ($type eq 'MacOS') {
274         if( !length($basename) && $dirname !~ /^[^:]+:\z/) {
275             _strip_trailing_sep($dirname);
276             ($basename,$dirname) = fileparse $dirname;
277         }
278         $dirname .= ":" unless $dirname =~ /:\z/;
279     }
280     elsif (grep { $type eq $_ } qw(MSDOS DOS MSWin32 OS2)) { 
281         _strip_trailing_sep($dirname);
282         unless( length($basename) ) {
283             ($basename,$dirname) = fileparse $dirname;
284             _strip_trailing_sep($dirname);
285         }
286     }
287     elsif ($type eq 'AmigaOS') {
288         if ( $dirname =~ /:\z/) { return $dirname }
289         chop $dirname;
290         $dirname =~ s#[^:/]+\z## unless length($basename);
291     }
292     else {
293         _strip_trailing_sep($dirname);
294         unless( length($basename) ) {
295             ($basename,$dirname) = fileparse $dirname;
296             _strip_trailing_sep($dirname);
297         }
298     }
299
300     $dirname;
301 }
302
303
304 # Strip the trailing path separator.
305 sub _strip_trailing_sep  {
306     my $type = $Fileparse_fstype;
307
308     if ($type eq 'MacOS') {
309         $_[0] =~ s/([^:]):\z/$1/s;
310     }
311     elsif (grep { $type eq $_ } qw(MSDOS DOS MSWin32 OS2)) { 
312         $_[0] =~ s/([^:])[\\\/]*\z/$1/;
313     }
314     else {
315         $_[0] =~ s{(.)/*\z}{$1}s;
316     }
317 }
318
319
320 =item C<fileparse_set_fstype>
321
322   my $type = fileparse_set_fstype();
323   my $previous_type = fileparse_set_fstype($type);
324
325 Normally File::Basename will assume a file path type native to your current
326 operating system (ie. /foo/bar style on Unix, \foo\bar on Windows, etc...).
327 With this function you can override that assumption.
328
329 Valid $types are "MacOS", "VMS", "AmigaOS", "OS2", "RISCOS",
330 "MSWin32", "DOS" (also "MSDOS" for backwards bug compatibility),
331 "Epoc" and "Unix" (all case-insensitive).  If an unrecognized $type is
332 given "Unix" will be assumed.
333
334 If you've selected VMS syntax, and the file specification you pass to
335 one of these routines contains a "/", they assume you are using Unix
336 emulation and apply the Unix syntax rules instead, for that function
337 call only.
338
339 =back
340
341 =cut
342
343
344 BEGIN {
345
346 my @Ignore_Case = qw(MacOS VMS AmigaOS OS2 RISCOS MSWin32 MSDOS DOS Epoc);
347 my @Types = (@Ignore_Case, qw(Unix));
348
349 sub fileparse_set_fstype {
350     my $old = $Fileparse_fstype;
351
352     if (@_) {
353         my $new_type = shift;
354
355         $Fileparse_fstype = 'Unix';  # default
356         foreach my $type (@Types) {
357             $Fileparse_fstype = $type if $new_type =~ /^$type/i;
358         }
359
360         $Fileparse_igncase = 
361           (grep $Fileparse_fstype eq $_, @Ignore_Case) ? 1 : 0;
362     }
363
364     return $old;
365 }
366
367 }
368
369
370 1;
371
372
373 =head1 SEE ALSO
374
375 L<dirname(1)>, L<basename(1)>, L<File::Spec>