Debian Codegraph @

lib/ansible/module_utils/common/process.py

raw
1 # Copyright (c) 2018, Ansible Project
2 # Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause)
3
4 from __future__ import annotations
5
6 import os
7
8 from ansible.module_utils.common.file import is_executable
9
10
11 def get_bin_path(arg, opt_dirs=None):
12 """
13 Find system executable in PATH. Raises ValueError if the executable is not found.
14
15 :param arg: the executable to find
16 :type arg: string
17 :param opt_dirs: optional list of directories to search in addition to PATH
18 :type opt_dirs: list of strings
19 :returns: path to arg (should be absolute path unless PATH or opt_dirs are relative paths)
20 :raises: ValueError: if arg is not found
21
22 In addition to PATH and opt_dirs, this function also looks through /sbin, /usr/sbin and /usr/local/sbin. A lot of
23 modules, especially for gathering facts, depend on this behaviour.
24 """
25 paths = []
26 sbin_paths = ['/sbin', '/usr/sbin', '/usr/local/sbin']
27 opt_dirs = [] if opt_dirs is None else opt_dirs
28
29 # Construct possible paths with precedence
30 # passed in paths
31 for d in opt_dirs:
32 if d is not None and os.path.exists(d):
33 paths.append(d)
34 # system configured paths
35 paths += os.environ.get('PATH', '').split(os.pathsep)
36
37 # existing /sbin dirs, if not there already
38 for p in sbin_paths:
39 if p not in paths and os.path.exists(p):
40 paths.append(p)
41
42 # Search for binary
43 bin_path = None
44 for d in paths:
45 if not d:
46 continue
47 path = os.path.join(d, arg)
48 if os.path.exists(path) and not os.path.isdir(path) and is_executable(path):
49 # fist found wins
50 bin_path = path
51 break
52
53 if bin_path is None:
54 raise ValueError('Failed to find required executable "%s" in paths: %s' % (arg, os.pathsep.join(paths)))
55
56 return bin_path