core/homeassistant/scripts/__init__.py

78 lines
2.3 KiB
Python
Raw Normal View History

"""Home Assistant command line scripts."""
import argparse
import asyncio
import importlib
import logging
import os
import sys
2019-09-20 15:23:34 +00:00
from typing import List, Optional, Sequence, Text
from homeassistant import runner
from homeassistant.bootstrap import async_mount_local_lib_path
from homeassistant.config import get_default_config_dir
from homeassistant.requirements import pip_kwargs
from homeassistant.util.package import install_package, is_installed, is_virtual_env
2019-09-20 15:23:34 +00:00
# mypy: allow-untyped-defs, no-warn-return-any
2019-07-31 19:25:30 +00:00
def run(args: List) -> int:
"""Run a script."""
2016-08-01 03:58:39 +00:00
scripts = []
path = os.path.dirname(__file__)
for fil in os.listdir(path):
2019-07-31 19:25:30 +00:00
if fil == "__pycache__":
2016-08-01 03:58:39 +00:00
continue
if os.path.isdir(os.path.join(path, fil)):
2016-08-01 03:58:39 +00:00
scripts.append(fil)
2019-07-31 19:25:30 +00:00
elif fil != "__init__.py" and fil.endswith(".py"):
2016-08-01 03:58:39 +00:00
scripts.append(fil[:-3])
if not args:
2019-07-31 19:25:30 +00:00
print("Please specify a script to run.")
print("Available scripts:", ", ".join(scripts))
return 1
if args[0] not in scripts:
2019-07-31 19:25:30 +00:00
print("Invalid script specified.")
print("Available scripts:", ", ".join(scripts))
return 1
script = importlib.import_module(f"homeassistant.scripts.{args[0]}")
config_dir = extract_config_dir()
loop = asyncio.get_event_loop()
if not is_virtual_env():
loop.run_until_complete(async_mount_local_lib_path(config_dir))
_pip_kwargs = pip_kwargs(config_dir)
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
2018-01-30 11:30:47 +00:00
2019-07-31 19:25:30 +00:00
for req in getattr(script, "REQUIREMENTS", []):
if is_installed(req):
continue
if not install_package(req, **_pip_kwargs):
2019-07-31 19:25:30 +00:00
print("Aborting script, could not install dependency", req)
return 1
asyncio.set_event_loop_policy(runner.HassEventLoopPolicy(False))
return script.run(args[1:]) # type: ignore
2019-09-20 15:23:34 +00:00
def extract_config_dir(args: Optional[Sequence[Text]] = None) -> str:
"""Extract the config dir from the arguments or get the default."""
parser = argparse.ArgumentParser(add_help=False)
2019-07-31 19:25:30 +00:00
parser.add_argument("-c", "--config", default=None)
2019-09-20 15:23:34 +00:00
parsed_args = parser.parse_known_args(args)[0]
2019-07-31 19:25:30 +00:00
return (
2019-09-20 15:23:34 +00:00
os.path.join(os.getcwd(), parsed_args.config)
if parsed_args.config
2019-07-31 19:25:30 +00:00
else get_default_config_dir()
)