GenerateID() produces unusable name for type in global namespace
- Dominant language
- No language data
- Stars
- 313
- Forks
- 40
- PR merge metrics
- No merged PRs in 30d
Description
### The problem
When writing Python configs for a component, if an ID is required for a type within the global namespace (i.e. a C struct) the auto-generated name is simply the name of the type, which is unusable as a name. E.g.
```
lv_obj_t = cg.global_ns.struct("lv_obj_t")
OBJ_SCHEMA = cv.Schema(
{
cv.GenerateID(): cv.declare_id(lv_obj_t),
}
)
```
If no id is provided in the yaml, the auto-generated ID name is `lv_obj_t` which is a type name.
The problem is inside the core.ID class:
```
def resolve(self, registered_ids):
from esphome.config_validation import RESERVED_IDS
if self.id is None:
base = str(self.type).replace("::", "_").lower()
name = "".join(c for c in base if c.isalnum() or c == "_")
used = set(registered_ids) | set(RESERVED_IDS) | CORE.loaded_integrations
self.id = ensure_unique_string(name, used)
return self.id
```
So where no name is provided, the base name is derived by replacing `::` with `_`, but if there is no namespace in the type name, this just returns the undecorated type.
Possible fix (working for me):
```
if self.id is None:
base = str(self.type).replace("::", "_").lower()
if base == str(self.type):
base = "_ns_" + str(self.type)
name = "".join(c for c in base if c.isalnum() or c == "_")
used = set(registered_ids) | set(RESERVED_IDS) | CORE.loaded_integrations
self.id = ensure_unique_string(name, used)
return self.id
```
### Which version of ESPHome has the issue?
dev
### What type of installation are you using?
Home Assistant Add-on
### Which version of Home Assistant has the issue?
_No response_
### What platform are you using?
ESP8266
### Board
_No response_
### Component causing the issue
_No response_
### Example YAML snippet
_No response_
### Anything in the logs that might be useful for us?
_No response_
### Additional information
_No response_
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.