def grok(self, name, module, module_info, config, **kw): get = lambda d: d.bind().get(module) ext_name = get(silvaconf.extension_name) ext_title = get(silvaconf.extension_title) if not ext_name or not ext_title: return False if not module_info.isPackage(): raise GrokError( "Your extension %s is not defined in a package." % ext_title, module) is_system = get(silvaconf.extension_system) is_default = get(silvaconf.extension_default) ext_depends = get(silvaconf.extension_depends) if is_system: if is_default: raise GrokError( u"System extension %s doesn't have an installer. " u"So you cannot install it by default." % ext_title) try: install_module = resolve('%s.install' % name) if not isinstance(install_module, SystemExtensionInstaller): raise GrokError( u"System extension installer must extend the " u"base class 'SystemExtensionInstaller'.", module) except ImportError: install_module = SystemExtensionInstaller() else: try: install_module = resolve('%s.install' % name) except ImportError: raise GrokError( u"You need to create an installer for your " u"extension %s based on 'DefaultInstaller'." % ( ext_title), module) extensionRegistry.register( ext_name, ext_title, install_module=install_module, module_path=module_info.package_dotted_name, depends_on=ext_depends) extension = extensionRegistry.get_extension(ext_name) if is_system: alsoProvides(extension, ISystemExtension) if is_default: config.action( discriminator=None, callable=component.provideHandler, args=(install(ext_name), (IRoot, IInstallRootEvent))) return True
def extract(packages, output_dir, output_package, domain, products): """Extract i18n strings """ parser = OptionParser() parser.add_option( "-o", "--output", dest="output_dir", help="alternate output directory for the extracted file") parser.add_option( "-p", "--package", action="store_true", dest="output_package", help="extract to the output package") (options, args) = parser.parse_args() if products: load_products(products) output_file = domain + '.pot' if options.output_dir: if not os.path.exists(options.output_dir): print "Selected directory doesn't exists: %s" % options.output_dir return output_file = os.path.join(options.output_dir, output_file) elif options.output_package: if not output_package: print "No output package selected." return python_package = resolve(output_package) path = os.path.join(os.path.dirname(python_package.__file__), 'i18n') if not os.path.exists(path): print "Selected package doesn't have translations: %s" % path return output_file = os.path.join(path, output_file) elif output_dir: if not os.path.exists(output_dir): os.mkdir(output_dir) output_file = os.path.join(output_dir, output_file) print "Domain: %s" % domain print "Output file: %r" % output_file maker = MultiplePOTMaker(output_file, '') for package in packages: print "Processing package %s..." % package python_package = resolve(package) path = os.path.dirname(python_package.__file__) maker.add(py_strings(path, domain, verify_domain=True), path, package) maker.add(tal_strings(path, domain), path, package) # For Chameleon templates maker.add(tal_strings(path, domain, filePattern='*.cpt'), path, package) maker.add(formulator_strings(path, domain), path, package) maker.add(metadata_strings(path, domain), path, package) maker.write() return output_file
def session(_context, name=u"", engine=u"", twophase=False, factory="z3c.saconfig.utility.GloballyScopedSession"): if _context.package is None: ScopedSession = resolve(factory) else: ScopedSession = resolve(factory, package=_context.package.__name__) scoped_session = ScopedSession(engine=engine, twophase=twophase) zope.component.zcml.utility( _context, provides=interfaces.IScopedSession, component=scoped_session, permission=zope.component.zcml.PublicPermission, name=name)
def engine(_context, url, name=u"", convert_unicode=False, echo=None, setup=None, twophase=False, pool_size=None, max_overflow=None, pool_recycle=None, pool_timeout=None): kwargs = { 'echo': echo, 'convert_unicode': convert_unicode, } # Only add these if they're actually set, since we want to let SQLAlchemy # control the defaults if pool_size is not None: kwargs['pool_size'] = pool_size if max_overflow is not None: kwargs['max_overflow'] = max_overflow if pool_recycle is not None: kwargs['pool_recycle'] = pool_recycle if pool_timeout is not None: kwargs['pool_timeout'] = pool_timeout factory = EngineFactory(url, **kwargs) zope.component.zcml.utility(_context, provides=IEngineFactory, component=factory, permission=PublicPermission, name=name) if setup: if isinstance(setup, bytes): setup = setup.decode() if _context.package is None: callback = resolve(setup) else: callback = resolve(setup, package=_context.package.__name__) _context.action(discriminator=(IEngineFactory, name), callable=callback, args=(factory(), ), order=9999)
def _register_content( self, config, content, factories, default_factory, icon, zmi_addable=True): """ Register the content in Zope. """ menu_factory = None extension_name, methods = self._get_extension_detail(content) if not len(factories): if default_factory is None: raise GrokError( "You need to provide a factory for %s." % content.__name__, content) factories = [default_factory(content),] else: factories = map( lambda f: resolve('%s.%s' % (content.__module__, f)), factories) registerFactory(methods, content, factories) if zmi_addable: menu_factory = 'manage_addProduct/%s/%s' % ( extension_name, factories[0].__name__) registerClass(content, extension_name, zmi_addable, menu_factory) if icon: registerIcon(config, extension_name, content, icon[None])
def session(_context, name=u"", engine=u"", twophase=False, factory="z3c.saconfig.utility.GloballyScopedSession"): if _context.package is None: ScopedSession = resolve(factory) else: ScopedSession = resolve(factory, package=_context.package.__name__) scoped_session = ScopedSession(engine=engine, twophase=twophase) zope.component.zcml.utility(_context, provides=interfaces.IScopedSession, component=scoped_session, permission=PublicPermission, name=name)
def suite_from_package(package_name, factory): """This method looks files in a directory of a package_name and create test suite with files contained in it. """ suite = unittest.TestSuite() try: python_package = resolve(package_name) except ImportError: raise ValueError("Could not import package %s" % package_name) testing_path = os.path.dirname(python_package.__file__) for filename in os.listdir(testing_path): name, extension = os.path.splitext(filename) if extension not in TEST_FACTORIES.keys(): continue if name.endswith('_fixture') or name == '__init__': continue suite_factory = TEST_FACTORIES[extension] suite_options = {} suite_options.update(TEST_OPTIONS.get(extension, {})) if suite_factory is doctest.DocTestSuite: test_name = '.'.join((package_name, name)) else: test_name = os.path.join(testing_path, filename) def build_suite(*files, **options): options.update(suite_options) return suite_factory(*files, **options) test = factory(build_suite, test_name) suite.addTest(test) return suite
def engine(_context, url, name=u"", echo=False, setup=None, twophase=False): factory = utility.EngineFactory(url, echo=echo) zope.component.zcml.utility( _context, provides=interfaces.IEngineFactory, component=factory, permission=zope.component.zcml.PublicPermission, name=name) if setup: if _context.package is None: callback = resolve(setup) else: callback = resolve(setup, package=_context.package.__name__) callback(factory())
def execute( self, content, config, icon, priority, factory, zmi_addable, version_class, version_factory, **kw): """Register a versioned content type and the implementation of its version. """ if version_class is None: # TODO we could search like grok search context raise GrokError( "You need to provide a version class for %s." % ( content.__name__), content) version = version_class if isinstance(version, str): version = resolve('%s.%s' % (content.__module__, version_class)) extension = self._get_extension_name(content) default_factory = lambda c: VersionedContentFactory(extension, c, version) self._register_content( config, content, factory, default_factory, icon, zmi_addable) self._register_content( config, version, version_factory, VersionFactory, None, zmi_addable) self._register_silva( content, priority, version) return True
def _importNode(self, node): """Import the object from the DOM node.""" dir = str(node.getAttribute('directory')) if ':' in dir: (prefix, dirpart) = dir.split(':') package = resolve(prefix) dir = os.path.join(os.path.dirname(package.__file__), dirpart) self.context.manage_properties(dir)
def register(self, name, title, install_module=None, module_path=None, depends_on=(u'Silva', )): # Figure out which is the extension path. path = None assert not ((install_module is None) and (module_path is None)) if module_path: path = resolve(module_path).__file__ elif isinstance(install_module, types.ModuleType): # Installer is a module install.py which HAVE TO BE in the # extension package. module_path = '.'.join(install_module.__name__.split('.')[:-1]) path = install_module.__file__ else: # Installer is a class in the __init__.py of the extension. module_path = install_module.__module__ path = resolve(module_path).__file__ assert os.path.exists(path) # Remove any symbolic links encountered (like setuptools) path = os.path.realpath(path) # Search throught eggs to see if extension is an egg. ext = None for egg in pkg_resources.working_set: if (path.startswith(egg.location) and path[len(egg.location)] == os.path.sep): ext = EggExtension(egg, name, install_module, module_path, title, None, depends_on) break # Otherwise, that's a product. if ext is None: ext = ProductExtension(name, install_module, module_path, title, None, depends_on) self._extensions[ext.name] = ext self._extensions_by_module[ext.module_name] = ext # Try to order based on dependencies self._orderExtensions()
def register(self, name, title, install_module=None, module_path=None, depends_on=(u'Silva',)): # Figure out which is the extension path. path = None assert not ((install_module is None) and (module_path is None)) if module_path: path = resolve(module_path).__file__ elif isinstance(install_module, types.ModuleType): # Installer is a module install.py which HAVE TO BE in the # extension package. module_path = '.'.join(install_module.__name__.split('.')[:-1]) path = install_module.__file__ else: # Installer is a class in the __init__.py of the extension. module_path = install_module.__module__ path = resolve(module_path).__file__ assert os.path.exists(path) # Remove any symbolic links encountered (like setuptools) path = os.path.realpath(path) # Search throught eggs to see if extension is an egg. ext = None for egg in pkg_resources.working_set: if (path.startswith(egg.location) and path[len(egg.location)] == os.path.sep): ext = EggExtension( egg, name, install_module, module_path, title, None, depends_on) break # Otherwise, that's a product. if ext is None: ext = ProductExtension( name, install_module, module_path, title, None, depends_on) self._extensions[ext.name] = ext self._extensions_by_module[ext.module_name] = ext # Try to order based on dependencies self._orderExtensions()
def engine(_context, url, name=u"", convert_unicode=False, echo=None, setup=None, twophase=False, pool_size=None, max_overflow=None, pool_recycle=None, pool_timeout=None): kwargs = { 'echo': echo, 'convert_unicode': convert_unicode, } # Only add these if they're actually set, since we want to let SQLAlchemy # control the defaults if pool_size is not None: kwargs['pool_size'] = pool_size if max_overflow is not None: kwargs['max_overflow'] = max_overflow if pool_recycle is not None: kwargs['pool_recycle'] = pool_recycle if pool_timeout is not None: kwargs['pool_timeout'] = pool_timeout factory = EngineFactory(url, **kwargs) zope.component.zcml.utility( _context, provides=IEngineFactory, component=factory, permission=PublicPermission, name=name) if setup: if isinstance(setup, bytes): setup = setup.decode() if _context.package is None: callback = resolve(setup) else: callback = resolve(setup, package=_context.package.__name__) _context.action( discriminator=(IEngineFactory, name), callable=callback, args=(factory(), ), order=9999)
def __call__(self, content, default=None): name = self.name if name not in self.cache: try: self.cache[name] = resolve(name) except ImportError: self.cache[name] = None if name in self.cache: adapter = self.cache[name] if adapter is not None: return adapter(content, default)
def manage(output_package, products, domain): """Merge translations for the given packages. """ parser = OptionParser() parser.add_option( "-p", "--path", dest="path", help=("path where the translation to merge are, " "default to the package '%s'" % output_package)) parser.add_option( "-c", "--compile", dest="compile", action="store_true", help="compile all translation files") parser.add_option( "-m", "--merge", dest="merge", action="store_true", help="merge all templates to in all translation files") parser.add_option( "-i", "--import-tarball", dest="import_tarball", help=("the translations are packed in a tarball, " "and will be imported in the package '%s'" % output_package)) parser.add_option( "-e", "--export-tarball", dest="export_tarball", help=("a tarball will be created containing the translations")) parser.add_option( "--pot-only", dest="pot_only", action='store_true', default=False, help=("apply the action only on the pot file")) (options, args) = parser.parse_args() if products: load_products(products) if options.path: path = options.path else: python_package = resolve(output_package) path = os.path.dirname(python_package.__file__) for i18n_part in ('i18n', 'locales'): i18n_path = os.path.join(path, i18n_part) if os.path.isdir(i18n_path): print "Processing package %s..." % i18n_path if options.import_tarball: import_tarball(options.import_tarball, i18n_path, options) elif options.export_tarball: export_tarball( options.export_tarball, i18n_path, domain, pot_only=options.pot_only) else: merge_or_compile_files(i18n_path, options)
def registerFactory(methods, class_, factory): """Register a manage_add<Something> style factory method. """ permission = getAddPermissionName(class_) default = ('Manager',) AccessControl.Permission.registerPermissions(((permission, (), default),)) permission_setting = PermissionRole(permission, default) if not (isinstance(factory, tuple) or isinstance(factory, list)): factory = [factory,] for method in factory: name = method.__name__ if not name.startswith('manage_add'): method.__name__ = name = getFactoryName(class_) module = resolve(class_.__module__) setattr(module, name, method) methods[name] = method methods[name + '__roles__'] = permission_setting
def _add(self, parent, data): """Purely create the object. This method can be overriden to support custom creation needs. """ # Search for an addable and a factory addable = extensionRegistry.get_addable(self._content_type) if not addable: raise ValueError(u"Content factory cannot be found. ") factory = getattr( resolve(addable['instance'].__module__), getFactoryName(addable['instance'])) # Build the content identifier = str(data.getWithDefault('id')) factory(parent, identifier, data.getWithDefault('title')) content = getattr(parent, identifier) self._edit(parent, content, data) return content
def _callFUT(self, *args, **kw): from zope.configuration.name import resolve return resolve(*args, **kw)
verify_domain = False site_zcml = None makers = [] eggPaths = [] header_template = None for opt, arg in opts: if opt in ('-h', '--help'): usage(0) elif opt in ('-d', '--domain'): domain = arg elif opt in ('-s', '--site_zcml'): site_zcml = arg elif opt in ('-e', '--exclude-default-domain'): include_default_domain = False elif opt in ('-m', ): makers.append(resolve(arg)) elif opt in ('-o', ): output_dir = arg elif opt in ('-x', ): exclude_dirs.append(arg) elif opt in ('--python-only',): python_only = True elif opt in ('--verify-domain'): verify_domain = True elif opt in ('-p', '--package'): package = resolve(arg) path = os.path.dirname(package.__file__) if not os.path.exists(path): usage(1, 'The specified path does not exist.') eggPaths.append((arg, path)) elif opt in ('-t', ):
def setClassName( self, name ): self._class_name = name self._class = resolve( name )
def provides(context, ob, interface_name): """ proxy for zope interface.providedBy """ interface = resolve(interface_name) return interface.providedBy(ob)
elif opt in ('-d', '--domain'): domain = arg elif opt in ('-s', '--site_zcml'): site_zcml = arg elif opt in ('-e', '--exclude-default-domain'): include_default_domain = False elif opt in ('-m', ): makers.append(arg) elif opt in ('-o', ): output_dir = arg elif opt in ('-x', ): exclude_dirs.append(arg) elif opt in ('--python-only',): python_only = True elif opt in ('-p', '--package'): package = resolve(arg) path = os.path.dirname(package.__file__) if not os.path.exists(path): usage(1, 'The specified path does not exist.') eggPaths.append((arg, path)) # setup output file output_file = domain+'.pot' if output_dir: if not os.path.exists(output_dir): os.mkdir(output_dir) output_file = os.path.join(output_dir, output_file) print "domain: %r\n" \ "configuration: %s\n" \ "exclude dirs: %r\n" \
def main(argv=sys.argv): try: opts, args = getopt.getopt( argv[1:], "hed:s:i:m:p:o:x:t:", [ "help", "domain=", "site_zcml=", "path=", "python-only", "verify-domain", "exclude-default-domain", ], ) except getopt.error as msg: usage(1, msg) domain = "z3c" include_default_domain = True output_dir = None exclude_dirs = [] python_only = False verify_domain = False site_zcml = None makers = [] eggPaths = [] header_template = None for opt, arg in opts: if opt in ("-h", "--help"): usage(0) elif opt in ("-d", "--domain"): domain = arg elif opt in ("-s", "--site_zcml"): site_zcml = arg elif opt in ("-e", "--exclude-default-domain"): include_default_domain = False elif opt in ("-m",): makers.append(resolve(arg)) elif opt in ("-o",): output_dir = arg elif opt in ("-x",): exclude_dirs.append(arg) elif opt in ("--python-only",): python_only = True elif opt in ("--verify-domain"): verify_domain = True elif opt in ("-p", "--package"): package = resolve(arg) path = os.path.dirname(package.__file__) if not os.path.exists(path): usage(1, "The specified path does not exist.") eggPaths.append((arg, path)) elif opt in ("-t",): if not os.path.exists(arg): usage(1, "The specified header template does not exist.") header_template = arg # setup output file output_file = domain + ".pot" if output_dir: if not os.path.exists(output_dir): os.mkdir(output_dir) output_file = os.path.join(output_dir, output_file) print( "domain: %r\n" "configuration: %s\n" "exclude dirs: %r\n" "include default domain: %r\n" "python only: %r\n" "verify domain: %r\n" "header template: %r\n" % ( domain, site_zcml, exclude_dirs, include_default_domain, python_only, verify_domain, header_template, ) ) # setup pot maker maker = POTMaker(output_file, "", header_template) # add maker for each given path for pkgName, path in eggPaths: basePath = path moduleNames = pkgName.split(".") moduleNames.reverse() for mName in moduleNames: mIdx = path.rfind(mName) basePath = basePath[:mIdx] pkgPath = path[len(basePath):] print( "package: %r\n" "base: %r\n" "path: %r\n" % (pkgPath, basePath, path) ) maker.add( py_strings( path, domain, exclude=exclude_dirs, verify_domain=verify_domain ), basePath, ) if not python_only: maker.add(zcml_strings(path, domain, site_zcml), basePath) maker.add( tal_strings( path, domain, include_default_domain, exclude=exclude_dirs ), basePath, ) for maker_func in makers: try: maker.add( maker_func( path=path, base_path=basePath, exclude_dirs=exclude_dirs, domain=domain, include_default_domain=include_default_domain, site_zcml=site_zcml, ), basePath, ) except TypeError: # BBB: old arguments maker.add(maker_func(path, basePath, exclude_dirs), basePath) maker.write() print("output: %r\n" % output_file)
def module(self): return resolve(self.module_name)
"'site.zcml' location: %s\n" \ "exclude dirs: %r\n" \ "domain: %r\n" \ "include default domain: %r\n" \ "output file: %r\n" \ "Python only: %r" \ "parse html files: %r" \ % (base_dir, path, site_zcml, exclude_dirs, domain, include_default_domain, output_file, python_only, extract_html) from zope.app.locales.extract import POTMaker, \ py_strings, tal_strings, zcml_strings maker = POTMaker(output_file, path) maker.add(py_strings(path, domain, exclude=exclude_dirs), base_dir) if not python_only: maker.add(zcml_strings(path, domain, site_zcml), base_dir) maker.add(tal_strings(path, domain, include_default_domain, exclude=exclude_dirs), base_dir) if extract_html: maker.add(tal_strings(path, domain, include_default_domain, exclude=exclude_dirs, filePattern='*.html'), base_dir) for m in makers: poMaker = resolve(m) maker.add(poMaker(path, base_dir, exclude_dirs)) maker.write() if __name__ == '__main__': main()
def main(argv=sys.argv): try: opts, args = getopt.getopt( argv[1:], 'hed:s:i:m:p:o:x:t:', ['help', 'domain=', 'site_zcml=', 'path=', 'python-only', 'verify-domain', 'exclude-default-domain']) except getopt.error as msg: usage(1, msg) domain = 'z3c' include_default_domain = True output_dir = None exclude_dirs = [] python_only = False verify_domain = False site_zcml = None makers = [] eggPaths = [] header_template = None for opt, arg in opts: if opt in ('-h', '--help'): usage(0) elif opt in ('-d', '--domain'): domain = arg elif opt in ('-s', '--site_zcml'): site_zcml = arg elif opt in ('-e', '--exclude-default-domain'): include_default_domain = False elif opt in ('-m', ): makers.append(resolve(arg)) elif opt in ('-o', ): output_dir = arg elif opt in ('-x', ): exclude_dirs.append(arg) elif opt in ('--python-only',): python_only = True elif opt in ('--verify-domain'): verify_domain = True elif opt in ('-p', '--package'): package = resolve(arg) path = os.path.dirname(package.__file__) if not os.path.exists(path): usage(1, 'The specified path does not exist.') eggPaths.append((arg, path)) elif opt in ('-t', ): if not os.path.exists(arg): usage(1, 'The specified header template does not exist.') header_template = arg # setup output file output_file = domain+'.pot' if output_dir: if not os.path.exists(output_dir): os.mkdir(output_dir) output_file = os.path.join(output_dir, output_file) print("domain: %r\n" \ "configuration: %s\n" \ "exclude dirs: %r\n" \ "include default domain: %r\n" \ "python only: %r\n" \ "verify domain: %r\n" \ "header template: %r\n" \ % (domain, site_zcml, exclude_dirs, include_default_domain, python_only, verify_domain, header_template)) # setup pot maker maker = POTMaker(output_file, '', header_template) # add maker for each given path for pkgName, path in eggPaths: basePath = path moduleNames = pkgName.split('.') moduleNames.reverse() for mName in moduleNames: mIdx = path.rfind(mName) basePath = basePath[:mIdx] pkgPath = path[len(basePath):] print("package: %r\n" \ "base: %r\n" \ "path: %r\n" \ % (pkgPath, basePath, path)) maker.add(py_strings(path, domain, exclude=exclude_dirs, verify_domain=verify_domain), basePath) if not python_only: maker.add(zcml_strings(path, domain, site_zcml), basePath) maker.add(tal_strings(path, domain, include_default_domain, exclude=exclude_dirs), basePath) for maker_func in makers: try: maker.add( maker_func( path=path, base_path=basePath, exclude_dirs=exclude_dirs, domain=domain, include_default_domain=include_default_domain, site_zcml=site_zcml, ), basePath) except TypeError: # BBB: old arguments maker.add(maker_func(path, basePath, exclude_dirs), basePath) maker.write() print("output: %r\n" % output_file)