/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
0.27.16 by Martin von Gagern
Added distutils setup script and plugin meta data.
1
#!/usr/bin/env python
0.27.2 by Martin von Gagern
First programmatic generation of completions.
2
5147.5.4 by Martin von Gagern
Assign copyright to Canonical Ltd.
3
# Copyright (C) 2009, 2010 Canonical Ltd
0.27.14 by Martin von Gagern
Added GPL 2 license document and copyright notice.
4
#
5147.5.5 by Martin von Gagern
Adjust copyright notice comments for bash_completion.
5
# This program is free software; you can redistribute it and/or modify
6
# it under the terms of the GNU General Public License as published by
7
# the Free Software Foundation; either version 2 of the License, or
8
# (at your option) any later version.
9
#
10
# This program is distributed in the hope that it will be useful,
11
# but WITHOUT ANY WARRANTY; without even the implied warranty of
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
# GNU General Public License for more details.
0.27.14 by Martin von Gagern
Added GPL 2 license document and copyright notice.
14
#
15
# 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.
16
# along with this program; if not, write to the Free Software
17
# 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.
18
0.27.17 by Martin von Gagern
Mention version and homepage in generated shell code comment.
19
from meta import __version__
0.28.2 by Martin von Gagern
merge from trunk
20
from bzrlib import (
21
    commands,
22
    config,
23
    help_topics,
24
    option,
25
    plugin,
26
)
0.27.36 by Martin von Gagern
List versions of bzr and plugins.
27
import bzrlib
0.27.18 by Martin von Gagern
Add global options in all cases
28
import re
0.27.2 by Martin von Gagern
First programmatic generation of completions.
29
0.27.7 by Martin von Gagern
Introduce --function-only option
30
head="""\
0.30.3 by Martin von Gagern
Lazy initialization
31
# Programmable completion for the Bazaar-NG bzr command under bash.
32
# Known to work with bash 2.05a as well as bash 4.1.2, and probably
33
# all versions in between as well.
0.27.1 by Martin von Gagern
Original script from bzr.dev/contrib/bash/bzr
34
35
# Based originally on the svn bash completition script.
36
# Customized by Sven Wilhelm/Icecrash.com
0.27.2 by Martin von Gagern
First programmatic generation of completions.
37
# Adjusted for automatic generation by Martin von Gagern
0.27.1 by Martin von Gagern
Original script from bzr.dev/contrib/bash/bzr
38
0.27.17 by Martin von Gagern
Mention version and homepage in generated shell code comment.
39
# Generated using the bzr-bash-completion plugin version %(version)s.
40
# See https://launchpad.net/bzr-bash-completion for details.
41
0.27.36 by Martin von Gagern
List versions of bzr and plugins.
42
# Commands and options of bzr %(bzr_version)s
43
0.27.20 by Martin von Gagern
More flexible handling of fixed word lists.
44
shopt -s progcomp
0.27.7 by Martin von Gagern
Introduce --function-only option
45
"""
46
fun="""\
0.27.4 by Martin von Gagern
Introduce --function-name switch. (LP #439829)
47
%(function_name)s ()
0.27.1 by Martin von Gagern
Original script from bzr.dev/contrib/bash/bzr
48
{
0.27.20 by Martin von Gagern
More flexible handling of fixed word lists.
49
	local cur cmds cmdIdx cmd cmdOpts fixedWords i globalOpts
0.27.30 by Martin von Gagern
Complete values for enum_switch of RegistryOptions.
50
	local curOpt optEnums
0.27.1 by Martin von Gagern
Original script from bzr.dev/contrib/bash/bzr
51
52
	COMPREPLY=()
53
	cur=${COMP_WORDS[COMP_CWORD]}
54
0.27.2 by Martin von Gagern
First programmatic generation of completions.
55
	cmds='%(cmds)s'
0.27.19 by Martin von Gagern
Take global options preceding the command into account.
56
	globalOpts='%(global_options)s'
57
58
	# do ordinary expansion if we are anywhere after a -- argument
59
	for ((i = 1; i < COMP_CWORD; ++i)); do
60
		[[ ${COMP_WORDS[i]} == "--" ]] && return 0
61
	done
62
63
	# find the command; it's the first word not starting in -
64
	cmd=
65
	for ((cmdIdx = 1; cmdIdx < ${#COMP_WORDS[@]}; ++cmdIdx)); do
66
		if [[ ${COMP_WORDS[cmdIdx]} != -* ]]; then
67
			cmd=${COMP_WORDS[cmdIdx]}
68
			break
69
		fi
70
	done
71
72
	# complete command name if we are not already past the command
0.27.30 by Martin von Gagern
Complete values for enum_switch of RegistryOptions.
73
	if [[ $COMP_CWORD -le cmdIdx ]]; then
0.27.18 by Martin von Gagern
Add global options in all cases
74
		COMPREPLY=( $( compgen -W "$cmds $globalOpts" -- $cur ) )
0.27.1 by Martin von Gagern
Original script from bzr.dev/contrib/bash/bzr
75
		return 0
76
	fi
77
0.27.30 by Martin von Gagern
Complete values for enum_switch of RegistryOptions.
78
	# find the option for which we want to complete a value
79
	curOpt=
80
	if [[ $cur != -* ]] && [[ $COMP_CWORD -gt 1 ]]; then
81
		curOpt=${COMP_WORDS[COMP_CWORD - 1]}
82
		if [[ $curOpt == = ]]; then
83
			curOpt=${COMP_WORDS[COMP_CWORD - 2]}
84
		fi
85
	fi
0.27.31 by Martin von Gagern
Introduce --debug switch to enable some debugging code.
86
%(debug)s
0.27.1 by Martin von Gagern
Original script from bzr.dev/contrib/bash/bzr
87
	cmdOpts=
0.27.30 by Martin von Gagern
Complete values for enum_switch of RegistryOptions.
88
	optEnums=
0.27.20 by Martin von Gagern
More flexible handling of fixed word lists.
89
	fixedWords=
0.27.19 by Martin von Gagern
Take global options preceding the command into account.
90
	case $cmd in
0.27.2 by Martin von Gagern
First programmatic generation of completions.
91
%(cases)s\
0.27.1 by Martin von Gagern
Original script from bzr.dev/contrib/bash/bzr
92
	*)
0.27.2 by Martin von Gagern
First programmatic generation of completions.
93
		cmdOpts='--help -h'
0.27.1 by Martin von Gagern
Original script from bzr.dev/contrib/bash/bzr
94
		;;
95
	esac
96
0.27.20 by Martin von Gagern
More flexible handling of fixed word lists.
97
	# if not typing an option, and if we don't know all the
98
	# possible non-option arguments for the current command,
99
	# then fallback on ordinary filename expansion
0.27.30 by Martin von Gagern
Complete values for enum_switch of RegistryOptions.
100
	if [[ -z $fixedWords ]] && [[ -z $optEnums ]] && [[ $cur != -* ]]; then
0.27.20 by Martin von Gagern
More flexible handling of fixed word lists.
101
		return 0
102
	fi
103
0.27.30 by Martin von Gagern
Complete values for enum_switch of RegistryOptions.
104
	if [[ $cur == = ]] && [[ -n $optEnums ]]; then
105
		# complete directly after "--option=", list all enum values
106
		COMPREPLY=( $optEnums )
107
	else
108
		fixedWords="$cmdOpts $globalOpts $optEnums $fixedWords"
109
		COMPREPLY=( $( compgen -W "$fixedWords" -- $cur ) )
110
	fi
0.27.1 by Martin von Gagern
Original script from bzr.dev/contrib/bash/bzr
111
112
	return 0
113
}
0.27.7 by Martin von Gagern
Introduce --function-only option
114
"""
115
tail="""\
0.27.4 by Martin von Gagern
Introduce --function-name switch. (LP #439829)
116
complete -F %(function_name)s -o default bzr
0.27.2 by Martin von Gagern
First programmatic generation of completions.
117
"""
0.27.31 by Martin von Gagern
Introduce --debug switch to enable some debugging code.
118
debug_output=r"""
119
	# Debugging code enabled using the --debug command line switch.
120
	# Will dump some variables to the top portion of the terminal.
121
	echo -ne '\e[s\e[H'
122
	for (( i=0; i < ${#COMP_WORDS[@]}; ++i)); do
123
		echo "\$COMP_WORDS[$i]='${COMP_WORDS[i]}'"$'\e[K'
124
	done
125
	for i in COMP_CWORD COMP_LINE COMP_POINT COMP_TYPE COMP_KEY cur curOpt; do
126
		echo "\$${i}=\"${!i}\""$'\e[K'
127
	done
128
	echo -ne '---\e[K\e[u'
129
"""
0.27.2 by Martin von Gagern
First programmatic generation of completions.
130
0.28.1 by Martin von Gagern
Include negated switches as well, using a modified options parser.
131
def wrap_container(list, parser):
132
    def tweaked_add_option(*opts, **attrs):
133
        list.extend(opts)
134
    parser.add_option = tweaked_add_option
135
    return parser
136
137
def wrap_parser(list, parser):
138
    orig_add_option_group = parser.add_option_group
139
    def tweaked_add_option_group(*opts, **attrs):
140
        return wrap_container(list, orig_add_option_group(*opts, **attrs))
141
    parser.add_option_group = tweaked_add_option_group
142
    return wrap_container(list, parser)
143
0.27.31 by Martin von Gagern
Introduce --debug switch to enable some debugging code.
144
def bash_completion_function(out, function_name="_bzr", function_only=False,
0.27.38 by Martin von Gagern
Add --plugin switch to selectively include plugins.
145
                             debug=False,
146
                             no_plugins=False, selected_plugins=None):
0.27.12 by Martin von Gagern
Take user-configured aliases into account.
147
    cmds = []
0.27.2 by Martin von Gagern
First programmatic generation of completions.
148
    cases = ""
149
    reqarg = {}
0.27.36 by Martin von Gagern
List versions of bzr and plugins.
150
    plugins = set()
0.27.38 by Martin von Gagern
Add --plugin switch to selectively include plugins.
151
    if selected_plugins:
152
        selected_plugins = set([x.replace('-', '_') for x in selected_plugins])
153
    else:
154
        selected_plugins = None
0.27.12 by Martin von Gagern
Take user-configured aliases into account.
155
0.27.18 by Martin von Gagern
Add global options in all cases
156
    re_switch = re.compile(r'\n(--[A-Za-z0-9-_]+)(?:, (-\S))?\s')
157
    help_text = help_topics.topic_registry.get_detail('global-options')
158
    global_options = set()
159
    for long, short in re_switch.findall(help_text):
160
        global_options.add(long)
161
        if short:
162
            global_options.add(short)
163
    global_options = " ".join(sorted(global_options))
164
0.27.12 by Martin von Gagern
Take user-configured aliases into account.
165
    user_aliases = {} # dict from cmd name to set of user-defined alias names
166
    for alias, expansion in config.GlobalConfig().get_aliases().iteritems():
167
        for token in commands.shlex_split_unicode(expansion):
168
            if not token.startswith("-"):
169
                user_aliases.setdefault(token, set()).add(alias)
170
                break
171
0.27.10 by Martin von Gagern
Complete help topics.
172
    all_cmds = sorted(commands.all_command_names())
173
    for cmdname in all_cmds:
174
        cmd = commands.get_cmd_object(cmdname)
0.27.12 by Martin von Gagern
Take user-configured aliases into account.
175
176
        # Find all aliases to the command; both cmd-defined and user-defined.
177
        # We assume a user won't override one command with a different one,
178
        # but will choose completely new names or add options to existing
179
        # ones while maintaining the actual command name unchanged.
180
        aliases = [cmdname]
181
        aliases.extend(cmd.aliases)
182
        aliases.extend(sorted([alias
183
                               for name in aliases
184
                               if name in user_aliases
185
                               for alias in user_aliases[name]
186
                               if alias not in aliases]))
187
        cases += "\t%s)\n" % "|".join(aliases)
188
        cmds.extend(aliases)
0.27.2 by Martin von Gagern
First programmatic generation of completions.
189
        plugin = cmd.plugin_name()
190
        if plugin is not None:
0.27.38 by Martin von Gagern
Add --plugin switch to selectively include plugins.
191
            if selected_plugins is not None and plugin not in selected_plugins:
192
                continue
0.27.36 by Martin von Gagern
List versions of bzr and plugins.
193
            plugins.add(plugin)
0.27.2 by Martin von Gagern
First programmatic generation of completions.
194
            cases += "\t\t# plugin \"%s\"\n" % plugin
195
        opts = cmd.options()
0.27.9 by Martin von Gagern
Remove suppression of alternate switches for the same option.
196
        switches = []
0.27.30 by Martin von Gagern
Complete values for enum_switch of RegistryOptions.
197
        enums = []
0.27.21 by Martin von Gagern
Allow help topic completion for aliases as well.
198
        fixedWords = None
0.27.2 by Martin von Gagern
First programmatic generation of completions.
199
        for optname in sorted(cmd.options()):
200
            opt = opts[optname]
0.28.1 by Martin von Gagern
Include negated switches as well, using a modified options parser.
201
            optswitches = []
202
            parser = option.get_optparser({optname: opt})
203
            parser = wrap_parser(optswitches, parser)
204
            optswitches[:] = []
205
            opt.add_option(parser, opt.short_name())
0.27.30 by Martin von Gagern
Complete values for enum_switch of RegistryOptions.
206
            if isinstance(opt, option.RegistryOption) and opt.enum_switch:
207
                enum_switch = '--%s' % optname
208
                keys = opt.registry.keys()
209
                if enum_switch in optswitches and keys:
210
                    optswitches.remove(enum_switch)
211
                    for key in keys:
212
                        optswitches.append('%s=%s' % (enum_switch, key))
213
                    enums.append("%s) optEnums='%s' ;;"
214
                                 % (enum_switch, ' '.join(keys)))
0.28.1 by Martin von Gagern
Include negated switches as well, using a modified options parser.
215
            switches.extend(optswitches)
0.27.10 by Martin von Gagern
Complete help topics.
216
        if 'help' == cmdname or 'help' in cmd.aliases:
0.27.21 by Martin von Gagern
Allow help topic completion for aliases as well.
217
            fixedWords = " ".join(sorted(help_topics.topic_registry.keys()))
218
            fixedWords = '"$cmds %s"' % fixedWords
219
0.27.9 by Martin von Gagern
Remove suppression of alternate switches for the same option.
220
        cases += "\t\tcmdOpts='" + " ".join(switches) + "'\n"
0.27.20 by Martin von Gagern
More flexible handling of fixed word lists.
221
        if fixedWords:
0.27.21 by Martin von Gagern
Allow help topic completion for aliases as well.
222
            if isinstance(fixedWords, list):
0.27.30 by Martin von Gagern
Complete values for enum_switch of RegistryOptions.
223
                fixedWords = "'" + join(fixedWords) + "'"
0.27.21 by Martin von Gagern
Allow help topic completion for aliases as well.
224
            cases += "\t\tfixedWords=" + fixedWords + "\n"
0.27.30 by Martin von Gagern
Complete values for enum_switch of RegistryOptions.
225
        if enums:
226
            cases += "\t\tcase $curOpt in\n\t\t\t"
227
            cases += "\n\t\t\t".join(enums)
228
            cases += "\n\t\tesac\n"
0.27.9 by Martin von Gagern
Remove suppression of alternate switches for the same option.
229
        cases += "\t\t;;\n"
0.27.36 by Martin von Gagern
List versions of bzr and plugins.
230
231
    bzr_version = bzrlib.version_string
232
    if not plugins:
233
        bzr_version += "."
234
    else:
235
        bzr_version += " and the following plugins:"
236
        for plugin in sorted(plugins):
237
            pv = bzrlib.plugin.plugins()[plugin].__version__
238
            if pv == 'unknown':
239
                pv = ''
240
            else:
241
                pv = ' ' + pv
242
                bzr_version += "\n# %s%s" % (plugin, pv)
243
0.27.7 by Martin von Gagern
Introduce --function-only option
244
    if function_only:
245
        template = fun
246
    else:
247
        template = head + fun + tail
0.27.12 by Martin von Gagern
Take user-configured aliases into account.
248
    out.write(template % {"cmds": " ".join(cmds),
0.27.2 by Martin von Gagern
First programmatic generation of completions.
249
                          "cases": cases,
0.27.4 by Martin von Gagern
Introduce --function-name switch. (LP #439829)
250
                          "function_name": function_name,
0.27.18 by Martin von Gagern
Add global options in all cases
251
                          "version": __version__,
252
                          "global_options": global_options,
0.27.31 by Martin von Gagern
Introduce --debug switch to enable some debugging code.
253
                          "debug": debug_output if debug else "",
0.27.36 by Martin von Gagern
List versions of bzr and plugins.
254
                          "bzr_version": bzr_version,
0.27.4 by Martin von Gagern
Introduce --function-name switch. (LP #439829)
255
                          })
0.27.2 by Martin von Gagern
First programmatic generation of completions.
256
257
if __name__ == '__main__':
258
259
    import sys
260
    import locale
0.27.32 by Martin von Gagern
Added OptionParser for script usage.
261
    import optparse
262
    from meta import __version__
263
0.27.38 by Martin von Gagern
Add --plugin switch to selectively include plugins.
264
    def plugin_callback(option, opt, value, parser):
265
        values = parser.values.selected_plugins
266
        if value == '-':
267
            del values[:]
268
        else:
269
            values.append(value)
270
0.27.32 by Martin von Gagern
Added OptionParser for script usage.
271
    parser = optparse.OptionParser(usage="%prog [-f NAME] [-o]",
272
                                   version="%%prog %s" % __version__)
273
    parser.add_option("--function-name", "-f", metavar="NAME",
274
                      help="Name of the generated function (default: _bzr)")
275
    parser.add_option("--function-only", "-o", action="store_true",
276
                      help="Generate only the shell function, don't enable it")
277
    parser.add_option("--debug", action="store_true",
278
                      help=optparse.SUPPRESS_HELP)
0.27.37 by Martin von Gagern
Introduce --no-plugins option to script execution mode.
279
    parser.add_option("--no-plugins", action="store_true",
280
                      help="Don't load any bzr plugins")
0.27.38 by Martin von Gagern
Add --plugin switch to selectively include plugins.
281
    parser.add_option("--plugin", metavar="NAME", type="string",
282
                      dest="selected_plugins", default=[],
283
                      action="callback", callback=plugin_callback,
284
                      help="Enable completions for the selected plugin"
285
                      + " (default: all plugins)")
0.27.32 by Martin von Gagern
Added OptionParser for script usage.
286
    (opts, args) = parser.parse_args()
287
    if args:
288
        parser.error("script does not take positional arguments")
289
    kwargs = dict()
290
    for name, value in opts.__dict__.iteritems():
291
        if value is not None:
292
            kwargs[name] = value
0.27.2 by Martin von Gagern
First programmatic generation of completions.
293
294
    locale.setlocale(locale.LC_ALL, '')
0.27.37 by Martin von Gagern
Introduce --no-plugins option to script execution mode.
295
    if not kwargs.get('no_plugins', False):
296
        plugin.load_plugins()
0.27.2 by Martin von Gagern
First programmatic generation of completions.
297
    commands.install_bzr_command_hooks()
0.27.32 by Martin von Gagern
Added OptionParser for script usage.
298
    bash_completion_function(sys.stdout, **kwargs)