1 ###############################################################################
3 # Package: NaturalDocs::File
5 ###############################################################################
7 # A package to manage file access across platforms. Incorporates functions from various standard File:: packages, but more
8 # importantly, works around the glorious suckage present in File::Spec, at least in version 0.82 and earlier. Read the "Why oh
9 # why?" sections for why this package was necessary.
11 # Usage and Dependencies:
13 # - The package doesn't depend on any other Natural Docs packages and is ready to use immediately.
15 # - All functions except <CanonizePath()> assume that all parameters are canonized.
17 ###############################################################################
19 # This file is part of Natural Docs, which is Copyright © 2003-2010 Greg Valure
20 # Natural Docs is licensed under version 3 of the GNU Affero General Public License (AGPL)
21 # Refer to License.txt for the complete details
30 package NaturalDocs::File;
34 # Function: CheckCompatibility
36 # Checks if the standard packages required by this one are up to snuff and dies if they aren't. This is done because I can't
37 # tell which versions of File::Spec have splitpath just by the version numbers.
39 sub CheckCompatibility
44 File::Spec->splitpath('');
49 NaturalDocs::Error->SoftDeath("Natural Docs requires a newer version of File::Spec than you have. "
50 . "You must either upgrade it or upgrade Perl.");
55 ###############################################################################
56 # Group: Path String Functions
60 # Function: CanonizePath
62 # Takes a path and returns a logically simplified version of it.
66 # Because File::Spec->canonpath doesn't strip quotes on Windows. So if you pass in "a b\c" or "a b"\c, they still end up as
67 # different strings even though they're logically the same.
69 # It also doesn't remove things like "..", so "a/b/../c" doesn't simplify to "a/c" like it should.
71 sub CanonizePath #(path)
73 my ($self, $path) = @_;
75 if ($::OSNAME eq 'MSWin32')
77 # We don't have to use a smarter algorithm for dropping quotes because they're invalid characters for actual file and
82 $path = File::Spec->canonpath($path);
84 # Condense a/b/../c into a/c.
86 my $upDir = File::Spec->updir();
87 if (index($path, $upDir) != -1)
89 my ($volume, $directoryString, $file) = $self->SplitPath($path);
90 my @directories = $self->SplitDirectories($directoryString);
93 while ($i < scalar @directories)
95 if ($i > 0 && $directories[$i] eq $upDir && $directories[$i - 1] ne $upDir)
97 splice(@directories, $i - 1, 2);
104 $directoryString = $self->JoinDirectories(@directories);
105 $path = $self->JoinPath($volume, $directoryString, $file);
113 # Function: PathIsAbsolute
115 # Returns whether the passed path is absolute.
117 sub PathIsAbsolute #(path)
119 my ($self, $path) = @_;
120 return File::Spec->file_name_is_absolute($path);
127 # Creates a path from its elements.
131 # volume - The volume, such as the drive letter on Windows. Undef if none.
132 # dirString - The directory string. Create with <JoinDirectories()> if necessary.
133 # file - The file name, or undef if none.
139 sub JoinPath #(volume, dirString, $file)
141 my ($self, $volume, $dirString, $file) = @_;
142 return File::Spec->catpath($volume, $dirString, $file);
147 # Function: JoinPaths
153 # basePath - May be a relative path, an absolute path, or undef.
154 # extraPath - May be a relative path, a file, a relative path and file together, or undef.
155 # noFileInExtra - Set this to true if extraPath is a relative path only, and doesn't have a file.
163 # Because nothing in File::Spec will simply slap two paths together. They have to be split up for catpath/file, and rel2abs
164 # requires the base to be absolute.
166 sub JoinPaths #(basePath, extraPath, noFileInExtra)
168 my ($self, $basePath, $extraPath, $noFileInExtra) = @_;
170 # If both are undef, it will return undef, which is what we want.
171 if (!defined $basePath)
172 { return $extraPath; }
173 elsif (!defined $extraPath)
174 { return $basePath; };
176 my ($baseVolume, $baseDirString, $baseFile) = File::Spec->splitpath($basePath, 1);
177 my ($extraVolume, $extraDirString, $extraFile) = File::Spec->splitpath($extraPath, $noFileInExtra);
179 my @baseDirectories = $self->SplitDirectories($baseDirString);
180 my @extraDirectories = $self->SplitDirectories($extraDirString);
182 my $fullDirString = $self->JoinDirectories(@baseDirectories, @extraDirectories);
184 my $fullPath = File::Spec->catpath($baseVolume, $fullDirString, $extraFile);
186 return $self->CanonizePath($fullPath);
191 # Function: SplitPath
193 # Takes a path and returns its elements.
197 # path - The path to split.
198 # noFile - Set to true if the path doesn't have a file at the end.
202 # The array ( volume, directoryString, file ). If any don't apply, they will be undef. Use <SplitDirectories()> to split the
203 # directory string if desired.
207 # Because File::Spec->splitpath may leave a trailing slash/backslash/whatever on the directory string, which makes
208 # it a bit hard to match it with results from File::Spec->catdir.
210 sub SplitPath #(path, noFile)
212 my ($self, $path, $noFile) = @_;
214 my @segments = File::Spec->splitpath($path, $noFile);
216 if (!length $segments[0])
217 { $segments[0] = undef; };
218 if (!length $segments[2])
219 { $segments[2] = undef; };
221 $segments[1] = File::Spec->catdir( File::Spec->splitdir($segments[1]) );
228 # Function: JoinDirectories
230 # Creates a directory string from an array of directory names.
234 # directory - A directory name. There may be as many of these as desired.
236 sub JoinDirectories #(directory, directory, ...)
238 my ($self, @directories) = @_;
239 return File::Spec->catdir(@directories);
244 # Function: SplitDirectories
246 # Takes a string of directories and returns an array of its elements.
250 # Because File::Spec->splitdir might leave an empty element at the end of the array, which screws up both joining in
251 # <ConvertToURL> and navigation in <MakeRelativePath>.
253 sub SplitDirectories #(directoryString)
255 my ($self, $directoryString) = @_;
257 my @directories = File::Spec->splitdir($directoryString);
259 if (!length $directories[-1])
260 { pop @directories; };
267 # Function: MakeRelativePath
269 # Takes two paths and returns a relative path between them.
273 # basePath - The starting path. May be relative or absolute, so long as the target path is as well.
274 # targetPath - The target path. May be relative or absolute, so long as the base path is as well.
276 # If both paths are relative, they are assumed to be relative to the same base.
280 # The target path relative to base.
284 # First, there's nothing that gives a relative path between two relative paths.
286 # Second, if target and base are absolute but on different volumes, File::Spec->abs2rel creates a totally non-functional
287 # relative path. It should return the target as is, since there is no relative path.
289 # Third, File::Spec->abs2rel between absolute paths on the same volume, at least on Windows, leaves the drive letter
290 # on. So abs2rel('a:\b\c\d', 'a:\b') returns 'a:c\d' instead of the expected 'c\d'. That makes no sense whatsoever. It's
291 # not like it was designed to handle only directory names, either; the documentation says 'path' and the code seems to
292 # explicitly handle it. There's just an 'unless' in there that tacks on the volume, defeating the purpose of a *relative* path
293 # and making the function worthless.
295 sub MakeRelativePath #(basePath, targetPath)
297 my ($self, $basePath, $targetPath) = @_;
299 my ($baseVolume, $baseDirString, $baseFile) = $self->SplitPath($basePath, 1);
300 my ($targetVolume, $targetDirString, $targetFile) = $self->SplitPath($targetPath);
302 # If the volumes are different, there is no possible relative path.
303 if ($targetVolume ne $baseVolume)
304 { return $targetPath; };
306 my @baseDirectories = $self->SplitDirectories($baseDirString);
307 my @targetDirectories = $self->SplitDirectories($targetDirString);
309 # Skip the parts of the path that are the same.
310 while (scalar @baseDirectories && @targetDirectories && $baseDirectories[0] eq $targetDirectories[0])
312 shift @baseDirectories;
313 shift @targetDirectories;
316 # Back out of the base path until it reaches where they were similar.
317 for (my $i = 0; $i < scalar @baseDirectories; $i++)
319 unshift @targetDirectories, File::Spec->updir();
322 $targetDirString = $self->JoinDirectories(@targetDirectories);
324 return File::Spec->catpath(undef, $targetDirString, $targetFile);
329 # Function: IsSubPathOf
331 # Returns whether the path is a descendant of another path.
335 # base - The base path to test against.
336 # path - The possible subpath to test.
340 # Whether path is a descendant of base.
342 sub IsSubPathOf #(base, path)
344 my ($self, $base, $path) = @_;
346 # This is a quick test that should find a false quickly.
347 if ($base eq substr($path, 0, length($base)))
349 # This doesn't guarantee true, because it could be "C:\A B" and "C:\A B C\File". So we test for it by seeing if the last
350 # directory in base is the same as the equivalent directory in path.
352 my ($baseVolume, $baseDirString, $baseFile) = NaturalDocs::File->SplitPath($base, 1);
353 my @baseDirectories = NaturalDocs::File->SplitDirectories($baseDirString);
355 my ($pathVolume, $pathDirString, $pathFile) = NaturalDocs::File->SplitPath($path);
356 my @pathDirectories = NaturalDocs::File->SplitDirectories($pathDirString);
358 return ( $baseDirectories[-1] eq $pathDirectories[ scalar @baseDirectories - 1 ] );
366 # Function: ConvertToURL
368 # Takes a relative path and converts it from the native format to a relative URL. Note that it _doesn't_ convert special characters
371 sub ConvertToURL #(path)
373 my ($self, $path) = @_;
375 my ($pathVolume, $pathDirString, $pathFile) = $self->SplitPath($path);
376 my @pathDirectories = $self->SplitDirectories($pathDirString);
379 while ($i < scalar @pathDirectories && $pathDirectories[$i] eq File::Spec->updir())
381 $pathDirectories[$i] = '..';
385 return join('/', @pathDirectories, $pathFile);
390 # Function: NoUpwards
392 # Takes an array of directory entries and returns one without all the entries that refer to the parent directory, such as '.' and '..'.
394 sub NoUpwards #(array)
396 my ($self, @array) = @_;
397 return File::Spec->no_upwards(@array);
402 # Function: NoFileName
404 # Takes a path and returns a version without the file name. Useful for sending paths to <CreatePath()>.
406 sub NoFileName #(path)
408 my ($self, $path) = @_;
410 my ($pathVolume, $pathDirString, $pathFile) = File::Spec->splitpath($path);
412 return File::Spec->catpath($pathVolume, $pathDirString, undef);
417 # Function: NoExtension
419 # Returns the path without an extension.
421 sub NoExtension #(path)
423 my ($self, $path) = @_;
425 my $extension = $self->ExtensionOf($path);
428 { $path = substr($path, 0, length($path) - length($extension) - 1); };
435 # Function: ExtensionOf
437 # Returns the extension of the passed path, or undef if none.
439 sub ExtensionOf #(path)
441 my ($self, $path) = @_;
443 my ($pathVolume, $pathDirString, $pathFile) = File::Spec->splitpath($path);
445 # We need the leading dot in the regex so files that start with a dot but don't have an extension count as extensionless files.
446 if ($pathFile =~ /.\.([^\.]+)$/)
454 # Function: IsCaseSensitive
456 # Returns whether the current platform has case-sensitive paths.
460 return !(File::Spec->case_tolerant());
465 ###############################################################################
466 # Group: Disk Functions
470 # Function: CreatePath
472 # Creates a directory tree corresponding to the passed path, regardless of how many directories do or do not already exist.
473 # Do _not_ include a file name in the path. Use <NoFileName()> first if you need to.
475 sub CreatePath #(path)
477 my ($self, $path) = @_;
478 File::Path::mkpath($path);
483 # Function: RemoveEmptyTree
485 # Removes an empty directory tree. The passed directory will be removed if it's empty, and it will keep removing its parents
486 # until it reaches one that's not empty or a set limit.
490 # path - The path to start from. It will try to remove this directory and work it's way down.
491 # limit - The path to stop at if it doesn't find any non-empty directories first. This path will *not* be removed.
493 sub RemoveEmptyTree #(path, limit)
495 my ($self, $path, $limit) = @_;
497 my ($volume, $directoryString) = $self->SplitPath($path, 1);
498 my @directories = $self->SplitDirectories($directoryString);
500 my $directory = $path;
502 while (-d $directory && $directory ne $limit)
504 opendir FH_ND_FILE, $directory;
505 my @entries = readdir FH_ND_FILE;
508 @entries = $self->NoUpwards(@entries);
510 if (scalar @entries || !rmdir($directory))
514 $directoryString = $self->JoinDirectories(@directories);
515 $directory = $self->JoinPath($volume, $directoryString);
523 # Copies a file from one path to another. If the destination file exists, it is overwritten.
527 # source - The file to copy.
528 # destination - The destination to copy to.
532 # Whether it succeeded
534 sub Copy #(source, destination) => bool
536 my ($self, $source, $destination) = @_;
537 return File::Copy::copy($source, $destination);