diff --git a/rocolib/library/__init__.py b/rocolib/library/__init__.py index 273604e13175eeb81d31fd6f7e1512ea4ff236dc..513e33d0b75e82255890f986f22ea65eecdd580b 100644 --- a/rocolib/library/__init__.py +++ b/rocolib/library/__init__.py @@ -52,7 +52,9 @@ pyComponents = _makeLibItems("py") allComponents = {**pyComponents, **yamlComponents} def _load_yaml(c): - with open(getYamlFile(c), 'r') as fd: + yamld, yamlc = _getLib(c, yamlComponents) + yamlFile = f"{libDirs[yamld]}/{yamlc}.yaml" + with open(yamlFile, 'r') as fd: return safe_load(fd) def _getSubcomponents(c): @@ -80,23 +82,32 @@ def _getComponentNx(): def getComponentTree(): return nx.topological_generations(_getComponentNx()) -def getYamlFile(c): - if c in yamlComponents: - c = yamlComponents[c] +def _getLib(c, components): + if c in components: + return components[c].split(":") + elif c in components.values(): + return c.split(":") elif ":" not in c: - raise ValueError(f"Cannot find appropriate yaml file for {c}") - d, c = c.split(":") - return f"{libDirs[d]}/{c}.yaml" - -def getPyComponent(c): - if c in pyComponents: - c = pyComponents[c] - elif ":" not in c: - raise ValueError(f"Cannot find appropriate python file / plugin library for {c}") - d, c = c.split(":") - - obj = getattr(importlib.import_module(f"{libModules[d]}.{c}"), c) - return obj() + return None, None + _, c = c.split(":") + return _getLib(c, components) + +def _getComponentObject(c): + pyd, pyc = _getLib(c, pyComponents) + yamld, yamlc = _getLib(c, yamlComponents) + + yamlFile = yamlc and f"{libDirs[yamld]}/{yamlc}.yaml" or None + pyobj = pyc and getattr(importlib.import_module(f"{libModules[pyd]}.{pyc}"), pyc) or None + + if pyobj: + log.debug(f"Found py: {pyd}:{pyc}" + (yamlFile and f"(yaml at {yamlFile})" or "")) + return pyobj(yamlFile=yamlFile) + elif yamlFile: + log.debug(f"Found bare yaml at {yamlFile}") + from rocolib.api.components import newComponent + return newComponent(yamlc, yamlFile=yamlFile) + else: + raise ValueError(f"Component {c} not found in any library") def getComponent(c, **kwargs): ''' @@ -104,15 +115,7 @@ def getComponent(c, **kwargs): Parameter c (str): component name e.g. 'Stool' kwargs: component parameter / value pairs (possibly including name) ''' - from rocolib.api.components import newComponent - if c in pyComponents.keys() or c in pyComponents.values(): - log.debug("Found python component in library, instantiating and returning object") - my_obj = getPyComponent(c) - elif c in yamlComponents.keys() or c in yamlComponents.values(): - log.debug("Found yaml component in library, creating newComponent from yamlFile") - my_obj = newComponent(c, yamlFile=getYamlFile(c)) - else: - raise ValueError(f"Component {c} not found in library") + my_obj = _getComponentObject(c) for k, v in kwargs.items(): if k == 'name':