blob: 880cda9af3ffeba381c44b1764c931623cc9e77a (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
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 <https://www.gnu.org/licenses/>.
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;
|