2020-03-12 01:22:45 +01:00
|
|
|
from typing import Union
|
|
|
|
|
2019-04-17 12:06:00 +02:00
|
|
|
import collections
|
2018-11-03 14:06:14 +01:00
|
|
|
import io
|
|
|
|
import logging
|
2019-06-07 14:26:28 +02:00
|
|
|
import os
|
2018-11-03 14:06:14 +01:00
|
|
|
import re
|
2019-01-19 17:54:41 +01:00
|
|
|
import subprocess
|
2018-11-03 14:06:14 +01:00
|
|
|
import sys
|
|
|
|
|
2019-02-28 10:11:05 +01:00
|
|
|
from esphome import const
|
|
|
|
|
2018-11-03 14:06:14 +01:00
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
|
2018-10-20 12:41:00 +02:00
|
|
|
|
2019-12-07 18:28:55 +01:00
|
|
|
class RegistryEntry:
|
2019-04-22 21:56:30 +02:00
|
|
|
def __init__(self, name, fun, type_id, schema):
|
|
|
|
self.name = name
|
|
|
|
self.fun = fun
|
|
|
|
self.type_id = type_id
|
|
|
|
self.raw_schema = schema
|
|
|
|
|
|
|
|
@property
|
|
|
|
def coroutine_fun(self):
|
|
|
|
from esphome.core import coroutine
|
|
|
|
return coroutine(self.fun)
|
|
|
|
|
|
|
|
@property
|
|
|
|
def schema(self):
|
|
|
|
from esphome.config_validation import Schema
|
|
|
|
return Schema(self.raw_schema)
|
|
|
|
|
|
|
|
|
2018-10-16 23:16:06 +02:00
|
|
|
class Registry(dict):
|
2019-04-22 21:56:30 +02:00
|
|
|
def __init__(self, base_schema=None, type_id_key=None):
|
2019-12-07 18:28:55 +01:00
|
|
|
super().__init__()
|
2019-04-22 21:56:30 +02:00
|
|
|
self.base_schema = base_schema or {}
|
|
|
|
self.type_id_key = type_id_key
|
|
|
|
|
|
|
|
def register(self, name, type_id, schema):
|
2018-10-16 23:16:06 +02:00
|
|
|
def decorator(fun):
|
2019-04-22 21:56:30 +02:00
|
|
|
self[name] = RegistryEntry(name, fun, type_id, schema)
|
2018-10-16 23:16:06 +02:00
|
|
|
return fun
|
|
|
|
|
|
|
|
return decorator
|
|
|
|
|
|
|
|
|
2019-04-22 21:56:30 +02:00
|
|
|
class SimpleRegistry(dict):
|
|
|
|
def register(self, name, data):
|
2018-10-16 23:16:06 +02:00
|
|
|
def decorator(fun):
|
2019-04-22 21:56:30 +02:00
|
|
|
self[name] = (fun, data)
|
2018-10-16 23:16:06 +02:00
|
|
|
return fun
|
|
|
|
|
|
|
|
return decorator
|
2018-10-20 12:41:00 +02:00
|
|
|
|
|
|
|
|
|
|
|
def safe_print(message=""):
|
2019-02-13 16:54:02 +01:00
|
|
|
from esphome.core import CORE
|
2018-12-18 19:31:43 +01:00
|
|
|
|
|
|
|
if CORE.dashboard:
|
|
|
|
try:
|
|
|
|
message = message.replace('\033', '\\033')
|
|
|
|
except UnicodeEncodeError:
|
|
|
|
pass
|
|
|
|
|
2018-10-20 12:41:00 +02:00
|
|
|
try:
|
|
|
|
print(message)
|
|
|
|
return
|
|
|
|
except UnicodeEncodeError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
try:
|
2019-01-19 16:48:16 +01:00
|
|
|
print(message.encode('utf-8', 'backslashreplace'))
|
2018-10-20 12:41:00 +02:00
|
|
|
except UnicodeEncodeError:
|
2019-01-19 16:48:16 +01:00
|
|
|
try:
|
|
|
|
print(message.encode('ascii', 'backslashreplace'))
|
|
|
|
except UnicodeEncodeError:
|
|
|
|
print("Cannot print line because of invalid locale!")
|
2018-11-03 14:06:14 +01:00
|
|
|
|
|
|
|
|
|
|
|
def shlex_quote(s):
|
|
|
|
if not s:
|
2019-12-07 18:28:55 +01:00
|
|
|
return "''"
|
2018-11-03 14:06:14 +01:00
|
|
|
if re.search(r'[^\w@%+=:,./-]', s) is None:
|
|
|
|
return s
|
|
|
|
|
2019-12-07 18:28:55 +01:00
|
|
|
return "'" + s.replace("'", "'\"'\"'") + "'"
|
2018-11-03 14:06:14 +01:00
|
|
|
|
|
|
|
|
2019-10-19 14:04:14 +02:00
|
|
|
ANSI_ESCAPE = re.compile(r'\033[@-_][0-?]*[ -/]*[@-~]')
|
|
|
|
|
|
|
|
|
2019-12-07 18:28:55 +01:00
|
|
|
class RedirectText:
|
2019-10-19 14:04:14 +02:00
|
|
|
def __init__(self, out, filter_lines=None):
|
2018-12-18 19:31:43 +01:00
|
|
|
self._out = out
|
2019-10-19 14:04:14 +02:00
|
|
|
if filter_lines is None:
|
|
|
|
self._filter_pattern = None
|
|
|
|
else:
|
|
|
|
pattern = r'|'.join(r'(?:' + pattern + r')' for pattern in filter_lines)
|
|
|
|
self._filter_pattern = re.compile(pattern)
|
|
|
|
self._line_buffer = ''
|
2018-12-18 19:31:43 +01:00
|
|
|
|
|
|
|
def __getattr__(self, item):
|
|
|
|
return getattr(self._out, item)
|
|
|
|
|
2019-10-19 14:04:14 +02:00
|
|
|
def _write_color_replace(self, s):
|
2019-02-13 16:54:02 +01:00
|
|
|
from esphome.core import CORE
|
2018-12-18 19:31:43 +01:00
|
|
|
|
|
|
|
if CORE.dashboard:
|
2019-10-19 14:04:14 +02:00
|
|
|
# With the dashboard, we must create a little hack to make color output
|
|
|
|
# work. The shell we create in the dashboard is not a tty, so python removes
|
|
|
|
# all color codes from the resulting stream. We just convert them to something
|
|
|
|
# we can easily recognize later here.
|
|
|
|
s = s.replace('\033', '\\033')
|
2018-12-18 19:31:43 +01:00
|
|
|
self._out.write(s)
|
|
|
|
|
2019-10-19 14:04:14 +02:00
|
|
|
def write(self, s):
|
2019-12-07 18:28:55 +01:00
|
|
|
# s is usually a str already (self._out is of type TextIOWrapper)
|
2019-10-19 14:04:14 +02:00
|
|
|
# However, s is sometimes also a bytes object in python3. Let's make sure it's a
|
2019-12-07 18:28:55 +01:00
|
|
|
# str
|
2019-10-19 14:04:14 +02:00
|
|
|
# If the conversion fails, we will create an exception, which is okay because we won't
|
|
|
|
# be able to print it anyway.
|
2019-12-31 03:23:03 +01:00
|
|
|
if not isinstance(s, str):
|
|
|
|
s = s.decode()
|
2019-10-19 14:04:14 +02:00
|
|
|
|
|
|
|
if self._filter_pattern is not None:
|
2019-12-31 03:23:03 +01:00
|
|
|
self._line_buffer += s
|
2019-10-19 14:04:14 +02:00
|
|
|
lines = self._line_buffer.splitlines(True)
|
|
|
|
for line in lines:
|
|
|
|
if '\n' not in line and '\r' not in line:
|
|
|
|
# Not a complete line, set line buffer
|
|
|
|
self._line_buffer = line
|
|
|
|
break
|
|
|
|
self._line_buffer = ''
|
|
|
|
|
|
|
|
line_without_ansi = ANSI_ESCAPE.sub('', line)
|
|
|
|
line_without_end = line_without_ansi.rstrip()
|
|
|
|
if self._filter_pattern.match(line_without_end) is not None:
|
|
|
|
# Filter pattern matched, ignore the line
|
|
|
|
continue
|
|
|
|
|
|
|
|
self._write_color_replace(line)
|
|
|
|
else:
|
2019-12-31 03:23:03 +01:00
|
|
|
self._write_color_replace(s)
|
2019-10-19 14:04:14 +02:00
|
|
|
|
|
|
|
# write() returns the number of characters written
|
|
|
|
# Let's print the number of characters of the original string in order to not confuse
|
|
|
|
# any caller.
|
|
|
|
return len(s)
|
|
|
|
|
2018-12-18 19:31:43 +01:00
|
|
|
# pylint: disable=no-self-use
|
|
|
|
def isatty(self):
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
2020-03-12 01:22:45 +01:00
|
|
|
def run_external_command(func, *cmd,
|
|
|
|
capture_stdout: bool = False,
|
|
|
|
filter_lines: str = None) -> Union[int, str]:
|
|
|
|
"""
|
|
|
|
Run a function from an external package that acts like a main method.
|
|
|
|
|
|
|
|
Temporarily replaces stdin/stderr/stdout, sys.argv and sys.exit handler during the run.
|
|
|
|
|
|
|
|
:param func: Function to execute
|
|
|
|
:param cmd: Command to run as (eg first element of sys.argv)
|
|
|
|
:param capture_stdout: Capture text from stdout and return that.
|
|
|
|
:param filter_lines: Regular expression used to filter captured output.
|
|
|
|
:return: str if `capture_stdout` is set else int exit code.
|
|
|
|
|
|
|
|
"""
|
2018-11-03 14:06:14 +01:00
|
|
|
def mock_exit(return_code):
|
|
|
|
raise SystemExit(return_code)
|
|
|
|
|
|
|
|
orig_argv = sys.argv
|
|
|
|
orig_exit = sys.exit # mock sys.exit
|
2019-12-07 18:28:55 +01:00
|
|
|
full_cmd = ' '.join(shlex_quote(x) for x in cmd)
|
|
|
|
_LOGGER.info("Running: %s", full_cmd)
|
2018-11-03 14:06:14 +01:00
|
|
|
|
2019-01-02 12:15:13 +01:00
|
|
|
orig_stdout = sys.stdout
|
2019-10-19 14:04:14 +02:00
|
|
|
sys.stdout = RedirectText(sys.stdout, filter_lines=filter_lines)
|
2019-01-02 12:15:13 +01:00
|
|
|
orig_stderr = sys.stderr
|
2019-10-19 14:04:14 +02:00
|
|
|
sys.stderr = RedirectText(sys.stderr, filter_lines=filter_lines)
|
2018-12-18 19:31:43 +01:00
|
|
|
|
2018-11-03 14:06:14 +01:00
|
|
|
if capture_stdout:
|
2019-10-18 16:51:16 +02:00
|
|
|
cap_stdout = sys.stdout = io.StringIO()
|
2018-11-03 14:06:14 +01:00
|
|
|
|
|
|
|
try:
|
|
|
|
sys.argv = list(cmd)
|
|
|
|
sys.exit = mock_exit
|
|
|
|
return func() or 0
|
|
|
|
except KeyboardInterrupt:
|
|
|
|
return 1
|
|
|
|
except SystemExit as err:
|
|
|
|
return err.args[0]
|
|
|
|
except Exception as err: # pylint: disable=broad-except
|
2019-12-07 18:28:55 +01:00
|
|
|
_LOGGER.error("Running command failed: %s", err)
|
|
|
|
_LOGGER.error("Please try running %s locally.", full_cmd)
|
2019-11-14 12:42:50 +01:00
|
|
|
return 1
|
2018-11-03 14:06:14 +01:00
|
|
|
finally:
|
|
|
|
sys.argv = orig_argv
|
|
|
|
sys.exit = orig_exit
|
|
|
|
|
2019-01-02 12:15:13 +01:00
|
|
|
sys.stdout = orig_stdout
|
|
|
|
sys.stderr = orig_stderr
|
2018-12-18 19:31:43 +01:00
|
|
|
|
2018-11-03 14:06:14 +01:00
|
|
|
if capture_stdout:
|
|
|
|
# pylint: disable=lost-exception
|
2019-01-02 12:15:13 +01:00
|
|
|
return cap_stdout.getvalue()
|
2019-01-19 17:54:41 +01:00
|
|
|
|
|
|
|
|
|
|
|
def run_external_process(*cmd, **kwargs):
|
2019-12-07 18:28:55 +01:00
|
|
|
full_cmd = ' '.join(shlex_quote(x) for x in cmd)
|
|
|
|
_LOGGER.info("Running: %s", full_cmd)
|
2019-10-19 14:04:14 +02:00
|
|
|
filter_lines = kwargs.get('filter_lines')
|
2019-01-19 17:54:41 +01:00
|
|
|
|
|
|
|
capture_stdout = kwargs.get('capture_stdout', False)
|
|
|
|
if capture_stdout:
|
|
|
|
sub_stdout = io.BytesIO()
|
|
|
|
else:
|
2019-10-19 14:04:14 +02:00
|
|
|
sub_stdout = RedirectText(sys.stdout, filter_lines=filter_lines)
|
2019-01-19 17:54:41 +01:00
|
|
|
|
2019-10-19 14:04:14 +02:00
|
|
|
sub_stderr = RedirectText(sys.stderr, filter_lines=filter_lines)
|
2019-01-19 17:54:41 +01:00
|
|
|
|
|
|
|
try:
|
|
|
|
return subprocess.call(cmd,
|
|
|
|
stdout=sub_stdout,
|
|
|
|
stderr=sub_stderr)
|
|
|
|
except Exception as err: # pylint: disable=broad-except
|
2019-12-07 18:28:55 +01:00
|
|
|
_LOGGER.error("Running command failed: %s", err)
|
|
|
|
_LOGGER.error("Please try running %s locally.", full_cmd)
|
2019-11-14 12:42:50 +01:00
|
|
|
return 1
|
2019-01-19 17:54:41 +01:00
|
|
|
finally:
|
|
|
|
if capture_stdout:
|
|
|
|
# pylint: disable=lost-exception
|
|
|
|
return sub_stdout.getvalue()
|
2019-02-28 10:11:05 +01:00
|
|
|
|
|
|
|
|
|
|
|
def is_dev_esphome_version():
|
|
|
|
return 'dev' in const.__version__
|
2019-04-17 12:06:00 +02:00
|
|
|
|
|
|
|
|
|
|
|
# Custom OrderedDict with nicer repr method for debugging
|
|
|
|
class OrderedDict(collections.OrderedDict):
|
|
|
|
def __repr__(self):
|
|
|
|
return dict(self).__repr__()
|
|
|
|
|
2019-06-07 14:26:28 +02:00
|
|
|
|
|
|
|
def list_yaml_files(folder):
|
|
|
|
files = filter_yaml_files([os.path.join(folder, p) for p in os.listdir(folder)])
|
|
|
|
files.sort()
|
|
|
|
return files
|
|
|
|
|
|
|
|
|
|
|
|
def filter_yaml_files(files):
|
|
|
|
files = [f for f in files if os.path.splitext(f)[1] == '.yaml']
|
|
|
|
files = [f for f in files if os.path.basename(f) != 'secrets.yaml']
|
|
|
|
files = [f for f in files if not os.path.basename(f).startswith('.')]
|
|
|
|
return files
|