1
0
mirror of https://github.com/esphome/esphome.git synced 2025-09-27 15:42:22 +01:00

Ensure filename is shown when YAML raises an error (#6139)

* Ensure filename is shown when YAML raises an error

fixes #5423
fixes #5377

* Ensure filename is shown when YAML raises an error

fixes #5423
fixes #5377

* Ensure filename is shown when YAML raises an error

fixes #5423
fixes #5377

* Ensure filename is shown when YAML raises an error

fixes #5423
fixes #5377

* Ensure filename is shown when YAML raises an error

fixes #5423
fixes #5377
This commit is contained in:
J. Nick Koston
2024-01-23 19:11:03 -10:00
committed by GitHub
parent 23071e932a
commit 25ab6f0297
3 changed files with 48 additions and 8 deletions

View File

@@ -7,6 +7,7 @@ import logging
import math
import os
import uuid
from io import TextIOWrapper
from typing import Any
import yaml
@@ -19,7 +20,7 @@ except ImportError:
FastestAvailableSafeLoader = PurePythonLoader
from esphome import core
from esphome.config_helpers import Extend, Remove, read_config_file
from esphome.config_helpers import Extend, Remove
from esphome.core import (
CORE,
DocumentRange,
@@ -418,19 +419,26 @@ def load_yaml(fname: str, clear_secrets: bool = True) -> Any:
def _load_yaml_internal(fname: str) -> Any:
"""Load a YAML file."""
content = read_config_file(fname)
try:
return _load_yaml_internal_with_type(ESPHomeLoader, fname, content)
except EsphomeError:
# Loading failed, so we now load with the Python loader which has more
# readable exceptions
return _load_yaml_internal_with_type(ESPHomePurePythonLoader, fname, content)
with open(fname, encoding="utf-8") as f_handle:
try:
return _load_yaml_internal_with_type(ESPHomeLoader, fname, f_handle)
except EsphomeError:
# Loading failed, so we now load with the Python loader which has more
# readable exceptions
# Rewind the stream so we can try again
f_handle.seek(0, 0)
return _load_yaml_internal_with_type(
ESPHomePurePythonLoader, fname, f_handle
)
except (UnicodeDecodeError, OSError) as err:
raise EsphomeError(f"Error reading file {fname}: {err}") from err
def _load_yaml_internal_with_type(
loader_type: type[ESPHomeLoader] | type[ESPHomePurePythonLoader],
fname: str,
content: str,
content: TextIOWrapper,
) -> Any:
"""Load a YAML file."""
loader = loader_type(content)