speed up ==, hash, <, >, <=, and >= for plain_data
[nmutil.git] / src / nmutil / toolchain.py
1 import os
2 import shutil
3
4
5 __all__ = ["ToolNotFound", "tool_env_var", "has_tool", "require_tool"]
6
7
8 class ToolNotFound(Exception):
9 pass
10
11
12 def tool_env_var(name):
13 return name.upper().replace("-", "_").replace("+", "X")
14
15
16 def _get_tool(name):
17 return os.environ.get(tool_env_var(name), name)
18
19
20 def has_tool(name):
21 return shutil.which(_get_tool(name)) is not None
22
23
24 def require_tool(name):
25 env_var = tool_env_var(name)
26 path = _get_tool(name)
27 if shutil.which(path) is None:
28 if env_var in os.environ:
29 raise ToolNotFound("Could not find required tool {} in {} as "
30 "specified via the {} environment variable".
31 format(name, path, env_var))
32 else:
33 raise ToolNotFound("Could not find required tool {} in PATH. Place "
34 "it directly in PATH or specify path explicitly "
35 "via the {} environment variable".
36 format(name, env_var))
37 return path