2019-08-28 05:32:18 -06:00
|
|
|
import os
|
2019-08-30 17:27:22 -06:00
|
|
|
import shutil
|
2019-08-28 05:32:18 -06:00
|
|
|
|
|
|
|
|
2019-10-13 07:53:24 -06:00
|
|
|
__all__ = ["ToolNotFound", "tool_env_var", "has_tool", "require_tool"]
|
2019-08-30 17:27:22 -06:00
|
|
|
|
|
|
|
|
|
|
|
class ToolNotFound(Exception):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
2019-10-13 07:53:24 -06:00
|
|
|
def tool_env_var(name):
|
2021-07-16 11:16:56 -06:00
|
|
|
return name.upper().replace("-", "_").replace("+", "X")
|
2019-08-28 05:32:18 -06:00
|
|
|
|
|
|
|
|
2019-10-13 07:53:24 -06:00
|
|
|
def _get_tool(name):
|
|
|
|
return os.environ.get(tool_env_var(name), name)
|
2019-08-30 17:27:22 -06:00
|
|
|
|
|
|
|
|
|
|
|
def has_tool(name):
|
2019-10-13 07:53:24 -06:00
|
|
|
return shutil.which(_get_tool(name)) is not None
|
2019-08-30 17:27:22 -06:00
|
|
|
|
|
|
|
|
|
|
|
def require_tool(name):
|
2019-10-13 07:53:24 -06:00
|
|
|
env_var = tool_env_var(name)
|
|
|
|
path = _get_tool(name)
|
2019-08-30 17:27:22 -06:00
|
|
|
if shutil.which(path) is None:
|
2019-10-13 07:53:24 -06:00
|
|
|
if env_var in os.environ:
|
|
|
|
raise ToolNotFound("Could not find required tool {} in {} as "
|
|
|
|
"specified via the {} environment variable".
|
|
|
|
format(name, path, env_var))
|
|
|
|
else:
|
2019-08-30 17:27:22 -06:00
|
|
|
raise ToolNotFound("Could not find required tool {} in PATH. Place "
|
|
|
|
"it directly in PATH or specify path explicitly "
|
|
|
|
"via the {} environment variable".
|
|
|
|
format(name, env_var))
|
|
|
|
return path
|