Dependencies

Annotate this POD

# CPAN RT

 New 2 Open 1
View/Report Bugs

# SYNOPSIS

The Badger::Filesystem module defines a number of importable constructor functions for creating objects that represents files, directories and generic paths in a filesystem.

    use Badger::Filesystem 'cwd Cwd Path File Dir Directory';
use Badger::Filesystem 'cwd :types';        # same thing

# cwd returns current working directory as text string,
# Cwd return it as a Badger::Filesystem::Directory object
print cwd;                                  # /path/to/cwd
print Cwd->parent;                          # /path/to

# native OS-specific paths:
$path = Path('/path/to/file/or/dir');$file = File('/path/to/file');
$dir = Dir('/path/to/directory'); # short name$dir  = Directory('/path/to/directory');     # long name

# or generic OS-independant paths
$path = File('path', 'to', 'file', 'or', 'dir');$file = File('path', 'to', 'file');
$dir = Dir('path', 'to', 'directory');$dir  = Directory('path', 'to', 'directory');

These constructor functions are simply shortcuts to Badger::Filesystem class methods.

    use Badger::Filesystem;

# we'll just show native paths from now on for brevity
$path = Badger::Filesystem->path('/path/to/file/or/dir');$file = Badger::Filesystem->file('/path/to/file');
$dir = Badger::Filesystem->dir('/path/to/directory'); # 'FS' is an alias for 'Badger::Filesystem' 4 lzy ppl lk me use Badger::Filesystem 'FS'$path = FS->path('/path/to/file/or/dir');
$file = FS->file('/path/to/file');$dir  = FS->dir('/path/to/directory');

You can also create Badger::Filesystem objects.

my $dir = Dir('/path/to/directory'); # Badger::Filesystem::Directory The File() and Dir() subroutines are used to create Badger::Filesystem::File and Badger::Filesystem::Directory objects. You should read the documentation for those modules first as they cover pretty much everything you need to know about working with files and directories for simple day-to-day tasks. In fact, you should start with the documentation for Badger::Filesystem::Path because that's the base class for both of them. If you want to do something a little more involved than inspecting, reading and writing files, or if you want to find out more about the filesystem functionality hidden behind the file and directory objects, then read on! # DESCRIPTION The Badger::Filesystem module defines an object class for accessing and manipulating files and directories in a file system. It provides a number of methods that encapsulate the behaviours of various other filesystem related modules, including File::Spec, File::Path, IO::File, IO::Dir and Cwd. For example:  # path manipulation my$dir  = Badger::Filesystem->join_dir('foo', 'bar', 'baz');

# path inspection

# file manipulation

# directory manipulation
Badger::Filesystem->mkdir('/path/to/dir')

If you get tired of writing Badger::Filesystem over and over again, you can import the FS symbol which is an alias to it (or you can define your own alias of course).

    use Badger::Filesystem 'FS';

FS->is_relative('foo/bar/baz');     # true
FS->is_absolute('foo/bar/baz');     # false

The Badger::Filesystem module also defines methods that create objects to represent files (Badger::Filesystem::File), directories (Badger::Filesystem::Directory), and generic paths (Badger::Filesystem::Path) that may refer to a file, directory, or a resource that doesn't physically exist (e.g. a URI).

These are very similar (although not identical) to the corresponding Path::Class modules which you may already be familiar with. The main difference between them is that Badger files, directories and paths are flyweight objects that call back to the Badger::Filesystem to perform any filesystem operations. This gives us a more control over restricting certain filesystem operations (e.g. writing files) and more flexibility in what we define a filesystem to be (e.g. allowing virtually mounted and/or composite file systems - see Badger::Filesystem::Virtual for further details).

    use Badger::Filesystem 'FS';

# file manipulation - via Badger::Filesystem::File object
my $file = FS->file('/path/to/file'); print$file->size;                  # metadata
print $file->modified; # more metadata my$text = $file->read; # read file content$file->write("New content");        # write file content

# directory manipulation - via Badger::Filesystem::Directory object
my $dir = FS->directory('/path/to/dir'); print$dir->mode;                   # metadata
print $dir->modified; # more metadata my @entries =$dir->read;           # read directory entries
my $file =$dir->file('foo');       # fetch a file
my $sub =$dir->dir('bar');        # fetch a sub-directory

The module also defines the Path(), File() and Directory() subroutines to easily create Badger::Filesystem::Path, Badger::Filesystem::File and Badger::Filesystem::Directory objects, respectively. The Dir subroutine is provided as an alias for Directory.

    use Badger::Filesystem 'Path File Dir';

my $path = Path('/any/generic/path'); my$file = File('/path/to/file');
my $dir = Dir('/path/to/dir'); These subroutines are provided as a convenient way to call the path(), file() and dir() class methods. The above examples are functionally equivalent to those shown below.  use Badger::Filesystem; my$path = Badger::Filesystem->path('/any/generic/path');
my $file = Badger::Filesystem->file('/path/to/file'); my$dir  = Badger::Filesystem->dir('/path/to/dir');

The constructor subroutines and the corresponding methods behind them accept a list (or reference to a list) of path components as well as a single path string. This allows you to specify paths in an operating system agnostic manner.

    # these all do the same thing (assuming you're on a Unix-like system)
File('/path/to/file');
File('path', 'to', 'file');
File(['path', 'to', 'file']);

# these too
Badger::Filesystem->file(['path', 'to', 'file']);

The above examples assume a Unix-like filesystem using / as the path separator. On a windows machine, for example, you would need to specify paths using backslashes to satisfy their brain-dead file system. However, specifying a list of separate path components remains portable.

    # if you're stuck on windows :-(
File('\path\to\file');                  # OS specific
File('path', 'to', 'file');             # OS agnostic

If you're using Perl on a windows machine then you should probably consider getting a new machine. Try a nice shiny Mac, or an Ubuntu box. Go on, you know you deserve better.

You can also create a Badger::Filesystem object and call object methods against it.

    use Badger::Filesystem;

my $fs = Badger::Filesystem->new; my$file = $fs->file('/path/to/file'); my$dir  = $fs->dir('/path/to/dir'); Creating an object allows you to define additional configuration parameters for the filesystem. There aren't any interesting paramters worth mentioning in the base class Badger::Filesystem module at the moment, but subclasses (like Badger::Filesystem::Virtual) do use them. # EXPORTABLE SUBROUTINES The Badger::Filesystem module defines the Path, File and Directory subroutines which can be used to create Badger::Filesystem::Path, Badger::Filesystem::File and Badger::Filesystem::Directory objects, respectively. The Dir subroutine is provided as an alias for Directory. To use these subroutines you must import them explicitly when you use Badger::Filesystem.  use Badger::Filesystem 'File Dir'; my$file = File('/path/to/file');
my $dir = Dir('/path/to/dir'); You can specify multiple items in a single string as shown in the example above, or as multiple items in more traditional Perl style, as shown below.  use Badger::Filesystem qw(File Dir); You can pass multiple arguments to these subroutines if you want to specify your path in a platform-agnostic way.  my$file = File('path', 'to, 'file');
my $dir = Dir('path', 'to', 'dir'); A reference to a list works equally well.  my$file = File(['path', 'to, 'file']);
my $dir = Dir(\@paths); If you don't provide any arguments then the subroutines return the class name associated with the object. For example, the File() subroutine returns Badger::Filesystem::File. This allows you to use them as virtual classes, (i.e. short-cuts) for the longer class names, if doing things the Object Oriented way is your thing.  my$file = File->new('path/to/file');
my $dir = Dir->new('path/to/dir'); The above examples are functionally identical to:  my$file = Badger::Filesystem::File->new('path/to/file');
$dir = Dir('path', 'to', 'dir'); ## Cwd() This returns a Badger::Filesystem::Directory object for the current working directory.  use Badger::Filesystem 'Cwd'; print Cwd; # /foraging/for/nuts/and/berries print Cwd->parent; # /foraging/for/nuts/and ## Bin() This returns a Badger::Filesystem::Directory object for the directory in which the currently executing script is located. It is a simple wrapper around the value defined in$Bin.

    use Badger::Filesystem 'Bin';

print Bin;              # /path/to/current/script
print Bin->parent;      # /path/to/current

## cwd()

This returns a simple text string representing the current working directory. It is a a wrapper around the getcwd function in Cwd. It also sanitises the path (via the canonpath() function in File::Spec) to ensure that the path is returned in the local filesystem convention (e.g. / is converted to \ on Win32).

## $Bin This load the FindBin module and exports the $Bin variable into the caller's namespace.

    use Badger::Filesystem '$Bin'; use lib "$Bin/../lib";

This is exactly the same as:

    use FindBin '$Bin'; use lib "$Bin/../lib";

One benefit is that you can use it in conjunction with other import options to save on a little typing. For example:

    use Badger::Filesystem 'Cwd File $Bin'; Compared to something like:  use Cwd; use Path::Class; use FindBin '$Bin';
use lib "$Bin/../lib"; ## getcwd() This is a direct alias to the getcwd function in Cwd. ## :types Import Option Specifying this an an import option will export all of the Path(), File, Dir, Directory and Cwd subroutines to the caller.  use Badger::Filesystem ':types'; my$path   = Path('/some/where');
my $dir = Dir('/over/there'); my$file   = File('example.html');
my $parent = Cwd->parent; # CONSTRUCTOR METHODS ## new(%config) This is a constructor method to create a new Badger::Filesystem object.  my$fs = Badger::Filesystem->new;

In most cases there's no need to create a Badger::Filesystem object at all. You can either call class methods, like this:

    my $file = Badger::Filesystem->file('/path/to/file'); Or use the constructor subroutines like this:  use Badger::Filesystem 'File'; my$file = File('/path/to/file');

However, you might want to create a filesystem object to pass to some other method or object to work with. In that case, the Badger::Filesystem methods work equally well being called as object or class methods.

You may also want to use a subclass of Badger::Filesystem such as Badger::Filesystem::Virtual which requires configuration parameters to be properly initialised.

## path(@path)

Creates a new Badger::Filesystem::Path object. This is typically used for manipulating paths that don't relate to a specific file or directory in a real filesystem.

    # single path (platform specific)
my $path =$fs->path('/path/to/something');

# list or list ref of path components (platform agnostic)
my $path =$fs->path('path', 'to', 'something');
my $path =$fs->path(['path', 'to', 'something']);

## file(@path)

Creates a new Badger::Filesystem::File object to represent a file in a filesystem.

    # single file path (platform specific)
my $file =$fs->file('/path/to/file');

# list or list ref of file path components (platform agnostic)
my $file =$fs->file('path', 'to', 'file');
my $file =$fs->file(['path', 'to', 'file']);

## dir(@path) / directory(@path)

Creates a new Badger::Filesystem::Directory object to represent a file in a filesystem. dir() is an alias for directory() to save on typing.

    # single directory path (platform specific)
my $dir =$fs->dir('/path/to/directory');

# list or list ref of directory path components (platform agnostic)
my $dir =$fs->dir('path', 'to', 'directory');
my $dir =$fs->dir(['path', 'to', 'directory']);

If you don't specify a directory path explicitly then it will default to the current working directory, as returned by cwd().

    my $cwd =$fs->dir;

# PATH MANIPULATION METHODS

## merge_paths($path1,$path2)

Joins two paths into one.

    $fs->merge_paths('/path/one', 'path/two'); # /path/one/path/two No attempt will be made to verify that the second argument is an absolute path. In fact, it is considered a feature that this method will do its best to merge two paths even if they look like they shouldn't go together (this is particularly relevant when using virtual filesystems - see Badger::Filesystem::Virtual) $fs->merge_paths('/path/one', '/path/two');     # /path/one/path/two

If either defines a volume then it will be used as the volume for the combined path. If both paths define a volume then it must be the same or an error will be thrown.

    $fs->merge_paths('C:\path\one', 'path\two'); # C:\path\one\path\two$fs->merge_paths('\path\one', 'C:\path\two');   # C:\path\one\path\two
$fs->merge_paths('C:\path\one', 'C:\path\two'); # C:\path\one\path\two ## split_path($path)

Splits a composite path into volume, directory name and file name components. This is a wrapper around the splitpath() function in File::Spec.

    ($vol,$dir, $file) =$fs->split_path($path); ## join_path($volume, $dir,$file)

Combines a filesystem volume (where applicable), directory name and file name into a single path. This is a wrapper around the catpath() and canonpath() functions in File::Spec.

    my $path =$fs->join_path($volume,$directory, $file); ## split_dir($dir) / split_directory($dir) Splits a directory path into individual directory names. This is a wrapper around the splitdir() function in File::Spec.  @dirs =$fs->split_dir($dir); ## join_dir(@dirs) / join_directory(@dirs) Combines multiple directory names into a single path. This is a wrapper around the catdir() function in File::Spec.  my$dir = $fs->join_dir('path', 'to', 'my', 'dir'); The final element can also be a file name. TODO: is that portable?  my$dir = $fs->join_dir('path', 'to', 'my', 'file'); ## collapse_dir($dir) / collapse_directory($dir) Reduces a directory to its simplest form by resolving and removing any . (current directory) and .. (parent directory) components (or whatever the corresponding tokens are for the current and parent directories of your filesystem).  print$fs->collapse_dir('/foo/bar/../baz');   # /foo/baz

The reduction is purely syntactic. No attempt is made to verify that the directories exist, or to intelligently resolve parent directory where symbolic links are involved.

Note that this may not work portably across all operating systems. If you're using a Unix-based filesystem (including Mac OSX) or MS Windows then you should be OK. If you're using an old MacOS machine (pre-OSX), VMS, or something made out of clockwork, then be warned that this method is untested on those platforms.

collapse_dir() is a direct alias of collapse_directory() to save on typing.

    print $fs->slash_directory('foo'); # foo/ # PATH INSPECTION METHODS ## is_absolute($path)

Returns true if the path specified is absolute. That is, if it starts with a /, or whatever the corresponding token for the root directory is for your file system.

    $fs->is_absolute('/foo'); # true$fs->is_absolute('foo');                # false

$fs->is_relative('foo'); # true # PATH CONVERSION METHODS ## absolute($path, $base) Converts a relative path to an absolute one. The path passed as an argument is assumed to be relative to the current working directory unless you explicitly provide a $base parameter.

    $fs->cwd; # /foo/bar (for example)$fs->absolute('baz');                   # /foo/bar/baz
$fs->absolute('baz', '/wam/bam'); # /wam/bam/baz Note how potentially confusing that last example is. The base path is the second argument which ends up in front of the first argument. It's an unfortunately consequence of the way the parameters are ordered (the optional parameter must come after the mandatory one) and can't be avoided. ## relative($path, $base) Converts an absolute path to a relative one. It is assumed to be relative to the current working direct unless you explicitly provide a $base parameter.

    $fs->cwd; # /foo/bar (for example)$fs->relative('/foo/bar/wam/bam');      # wam/bam
$fs->relative('/baz/wam/bam', '/baz'); # wam/bam Again note that last example where ## definitive($path)

Converts an absolute or relative path to a definitive one. In most cases, a definitive path is identical to an absolute one.

    $fs->definitive('/foo/bar'); # /foo/bar However, if you're using a virtual filesystem with a virtual root directory, then a definitive path will include the virtual root directory, whereas a an absolute path will not.  my$vfs = Badger::Filesystem::Virtual->new( root => '/my/vfs' );
$vfs->absolute('/foo/bar'); # /foo/bar$vfs->definitive('/foo/bar');            # /my/vfs/foo/bar

The Badger::Filesystem module uses definitive paths when performing any operations on the file system (e.g. opening and reading files and directories). You can think of absolute paths as being like conceptual URIs (identifiers) and definitive paths as being like concrete URLs (locators). In practice, they'll both have the same value unless unless you're using a virtual file system.

In the Badger::Filesystem base class, the definitive() method is mapped directly to the definitive_write() method. This has no real effect in this module, but provides the relevant hooks that allow the Badger::Filesystem::Virtual subclass to work properly.

## definitive_read($path) Converts an absolute or relative path to a definitive one for a read operation. See definitive(). ## definitive_write($path)

Converts an absolute or relative path to a definitive one for a write operation. See definitive().

# PATH TEST METHODS

## path_exists($path) Returns true if the path exists, false if not. ## file_exists($path)

Returns true if the path exists and is a file, false if not.

## dir_exists($path) / directory_exists($path)

Returns true if the path exists and is a directory, false if not.

## stat_path($path) Performs a stat() on the filesystem path. It returns a list (in list context) or a reference to a list (in scalar context) containing 17 items. The first 13 are those returned by Perl's inbuilt stat() function. The next 3 items are flags indicating if the file is readable, writeable and/or executable. The final item is a flag indicating if the file is owned by the current user (i.e. owner of the current process. A summary of the fields is shown below. See perldoc -f stat and the stat() method in Badger::Filesystem::Path for further details.  Field Description -------------------------------------------------------- 0 device number of filesystem 1 inode number 2 file mode (type and permissions) 3 number of (hard) links to the file 4 numeric user ID of file’s owner 5 numeric group ID of file’s owner 6 the device identifier (special files only) 7 total size of file, in bytes 8 last access time in seconds since the epoch 9 last modify time in seconds since the epoch 10 inode change time in seconds since the epoch (*) 11 preferred block size for file system I/O 12 actual number of blocks allocated 13 file is readable by current process 14 file is writeable by current process 15 file is executable by current process 16 file is owned by current process ## chmod_path($path)

Changes the file permissions on a path.

    $fs->chmod_path('/path/to/file', 0755); # FILE MANIPULATION METHODS ## create_file($path)

Creates an empty file if it doesn't already exist. Returns a true value if the file is created and a false value if it already exists. Errors are thrown as exceptions.

## open_file($path,$mode, $perms) Opens a file for reading (by default) or writing/appending (by passing $mode and optionally $perms). Accepts the same parameters as for the IO::File::open() method and returns an IO::File object.  my$fh = $fs->open_file('/path/to/file'); my$fh = $fs->open_file('/path/to/file', 'w'); my$fh = $fs->open_file('/path/to/file', 'w', 0644); ## read_file($path)

Reads the content of a file, returning it as a list of lines (in list context) or a single text string (in scalar context).

    my $text =$fs->read_file('/path/to/file');
my @lines = $fs->read_file('/path/to/file'); ## write_file($path, @content)

When called with a single $path argument, this method opens the specified file for writing and returns an IO::File object.  my$fh = $fs->write_file('/path/to/file');$fh->print("Hello World!\n");
$fh->close; If any additional @content argument(s) are passed then they will be written to the file. The file is then closed and a true value returned to indicate success. Errors are thrown as exceptions. $fs->write_file('/path/to/file', "Hello World\n", "Regards, Badger\n");

## append_file($path, @content) This method is similar to write_file(), but opens the file for appending instead of overwriting. When called with a single $path argument, it opens the file for appending and returns an IO::File object.

    my $fh =$fs->append_file('/path/to/file');
$fh->print("Hello World!\n");$fh->close;

If any additional @content argument(s) are passed then they will be appended to the file. The file is then closed and a true value returned to indicate success. Errors are thrown as exceptions.

    $fs->append_file('/path/to/file', "Hello World\n", "Regards, Badger\n"); ## copy_file($from, $to, %params) Copies a file from the $from path to the $to path, using File::Copy $fs->copy_file($from,$to);

The $from and $to arguments can be file names, file objects, or file handles.

An optional list or reference to a hash array of named parameters can follow the file names. The mkdir option can be set to indicate that the destination direction should be created if it doesn't already exist, along with any intermediate directories.

    $fs->copy_file($from, $to, mkdir => 1); The dir_mode parameter can be used to specify the octal file permissions for any directories created. $fs->copy_file($from,$to, 1, mkdir => 1, dir_mode => 0770);

The file_mode parameter (or mode for short) can be used to specify the octal file permissions for the created file.

    $fs->copy_file($from, $to, file_mode => 0644); ## move_file($from, $to, %params) Moves a file from the $from path to the $to path, using File::Copy. The arguments are as per copy_file(). # DIRECTORY MANIPULATION METHODS ## create_dir($path) / create_directory($path) / mkdir($path)

Creates the directory specified by $path. Errors are thrown as exceptions. $fs->create_dir('/path/to/directory');

Additional arguments can be specified as per the File::Path mkpath() method. NOTE: this is subject to change. Better to use File::Path directly for now if you're relying on this.

}

## read_dir($dir,$all) / read_directory($dir,$all)

Returns a list (in list context) or a reference to a list (in scalar context) containing the entries in the directory. These are simple text strings containing the names of the files and/or sub-directories in the directory.

    my @paths = $fs->read_dir('/path/to/directory'); By default, this excludes the current and parent entries (. and .. or whatever the equivalents are for your filesystem. Pass a true value for the optional second argument to include these items.  my @paths =$fs->read_dir('/path/to/directory', 1);

Returns a list (in list context) or a reference to a list (in scalar context) of objects to represent the contents of a directory. As per read_dir(), the current (.) and parent (..) directories are excluded unless you set the $all flag to a true value. Files are returned as Badger::Filesystem::File objects, directories as Badger::Filesystem::File objects. Anything else is returned as a generic Badger::Filesystem::Path object. ## dir_child($path) / directory_child($path) Returns an object to represent a single item in a directory. Files are returned as Badger::Filesystem::File objects, directories as Badger::Filesystem::File objects. Anything else is returned as a generic Badger::Filesystem::Path object. # TEMPORARY DIRECTORY AND FILE METHODS ## temp_dir($dir) / temp_directory($dir) This returns a reference to a Badger::Filesystem::Directory object for the temporary directory on your system (as reported by tmpdir in File::Spec).  my$tmp = $fs->temp_dir; If any arguments are specified then they are appended as sub-directories to the temporary directory path.  my$tmp = $fs->temp_dir('foo', 'bar'); # e.g. /tmp/foo/bar  ## temp_file($name)

This returns a reference to a Badger::Filesystem::File object for a named file created in the temporary directory returned by the temp_directory() method.

    my $file =$fs->temp_file('foo.tmp');   # e.g. /tmp/foo.tmp

# VISITOR METHODS

## visitor(\%params)

This method creates a Badger::Filesystem::Visitor object from the arguments passed as a list or reference to a hash array of named parameters.

    # list of named parameters.
$fs->visitor( files => 1, dirs => 0 ); # reference to hash array of named parameters$fs->visitor( files => 1, dirs => 0 );

If the first argument is already a reference to a Badger::Filesystem::Visitor object or subclass then it will be returned unmodified.

## visit(\%params)

This methods forwards all arguments onto the visit() method of the root() directory.

# long form

## updir

Returns a text string containing the representation of the parent directory for your filesystem.

## separator

Returns a text string containing the representation of the path separator for your filesystem.

    print \$fs->separator;           # e.g. '/' on Unix-based file systems

## spec

Returns a text string containing the class name of File::Spec or some other user-definable module that implements the same functionality. This is used internally for splitting and joining file paths.

# EXPORTABLE CONSTANTS

## FS

An alias for Badger::Filesystem

## PATH

An alias for Badger::Filesystem::Path

## FILE

An alias for Badger::Filesystem::File

## DIR / DIRECTORY

An alias for Badger::Filesystem::Directory

# AUTHOR

Andy Wardley http://wardley.org/

This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

# ACKNOWLEDGEMENTS

The Badger::Filesystem modules are built around a number of Perl modules written by some most excellent people. May the collective gratitude of the Perl community shine forth upon them.

File::Spec by Ken Williams, Kenneth Albanowski, Andy Dougherty, Andreas Koenig, Tim Bunce, Charles Bailey, Ilya Zakharevich, Paul Schinder, Thomas Wegner, Shigio Yamaguchi, Barrie Slaymaker.

File::Path by Tim Bunce and Charles Bailey.

Cwd by Ken Williams and the Perl 5 Porters.

IO::File and IO::Dir by Graham Barr.

It was also inspired by, and draws heavily on the ideas and code in Path::Class by Ken Williams. There's also more than a passing influence from the Template::Plugin::File and Template::Plugin::Directory modules which were based on code originally by Michael Stevens.