From b545b593857e53b27b6e9e98cf2fa4642ce79c1a Mon Sep 17 00:00:00 2001 From: Carsten Grohmann Date: Mon, 10 Jun 2024 21:44:36 +0200 Subject: [PATCH] Add support for quoted environment variables Environment variables with spaces in them must be quoted, otherwise `make run` will report `command not found`: ``` $ grep DEYE_HA_PLUGIN_INVERTER_MODEL config.env DEYE_HA_PLUGIN_INVERTER_MODEL=SUN300G3 EU 230 $ make run config.env: line 49: EU: command not found 2024-06-10 21:13:44,180 - DeyeDaemon - INFO - Please help me build the list of compatible inverters. https://github.com/kbialek/deye-inverter-mqtt/issues/41 2024-06-10 21:13:44,190 - DeyePluginLoader - INFO - Loading plugin: 'deye_plugin_ha_discovery' 2024-06-10 21:13:44,191 - DeyeConnectorFactory - INFO - Creating Modbus/TCP Logger connector [...] ``` With the quotation marks, the environment variables in Docker are slightly different: **Setup:** ``` $ grep DEYE_HA_PLUGIN_INVERTER_MODEL config.env DEYE_HA_PLUGIN_INVERTER_MODEL="SUN300G3 EU 230" ``` **Local Python** ``` $ strings /proc//environ | grep DEYE_HA_PLUGIN_INVERTER_MODEL DEYE_HA_PLUGIN_INVERTER_MODEL=SUN300G3 EU 230 ``` **Docker** ``` $ strings /proc//environ | grep DEYE_HA_PLUGIN_INVERTER_MODEL DEYE_HA_PLUGIN_INVERTER_MODEL="SUN300G3 EU 230" ``` This change addresses the different behavior of Docker compared to a Unix shell and removes single and double quotes only if they are the first and last character of the string. The functionality was added to `DeyeEnv.integer()` and `DeyeEnv.boolean()` for the sake of convenience to avoid problems with quotes that may occur later. --- src/deye_config.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/deye_config.py b/src/deye_config.py index e5c4eca..1e4363f 100644 --- a/src/deye_config.py +++ b/src/deye_config.py @@ -35,9 +35,19 @@ def process(self, msg, kwargs): class DeyeEnv: + @staticmethod + def unquote(value: str) -> str: + """Remove single and double quotes at the beginning and the end""" + if value and value[0] == '"' and value[-1] == '"': + value = value[1:-1] + elif value and value[0] == "'" and value[-1] == "'": + value = value[1:-1] + return value + @staticmethod def integer(env_var_name: str, default_value: int = None) -> int: value = os.getenv(env_var_name) + value = DeyeEnv.unquote(value) if value: try: return int(value) @@ -51,6 +61,7 @@ def integer(env_var_name: str, default_value: int = None) -> int: @staticmethod def boolean(env_var_name: str, default_value: bool = None) -> bool: value = os.getenv(env_var_name) + value = DeyeEnv.unquote(value) if value and value == "true": return True elif value and value == "false": @@ -67,6 +78,7 @@ def boolean(env_var_name: str, default_value: bool = None) -> bool: @staticmethod def string(env_var_name: str, default_value: str = None) -> str | None: value = os.getenv(env_var_name) + value = DeyeEnv.unquote(value) if value: return value elif default_value is not None: