~launchpad-pqm/launchpad/devel

« back to all changes in this revision

Viewing changes to utilities/script_commands.py

  • Committer: Launchpad Patch Queue Manager
  • Date: 2011-08-04 18:06:38 UTC
  • mfrom: (13588.1.4 induce-latency)
  • Revision ID: launchpad@pqm.canonical.com-20110804180638-e1m4y7fcwlseqrle
[r=jcsackett][bug=821038] Add local-latency script.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
import optparse
 
2
 
 
3
 
 
4
class UserError(Exception):
 
5
    pass
 
6
 
 
7
 
 
8
class OptionParser(optparse.OptionParser):
 
9
 
 
10
    UNSPECIFIED = object()
 
11
 
 
12
    def add_option(self, *args, **kwargs):
 
13
        """Add an option, with the default that it not be included."""
 
14
        kwargs['default'] = kwargs.get('default', self.UNSPECIFIED)
 
15
        optparse.OptionParser.add_option(self, *args, **kwargs)
 
16
 
 
17
    def parse_args_dict(self, cmd_args):
 
18
        """Return a dict of specified options.
 
19
 
 
20
        Unspecified options with no explicit default are not included in the
 
21
        dict."""
 
22
        options, args = self.parse_args(cmd_args)
 
23
        option_dict = dict(
 
24
            item for item in options.__dict__.items()
 
25
            if item[1] is not self.UNSPECIFIED)
 
26
        return args, option_dict
 
27
 
 
28
 
 
29
class Command:
 
30
    """Base class for subcommands."""
 
31
 
 
32
    commands = {}
 
33
 
 
34
    @classmethod
 
35
    def parse_args(cls, args):
 
36
        if len(args) != 0:
 
37
            raise UserError('Too many arguments.')
 
38
        return {}
 
39
 
 
40
    @classmethod
 
41
    def run_from_args(cls, cmd_args):
 
42
        args, kwargs = cls.get_parser().parse_args_dict(cmd_args)
 
43
        kwargs.update(cls.parse_args(args))
 
44
        cls.run(**kwargs)
 
45
 
 
46
    @classmethod
 
47
    def run_subcommand(cls, argv):
 
48
        if len(argv) < 1:
 
49
            raise UserError('Must supply a command: %s.' %
 
50
                            ', '.join(cls.commands.keys()))
 
51
        try:
 
52
            command = cls.commands[argv[0]]
 
53
        except KeyError:
 
54
            raise UserError('%s invalid.  Valid commands: %s.' %
 
55
                            (argv[0], ', '.join(cls.commands.keys())))
 
56
        command.run_from_args(argv[1:])