/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
5147.5.4 by Martin von Gagern
Assign copyright to Canonical Ltd.
1
# Copyright (C) 2009, 2010 Canonical Ltd
0.27.14 by Martin von Gagern
Added GPL 2 license document and copyright notice.
2
#
5147.5.5 by Martin von Gagern
Adjust copyright notice comments for bash_completion.
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
0.27.14 by Martin von Gagern
Added GPL 2 license document and copyright notice.
12
#
13
# You should have received a copy of the GNU General Public License
5147.5.5 by Martin von Gagern
Adjust copyright notice comments for bash_completion.
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
0.27.14 by Martin von Gagern
Added GPL 2 license document and copyright notice.
16
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
17
from ... import (
5245.1.1 by Andrew Bennetts
Fix deprecation warning in bash_completion plugin.
18
    cmdline,
0.28.2 by Martin von Gagern
merge from trunk
19
    commands,
20
    config,
21
    help_topics,
22
    option,
23
    plugin,
24
)
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
25
import breezy
0.27.18 by Martin von Gagern
Add global options in all cases
26
import re
6386.1.2 by Jelmer Vernooij
Move sys import.
27
import sys
0.27.2 by Martin von Gagern
First programmatic generation of completions.
28
0.32.8 by Martin von Gagern
Refactor to increase modularity.
29
30
class BashCodeGen(object):
31
    """Generate a bash script for given completion data."""
32
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
33
    def __init__(self, data, function_name='_brz', debug=False):
0.32.8 by Martin von Gagern
Refactor to increase modularity.
34
        self.data = data
35
        self.function_name = function_name
36
        self.debug = debug
37
38
    def script(self):
39
        return ("""\
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
40
# Programmable completion for the Breezy brz command under bash.
0.30.3 by Martin von Gagern
Lazy initialization
41
# Known to work with bash 2.05a as well as bash 4.1.2, and probably
42
# all versions in between as well.
0.27.1 by Martin von Gagern
Original script from bzr.dev/contrib/bash/bzr
43
44
# Based originally on the svn bash completition script.
45
# Customized by Sven Wilhelm/Icecrash.com
0.27.2 by Martin von Gagern
First programmatic generation of completions.
46
# Adjusted for automatic generation by Martin von Gagern
0.27.1 by Martin von Gagern
Original script from bzr.dev/contrib/bash/bzr
47
5147.5.12 by Martin von Gagern
Use version of bzrlib. Drop meta.py.
48
# Generated using the bash_completion plugin.
0.27.17 by Martin von Gagern
Mention version and homepage in generated shell code comment.
49
# See https://launchpad.net/bzr-bash-completion for details.
50
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
51
# Commands and options of brz %(brz_version)s
0.27.36 by Martin von Gagern
List versions of bzr and plugins.
52
0.27.20 by Martin von Gagern
More flexible handling of fixed word lists.
53
shopt -s progcomp
0.32.8 by Martin von Gagern
Refactor to increase modularity.
54
%(function)s
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
55
complete -F %(function_name)s -o default brz
7143.15.2 by Jelmer Vernooij
Run autopep8.
56
""" % {
0.32.8 by Martin von Gagern
Refactor to increase modularity.
57
            "function_name": self.function_name,
58
            "function": self.function(),
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
59
            "brz_version": self.brz_version(),
0.32.8 by Martin von Gagern
Refactor to increase modularity.
60
        })
61
62
    def function(self):
63
        return ("""\
0.27.4 by Martin von Gagern
Introduce --function-name switch. (LP #439829)
64
%(function_name)s ()
0.27.1 by Martin von Gagern
Original script from bzr.dev/contrib/bash/bzr
65
{
7143.16.1 by Jelmer Vernooij
Fix E101.
66
    local cur cmds cmdIdx cmd cmdOpts fixedWords i globalOpts
67
    local curOpt optEnums
68
    local IFS=$' \\n'
69
70
    COMPREPLY=()
71
    cur=${COMP_WORDS[COMP_CWORD]}
72
73
    cmds='%(cmds)s'
74
    globalOpts=( %(global_options)s )
75
76
    # do ordinary expansion if we are anywhere after a -- argument
77
    for ((i = 1; i < COMP_CWORD; ++i)); do
78
        [[ ${COMP_WORDS[i]} == "--" ]] && return 0
79
    done
80
81
    # find the command; it's the first word not starting in -
82
    cmd=
83
    for ((cmdIdx = 1; cmdIdx < ${#COMP_WORDS[@]}; ++cmdIdx)); do
84
        if [[ ${COMP_WORDS[cmdIdx]} != -* ]]; then
85
            cmd=${COMP_WORDS[cmdIdx]}
86
            break
87
        fi
88
    done
89
90
    # complete command name if we are not already past the command
91
    if [[ $COMP_CWORD -le cmdIdx ]]; then
92
        COMPREPLY=( $( compgen -W "$cmds ${globalOpts[*]}" -- $cur ) )
93
        return 0
94
    fi
95
96
    # find the option for which we want to complete a value
97
    curOpt=
98
    if [[ $cur != -* ]] && [[ $COMP_CWORD -gt 1 ]]; then
99
        curOpt=${COMP_WORDS[COMP_CWORD - 1]}
100
        if [[ $curOpt == = ]]; then
101
            curOpt=${COMP_WORDS[COMP_CWORD - 2]}
102
        elif [[ $cur == : ]]; then
103
            cur=
104
            curOpt="$curOpt:"
105
        elif [[ $curOpt == : ]]; then
106
            curOpt=${COMP_WORDS[COMP_CWORD - 2]}:
107
        fi
108
    fi
0.27.31 by Martin von Gagern
Introduce --debug switch to enable some debugging code.
109
%(debug)s
7143.16.1 by Jelmer Vernooij
Fix E101.
110
    cmdOpts=( )
111
    optEnums=( )
112
    fixedWords=( )
113
    case $cmd in
0.27.2 by Martin von Gagern
First programmatic generation of completions.
114
%(cases)s\
7143.16.1 by Jelmer Vernooij
Fix E101.
115
    *)
116
        cmdOpts=(--help -h)
117
        ;;
118
    esac
119
120
    IFS=$'\\n'
121
    if [[ ${#fixedWords[@]} -eq 0 ]] && [[ ${#optEnums[@]} -eq 0 ]] && [[ $cur != -* ]]; then
122
        case $curOpt in
123
            tag:|*..tag:)
124
                fixedWords=( $(brz tags 2>/dev/null | sed 's/  *[^ ]*$//; s/ /\\\\\\\\ /g;') )
125
                ;;
126
        esac
127
        case $cur in
128
            [\\"\\']tag:*)
129
                fixedWords=( $(brz tags 2>/dev/null | sed 's/  *[^ ]*$//; s/^/tag:/') )
130
                ;;
131
            [\\"\\']*..tag:*)
132
                fixedWords=( $(brz tags 2>/dev/null | sed 's/  *[^ ]*$//') )
133
                fixedWords=( $(for i in "${fixedWords[@]}"; do echo "${cur%%..tag:*}..tag:${i}"; done) )
134
                ;;
135
        esac
136
    elif [[ $cur == = ]] && [[ ${#optEnums[@]} -gt 0 ]]; then
137
        # complete directly after "--option=", list all enum values
138
        COMPREPLY=( "${optEnums[@]}" )
139
        return 0
140
    else
141
        fixedWords=( "${cmdOpts[@]}"
142
                     "${globalOpts[@]}"
143
                     "${optEnums[@]}"
144
                     "${fixedWords[@]}" )
145
    fi
146
147
    if [[ ${#fixedWords[@]} -gt 0 ]]; then
148
        COMPREPLY=( $( compgen -W "${fixedWords[*]}" -- $cur ) )
149
    fi
150
151
    return 0
0.27.1 by Martin von Gagern
Original script from bzr.dev/contrib/bash/bzr
152
}
7143.15.2 by Jelmer Vernooij
Run autopep8.
153
""" % {
0.32.8 by Martin von Gagern
Refactor to increase modularity.
154
            "cmds": self.command_names(),
155
            "function_name": self.function_name,
156
            "cases": self.command_cases(),
157
            "global_options": self.global_options(),
158
            "debug": self.debug_output(),
159
        })
0.32.20 by Martin von Gagern
Allow completion of tags at end of revision range.
160
        # Help Emacs terminate strings: "
0.32.8 by Martin von Gagern
Refactor to increase modularity.
161
162
    def command_names(self):
163
        return " ".join(self.data.all_command_aliases())
164
165
    def debug_output(self):
166
        if not self.debug:
167
            return ''
168
        else:
169
            return (r"""
7143.16.1 by Jelmer Vernooij
Fix E101.
170
    # Debugging code enabled using the --debug command line switch.
171
    # Will dump some variables to the top portion of the terminal.
172
    echo -ne '\e[s\e[H'
173
    for (( i=0; i < ${#COMP_WORDS[@]}; ++i)); do
174
        echo "\$COMP_WORDS[$i]='${COMP_WORDS[i]}'"$'\e[K'
175
    done
176
    for i in COMP_CWORD COMP_LINE COMP_POINT COMP_TYPE COMP_KEY cur curOpt; do
177
        echo "\$${i}=\"${!i}\""$'\e[K'
178
    done
179
    echo -ne '---\e[K\e[u'
0.32.8 by Martin von Gagern
Refactor to increase modularity.
180
""")
181
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
182
    def brz_version(self):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
183
        brz_version = breezy.version_string
0.32.8 by Martin von Gagern
Refactor to increase modularity.
184
        if not self.data.plugins:
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
185
            brz_version += "."
0.32.8 by Martin von Gagern
Refactor to increase modularity.
186
        else:
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
187
            brz_version += " and the following plugins:"
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
188
            for name, plugin in sorted(self.data.plugins.items()):
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
189
                brz_version += "\n# %s" % plugin
190
        return brz_version
0.32.8 by Martin von Gagern
Refactor to increase modularity.
191
192
    def global_options(self):
193
        return " ".join(sorted(self.data.global_options))
194
195
    def command_cases(self):
196
        cases = ""
197
        for command in self.data.commands:
198
            cases += self.command_case(command)
199
        return cases
200
201
    def command_case(self, command):
202
        case = "\t%s)\n" % "|".join(command.aliases)
203
        if command.plugin:
204
            case += "\t\t# plugin \"%s\"\n" % command.plugin
205
        options = []
206
        enums = []
207
        for option in command.options:
208
            for message in option.error_messages:
209
                case += "\t\t# %s\n" % message
210
            if option.registry_keys:
211
                for key in option.registry_keys:
212
                    options.append("%s=%s" % (option, key))
0.32.15 by Martin von Gagern
Allow spaces in tag names. Use bash arrays more extensively.
213
                enums.append("%s) optEnums=( %s ) ;;" %
0.32.8 by Martin von Gagern
Refactor to increase modularity.
214
                             (option, ' '.join(option.registry_keys)))
215
            else:
216
                options.append(str(option))
0.32.15 by Martin von Gagern
Allow spaces in tag names. Use bash arrays more extensively.
217
        case += "\t\tcmdOpts=( %s )\n" % " ".join(options)
0.32.8 by Martin von Gagern
Refactor to increase modularity.
218
        if command.fixed_words:
219
            fixed_words = command.fixed_words
220
            if isinstance(fixed_words, list):
0.32.15 by Martin von Gagern
Allow spaces in tag names. Use bash arrays more extensively.
221
                fixed_words = "( %s )" + ' '.join(fixed_words)
0.32.8 by Martin von Gagern
Refactor to increase modularity.
222
            case += "\t\tfixedWords=%s\n" % fixed_words
223
        if enums:
224
            case += "\t\tcase $curOpt in\n\t\t\t"
225
            case += "\n\t\t\t".join(enums)
226
            case += "\n\t\tesac\n"
227
        case += "\t\t;;\n"
228
        return case
229
230
231
class CompletionData(object):
232
233
    def __init__(self):
234
        self.plugins = {}
235
        self.global_options = set()
236
        self.commands = []
237
238
    def all_command_aliases(self):
239
        for c in self.commands:
240
            for a in c.aliases:
241
                yield a
242
243
244
class CommandData(object):
245
246
    def __init__(self, name):
247
        self.name = name
248
        self.aliases = [name]
249
        self.plugin = None
250
        self.options = []
251
        self.fixed_words = None
252
253
254
class PluginData(object):
255
256
    def __init__(self, name, version=None):
257
        if version is None:
0.32.20 by Martin von Gagern
Allow completion of tags at end of revision range.
258
            try:
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
259
                version = breezy.plugin.plugins()[name].__version__
0.32.20 by Martin von Gagern
Allow completion of tags at end of revision range.
260
            except:
261
                version = 'unknown'
0.32.8 by Martin von Gagern
Refactor to increase modularity.
262
        self.name = name
263
        self.version = version
264
265
    def __str__(self):
266
        if self.version == 'unknown':
267
            return self.name
268
        return '%s %s' % (self.name, self.version)
269
270
271
class OptionData(object):
272
273
    def __init__(self, name):
274
        self.name = name
275
        self.registry_keys = None
276
        self.error_messages = []
277
278
    def __str__(self):
279
        return self.name
280
281
    def __cmp__(self, other):
282
        return cmp(self.name, other.name)
283
7027.6.1 by Jelmer Vernooij
Fix bash completion tests on Python 3.
284
    def __lt__(self, other):
285
        return self.name < other.name
286
0.32.8 by Martin von Gagern
Refactor to increase modularity.
287
288
class DataCollector(object):
289
290
    def __init__(self, no_plugins=False, selected_plugins=None):
291
        self.data = CompletionData()
292
        self.user_aliases = {}
293
        if no_plugins:
294
            self.selected_plugins = set()
295
        elif selected_plugins is None:
296
            self.selected_plugins = None
297
        else:
6619.3.12 by Jelmer Vernooij
Use 2to3 set_literal fixer.
298
            self.selected_plugins = {x.replace('-', '_')
7143.15.2 by Jelmer Vernooij
Run autopep8.
299
                                     for x in selected_plugins}
0.32.8 by Martin von Gagern
Refactor to increase modularity.
300
301
    def collect(self):
302
        self.global_options()
303
        self.aliases()
304
        self.commands()
305
        return self.data
306
307
    def global_options(self):
308
        re_switch = re.compile(r'\n(--[A-Za-z0-9-_]+)(?:, (-\S))?\s')
309
        help_text = help_topics.topic_registry.get_detail('global-options')
310
        for long, short in re_switch.findall(help_text):
311
            self.data.global_options.add(long)
312
            if short:
313
                self.data.global_options.add(short)
314
315
    def aliases(self):
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
316
        for alias, expansion in config.GlobalConfig().get_aliases().items():
5245.1.1 by Andrew Bennetts
Fix deprecation warning in bash_completion plugin.
317
            for token in cmdline.split(expansion):
0.32.8 by Martin von Gagern
Refactor to increase modularity.
318
                if not token.startswith("-"):
319
                    self.user_aliases.setdefault(token, set()).add(alias)
320
                    break
321
322
    def commands(self):
323
        for name in sorted(commands.all_command_names()):
324
            self.command(name)
325
326
    def command(self, name):
327
        cmd = commands.get_cmd_object(name)
328
        cmd_data = CommandData(name)
329
330
        plugin_name = cmd.plugin_name()
331
        if plugin_name is not None:
332
            if (self.selected_plugins is not None and
7143.15.2 by Jelmer Vernooij
Run autopep8.
333
                    plugin not in self.selected_plugins):
0.32.9 by Martin von Gagern
Added test cases for DataCollector and BashCodeGen.
334
                return None
0.32.8 by Martin von Gagern
Refactor to increase modularity.
335
            plugin_data = self.data.plugins.get(plugin_name)
336
            if plugin_data is None:
337
                plugin_data = PluginData(plugin_name)
338
                self.data.plugins[plugin_name] = plugin_data
339
            cmd_data.plugin = plugin_data
340
        self.data.commands.append(cmd_data)
0.27.12 by Martin von Gagern
Take user-configured aliases into account.
341
342
        # Find all aliases to the command; both cmd-defined and user-defined.
343
        # We assume a user won't override one command with a different one,
344
        # but will choose completely new names or add options to existing
345
        # ones while maintaining the actual command name unchanged.
0.32.8 by Martin von Gagern
Refactor to increase modularity.
346
        cmd_data.aliases.extend(cmd.aliases)
347
        cmd_data.aliases.extend(sorted([useralias
7143.15.2 by Jelmer Vernooij
Run autopep8.
348
                                        for cmdalias in cmd_data.aliases
349
                                        if cmdalias in self.user_aliases
350
                                        for useralias in self.user_aliases[cmdalias]
351
                                        if useralias not in cmd_data.aliases]))
0.32.8 by Martin von Gagern
Refactor to increase modularity.
352
0.27.2 by Martin von Gagern
First programmatic generation of completions.
353
        opts = cmd.options()
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
354
        for optname, opt in sorted(opts.items()):
0.32.8 by Martin von Gagern
Refactor to increase modularity.
355
            cmd_data.options.extend(self.option(opt))
356
357
        if 'help' == name or 'help' in cmd.aliases:
0.32.15 by Martin von Gagern
Allow spaces in tag names. Use bash arrays more extensively.
358
            cmd_data.fixed_words = ('($cmds %s)' %
7143.15.2 by Jelmer Vernooij
Run autopep8.
359
                                    " ".join(sorted(help_topics.topic_registry.keys())))
0.32.8 by Martin von Gagern
Refactor to increase modularity.
360
0.32.9 by Martin von Gagern
Added test cases for DataCollector and BashCodeGen.
361
        return cmd_data
362
0.32.8 by Martin von Gagern
Refactor to increase modularity.
363
    def option(self, opt):
364
        optswitches = {}
7045.4.23 by Jelmer Vernooij
Fix some help tests.
365
        parser = option.get_optparser([opt])
0.32.8 by Martin von Gagern
Refactor to increase modularity.
366
        parser = self.wrap_parser(optswitches, parser)
367
        optswitches.clear()
368
        opt.add_option(parser, opt.short_name())
369
        if isinstance(opt, option.RegistryOption) and opt.enum_switch:
370
            enum_switch = '--%s' % opt.name
371
            enum_data = optswitches.get(enum_switch)
372
            if enum_data:
0.27.41 by Martin von Gagern
Recover from ImportError when loading a registry.
373
                try:
0.32.8 by Martin von Gagern
Refactor to increase modularity.
374
                    enum_data.registry_keys = opt.registry.keys()
6619.3.2 by Jelmer Vernooij
Apply 2to3 except fix.
375
                except ImportError as e:
0.32.8 by Martin von Gagern
Refactor to increase modularity.
376
                    enum_data.error_messages.append(
377
                        "ERROR getting registry keys for '--%s': %s"
378
                        % (opt.name, str(e).split('\n')[0]))
379
        return sorted(optswitches.values())
380
381
    def wrap_container(self, optswitches, parser):
382
        def tweaked_add_option(*opts, **attrs):
383
            for name in opts:
384
                optswitches[name] = OptionData(name)
385
        parser.add_option = tweaked_add_option
386
        return parser
387
388
    def wrap_parser(self, optswitches, parser):
389
        orig_add_option_group = parser.add_option_group
7143.15.2 by Jelmer Vernooij
Run autopep8.
390
0.32.8 by Martin von Gagern
Refactor to increase modularity.
391
        def tweaked_add_option_group(*opts, **attrs):
392
            return self.wrap_container(optswitches,
7143.15.2 by Jelmer Vernooij
Run autopep8.
393
                                       orig_add_option_group(*opts, **attrs))
0.32.8 by Martin von Gagern
Refactor to increase modularity.
394
        parser.add_option_group = tweaked_add_option_group
395
        return self.wrap_container(optswitches, parser)
396
397
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
398
def bash_completion_function(out, function_name="_brz", function_only=False,
0.32.8 by Martin von Gagern
Refactor to increase modularity.
399
                             debug=False,
400
                             no_plugins=False, selected_plugins=None):
7143.15.2 by Jelmer Vernooij
Run autopep8.
401
    dc = DataCollector(no_plugins=no_plugins,
402
                       selected_plugins=selected_plugins)
0.32.8 by Martin von Gagern
Refactor to increase modularity.
403
    data = dc.collect()
404
    cg = BashCodeGen(data, function_name=function_name, debug=debug)
0.27.7 by Martin von Gagern
Introduce --function-only option
405
    if function_only:
0.32.8 by Martin von Gagern
Refactor to increase modularity.
406
        res = cg.function()
407
    else:
408
        res = cg.script()
409
    out.write(res)
410
0.27.2 by Martin von Gagern
First programmatic generation of completions.
411
5147.5.11 by Martin von Gagern
Register command lazily.
412
class cmd_bash_completion(commands.Command):
5147.5.14 by Martin von Gagern
Assign user-visible docstrings to __doc__.
413
    __doc__ = """Generate a shell function for bash command line completion.
5147.5.11 by Martin von Gagern
Register command lazily.
414
415
    This command generates a shell function which can be used by bash to
416
    automatically complete the currently typed command when the user presses
417
    the completion key (usually tab).
7195.5.1 by Martin
Fix remaining whitespace lint in codebase
418
5147.5.11 by Martin von Gagern
Register command lazily.
419
    Commonly used like this:
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
420
        eval "`brz bash-completion`"
5147.5.11 by Martin von Gagern
Register command lazily.
421
    """
422
423
    takes_options = [
7479.2.1 by Jelmer Vernooij
Drop python2 support.
424
        option.Option("function-name", short_name="f", type=str, argname="name",
7143.15.2 by Jelmer Vernooij
Run autopep8.
425
                      help="Name of the generated function (default: _brz)"),
5147.5.11 by Martin von Gagern
Register command lazily.
426
        option.Option("function-only", short_name="o", type=None,
7143.15.2 by Jelmer Vernooij
Run autopep8.
427
                      help="Generate only the shell function, don't enable it"),
5147.5.11 by Martin von Gagern
Register command lazily.
428
        option.Option("debug", type=None, hidden=True,
7143.15.2 by Jelmer Vernooij
Run autopep8.
429
                      help="Enable shell code useful for debugging"),
7479.2.1 by Jelmer Vernooij
Drop python2 support.
430
        option.ListOption("plugin", type=str, argname="name",
7143.15.2 by Jelmer Vernooij
Run autopep8.
431
                          # param_name="selected_plugins", # doesn't work, bug #387117
432
                          help="Enable completions for the selected plugin"
433
                          + " (default: all plugins)"),
5147.5.11 by Martin von Gagern
Register command lazily.
434
        ]
435
436
    def run(self, **kwargs):
437
        if 'plugin' in kwargs:
438
            # work around bug #387117 which prevents us from using param_name
5147.5.18 by Martin von Gagern
Include all plugins if --plugins isn't specified (fixes regression).
439
            if len(kwargs['plugin']) > 0:
440
                kwargs['selected_plugins'] = kwargs['plugin']
5147.5.11 by Martin von Gagern
Register command lazily.
441
            del kwargs['plugin']
442
        bash_completion_function(sys.stdout, **kwargs)
443
444
0.27.2 by Martin von Gagern
First programmatic generation of completions.
445
if __name__ == '__main__':
446
447
    import locale
0.27.32 by Martin von Gagern
Added OptionParser for script usage.
448
    import optparse
449
0.27.38 by Martin von Gagern
Add --plugin switch to selectively include plugins.
450
    def plugin_callback(option, opt, value, parser):
451
        values = parser.values.selected_plugins
452
        if value == '-':
453
            del values[:]
454
        else:
455
            values.append(value)
456
5147.5.12 by Martin von Gagern
Use version of bzrlib. Drop meta.py.
457
    parser = optparse.OptionParser(usage="%prog [-f NAME] [-o]")
0.27.32 by Martin von Gagern
Added OptionParser for script usage.
458
    parser.add_option("--function-name", "-f", metavar="NAME",
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
459
                      help="Name of the generated function (default: _brz)")
0.27.32 by Martin von Gagern
Added OptionParser for script usage.
460
    parser.add_option("--function-only", "-o", action="store_true",
461
                      help="Generate only the shell function, don't enable it")
462
    parser.add_option("--debug", action="store_true",
463
                      help=optparse.SUPPRESS_HELP)
0.27.37 by Martin von Gagern
Introduce --no-plugins option to script execution mode.
464
    parser.add_option("--no-plugins", action="store_true",
6622.1.28 by Jelmer Vernooij
More renames; commands in output, environment variables.
465
                      help="Don't load any brz plugins")
0.27.38 by Martin von Gagern
Add --plugin switch to selectively include plugins.
466
    parser.add_option("--plugin", metavar="NAME", type="string",
467
                      dest="selected_plugins", default=[],
468
                      action="callback", callback=plugin_callback,
469
                      help="Enable completions for the selected plugin"
470
                      + " (default: all plugins)")
0.27.32 by Martin von Gagern
Added OptionParser for script usage.
471
    (opts, args) = parser.parse_args()
472
    if args:
473
        parser.error("script does not take positional arguments")
474
    kwargs = dict()
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
475
    for name, value in opts.__dict__.items():
0.27.32 by Martin von Gagern
Added OptionParser for script usage.
476
        if value is not None:
477
            kwargs[name] = value
0.27.2 by Martin von Gagern
First programmatic generation of completions.
478
479
    locale.setlocale(locale.LC_ALL, '')
0.27.37 by Martin von Gagern
Introduce --no-plugins option to script execution mode.
480
    if not kwargs.get('no_plugins', False):
481
        plugin.load_plugins()
0.27.2 by Martin von Gagern
First programmatic generation of completions.
482
    commands.install_bzr_command_hooks()
0.27.32 by Martin von Gagern
Added OptionParser for script usage.
483
    bash_completion_function(sys.stdout, **kwargs)