def file_build(self, path, modname=None): """Build astroid from a source code file (i.e. from an ast) *path* is expected to be a python source file """ try: stream, encoding, data = open_source_file(path) except IOError as exc: raise exceptions.AstroidBuildingError( 'Unable to load file {path}:\n{error}', modname=modname, path=path, error=exc) from exc except (SyntaxError, LookupError) as exc: raise exceptions.AstroidSyntaxError( 'Python 3 encoding specification error or unknown encoding:\n' '{error}', modname=modname, path=path, error=exc) from exc except UnicodeError as exc: # wrong encoding # detect_encoding returns utf-8 if no encoding specified raise exceptions.AstroidBuildingError( 'Wrong or no encoding specified for {filename}.', filename=path) from exc with stream: # get module name if necessary if modname is None: try: modname = '.'.join(modutils.modpath_from_file(path)) except ImportError: modname = os.path.splitext(os.path.basename(path))[0] # build astroid representation module = self._data_build(data, modname, path) return self._post_build(module, encoding)
def _data_build(self, data, modname, path): """Build tree node from data and add some informations""" try: node = _parse_string(data) except (TypeError, ValueError, SyntaxError) as exc: raise exceptions.AstroidSyntaxError( "Parsing Python code failed:\n{error}", source=data, modname=modname, path=path, error=exc, ) from exc if path is not None: node_file = os.path.abspath(path) else: node_file = "<?>" if modname.endswith(".__init__"): modname = modname[:-9] package = True else: package = (path is not None and os.path.splitext( os.path.basename(path))[0] == "__init__") builder = rebuilder.TreeRebuilder(self._manager) module = builder.visit_module(node, modname, node_file, package) module._import_from_nodes = builder._import_from_nodes module._delayed_assattr = builder._delayed_assattr return module
def _data_build(self, data, modname, path): """Build tree node from data and add some informations""" try: node = _parse(data + '\n') except (TypeError, ValueError, SyntaxError) as exc: util.reraise( exceptions.AstroidSyntaxError( 'Parsing Python code failed:\n{error}', source=data, modname=modname, path=path, error=exc)) if path is not None: node_file = os.path.abspath(path) else: node_file = '<?>' if modname.endswith('.__init__'): modname = modname[:-9] package = True else: package = path and path.find('__init__.py') > -1 or False builder = rebuilder.TreeRebuilder(self._manager) module = builder.visit_module(node, modname, node_file, package) module._import_from_nodes = builder._import_from_nodes module._delayed_assattr = builder._delayed_assattr return module