Commits

Alain Poirier committed e4b4824

'nagare.admin.reference' and 'nagare.admin.command' extract from 'nagare.admin.util'

  • Participants
  • Parent commits 466f9d9

Comments (0)

Files changed (12)

File nagare/admin/command.py

+#--
+# Copyright (c) 2008-2012 Net-ng.
+# All rights reserved.
+#
+# This software is licensed under the BSD License, as described in
+# the file LICENSE.txt, which you should have received as part of
+# this distribution.
+#--
+
+"""The ``nagare-admin`` executable
+
+The ``run()`` function is called by the ``nagare-admin`` console script, created
+by  ``setuptools``
+"""
+
+import sys
+import optparse
+
+import pkg_resources
+
+# ---------------------------------------------------------------------------
+
+class Command(object):
+    """The base class of all the commands"""
+    desc = ''
+
+    @classmethod
+    def set_options(cls, parser):
+        pass
+
+    @classmethod
+    def run(cls, parser, options, args):
+        pass
+
+# ---------------------------------------------------------------------------
+
+def usage(commands):
+    """
+    Display the usage of ``nagare-admin``
+
+    In:
+      - ``commands`` -- dict of {command name -> command class}
+    """
+    yield '%prog <command>'
+    yield ''
+    yield 'with <command> :'
+
+    # Display the description of each command
+    l = max(map(len, commands))
+    for name in sorted(commands):
+        yield ' - %s: %s' % (name.ljust(l), commands[name].desc)
+
+# ---------------------------------------------------------------------------
+
+def run(entry_point_section='nagare.commands'):
+    """Dispatcher for the ``nagare-admin`` commands
+
+    The commands are classes, registered under the ``entry_point_section`` entry point
+    """
+
+    # Load all the commands
+    commands = {}
+    for entry_point in pkg_resources.iter_entry_points(entry_point_section):
+        try:
+            commands[entry_point.name] = entry_point.load()
+        except ImportError:
+            print "Warning: the command '%s' can't be imported" % entry_point.name
+            raise
+
+    parser = optparse.OptionParser(usage='\n'.join(usage(commands)))
+
+    if (len(sys.argv) == 1) or (sys.argv[1] == '-h') or (sys.argv[1] == '--help'):
+        parser.print_usage(sys.stderr)
+        parser.exit()
+
+    command_name = sys.argv[1]
+    command = commands.get(command_name)
+    if command is None:
+        parser.error("command '%s' not found" % command_name)
+
+    parser.usage = '%%prog %s [options]' % command_name
+
+    argv = command.set_options(parser)  # Let the command register its command line options
+    (options, args) = parser.parse_args((argv if argv is not None else sys.argv)[2:])   # Parse the command line
+
+    return command.run(parser, options, args)  # Run the command

File nagare/admin/create.py

 from StringIO import StringIO
 
 from configobj import ConfigObj
-from nagare.admin import util
+from nagare.admin import command
 
 
 def set_options(optparser):
         """ % params)
 
 
-class Create(util.Command):
+class Create(command.Command):
     desc = 'Create an application skeleton'
 
     set_options = staticmethod(set_options)

File nagare/admin/create_rules.py

 import os
 import pkg_resources
 
-from nagare.admin import util
+from nagare.admin import util, command
 
 
 def set_options(optparser):
 
 # ---------------------------------------------------------------------------
 
-class CreateRules(util.Command):
+class CreateRules(command.Command):
     desc = 'Create the rewrite rules'
 
     set_options = staticmethod(set_options)

File nagare/admin/db.py

 import pkg_resources
 
 from nagare import local, log, database
-from nagare.admin import util
+from nagare.admin import reference, util, command
 
 
 def read_options(debug, args, error):
             database_settings[0].create_all()
 
             if options.populate and populate:
-                util.load_object(populate)[0]()
+                reference.load_object(populate)[0]()
 
 
 def drop(parser, options, args):
 
 # ---------------------------------------------------------------------------
 
-class DBCreate(util.Command):
+class DBCreate(command.Command):
     desc = 'Create the database of an application'
 
     @staticmethod
     run = staticmethod(create)
 
 
-class DBDrop(util.Command):
+class DBDrop(command.Command):
     desc = 'Drop the database of an application'
 
     @staticmethod

File nagare/admin/info.py

 import sys
 import pkg_resources
 
-from nagare.admin import util
+from nagare.admin import command
 
 
-class Info(util.Command):
+class Info(command.Command):
     """Display informations about the framework environment"""
 
     desc = 'Display various informations'

File nagare/admin/main.py

-#--
-# Copyright (c) 2008-2012 Net-ng.
-# All rights reserved.
-#
-# This software is licensed under the BSD License, as described in
-# the file LICENSE.txt, which you should have received as part of
-# this distribution.
-#--
-
-"""The ``nagare-admin`` executable
-
-The ``main()`` function is called by the ``nagare-admin`` console script, created
-by  ``setuptools``
-"""
-
-import sys
-import optparse
-
-import pkg_resources
-
-
-def usage(commands):
-    """
-    Display the usage of ``nagare-admin``
-
-    In:
-      - ``commands`` -- list of the classes implementing the commands
-    """
-    yield '%prog <command>'
-    yield ''
-    yield 'with <command> :'
-
-    # Display the description of each command
-    l = max(map(len, commands))
-    for name in sorted(commands):
-        yield ' - %s: %s' % (name.ljust(l), commands[name].desc)
-
-# ---------------------------------------------------------------------------
-
-def main(entry_point_section='nagare.commands'):
-    """Dispatcher for the ``nagare-admin`` commands
-
-    The commands are classed, registered under the ``entry_point`` entry point
-    """
-
-    # Load all the commands
-    commands = {}
-    for entry_point in pkg_resources.iter_entry_points(entry_point_section):
-        try:
-            commands[entry_point.name] = entry_point.load()
-        except ImportError:
-            print "Warning: the command '%s' can't be imported" % entry_point.name
-            raise
-
-    parser = optparse.OptionParser(usage='\n'.join(usage(commands)))
-
-    if (len(sys.argv) == 1) or (sys.argv[1] == '-h') or (sys.argv[1] == '--help'):
-        parser.print_usage(sys.stderr)
-        parser.exit()
-
-    command_name = sys.argv[1]
-    command = commands.get(command_name)
-    if command is None:
-        parser.error("command '%s' not found" % command_name)
-
-    parser.usage = '%%prog %s [options]' % command_name
-
-    argv = command.set_options(parser)  # Let the command register its command line options
-    (options, args) = parser.parse_args((argv if argv is not None else sys.argv)[2:])   # Parse the command line
-
-    command.run(parser, options, args)  # Run the command

File nagare/admin/reference.py

+#--
+# Copyright (c) 2008-2012 Net-ng.
+# All rights reserved.
+#
+# This software is licensed under the BSD License, as described in
+# the file LICENSE.txt, which you should have received as part of
+# this distribution.
+#--
+
+"""Import an object from a string reference
+
+The possible reference syntaxes are:
+
+  - ``'python <module>:<object>'`` -- loads an object from a Python module
+    (for example: ``'python os.path:isfile'``)
+  - ``'<module>:<object>'``  -- same as ``'python <module>:<object>'``
+  - ``'file <file>:<object>'`` -- loads an object from a file
+    (for example: ``'file /tmp/counter.py:Counter'``)
+  - ``'egg <dist>:<app>'`` -- loads the registered application ``<app>``
+    from the ``<dist>`` distribution
+    (for example: ``'egg nagare:admin'`` or ``'egg nagare.examples:wiki'``)
+  - ``'app <app>'`` -- load the registered application ``<app>``
+    (for example: ``'app examples'``)
+"""
+
+import sys
+import os
+
+import pkg_resources
+
+
+def load_entry_point(app, entry_point):
+    """Load an object registered under an entry point
+
+    In:
+      - ``app`` -- name of the object
+      - ``entry_point`` -- name of the entry_point
+
+    Return:
+      - (the object, the distribution of the object)
+    """
+    apps = dict([(entry.name, entry) for entry in pkg_resources.iter_entry_points(entry_point)])
+    entry_point = apps[app]
+
+    return (entry_point.load(), entry_point.dist)
+
+
+def load_app(app, _):
+    """Load a registered application
+
+    In:
+      - ``app`` -- name of the application
+      - ``_`` -- *unused**
+
+    Return:
+      - (the application, the distribution of the application)
+    """
+    return load_entry_point(app, 'nagare.applications')
+
+
+def load_egg(dist, app):
+    """Load a registered application of a distribution
+
+    In:
+      - ``dist`` -- name of the distribution
+      - ``app`` -- name of the application
+
+    Return:
+      - (the application, the distribution of the application)
+    """
+    dist = pkg_resources.get_distribution(dist)
+    return (dist.get_entry_info('nagare.applications', app).load(), dist)
+
+
+def load_file(filename, app):
+    """Load an object from a file
+
+    In:
+      - ``filename`` -- name of the file
+      - ``app`` -- name of the object to load
+
+    Return:
+      - (the object, None)
+    """
+    dir = os.path.abspath(os.path.dirname(filename))
+    if dir not in sys.path:
+        sys.path.insert(0, dir)
+
+    name = os.path.splitext(os.path.basename(filename))[0]
+    return load_module(name, app)
+
+
+def load_module(module, app):
+    """Load an object from a Python module
+
+    In:
+      - ``module`` -- name of the module
+      - ``app`` -- name of the object to load
+
+    Return:
+      - (the object, None)
+    """
+    r = __import__(module, fromlist=('',))
+
+    if app is not None:
+        r = getattr(r, app)
+
+    return (r, None)
+
+
+loaders = {
+            '': load_module,
+            'python': load_module,
+            'egg': load_egg,
+            'file': load_file,
+            'app': load_app
+          }
+
+
+def load_object(reference):
+    """Load an object from a reference
+
+    In:
+      - ``reference`` -- reference as a string
+
+    Return:
+      - a tuple (object loaded, distribution where this object is located or ``None``)
+    """
+    if ' ' in reference:
+        scheme, reference = reference.split(' ', 1)
+    else:
+        scheme = ''
+
+    if ':' in reference:
+        (reference, o) = reference.split(':', 1)
+    else:
+        o = None
+
+    return loaders[scheme](reference, o)

File nagare/admin/serve.py

 import configobj
 
 from nagare import config, log
-from nagare.admin import reloader, util
+from nagare.admin import reloader, util, reference, command
 
 # ---------------------------------------------------------------------------
 
     if not wsgi_pipe:
         return app
 
-    return util.load_object(wsgi_pipe)[0](app, options, config_filename, config, error)
+    return reference.load_object(wsgi_pipe)[0](app, options, config_filename, config, error)
 
 # ---------------------------------------------------------------------------
 
 
 # ---------------------------------------------------------------------------
 
-class Serve(util.Command):
+class Serve(command.Command):
     desc = 'Launch an application'
 
     set_options = staticmethod(set_options)

File nagare/admin/serve_module.py

 import pkg_resources
 
 from nagare import wsgi, log
-from nagare.admin import util, reloader
+from nagare.admin import reference, command, reloader
 
 try:
     from weberror.evalexception import EvalException
       - ``args`` -- arguments in the command lines
 
     The unique argument is the path of the object to launch. The path syntax is described
-    into the module ``nagare.admin.util``. For example, ``/tmp/counter.py:Counter``
+    into the module ``nagare.admin.reference``. For example, ``/tmp/counter.py:Counter``
     is the path to the class ``Counter`` of the module ``tmp.counter.py``
 
     """
         path = 'file ' + args[0]
     else:
         path = 'python ' + args[0]
-    app = util.load_object(path)[0]
+    app = reference.load_object(path)[0]
 
     # Wrap it into a WSGIApp
     app = wsgi.create_WSGIApp(app)
 
 # ---------------------------------------------------------------------------
 
-class Serve(util.Command):
+class Serve(command.Command):
     desc = 'Launch a python module'
 
     set_options = staticmethod(set_options)

File nagare/admin/shell.py

 import pkg_resources
 
 from nagare import database, log, local
-from nagare.admin import util
+from nagare.admin import util, reference, command
 
 
-def create_globals(cfgfiles, debug, error):
-    """
+def activate_applications(cfgfiles, debug, error):
+    """Initialize applications
+
     In:
       - ``cfgfile`` -- paths to application configuration files or names of
         registered applications
       - ``error`` -- the function to call in case of configuration errors
 
     Return:
-      - the namespace with the ``apps`` and ``session`` variables defined
+      - database session
+      - {application name -> application object}
     """
     # Configure the local service
     local.worker = local.Process()
 
     session = database.session
     session.begin()
-    return dict(session=session, apps=apps)
+    return (session, apps)
+
+
+def activate_application(cfgfile, debug, error):
+    """Initialize one application
+
+    In:
+      - ``cfgfile`` -- path to an application configuration file or name of
+        a registered application
+      - ``debug`` -- enable the display of the generated SQL statements
+      - ``error`` -- the function to call in case of configuration errors
+
+    Return:
+      - database session
+      - application name
+      - application object
+    """
+    session, apps = activate_applications([cfgfile], debug, error)
+    return (session,) + apps.items()[0]
+
+
+def create_globals(cfgfiles, debug, error):
+    """Return a namespace with the initialized applications
+
+    In:
+      - ``cfgfile`` -- paths to application configuration files or names of
+        registered applications
+      - ``debug`` -- enable the display of the generated SQL statements
+      - ``error`` -- the function to call in case of configuration errors
+
+    Return:
+      - the namespace with the ``apps`` and ``session`` variables defined
+    """
+    session, apps = activate_applications(cfgfiles, debug, error)
+    return {'session': session, 'apps': apps}
 
 # -----------------------------------------------------------------------------
 
         """
         config = ipython.config.loader.Config()
         prompt = '[%s]' % app_names[0] if len(app_names) == 1 else ''
-        config.InteractiveShellEmbed.prompt_in1 = 'Nagare%s [\\#]: ' % prompt
+        config.PromptManager.in_template = 'Nagare%s [\\#]: ' % prompt
 
         self.shell = ipython.frontend.terminal.embed.InteractiveShellEmbed(config=config, user_ns=ns, banner1=banner)
         self.shell.confirm_exit = False
     create_python_shell(options.ipython, banner, [app.name for app in ns['apps'].values()], ns)
 
 
-class Shell(util.Command):
+class Shell(command.Command):
     desc = 'Launch a shell'
 
     set_options = staticmethod(set_shell_options)
     ns = create_globals(args[:1], options.debug, parser.error)
     __builtin__.__dict__.update(ns)
 
-    util.load_file(args[1], None)
+    reference.load_file(args[1], None)
 
 
-class Batch(util.Command):
+class Batch(command.Command):
     desc = 'Execute Python statements from a file'
 
     set_options = staticmethod(set_batch_options)

File nagare/admin/util.py

 
 """Various tools used be the administrative commands"""
 
-import sys
 import os
 
 import pkg_resources
 import configobj
 
+from nagare.admin import reference
 from nagare import wsgi, config
 
-# ---------------------------------------------------------------------------
-
-class Command:
-    """The base class of all the administration commands"""
-    desc = ''
-
-    @classmethod
-    def set_options(cls, parser):
-        pass
-
-    @classmethod
-    def run(cls, options, args):
-        pass
-
-# ---------------------------------------------------------------------------
-
-def load_entry_point(app, entry_point):
-    """Load an object registered under an entry point
-
-    In:
-      - ``app`` -- name of the object
-      - ``entry_point`` -- name of the entry_point
-
-    Return:
-      - (the object, the distribution of the object)
-    """
-    apps = dict([(entry.name, entry) for entry in pkg_resources.iter_entry_points(entry_point)])
-    entry_point = apps[app]
-
-    return (entry_point.load(), entry_point.dist)
-
-
-def load_app(app, _):
-    """Load a registered application
-
-    In:
-      - ``app`` -- name of the application
-      - ``_`` -- *unused**
-
-    Return:
-      - (the application, the distribution of the application)
-    """
-    return load_entry_point(app, 'nagare.applications')
-
-
-def load_egg(dist, app):
-    """Load a registered application of a distribution
-
-    In:
-      - ``dist`` -- name of the distribution
-      - ``app`` -- name of the application
-
-    Return:
-      - (the application, the distribution of the application)
-    """
-    dist = pkg_resources.get_distribution(dist)
-    return (dist.get_entry_info('nagare.applications', app).load(), dist)
-
-
-def load_file(filename, app):
-    """Load an object from a file
-
-    In:
-      - ``filename`` -- name of the file
-      - ``app`` -- name of the object to load
-
-    Return:
-      - (the object, None)
-    """
-    dir = os.path.abspath(os.path.dirname(filename))
-    if dir not in sys.path:
-        sys.path.insert(0, dir)
-
-    name = os.path.splitext(os.path.basename(filename))[0]
-    return load_module(name, app)
-
-
-def load_module(module, app):
-    """Load an object from a Python module
-
-    In:
-      - ``module`` -- name of the module
-      - ``app`` -- name of the object to load
-
-    Return:
-      - (the object, None)
-    """
-    r = __import__(module, fromlist=('',))
-
-    if app is not None:
-        r = getattr(r, app)
-
-    return (r, None)
-
-loaders = {
-            '': load_module,
-            'python': load_module,
-            'egg': load_egg,
-            'file': load_file,
-            'app': load_app
-          }
-
-
-def load_object(path):
-    """Load an object from a path
-
-    The possible path syntaxes are:
-
-      - ``'python <module>:<object>'`` -- loads an object from a Python module
-        (for example: ``'python os.path:isfile'``)
-      - ``'<module>:<object>'``  -- same as ``'python <module>:<object>'``
-      - ``'file <file>:<object>'`` -- loads an object from a file
-        (for example: ``'file /tmp/counter.py:Counter'``)
-      - ``'egg <dist>:<app>'`` -- loads the registered application ``<app>``
-        from the ``<dist>`` distribution
-        (for example: ``'egg nagare:admin'`` or ``'egg nagare.examples:wiki'``)
-      - ``'app <app>'`` -- load the registered application ``<app>``
-        (for example: ``'app examples'``)
-
-    Return:
-      - a tuple (object loaded, distribution where this object is located or ``None``)
-    """
-    if ' ' in path:
-        scheme, path = path.split(' ', 1)
-    else:
-        scheme = ''
-
-    if ':' in path:
-        (path, o) = path.split(':', 1)
-    else:
-        o = None
-
-    return loaders[scheme](path, o)
-
-# ---------------------------------------------------------------------------
-
 # The default application configuration
 # -------------------------------------
 
     aconf = read_application_options(cfgfile, error)
 
     # From the path of the application, create the application object
-    (app, dist) = load_object(aconf['application']['path'])
+    (app, dist) = reference.load_object(aconf['application']['path'])
 
     defaults = dict(here='string(default="%s")' % os.path.abspath(os.path.dirname(cfgfile)))
     if dist is not None:
         return None
 
     # Import the metadata object
-    metadata = load_object(metadata)[0]
+    metadata = reference.load_object(metadata)[0]
 
     # All the parameters, of the [database] section, with an unknown name are
     # given to the database engine
       generate_html = nagare.doc.setuplib:GenerateHTML [doc]
 
       [console_scripts]
-      nagare-admin = nagare.admin.main:main
+      nagare-admin = nagare.admin.command:run
 
       [nagare.commands]
       info = nagare.admin.info:Info