NAME

Doit::Util - utility functions for Doit

SYNOPSIS

use Doit::Util;
use Doit::Util qw(in_directory new_scope_cleanup copy_stat get_sudo_cmd get_os_release);

DESCRIPTION

FUNCTIONS

in_directory

in_directory {
   ... code ...
} $directory;

Temporary change to the specified $directory and execute the code in the enclosed block. After execution, the previous directory is restored. Dies if the specified $directory does not exist.

Note: commands like last or return apply to the enclosed block, not to the outer function. As this is confusing and the behavior may change it's best to avoid them.

new_scope_cleanup

{
    my $scope_cleanup = new_scope_cleanup(sub { say "This is printed when leaving the current block" });
    ... code ...
}
# at this point the cleanups are executed

Register a callback which is executed when leaving the current block — either at the end of the block, or when using return, goto or similar commands. Note that the return value of the new_scope_cleanup needs to be assigned to a lexical variable — if this lexical variable goes out of scope, then the callback will be executed.

copy_stat

copy_stat($source_file, $dest_file);
copy_stat($source_file, $dest_file, { ownership => 1, mode => 1, time => 1 });

Copy file properties from $source_file to $dest_file. By default, all possible properties (ownership: owner and group; mode; time: atime and mtime) are copied, but this can be limitted by specifying a third parameter as shown above.

If some of the properties cannot be copied, then just warnings will be issued.

get_sudo_cmd

Return an empty list if using sudo is not required (i.e. the current user is the root user), otherwise returns a list with sudo. Handy for writing commands like:

$doit->system(get_sudo_cmd(), 'apt-get', '-y', 'install', @missing_packages);

get_os_release

Return a hash reference of /etc/os-release contents, or undef if such a file does not exist. Usually the hash will contain keys like

ID => 'ubuntu',
VERSION_ID => '22.04'

The file is parsed only once and cached for subsequent calls. To force a cache refresh use the option

refresh => 1

To specify another file than /etc/os-release use the option

file => /path/to/another/os-release

This is probably only useful for test purposes.

AUTHOR

Slaven Rezic <srezic@cpan.org>

COPYRIGHT

Copyright (c) 2022,2023 Slaven Rezic. All rights reserved. This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

SEE ALSO

Doit, "stat EXPR" in perlfunc, sudo(8).