package Local::Util; # Copyright (C) 2019 Sean Whitton # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . use strict; use warnings; use Exporter 'import'; our @EXPORT_OK = qw(as_root executable_find); # Prefix a command if that's necessary to run it as root. Currently # supports only sudo(1). If passed more than one argument, prepends # this list with 'sudo'. If passed a single string argument, returns # a list or a string depending on context and whether the string # argument contains spaces sub as_root { my $context = wantarray(); return unless defined $context; if (@_ == 0) { return $context ? () : ""; } elsif (@_ == 1) { my $prepend = $context && $_[0] !~ /\s/; if ($> == 0) { return $prepend ? @_ : $_[0]; } else { return $prepend ? ("sudo", @_) : "sudo ".$_[0]; } } else { # Ignore context in this case, because joining the list of # arguments into a single string completely correctly is # fairly involved return $> == 0 ? @_ : ("sudo", @_); } } =head executable_find($name) Return the full path to $name if it is on PATH, else error. =cut sub executable_find { chomp(my $output = `sh -c "command -v $_[0]"`); $? == 0 ? return $output : die "$_[0] not found on PATH" } 1;