update to lgc.clcommands 0.51 api stable
authorSylvain Thénault <sylvain.thenault@logilab.fr>
Wed, 25 Aug 2010 09:42:55 +0200
branchstable
changeset 6138 65f5e488f983
parent 6132 440df442d705
child 6139 f76599a96238
child 6143 d7d2edf70011
update to lgc.clcommands 0.51 api
__pkginfo__.py
cwconfig.py
cwctl.py
debian/control
devtools/devctl.py
server/serverctl.py
toolsutils.py
--- a/__pkginfo__.py	Fri Aug 20 17:08:08 2010 +0200
+++ b/__pkginfo__.py	Wed Aug 25 09:42:55 2010 +0200
@@ -40,7 +40,7 @@
 ]
 
 __depends__ = {
-    'logilab-common': '>= 0.50.2',
+    'logilab-common': '>= 0.51.0',
     'logilab-mtconverter': '>= 0.8.0',
     'rql': '>= 0.26.2',
     'yams': '>= 0.29.1',
--- a/cwconfig.py	Fri Aug 20 17:08:08 2010 +0200
+++ b/cwconfig.py	Wed Aug 25 09:42:55 2010 +0200
@@ -297,7 +297,6 @@
     # nor remove appobjects based on unused interface [???]
     cleanup_interface_sobjects = True
 
-
     if (CWDEV and _forced_mode != 'system'):
         mode = 'user'
         _CUBES_DIR = join(CW_SOFTWARE_ROOT, '../cubes')
--- a/cwctl.py	Fri Aug 20 17:08:08 2010 +0200
+++ b/cwctl.py	Wed Aug 25 09:42:55 2010 +0200
@@ -37,12 +37,15 @@
 
 from os.path import exists, join, isfile, isdir, dirname, abspath
 
-from logilab.common.clcommands import register_commands, pop_arg
+from logilab.common.clcommands import CommandLine
 from logilab.common.shellutils import ASK
 
 from cubicweb import ConfigurationError, ExecutionError, BadCommandUsage
 from cubicweb.cwconfig import CubicWebConfiguration as cwcfg, CWDEV, CONFIGURATIONS
-from cubicweb.toolsutils import Command, main_run, rm, create_dir, underline_title
+from cubicweb.toolsutils import Command, rm, create_dir, underline_title
+from cubicweb.__pkginfo__ import version
+
+CWCTL = CommandLine('cubicweb-ctl', 'The CubicWeb swiss-knife.', version=version)
 
 def wait_process_end(pid, maxtry=10, waittime=1):
     """wait for a process to actually die"""
@@ -301,6 +304,7 @@
     """
     name = 'create'
     arguments = '<cube> <instance>'
+    min_args = max_args = 2
     options = (
         ("config-level",
          {'short': 'l', 'type' : 'int', 'metavar': '<level>',
@@ -325,8 +329,8 @@
         """run the command with its specific arguments"""
         from logilab.common.textutils import splitstrip
         configname = self.config.config
-        cubes = splitstrip(pop_arg(args, 1))
-        appid = pop_arg(args)
+        appid, cubes = args
+        cubes = splitstrip(cubes)
         # get the configuration and helper
         config = cwcfg.config_for(appid, configname)
         config.set_language = False
@@ -415,12 +419,12 @@
     """
     name = 'delete'
     arguments = '<instance>'
-
+    min_args = max_args = 1
     options = ()
 
     def run(self, args):
         """run the command with its specific arguments"""
-        appid = pop_arg(args, msg="No instance specified !")
+        appid = args[0]
         configs = [cwcfg.config_for(appid, configname)
                    for configname in cwcfg.possible_configurations(appid)]
         if not configs:
@@ -796,6 +800,7 @@
     """
     name = 'shell'
     arguments = '<instance> [batch command file(s)] [-- <script arguments>]'
+    min_args = 1
     options = (
         ('system-only',
          {'short': 'S', 'action' : 'store_true',
@@ -834,7 +839,7 @@
         )
 
     def run(self, args):
-        appid = pop_arg(args, None, msg="No instance specified !")
+        appid = args.pop(0)
         if self.config.pyro:
             from cubicweb import AuthenticationError
             from cubicweb.dbapi import connect
@@ -930,30 +935,29 @@
         for cube in cwcfg.available_cubes():
             print cube
 
-register_commands((ListCommand,
-                   CreateInstanceCommand,
-                   DeleteInstanceCommand,
-                   StartInstanceCommand,
-                   StopInstanceCommand,
-                   RestartInstanceCommand,
-                   ReloadConfigurationCommand,
-                   StatusCommand,
-                   UpgradeInstanceCommand,
-                   ShellCommand,
-                   RecompileInstanceCatalogsCommand,
-                   ListInstancesCommand, ListCubesCommand,
-                   ))
+for cmdcls in (ListCommand,
+               CreateInstanceCommand, DeleteInstanceCommand,
+               StartInstanceCommand, StopInstanceCommand, RestartInstanceCommand,
+               ReloadConfigurationCommand, StatusCommand,
+               UpgradeInstanceCommand,
+               ShellCommand,
+               RecompileInstanceCatalogsCommand,
+               ListInstancesCommand, ListCubesCommand,
+               ):
+    CWCTL.register(cmdcls)
 
 
 def run(args):
     """command line tool"""
     cwcfg.load_cwctl_plugins()
-    main_run(args, """%%prog %s [options] %s
-
-The CubicWeb swiss-knife.
-
-%s"""
-)
+    try:
+        CWCTL.run(args)
+    except ConfigurationError, err:
+        print 'ERROR: ', err
+        sys.exit(1)
+    except ExecutionError, err:
+        print err
+        sys.exit(2)
 
 if __name__ == '__main__':
     run(sys.argv[1:])
--- a/debian/control	Fri Aug 20 17:08:08 2010 +0200
+++ b/debian/control	Wed Aug 25 09:42:55 2010 +0200
@@ -97,7 +97,7 @@
 Package: cubicweb-common
 Architecture: all
 XB-Python-Version: ${python:Versions}
-Depends: ${python:Depends}, graphviz, gettext, python-logilab-mtconverter (>= 0.8.0), python-logilab-common (>= 0.50.2), python-yams (>= 0.29.1), python-rql (>= 0.26.3), python-lxml
+Depends: ${python:Depends}, graphviz, gettext, python-logilab-mtconverter (>= 0.8.0), python-logilab-common (>= 0.51.0), python-yams (>= 0.29.1), python-rql (>= 0.26.3), python-lxml
 Recommends: python-simpletal (>= 4.0), python-crypto
 Conflicts: cubicweb-core
 Replaces: cubicweb-core
--- a/devtools/devctl.py	Fri Aug 20 17:08:08 2010 +0200
+++ b/devtools/devctl.py	Wed Aug 25 09:42:55 2010 +0200
@@ -31,10 +31,10 @@
 from warnings import warn
 
 from logilab.common import STD_BLACKLIST
-from logilab.common.clcommands import register_commands, pop_arg
 
 from cubicweb.__pkginfo__ import version as cubicwebversion
 from cubicweb import CW_SOFTWARE_ROOT as BASEDIR, BadCommandUsage
+from cubicweb.cwctl import CWCTL
 from cubicweb.toolsutils import (SKEL_EXCLUDE, Command,
                                  copy_skeleton, underline_title)
 from cubicweb.web.webconfig import WebConfiguration
@@ -684,6 +684,7 @@
     """Generate schema image for the given cube"""
     name = "schema"
     arguments = '<cube>'
+    min_args = max_args = 1
     options = [('output-file', {'type':'file', 'default': None,
                  'metavar': '<file>', 'short':'o', 'help':'output image file',
                  'input':False}),
@@ -720,7 +721,7 @@
         from yams import schema2dot, BASE_TYPES
         from cubicweb.schema import (META_RTYPES, SCHEMA_TYPES, SYSTEM_RTYPES,
                                      WORKFLOW_TYPES, INTERNAL_TYPES)
-        cubes = splitstrip(pop_arg(args, 1))
+        cubes = splitstrip(args[0])
         dev_conf = DevConfiguration(*cubes)
         schema = dev_conf.load_schema()
         out, viewer = self['output-file'], self['viewer']
@@ -751,11 +752,12 @@
         from cubicweb.devtools.qunit import make_qunit_html
         print make_qunit_html(args[0], args[1:])
 
-register_commands((UpdateCubicWebCatalogCommand,
-                   UpdateTemplateCatalogCommand,
-                   #LiveServerCommand,
-                   NewCubeCommand,
-                   ExamineLogCommand,
-                   GenerateSchema,
-                   GenerateQUnitHTML,
-                   ))
+for cmdcls in (UpdateCubicWebCatalogCommand,
+               UpdateTemplateCatalogCommand,
+               #LiveServerCommand,
+               NewCubeCommand,
+               ExamineLogCommand,
+               GenerateSchema,
+               GenerateQUnitHTML,
+               ):
+    CWCTL.register(cmdcls)
--- a/server/serverctl.py	Fri Aug 20 17:08:08 2010 +0200
+++ b/server/serverctl.py	Wed Aug 25 09:42:55 2010 +0200
@@ -26,11 +26,11 @@
 import os
 
 from logilab.common.configuration import Configuration
-from logilab.common.clcommands import register_commands, cmd_run, pop_arg
 from logilab.common.shellutils import ASK
 
 from cubicweb import AuthenticationError, ExecutionError, ConfigurationError
 from cubicweb.toolsutils import Command, CommandHandler, underline_title
+from cubicweb.cwctl import CWCTL
 from cubicweb.server import SOURCE_TYPES
 from cubicweb.server.serverconfig import (USER_OPTIONS, ServerConfiguration,
                                           SourceConfiguration)
@@ -217,7 +217,7 @@
     def postcreate(self):
         if ASK.confirm('Run db-create to create the system database ?'):
             verbosity = (self.config.mode == 'installed') and 'y' or 'n'
-            cmd_run('db-create', self.config.appid, '--verbose=%s' % verbosity)
+            CWCTL.run(['db-create', self.config.appid, '--verbose=%s' % verbosity])
         else:
             print ('-> nevermind, you can do it later with '
                    '"cubicweb-ctl db-create %s".' % self.config.appid)
@@ -299,7 +299,7 @@
     """
     name = 'db-create'
     arguments = '<instance>'
-
+    min_args = max_args = 1
     options = (
         ('create-db',
          {'short': 'c', 'type': 'yn', 'metavar': '<y or n>',
@@ -323,7 +323,7 @@
         from logilab.database import get_db_helper
         verbose = self.get('verbose')
         automatic = self.get('automatic')
-        appid = pop_arg(args, msg='No instance specified !')
+        appid = args.pop()
         config = ServerConfiguration.config_for(appid)
         source = config.sources()['system']
         dbname = source['db-name']
@@ -371,7 +371,7 @@
         print '-> database for instance %s created and necessary extensions installed.' % appid
         print
         if automatic or ASK.confirm('Run db-init to initialize the system database ?'):
-            cmd_run('db-init', config.appid)
+            CWCTL.run(['db-init', config.appid])
         else:
             print ('-> nevermind, you can do it later with '
                    '"cubicweb-ctl db-init %s".' % config.appid)
@@ -389,7 +389,7 @@
     """
     name = 'db-init'
     arguments = '<instance>'
-
+    min_args = max_args = 1
     options = (
         ('drop',
          {'short': 'd', 'action': 'store_true',
@@ -402,7 +402,7 @@
         print '\n'+underline_title('Initializing the system database')
         from cubicweb.server import init_repository
         from logilab.database import get_connection
-        appid = pop_arg(args, msg='No instance specified !')
+        appid = args[0]
         config = ServerConfiguration.config_for(appid)
         try:
             system = config.sources()['system']
@@ -431,7 +431,7 @@
     """
     name = 'db-grant-user'
     arguments = '<instance> <user>'
-
+    min_args = max_args = 2
     options = (
         ('set-owner',
          {'short': 'o', 'type' : 'yn', 'metavar' : '<yes or no>',
@@ -442,8 +442,7 @@
     def run(self, args):
         """run the command with its specific arguments"""
         from cubicweb.server.sqlutils import sqlexec, sqlgrants
-        appid = pop_arg(args, 1, msg='No instance specified !')
-        user = pop_arg(args, msg='No user specified !')
+        appid, user = args
         config = ServerConfiguration.config_for(appid)
         source = config.sources()['system']
         set_owner = self.config.set_owner
@@ -475,7 +474,7 @@
     def run(self, args):
         """run the command with its specific arguments"""
         from cubicweb.server.utils import crypt_password, manager_userpasswd
-        appid = pop_arg(args, 1, msg='No instance specified !')
+        appid = args[0]
         config = ServerConfiguration.config_for(appid)
         sourcescfg = config.read_sources_file()
         try:
@@ -526,7 +525,7 @@
     """
     name = 'start-repository'
     arguments = '<instance>'
-
+    min_args = max_args = 1
     options = (
         ('debug',
          {'short': 'D', 'action' : 'store_true',
@@ -542,7 +541,7 @@
         from logilab.common.daemon import daemonize
         from cubicweb.cwctl import init_cmdline_log_threshold
         from cubicweb.server.server import RepositoryServer
-        appid = pop_arg(args, msg='No instance specified !')
+        appid = args[0]
         debug = self['debug']
         if sys.platform == 'win32' and not debug:
             from logging import getLogger
@@ -673,7 +672,7 @@
     """
     name = 'db-dump'
     arguments = '<instance>'
-
+    min_args = max_args = 1
     options = (
         ('output',
          {'short': 'o', 'type' : 'string', 'metavar' : '<file>',
@@ -688,7 +687,7 @@
         )
 
     def run(self, args):
-        appid = pop_arg(args, 1, msg='No instance specified !')
+        appid = args[0]
         if ':' in appid:
             host, appid = appid.split(':')
             _remote_dump(host, appid, self.config.output, self.config.sudo)
@@ -704,6 +703,7 @@
     """
     name = 'db-restore'
     arguments = '<instance> <backupfile>'
+    min_args = max_args = 2
 
     options = (
         ('no-drop',
@@ -721,8 +721,7 @@
         )
 
     def run(self, args):
-        appid = pop_arg(args, 1, msg='No instance specified !')
-        backupfile = pop_arg(args, msg='No backup file or timestamp specified !')
+        appid, backupfile = args
         _local_restore(appid, backupfile,
                        drop=not self.config.no_drop,
                        systemonly=not self.config.restore_all)
@@ -740,7 +739,7 @@
     """
     name = 'db-copy'
     arguments = '<src-instance> <dest-instance>'
-
+    min_args = max_args = 2
     options = (
         ('no-drop',
          {'short': 'n', 'action' : 'store_true',
@@ -762,8 +761,7 @@
 
     def run(self, args):
         import tempfile
-        srcappid = pop_arg(args, 1, msg='No source instance specified !')
-        destappid = pop_arg(args, msg='No destination instance specified !')
+        srcappid, destappid = args
         fd, output = tempfile.mkstemp()
         os.close(fd)
         if ':' in srcappid:
@@ -786,7 +784,7 @@
     """
     name = 'db-check'
     arguments = '<instance>'
-
+    min_args = max_args = 1
     options = (
         ('checks',
          {'short': 'c', 'type' : 'csv', 'metavar' : '<check list>',
@@ -816,8 +814,7 @@
         )
 
     def run(self, args):
-        from cubicweb.server.checkintegrity import check
-        appid = pop_arg(args, 1, msg='No instance specified !')
+        appid = args[0]
         config = ServerConfiguration.config_for(appid)
         config.repairing = self.config.force
         repo, cnx = repo_cnx(config)
@@ -833,12 +830,11 @@
     """
     name = 'db-rebuild-fti'
     arguments = '<instance>'
-
-    options = ()
+    min_args = max_args = 1
 
     def run(self, args):
         from cubicweb.server.checkintegrity import reindex_entities
-        appid = pop_arg(args, 1, msg='No instance specified !')
+        appid = args[0]
         config = ServerConfiguration.config_for(appid)
         repo, cnx = repo_cnx(config)
         session = repo._get_session(cnx.sessionid, setpool=True)
@@ -857,9 +853,10 @@
     """
     name = 'schema-sync'
     arguments = '<instance>'
+    min_args = max_args = 1
 
     def run(self, args):
-        appid = pop_arg(args, msg='No instance specified !')
+        appid = args[0]
         config = ServerConfiguration.config_for(appid)
         mih = config.migration_handler()
         mih.cmd_synchronize_schema()
@@ -885,24 +882,19 @@
     def run(self, args):
         from cubicweb.server.checkintegrity import check_mapping
         from cubicweb.server.sources.pyrorql import load_mapping_file
-        appid = pop_arg(args, 1, msg='No instance specified !')
-        mappingfile = pop_arg(args, msg='No mapping file specified !')
+        appid, mappingfile = args
         config = ServerConfiguration.config_for(appid)
         config.quick_start = True
         mih = config.migration_handler(connect=False, verbosity=1)
         repo = mih.repo_connect() # necessary to get cubes
         check_mapping(config.load_schema(), load_mapping_file(mappingfile))
 
-register_commands( (CreateInstanceDBCommand,
-                    InitInstanceCommand,
-                    GrantUserOnInstanceCommand,
-                    ResetAdminPasswordCommand,
-                    StartRepositoryCommand,
-                    DBDumpCommand,
-                    DBRestoreCommand,
-                    DBCopyCommand,
-                    CheckRepositoryCommand,
-                    RebuildFTICommand,
-                    SynchronizeInstanceSchemaCommand,
-                    CheckMappingCommand,
-                    ) )
+for cmdclass in (CreateInstanceDBCommand, InitInstanceCommand,
+                 GrantUserOnInstanceCommand, ResetAdminPasswordCommand,
+                 StartRepositoryCommand,
+                 DBDumpCommand, DBRestoreCommand, DBCopyCommand,
+                 CheckRepositoryCommand, RebuildFTICommand,
+                 SynchronizeInstanceSchemaCommand,
+                 CheckMappingCommand,
+                 ):
+    CWCTL.register(cmdclass)
--- a/toolsutils.py	Fri Aug 20 17:08:08 2010 +0200
+++ b/toolsutils.py	Wed Aug 25 09:42:55 2010 +0200
@@ -15,9 +15,8 @@
 #
 # You should have received a copy of the GNU Lesser General Public License along
 # with CubicWeb.  If not, see <http://www.gnu.org/licenses/>.
-"""some utilities for cubicweb tools
+"""some utilities for cubicweb command line tools"""
 
-"""
 __docformat__ = "restructuredtext en"
 
 # XXX move most of this in logilab.common (shellutils ?)
@@ -33,8 +32,7 @@
     def symlink(*args):
         raise NotImplementedError
 
-from logilab.common.clcommands import Command as BaseCommand, \
-     main_run as base_main_run
+from logilab.common.clcommands import Command as BaseCommand
 from logilab.common.compat import any
 from logilab.common.shellutils import ASK
 
@@ -260,17 +258,6 @@
         sys.exit(1)
 
 
-def main_run(args, doc):
-    """command line tool"""
-    try:
-        base_main_run(args, doc, copyright=None)
-    except ConfigurationError, err:
-        print 'ERROR: ', err
-        sys.exit(1)
-    except ExecutionError, err:
-        print err
-        sys.exit(2)
-
 CONNECT_OPTIONS = (
     ("user",
      {'short': 'u', 'type' : 'string', 'metavar': '<user>',