<commit_before>############################################################################
##
## Copyright (C) 2006-2007 University of Utah. All rights reserved.
##
## This file is part of VisTrails.
##
## This file may be used under the terms of the GNU General Public
## License version 2.0 as published by the Free Software Foundation
## and appearing in the file LICENSE.GPL included in the packaging of
## this file.  Please review the following to ensure GNU General Public
## Licensing requirements will be met:
## http://www.opensource.org/licenses/gpl-license.php
##
## If you are unsure which license is appropriate for your use (for
## instance, you are interested in developing a commercial derivative
## of VisTrails), please contact us at <EMAIL>.
##
## This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
## WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
##
############################################################################

"""The package manager takes care of everything that has got to do
with handling packages, from setting paths to adding new packages
to checking dependencies to initializing them."""

from core import debug
from core.modules.module_registry import registry
from core.utils import VistrailsInternalError, InstanceObject
from core.utils.uxml import (named_elements,
                             elements_filter, enter_named_element)
from core.configuration import ConfigurationObject, get_vistrails_configuration
import copy
import core.data_structures.graph
import os
import sys

##############################################################################

class Package(object):

    Base, User, Other = 0, 1, 2

    class InitializationFailed(Exception):
        def __init__(self, package, exception):
            self.package = package
            self.exception = exception
        def __str__(self):
            return ("Package '%s' failed to initialize, raising '%s: %s'" %
                    (self.package.name,
                     self.exception.__class__.__name__,
                     self.exception))

    def __init__(self, codepath, load_configuration=True):
        self._codepath = codepath
        self._load_configuration = load_configuration
        self._module = None
        self._initialized = False

    def load(self, module=None):
        """load(module=None). Loads package's module. If module is not None,
        then uses that as the module instead of 'import'ing it.

        If package is already initialized, this is a NOP.

        """
        
        errors = []
        def module_import(name):
            return 
            
        if self._initialized:
            return
        if module is not None:
            self._module = module
            self._package_type = self.Other
            return
        def import_from(prefix):
            try:
                self._module = getattr(__import__(prefix+self._codepath,
                                                  globals(),
                                                  locals(), []),
                                       self._codepath)
                self._package_type = self.Base
            except ImportError, e:
                errors.append(e)
                return False
            return True

        if (not import_from('packages.') and
            not import_from('userpackages.')):
            dbg = debug.DebugPrint
            dbg.critical("Could not enable package %s" % self._codepath)
            for e in errors:
                dbg.critical("Exceptions raised:")
                dbg.critical(str(e))
            raise ImportError("Package %s not present "
                              "(or one of its imports failed)" % self._codepath)

        # Sometimes we don't want to change startup.xml, for example
        # when peeking at a package that's on the available package list
        # on edit -> preferences. That's what the _load_configuration field
        # is for
        if self._load_configuration:
            if hasattr(self._module, 'configuration'):
                # hold a copy of the initial configuration so it can be reset
                self._initial_configuration = copy.copy(self._module.configuration)
            self.load_persistent_configuration()
            self.create_startup_package_node()

    def initialize(self):
        if self._initialized:
            return
        print "Initializing", self._codepath
        registry.set_current_package_name(self._get_identifier())
        try:
            self._module.initialize()
        except Exception, e:
            raise self.InitializationFailed(self, e)

        # The package might have decided to rename itself, let's store that
        registry.set_current_package_name(None)<commit_msg>-- Includes traceback on report of package initialization failure to make it easier to debug. --<commit_after>############################################################################
##
## Copyright (C) 2006-2007 University of Utah. All rights reserved.
##
## This file is part of VisTrails.
##
## This file may be used under the terms of the GNU General Public
## License version 2.0 as published by the Free Software Foundation
## and appearing in the file LICENSE.GPL included in the packaging of
## this file.  Please review the following to ensure GNU General Public
## Licensing requirements will be met:
## http://www.opensource.org/licenses/gpl-license.php
##
## If you are unsure which license is appropriate for your use (for
## instance, you are interested in developing a commercial derivative
## of VisTrails), please contact us at <EMAIL>.
##
## This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
## WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
##
############################################################################

"""The package manager takes care of everything that has got to do
with handling packages, from setting paths to adding new packages
to checking dependencies to initializing them."""

from core import debug
from core.modules.module_registry import registry
from core.utils import VistrailsInternalError, InstanceObject
from core.utils.uxml import (named_elements,
                             elements_filter, enter_named_element)
from core.configuration import ConfigurationObject, get_vistrails_configuration
import copy
import core.data_structures.graph
import os
import sys
import traceback

##############################################################################

class Package(object):

    Base, User, Other = 0, 1, 2

    class InitializationFailed(Exception):
        def __init__(self, package, exception, traceback):
            self.package = package
            self.exception = exception
            self.traceback = traceback
        def __str__(self):
            return ("Package '%s' failed to initialize, raising '%s: %s'. Traceback:\n%s" %
                    (self.package.name,
                     self.exception.__class__.__name__,
                     self.exception,
                     self.traceback))

    def __init__(self, codepath, load_configuration=True):
        self._codepath = codepath
        self._load_configuration = load_configuration
        self._module = None
        self._initialized = False

    def load(self, module=None):
        """load(module=None). Loads package's module. If module is not None,
        then uses that as the module instead of 'import'ing it.

        If package is already initialized, this is a NOP.

        """
        
        errors = []
        def module_import(name):
            return 
            
        if self._initialized:
            return
        if module is not None:
            self._module = module
            self._package_type = self.Other
            return
        def import_from(prefix):
            try:
                self._module = getattr(__import__(prefix+self._codepath,
                                                  globals(),
                                                  locals(), []),
                                       self._codepath)
                self._package_type = self.Base
            except ImportError, e:
                errors.append(e)
                return False
            return True

        if (not import_from('packages.') and
            not import_from('userpackages.')):
            dbg = debug.DebugPrint
            dbg.critical("Could not enable package %s" % self._codepath)
            for e in errors:
                dbg.critical("Exceptions raised:")
                dbg.critical(str(e))
            raise ImportError("Package %s not present "
                              "(or one of its imports failed)" % self._codepath)

        # Sometimes we don't want to change startup.xml, for example
        # when peeking at a package that's on the available package list
        # on edit -> preferences. That's what the _load_configuration field
        # is for
        if self._load_configuration:
            if hasattr(self._module, 'configuration'):
                # hold a copy of the initial configuration so it can be reset
                self._initial_configuration = copy.copy(self._module.configuration)
            self.load_persistent_configuration()
            self.create_startup_package_node()

    def initialize(self):
        if self._initialized:
            return
        print "Initializing", self._codepath
        registry.set_current_package_name(self._get_identifier())
        try:
            self._module.initialize()
        except Exception, e:
            raise self.InitializationFailed(self, e, traceback.format_exc())

        # The package might have decided to rename itself, let's store that
        registry.set_current_package_name(None)
{'fraction_non_alphanumeric': 0.1162625545297758, 'fraction_numerical': 0.002637719387237496, 'mean_word_length': 2.2925851703406814, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 4}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 10, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5648628', 'n_tokens_mistral': 2311, 'n_tokens_neox': 2212, 'n_words': 826}