James Palmer avatar James Palmer committed a78f3a6

Remove uneccessary code (refactoring). Outline code for adding local libs.

Comments (0)

Files changed (7)

ignite/bool_optparse.py

-# (c) 2005 Ian Bicking and contributors; written for Paste
-# (http://pythonpaste.org)
-#
-# Licensed under the MIT license:
-# http://www.opensource.org/licenses/mit-license.php
-"""
-A subclass of ``optparse.OptionParser`` that allows boolean long
-options (like ``--verbose``) to also take arguments (like
-``--verbose=true``).  Arguments *must* use ``=``.
-"""
-
-import optparse
-
-try:
-    _ = optparse._
-except AttributeError:
-    from gettext import gettext as _
-
-
-class BoolOptionParser(optparse.OptionParser):
-
-    def _process_long_opt(self, rargs, values):
-        arg = rargs.pop(0)
-
-        # Value explicitly attached to arg?  Pretend it's the next
-        # argument.
-        if "=" in arg:
-            (opt, next_arg) = arg.split("=", 1)
-            rargs.insert(0, next_arg)
-            had_explicit_value = True
-        else:
-            opt = arg
-            had_explicit_value = False
-
-        opt = self._match_long_opt(opt)
-        option = self._long_opt[opt]
-        if option.takes_value():
-            nargs = option.nargs
-            if len(rargs) < nargs:
-                if nargs == 1:
-                    self.error(_("%s option requires an argument") % opt)
-                else:
-                    self.error(_("%s option requires %d arguments")
-                               % (opt, nargs))
-            elif nargs == 1:
-                value = rargs.pop(0)
-            else:
-                value = tuple(rargs[0:nargs])
-                del rargs[0:nargs]
-
-        elif had_explicit_value:
-            value = rargs[0].lower().strip()
-            del rargs[0:1]
-            if value in ('true', 'yes', 'on', '1', 'y', 't'):
-                value = None
-            elif value in ('false', 'no', 'off', '0', 'n', 'f'):
-                # Don't process
-                return
-            else:
-                self.error(_('%s option takes a boolean value only ' +
-                             '(true/false)') % opt)
-
-        else:
-            value = None
-
-        option.process(opt, value, values, self)

ignite/command.py

 # http://www.opensource.org/licenses/mit-license.php
 import pkg_resources
 import sys
-import optparse
-import bool_optparse
+from optparse2 import OptionParser
 import os
 import re
 import textwrap
 
 python_version = sys.version.splitlines()[0].strip()
 
-parser = optparse.OptionParser(
+parser = OptionParser(
     add_help_option=False,
     version='%s from %s (python %s)'
     % (dist, dist.location, python_version),
     if not args:
         print 'Usage: %s COMMAND' % sys.argv[0]
         args = ['help']
+
     command_name = args[0]
     if command_name not in commands:
-        command = NotFoundCommand
-    else:
-        command = commands[command_name].load()
-    invoke(command, command_name, options, args[1:])
+        print ('Command %r not known (you may need to run setup.py egg_info)'
+               % command_name)
+
+        commands = get_commands().items()
+        if not commands:
+            print 'No commands registered.'
+            print 'Have you installed Ignite?'
+            print '(try running python setup.py develop)'
+            sys.exit(2)
+
+        print 'Known commands:'
+        commands.sort()
+        longest = max([len(n) for n, c in commands])
+        for name, command in commands:
+            print '  %s  %s' % (self.pad(name, length=longest),
+                                command.load().summary)
+
+        sys.exit(2)
+
+    command_class = commands[command_name].load()
+
+    try:
+        command = command_class()
+        exit_code = command.run(args)
+    except BadCommand, e:
+        print e.message
+        exit_code = e.exit_code
+
+    sys.exit(exit_code)
 
 
 def parse_exe_file(config):
         if base_dir not in sys.path:
             sys.path.insert(0, base_dir)
             pkg_resources.working_set.add_entry(base_dir)
+    # REFACTOR resolve_plugins
     plugins = pluginlib.resolve_plugins(plugins)
+    # REFACTOR load_commands_from_plugin called once
     commands = pluginlib.load_commands_from_plugins(plugins)
+    # REFACTOR load_global_commands called once
     commands.update(pluginlib.load_global_commands())
+
+    # Load local stuff..
+    # STEP 1. GO UP PARENT CHAIN LOOKING FOR "IgniteFile"
+    # STEP 2. GET THE libs DIRECTORY from THAT DIR
+    # STEP 3. INSIDE EACH SUBDIR LOOK FOR ignite/__init__.py
+    # STEP 4. LOOK FOR CLASSES THAT GOT PUBLISHED IN INIT..
+    # STEP 5. ITERATE OVER CLASSES AND ADD TO COMMANDS
+
     return commands
 
 
-def invoke(command, command_name, options, args):
-    try:
-        runner = command(command_name)
-        exit_code = runner.run(args)
-    except BadCommand, e:
-        print e.message
-        exit_code = e.exit_code
-    sys.exit(exit_code)
-
-
 class Command(object):
 
-    def __init__(self, name):
-        self.command_name = name
+    command_name = ''
+    description = None
+    usage = None
 
-    max_args = None
-    max_args_error = 'You must provide no more than %(max_args)s arguments'
-    min_args = None
-    min_args_error = 'You must provide at least %(min_args)s arguments'
-    required_args = None
-    # If this command takes a configuration file, set this to 1 or -1
-    # Then if invoked through #! the config file will be put into the
-    # positional arguments -- at the beginning with 1, at the end with -1
-    takes_config_file = None
-
-    # Grouped in help messages by this:
-    group_name = ''
-
-    required_args = ()
-    description = None
-    usage = ''
-    hidden = False
-    # This is the default verbosity level; --quiet subtracts,
-    # --verbose adds:
-    default_verbosity = 0
-    # This is the default interactive state:
-    default_interactive = 0
-    return_code = 0
-
-    BadCommand = BadCommand
-
-    # Must define:
+    # Subclasses must implement these:
     #   parser
     #   summary
     #   command()
                 setattr(self.options, name, default)
         if getattr(self.options, 'simulate', False):
             self.options.verbose = max(self.options.verbose, 1)
-        self.interactive = self.default_interactive
+
+        self.interactive = 0
         if getattr(self.options, 'interactive', False):
             self.interactive += self.options.interactive
         if getattr(self.options, 'no_interactive', False):
             self.interactive = False
-        self.verbose = self.default_verbosity
+
+        self.verbose = 0
         self.verbose += self.options.verbose
         self.verbose -= self.options.quiet
         self.simulate = getattr(self.options, 'simulate', False)
 
-        # For #! situations:
-        if (os.environ.get('IGNITE_CONFIG_FILE')
-            and self.takes_config_file is not None):
-            take = self.takes_config_file
-            filename = os.environ.get('IGNITE_CONFIG_FILE')
-            if take == 1:
-                self.args.insert(0, filename)
-            elif take == -1:
-                self.args.append(filename)
-            else:
-                assert 0, (
-                    "Value takes_config_file must be None, 1, or -1 (not %r)"
-                    % take)
-
         if (os.environ.get('IGNITE_DEFAULT_QUIET')):
             self.verbose = 0
 
-        # Validate:
-        if self.min_args is not None and len(self.args) < self.min_args:
-            raise BadCommand(
-                self.min_args_error % {'min_args': self.min_args,
-                                       'actual_args': len(self.args)})
-        if self.max_args is not None and len(self.args) > self.max_args:
-            raise BadCommand(
-                self.max_args_error % {'max_args': self.max_args,
-                                       'actual_args': len(self.args)})
-        for var_name, option_name in self.required_args:
-            if not getattr(self.options, var_name, None):
-                raise BadCommand(
-                    'You must provide the option %s' % option_name)
         result = self.command()
         if result is None:
-            return self.return_code
+            return 0
         else:
             return result
 
         self.options, self.args = self.parser.parse_args(args)
 
     def _prog_name(self):
-        return '%s %s' % (os.path.basename(sys.argv[0]), self.command_name)
+        return '%s %s' % (os.path.basename(sys.argv[0]), self.__class__.command_name)
 
     ########################################
     ## Utility methods
         Subclasses may redefine ``standard_parser``, so use the
         nearest superclass's class method.
         """
-        parser = bool_optparse.BoolOptionParser()
+        parser = OptionParser()
         if verbose:
             parser.add_option('-v', '--verbose',
                               action='count',

ignite/create_distro.py

 
 class CreateDistroCommand(Command):
 
+    name = "create"
     usage = 'PACKAGE_NAME [VAR=VALUE VAR2=VALUE2 ...]'
     summary = "Create the file layout for a Python distribution"
     short_description = summary
 
     parser = Command.standard_parser(
         simulate=True, no_interactive=True, quiet=True, overwrite=True)
+
     parser.add_option('-t', '--template',
                       dest='templates',
                       metavar='TEMPLATE',
         if package_dir:
             output_dir = os.path.join(output_dir, package_dir)
 
-        # With no setup.py this doesn't make sense:
-        if found_setup_py:
-            # Only write ignite_plugins.txt if it wasn't written by
-            # egg_info (the correct way). leaving us to do it is
-            # deprecated and you'll get warned
-            egg_info_dir = pluginlib.egg_info_dir(output_dir, dist_name)
-            plugins_path = os.path.join(egg_info_dir, 'ignite_plugins.txt')
-            if len(egg_plugins) and (not os.path.exists(plugins_path) or \
-                    os.path.getmtime(plugins_path) == ignite_plugins_mtime):
-                if self.verbose:
-                    print >> sys.stderr, \
-                        ('Manually creating ignite_plugins.txt (deprecated! '
-                         'pass a ignite_plugins keyword to setup() instead)')
-                for plugin in egg_plugins:
-                    if self.verbose:
-                        print 'Adding %s to ignite_plugins.txt' % plugin
-                    if not self.simulate:
-                        pluginlib.add_plugin(egg_info_dir, plugin)
-
         if self.options.svn_repository:
             self.add_svn_repository(vars, output_dir)
 

ignite/entrypoints.py

     entry point is named.
     """
 
-    max_args = 2
-
     parser = Command.standard_parser(verbose=False)
     parser.add_option('--list', '-l',
                       dest='list_entry_points',
 
 class HelpCommand(Command):
 
-    summary = "Display help"
+    name = 'help'
+    summary = 'Display help'
     usage = '[COMMAND]'
 
-    max_args = 1
-
     parser = Command.standard_parser()
 
     def command(self):
             return
 
         command = commands[name].load()
-        runner = command(name)
+        runner = command()
         runner.run(['-h'])
 
     def generic_help(self):
             except Exception, e:
                 print 'Cannot load command %s: %s' % (name, e)
                 continue
-            if getattr(command, 'hidden', False):
-                continue
-            commands_grouped.setdefault(
-                command.group_name, []).append((name, command))
+            commands_grouped.append((name, command))
         commands_grouped = commands_grouped.items()
         commands_grouped.sort()
         print 'Commands:'

ignite/optparse2.py

+# (c) 2005 Ian Bicking and contributors; written for Paste
+# (http://pythonpaste.org)
+#
+# Licensed under the MIT license:
+# http://www.opensource.org/licenses/mit-license.php
+"""
+A subclass of ``optparse.OptionParser`` that allows boolean long
+options (like ``--verbose``) to also take arguments (like
+``--verbose=true``).  Arguments *must* use ``=``.
+"""
+
+import optparse
+
+try:
+    _ = optparse._
+except AttributeError:
+    from gettext import gettext as _
+
+
+class OptionParser(optparse.OptionParser):
+
+    def _process_long_opt(self, rargs, values):
+        arg = rargs.pop(0)
+
+        # Value explicitly attached to arg?  Pretend it's the next
+        # argument.
+        if "=" in arg:
+            (opt, next_arg) = arg.split("=", 1)
+            rargs.insert(0, next_arg)
+            had_explicit_value = True
+        else:
+            opt = arg
+            had_explicit_value = False
+
+        opt = self._match_long_opt(opt)
+        option = self._long_opt[opt]
+        if option.takes_value():
+            nargs = option.nargs
+            if len(rargs) < nargs:
+                if nargs == 1:
+                    self.error(_("%s option requires an argument") % opt)
+                else:
+                    self.error(_("%s option requires %d arguments")
+                               % (opt, nargs))
+            elif nargs == 1:
+                value = rargs.pop(0)
+            else:
+                value = tuple(rargs[0:nargs])
+                del rargs[0:nargs]
+
+        elif had_explicit_value:
+            value = rargs[0].lower().strip()
+            del rargs[0:1]
+            if value in ('true', 'yes', 'on', '1', 'y', 't'):
+                value = None
+            elif value in ('false', 'no', 'off', '0', 'n', 'f'):
+                # Don't process
+                return
+            else:
+                self.error(_('%s option takes a boolean value only ' +
+                             '(true/false)') % opt)
+
+        else:
+            value = None
+
+        option.process(opt, value, values, self)

ignite/pluginlib.py

 import pkg_resources
 
 
-def add_plugin(egg_info_dir, plugin_name):
-    """
-    Add the plugin to the given distribution (or spec), in
-    .egg-info/ignite_plugins.txt
-    """
-    fn = os.path.join(egg_info_dir, 'ignite_plugins.txt')
-    if not os.path.exists(fn):
-        lines = []
-    else:
-        f = open(fn)
-        lines = [l.strip() for l in f.readlines() if l.strip()]
-        f.close()
-    if plugin_name in lines:
-        # Nothing to do
-        return
-    lines.append(plugin_name)
-    if not os.path.exists(os.path.dirname(fn)):
-        os.makedirs(os.path.dirname(fn))
-    f = open(fn, 'w')
-    for line in lines:
-        f.write(line)
-        f.write('\n')
-    f.close()
-
-
-def remove_plugin(egg_info_dir, plugin_name):
-    """
-    Remove the plugin to the given distribution (or spec), in
-    .egg-info/ignite_plugins.txt.  Raises ValueError if the
-    plugin is not in the file.
-    """
-    fn = os.path.join(egg_info_dir, 'ignite_plugins.txt')
-    if not os.path.exists(fn):
-        raise ValueError(
-            "Cannot remove plugin from %s; file does not exist"
-            % fn)
-    f = open(fn)
-    lines = [l.strip() for l in f.readlines() if l.strip()]
-    f.close()
-    for line in lines:
-        # What about version specs?
-        if line.lower() == plugin_name.lower():
-            break
-    else:
-        raise ValueError(
-            "Plugin %s not found in file %s (from: %s)"
-            % (plugin_name, fn, lines))
-    lines.remove(line)
-    print 'writing', lines
-    f = open(fn, 'w')
-    for line in lines:
-        f.write(line)
-        f.write('\n')
-    f.close()
-
-
 def find_egg_info_dir(dir):
     while 1:
         try:
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.