NAME
CAF::Path - check that things are really the way we expect them to be
DESCRIPTION
Simplify common file and directory related operations e.g.
- directory creation
- cleanup
- (mockable) file/directory tests
The class is based on LC::Check with following major difference
CAF::Object::NoActionsupport builtin (andkeeps_stateoption to override it).- support Reporter (incl.
CAF::History) - raised exceptions are catched, methods return SUCCESS on succes,
undef on failure and store the error message in the
failattribute. - available as class-methods
- return values
- undef: failure occured
- SUCCESS: nothing changed (boolean true)
- CHANGED: something changed (boolean true).
Functions
-
mkcafpath
Returns an instance of Object and
CAF::Path. This instance is a simple way to useCAF::Pathwhen subclassing is not possible. Allowed options are<log =$logger>> and<NoAction =$noaction>>.This function is not exported, to be used as e.g. use CAF::Path; ... my $cafpath = CAF::Path::mkcafpath(log => $logger); if(! defined($cafpath->directory($name)) { $logger->error("Failed to make directory $name: $cafpath->{fail}"); };
Methods
-
_get_noaction
Return NoAction setting:
-
Return 0 is
keeps_stateis trueAny other value of
keeps_stateis ignored. (In particular, you cannot usekeeps_stateto enable NoAction). -
Return value of
CAF::Object::NoActionotherwise.
Supports an optional
msgthat is prefixed to reporter. -
-
_reset_exception_fail
Reset previous exceptions and/or fail attribute.
-
_function_catch
Execute function reference
funcrefwith arrayref$argsand hashref$opts.Method resets/ignores any existing errors and fail attribute, and catches any exception thrown. No error is reported, it returns undef in this case and the fail attribute is set.
-
_safe_eval
Run function reference
funcrefwith arrayrefargsrefand hashrefoptsref.Return and set fail attribute with
failmsgon die or an error (undefreturned byfuncref), or print (at verbose level)msgon success (respectively $@ and stringified result are appended). Note that_safe_evaldoesn't work with functions that don't return a defined value when they succeed.Resets previous exceptions and/or fail attribute
-
LC_Check
Execute function
<LC::Check::<function>> with arrayref$argsand hashref$opts.CAF::Object::NoActionis added to the options, unlesskeeps_stateis set.The function is executed with
_function_catch. -
_untaint_path
Untaint the path argument.
Returns undef on failure and sets the fail attribute with
msg -
directory_exists
Test if
directoryexists and is a directory.This is basically the perl builtin
-d, wrapped in a method to allow unittesting.If
directoryis a symlink, the symlink target is tested. If the symlink is broken (no target),directory_existsreturns false. -
file_exists
Test if
filenameexists and is a file.This is basically the perl builtin
-f, wrapped in a method to allow unittesting.If
filenameis a symlink, the symlink target is tested. If the symlink is broken (no target),file_existsreturns false. -
any_exists
Test if path exists.
This is basically the perl builtin
-e || -l, wrapped in a method to allow unittesting.A broken symlink (symlink whose target doesn't exist) exists:
any_existsreturns true. -
is_symlink
Test if path is a symlink.
Returns true as long as path is a symlink, including when the symlink target doesn't exist.
-
cleanup
cleanup removes
destwith backup support.(Works like
LC::Check::_unlink, but has directory support and no error throwing).Returns CHANGED is something was cleaned-up, SUCCESS if nothing was done and undef on failure (and sets the fail attribute).
The <backup> is a suffix for
dest.If backup is undefined, use
backupattribute. (Pass an empty string to disable backup withbackupattribute defined) Any previous backup iscleanuped (without backup). (Aside from thebackupattribute, this is the same asLC::Check::_unlink(and thus alsoCAF::File*)).Additional options
- keeps_state: boolean passed to
_get_noaction.
- keeps_state: boolean passed to
-
directory
Make sure a directory exists with proper options.
If the directory does not exists (or the
tempoption is set), it is created (including the parent directories as needed), and usesLC::Check::directoryviaLC_Check.Returns CHANGED if a change was made, SUCCESS if no changes were made and undef in case of failure (and the
failattribute is set).The return value in absence of failure is a dualvar with integer value SUCCESS/CHANGED, and the directory as string value (in particular relevant for temporary directories).
Additional options
- owner/group/mode/mtime : options for
CAF::Path::status -
temp
A boolean if true will create a a temporary directory using File::Temp::tempdir.
The directory name is the template to use (any trailing
Xcharacters will be replaced with random characters bytempdir; and the directory name will be padded up to at least 4X).The
CLEANUPoption is also set (an removal attempt (incl. any files and/or subdirectries) will be made at the end of the program). -
keeps_state: boolean passed to
_get_noaction.
- owner/group/mode/mtime : options for
-
_make_link
This method is mainly a wrapper over
LC::Check::linkreturning the standardCAF::Pathreturn values. Every option supported byLC::Check::linkis supported.NoActionflag is handled byLC::Check::linkandkeeps_stateoption is honored (overridesNoActionif true). One important difference is the order of the arguments:CAF::Path:_make_linkand the methods based on it are following the Perlsymlink(andlncommand) argument order.This is an internal method, not supposed to be called directly. Either call symlink or
hardlinkpublic methods instead. -
hardlink
Create a hardlink
link_pathwhose target istarget.On failure, returns undef and sets the fail attribute. If
link_pathexists and is a file, it is updated.targetmust exist (checkflag available in symlink() is ignored for hardlinks) and it must reside in the same filesystem aslink_path. Iftarget_pathis a relative path, it is interpreted from the current directory.link_nameparent directory is created if it doesn't exist.Returns SUCCESS on sucess if the hardlink already existed with the same target, CHANGED if the hardlink was created or updated, undef otherwise.
This method relies on
_make_linkmethod to do the real work, after enforcing the option saying that it is a hardlink. -
symlink
Create a symlink
link_pathwhose target istarget.Returns undef and sets the fail attribute if
link_pathalready exists and is not a symlink, except if this is a file and optionforceis defined and true. Iflink_pathexists and is a symlink, it is updated. By default, the target is not required to exist. If you want to ensure that it exists, define optioncheckto true. Bothlink_pathandtargetcan be relative paths:link_pathis interpreted as relatif to the current directory andtargetis kept relative.link_pathparent directory is created if it doesn't exist.Returns SUCCESS on sucess if the symlink already existed with the same target, CHANGED if the symlink was created or updated, undef otherwise.
This method relies on
_make_linkmethod to do the real work, after enforcing the option saying that it is a symlink. -
has_hardlinks
Method that returns the number of hardlinks for
file. The number of hardlinks is the number of entries referring to the inodes minus 1. Iffilehas no hardlink, the return value is 0. Iffileis not a file, the return value isundef. -
is_hardlink
This method returns SUCCESS if
path1andpath2refer to the same file (inode). It returns 0 ifpath1andpath2both exist but are different files or are the same path andundefif one of the paths doesn't exist or is not a file.Note: the result returned will be identical whatever is the order of
path1andpath2arguments. -
status
Set the path stat options:
owner,group,modeand/ormtime.This is a wrapper around
LC::Check::statusand executed withLC_Check.Returns CHANGED if a change was made, SUCCESS if no changes were made and undef in case of failure (and the
failattribute is set).Additional options
- keeps_state: boolean passed to
_get_noaction.
- keeps_state: boolean passed to
-
move
Move/rename
srctodest.The final goal is to make sure
srcdoes not exist anymore, not thatdestexists after move (in particular, ifsrcdoes not exist to start with, success is immediately returned, and no backup ofdestis created).The <backup> is a suffix for the cleanup of
dest(and passed tocleanupmethod).(The basedir of
destis created usingdirectorymethod.)Additional options
- keeps_state: boolean passed to
_get_noaction.
- keeps_state: boolean passed to
-
listdir
Return an arrayref of sorted directory entry names or undef on failure. (The
.and..are removed).Can be used to replace
glob()as follows:... foreach my $file (glob('/path/*.ext')) { ... replace by ... foreach my $file (@{$self->listdir('/path', filter => '\.ext$', adddir => 1)}) { ...Options
-
test
An (anonymous) sub used for testing. The return value is interpreted as boolean value for filtering the directory entry names (true value means the name is kept).
Accepts 2 arguments: first argument (
$_[0]) the directory entry name, 2nd argument ($_[1]) the directory. -
filter
A pattern or compiled pattern to filter directory entry names. Matching names are kept.
-
inverse
Apply inverse test (or filter) logic.
-
adddir
Prefix the directory to the returned filenames (default false).
-
file_exists
Shortcut for test function that uses
CAF::Path::file_existsas test function.
-