def install_import_hook(): original_importer = builtins.__import__ def importer(*args, **kwargs): m = original_importer(*args, **kwargs) if module_eligible(m) and not pyfence.options['off']: debug('Importing %s' % (m.__name__)) fence_namespace(m) return m builtins.__import__ = importer debug('Import hook installed')
def fence_namespace(m, stack=None, fqn=None): """ Fences contents of namespace (module or class) :param m: namespace :param fqn: fully qualified name """ if hasattr(m, FENCE_TAG): return if hasattr(m, '__module__'): if not module_eligible(m.__module__): return try: setattr(m, FENCE_TAG, True) except TypeError: pass stack = stack or [] if not stack: fqn = m.__name__ debug('Processing %s (%s)' % (fqn, m)) for key in m.__dict__: if key.startswith('__') and key.endswith('__'): continue if not hasattr(m, key): continue if hasattr(m, '__dict__'): value = m.__dict__[key] else: value = getattr(m, key) if hasattr(value, '__module__'): if not module_eligible(value.__module__): continue if value in stack: continue if type(value) in [types.ClassType, types.TypeType]: fence_namespace(value, stack + [value], fqn + '.' + value.__name__) if type(value) in [types.MethodType, types.FunctionType]: fenced = fence_function(value, parent=m, fqn=fqn+'.'+value.__name__) if fenced is not None: setattr(m, key, fenced)
def importer(*args, **kwargs): m = original_importer(*args, **kwargs) if module_eligible(m) and not pyfence.options['off']: debug('Importing %s' % (m.__name__)) fence_namespace(m) return m