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