~ubuntu-branches/ubuntu/wily/python-argh/wily

« back to all changes in this revision

Viewing changes to argh/helpers.py

  • Committer: Package Import Robot
  • Author(s): Marco Nenciarini
  • Date: 2012-10-22 16:39:30 UTC
  • mfrom: (1.1.1)
  • Revision ID: package-import@ubuntu.com-20121022163930-8y8c9c1gnpfh8sjh
Tags: 0.16.0-1
ImportedĀ UpstreamĀ versionĀ 0.16.0

Show diffs side-by-side

added added

removed removed

Lines of Context:
25
25
    ATTR_ALIAS, ATTR_ARGS, ATTR_NO_NAMESPACE, ATTR_WRAPPED_EXCEPTIONS
26
26
)
27
27
 
 
28
 
28
29
if PY3:
29
30
    def raw_input(text):
30
31
        return input(text.decode())
31
32
 
 
33
 
32
34
__all__ = [
33
 
    'ArghParser', 'add_commands', 'autocomplete', 'dispatch', 'confirm',
34
 
    'wrap_errors'
 
35
    'ArghParser', 'add_commands', 'autocomplete', 'confirm', 'dispatch',
 
36
    'dispatch_command', 'set_default_command', 'wrap_errors'
35
37
]
 
38
 
 
39
 
 
40
def set_default_command(parser, function):
 
41
    """ Sets default command (i.e. a function) for given parser.
 
42
 
 
43
    .. note::
 
44
 
 
45
       An attempt to set default command to a parser which already has
 
46
       subparsers (e.g. added with :func:`~argh.helpers.add_commands`)
 
47
       results in a `RuntimeError`.
 
48
 
 
49
    """
 
50
    if parser._subparsers:
 
51
        raise RuntimeError('Cannot set default command to a parser with '
 
52
                           'existing subparsers')
 
53
 
 
54
    for a_args, a_kwargs in getattr(function, ATTR_ARGS, []):
 
55
        parser.add_argument(*a_args, **a_kwargs)
 
56
    parser.set_defaults(function=function)
 
57
 
 
58
 
36
59
def add_commands(parser, functions, namespace=None, title=None,
37
60
                 description=None, help=None):
38
61
    """Adds given functions as commands to given parser.
93
116
        stable. If some implementation details would change and break `argh`,
94
117
        we'll simply add a workaround a keep it compatibile.
95
118
 
 
119
    .. note::
 
120
 
 
121
       An attempt to add commands to a parser which already has a default
 
122
       function (e.g. added with :func:`~argh.helpers.set_default_command`)
 
123
       results in a `RuntimeError`.
 
124
 
96
125
    """
 
126
    if 'function' in parser._defaults:
 
127
        raise RuntimeError('Cannot add commands to a single-command parser')
 
128
 
97
129
    subparsers = get_subparsers(parser, create=True)
98
130
 
99
131
    if namespace:
113
145
        cmd_name = getattr(func, ATTR_ALIAS, func.__name__.replace('_','-'))
114
146
        cmd_help = func.__doc__
115
147
        command_parser = subparsers.add_parser(cmd_name, help=cmd_help)
116
 
        for a_args, a_kwargs in getattr(func, ATTR_ARGS, []):
117
 
            command_parser.add_argument(*a_args, **a_kwargs)
118
 
        command_parser.set_defaults(function=func)
 
148
        set_default_command(command_parser, func)
 
149
 
 
150
 
 
151
def dispatch_command(function, *args, **kwargs):
 
152
    """ A wrapper for :func:`dispatch` that creates a one-command parser.
 
153
 
 
154
    This::
 
155
 
 
156
        @command
 
157
        def foo():
 
158
            return 1
 
159
 
 
160
        dispatch_command(foo)
 
161
 
 
162
    ...is a shortcut for::
 
163
 
 
164
        @command
 
165
        def foo():
 
166
            return 1
 
167
 
 
168
        parser = ArgumentParser()
 
169
        set_default_command(parser, foo)
 
170
        dispatch(parser)
 
171
 
 
172
    This function can also be used as a decorator. Here's a more or less
 
173
    sensible example::
 
174
 
 
175
        from argh import *
 
176
 
 
177
        @dispatch_command
 
178
        @arg('name')
 
179
        def main(args):
 
180
            return args.name
 
181
 
 
182
    """
 
183
    parser = argparse.ArgumentParser()
 
184
    set_default_command(parser, function)
 
185
    dispatch(parser, *args, **kwargs)
 
186
 
119
187
 
120
188
def dispatch(parser, argv=None, add_help_command=True, encoding=None,
121
189
             completion=True, pre_call=None, output_file=sys.stdout,
215
283
        f.seek(0)
216
284
        return f.read()
217
285
 
 
286
 
218
287
def _encode(line, output_file, encoding=None):
219
288
    """Converts given string to given encoding. If no encoding is specified, it
220
289
    is determined from terminal settings or, if none, from system settings.
236
305
    # Convert string from Unicode to the output encoding
237
306
    return line.encode(encoding)
238
307
 
 
308
 
239
309
def _execute_command(args):
240
310
    """Asserts that ``args.function`` is present and callable. Tries different
241
311
    approaches to calling the function (with an `argparse.Namespace` object or
295
365
    wrappers for stand-alone functions :func:`add_commands` ,
296
366
    :func:`autocomplete` and :func:`dispatch`.
297
367
    """
 
368
    def set_default_command(self, *args, **kwargs):
 
369
        "Wrapper for :func:`set_default_command`."
 
370
        return set_default_command(self, *args, **kwargs)
 
371
 
298
372
    def add_commands(self, *args, **kwargs):
299
373
        "Wrapper for :func:`add_commands`."
300
374
        return add_commands(self, *args, **kwargs)
372
446
        return default
373
447
    return None
374
448
 
 
449
 
375
450
def wrap_errors(*exceptions):
376
451
    """Decorator. Wraps given exceptions into :class:`CommandError`. Usage::
377
452