configuration: fix error handling of keys missing a '.'

Fixes #600

De-duplicate the `option.split('.', 1)` "parsing" code into a new,
minimalistic and centralized `_InternalCF.key_parse` function. Add two
lines of error handling in this new function in order to provide a
meaningful error message instead of this cryptic and context free exception
when using a "build_board" key name without a dot:

```
    ...
    File "/usr/lib/python3.10/site-packages/west/configuration.py", in _get
    section, key = option.split('.', 1)
    ValueError: not enough values to unpack (expected 2, got 1)
```

The API user now gets this:

```
    ...
    File "/usr/lib/python3.10/site-packages/west/configuration.py", in parse_key
        raise ValueError(f"Invalid key name: '{dotted_name}'")
ValueError: Invalid key name: 'build_board'

```

Signed-off-by: Marc Herbert <marc.herbert@intel.com>
This commit is contained in:
Marc Herbert 2022-09-07 21:29:45 -07:00 committed by Marti Bolivar
parent ed01ab5fa1
commit 63569cefe3
1 changed files with 11 additions and 4 deletions

View File

@ -57,6 +57,13 @@ class _InternalCF:
# writing INI-style [section] key = value configuration files,
# but presenting a west-style section.key = value style API.
@staticmethod
def parse_key(dotted_name: str):
section_child = dotted_name.split('.', 1)
if len(section_child) != 2:
raise ValueError(f"Invalid key name: '{dotted_name}'")
return section_child
@staticmethod
def from_path(path: Optional[Path]) -> Optional['_InternalCF']:
return _InternalCF(path) if path and path.exists() else None
@ -69,7 +76,7 @@ class _InternalCF:
raise FileNotFoundError(path)
def __contains__(self, option: str) -> bool:
section, key = option.split('.', 1)
section, key = _InternalCF.parse_key(option)
return section in self.cp and key in self.cp[section]
@ -86,7 +93,7 @@ class _InternalCF:
return self._get(option, self.cp.getfloat)
def _get(self, option, getter):
section, key = option.split('.', 1)
section, key = _InternalCF.parse_key(option)
try:
return getter(section, key)
@ -94,7 +101,7 @@ class _InternalCF:
raise KeyError(option)
def set(self, option: str, value: Any):
section, key = option.split('.', 1)
section, key = _InternalCF.parse_key(option)
if section not in self.cp:
self.cp[section] = {}
@ -105,7 +112,7 @@ class _InternalCF:
self.cp.write(f)
def delete(self, option: str):
section, key = option.split('.', 1)
section, key = _InternalCF.parse_key(option)
if section not in self.cp:
raise KeyError(option)