/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.1 by Martin von Gagern
Complete tag names.
111
		fixedWords=$optEnums
0.27.30 by Martin von Gagern
Complete values for enum_switch of RegistryOptions.
112
	else
113
		fixedWords="$cmdOpts $globalOpts $optEnums $fixedWords"
0.32.1 by Martin von Gagern
Complete tag names.
114
	fi
115
116
	if [[ -n $fixedWords ]]; then
0.27.30 by Martin von Gagern
Complete values for enum_switch of RegistryOptions.
117
		COMPREPLY=( $( compgen -W "$fixedWords" -- $cur ) )
118
	fi
0.27.1 by Martin von Gagern
Original script from bzr.dev/contrib/bash/bzr
119
120
	return 0
121
}
0.27.7 by Martin von Gagern
Introduce --function-only option
122
"""
123
tail="""\
0.27.4 by Martin von Gagern
Introduce --function-name switch. (LP #439829)
124
complete -F %(function_name)s -o default bzr
0.27.2 by Martin von Gagern
First programmatic generation of completions.
125
"""
0.27.31 by Martin von Gagern
Introduce --debug switch to enable some debugging code.
126
debug_output=r"""
127
	# Debugging code enabled using the --debug command line switch.
128
	# Will dump some variables to the top portion of the terminal.
129
	echo -ne '\e[s\e[H'
130
	for (( i=0; i < ${#COMP_WORDS[@]}; ++i)); do
131
		echo "\$COMP_WORDS[$i]='${COMP_WORDS[i]}'"$'\e[K'
132
	done
133
	for i in COMP_CWORD COMP_LINE COMP_POINT COMP_TYPE COMP_KEY cur curOpt; do
134
		echo "\$${i}=\"${!i}\""$'\e[K'
135
	done
136
	echo -ne '---\e[K\e[u'
137
"""
0.27.2 by Martin von Gagern
First programmatic generation of completions.
138
0.28.1 by Martin von Gagern
Include negated switches as well, using a modified options parser.
139
def wrap_container(list, parser):
140
    def tweaked_add_option(*opts, **attrs):
141
        list.extend(opts)
142
    parser.add_option = tweaked_add_option
143
    return parser
144
145
def wrap_parser(list, parser):
146
    orig_add_option_group = parser.add_option_group
147
    def tweaked_add_option_group(*opts, **attrs):
148
        return wrap_container(list, orig_add_option_group(*opts, **attrs))
149
    parser.add_option_group = tweaked_add_option_group
150
    return wrap_container(list, parser)
151
0.27.31 by Martin von Gagern
Introduce --debug switch to enable some debugging code.
152
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.
153
                             debug=False,
154
                             no_plugins=False, selected_plugins=None):
0.27.12 by Martin von Gagern
Take user-configured aliases into account.
155
    cmds = []
0.27.2 by Martin von Gagern
First programmatic generation of completions.
156
    cases = ""
157
    reqarg = {}
0.27.36 by Martin von Gagern
List versions of bzr and plugins.
158
    plugins = set()
0.27.38 by Martin von Gagern
Add --plugin switch to selectively include plugins.
159
    if selected_plugins:
160
        selected_plugins = set([x.replace('-', '_') for x in selected_plugins])
161
    else:
162
        selected_plugins = None
0.27.12 by Martin von Gagern
Take user-configured aliases into account.
163
0.27.18 by Martin von Gagern
Add global options in all cases
164
    re_switch = re.compile(r'\n(--[A-Za-z0-9-_]+)(?:, (-\S))?\s')
165
    help_text = help_topics.topic_registry.get_detail('global-options')
166
    global_options = set()
167
    for long, short in re_switch.findall(help_text):
168
        global_options.add(long)
169
        if short:
170
            global_options.add(short)
171
    global_options = " ".join(sorted(global_options))
172
0.27.12 by Martin von Gagern
Take user-configured aliases into account.
173
    user_aliases = {} # dict from cmd name to set of user-defined alias names
174
    for alias, expansion in config.GlobalConfig().get_aliases().iteritems():
175
        for token in commands.shlex_split_unicode(expansion):
176
            if not token.startswith("-"):
177
                user_aliases.setdefault(token, set()).add(alias)
178
                break
179
0.27.10 by Martin von Gagern
Complete help topics.
180
    all_cmds = sorted(commands.all_command_names())
181
    for cmdname in all_cmds:
182
        cmd = commands.get_cmd_object(cmdname)
0.27.12 by Martin von Gagern
Take user-configured aliases into account.
183
184
        # Find all aliases to the command; both cmd-defined and user-defined.
185
        # We assume a user won't override one command with a different one,
186
        # but will choose completely new names or add options to existing
187
        # ones while maintaining the actual command name unchanged.
188
        aliases = [cmdname]
189
        aliases.extend(cmd.aliases)
190
        aliases.extend(sorted([alias
191
                               for name in aliases
192
                               if name in user_aliases
193
                               for alias in user_aliases[name]
194
                               if alias not in aliases]))
195
        cases += "\t%s)\n" % "|".join(aliases)
196
        cmds.extend(aliases)
0.27.2 by Martin von Gagern
First programmatic generation of completions.
197
        plugin = cmd.plugin_name()
198
        if plugin is not None:
0.27.38 by Martin von Gagern
Add --plugin switch to selectively include plugins.
199
            if selected_plugins is not None and plugin not in selected_plugins:
200
                continue
0.27.36 by Martin von Gagern
List versions of bzr and plugins.
201
            plugins.add(plugin)
0.27.2 by Martin von Gagern
First programmatic generation of completions.
202
            cases += "\t\t# plugin \"%s\"\n" % plugin
203
        opts = cmd.options()
0.27.9 by Martin von Gagern
Remove suppression of alternate switches for the same option.
204
        switches = []
0.27.30 by Martin von Gagern
Complete values for enum_switch of RegistryOptions.
205
        enums = []
0.27.21 by Martin von Gagern
Allow help topic completion for aliases as well.
206
        fixedWords = None
0.27.2 by Martin von Gagern
First programmatic generation of completions.
207
        for optname in sorted(cmd.options()):
208
            opt = opts[optname]
0.28.1 by Martin von Gagern
Include negated switches as well, using a modified options parser.
209
            optswitches = []
210
            parser = option.get_optparser({optname: opt})
211
            parser = wrap_parser(optswitches, parser)
212
            optswitches[:] = []
213
            opt.add_option(parser, opt.short_name())
0.27.30 by Martin von Gagern
Complete values for enum_switch of RegistryOptions.
214
            if isinstance(opt, option.RegistryOption) and opt.enum_switch:
215
                enum_switch = '--%s' % optname
0.27.41 by Martin von Gagern
Recover from ImportError when loading a registry.
216
                try:
217
                    keys = opt.registry.keys()
218
                except ImportError, e:
219
                    cases += ("\t\t# ERROR getting registry keys for '--%s':"
220
                              + " %s\n") % (optname, str(e).split('\n')[0])
221
                else:
222
                    if enum_switch in optswitches and keys:
223
                        optswitches.remove(enum_switch)
224
                        for key in keys:
225
                            optswitches.append('%s=%s' % (enum_switch, key))
226
                            enums.append("%s) optEnums='%s' ;;"
227
                                         % (enum_switch, ' '.join(keys)))
0.28.1 by Martin von Gagern
Include negated switches as well, using a modified options parser.
228
            switches.extend(optswitches)
0.27.10 by Martin von Gagern
Complete help topics.
229
        if 'help' == cmdname or 'help' in cmd.aliases:
0.27.21 by Martin von Gagern
Allow help topic completion for aliases as well.
230
            fixedWords = " ".join(sorted(help_topics.topic_registry.keys()))
231
            fixedWords = '"$cmds %s"' % fixedWords
232
0.27.9 by Martin von Gagern
Remove suppression of alternate switches for the same option.
233
        cases += "\t\tcmdOpts='" + " ".join(switches) + "'\n"
0.27.20 by Martin von Gagern
More flexible handling of fixed word lists.
234
        if fixedWords:
0.27.21 by Martin von Gagern
Allow help topic completion for aliases as well.
235
            if isinstance(fixedWords, list):
0.27.30 by Martin von Gagern
Complete values for enum_switch of RegistryOptions.
236
                fixedWords = "'" + join(fixedWords) + "'"
0.27.21 by Martin von Gagern
Allow help topic completion for aliases as well.
237
            cases += "\t\tfixedWords=" + fixedWords + "\n"
0.27.30 by Martin von Gagern
Complete values for enum_switch of RegistryOptions.
238
        if enums:
239
            cases += "\t\tcase $curOpt in\n\t\t\t"
240
            cases += "\n\t\t\t".join(enums)
241
            cases += "\n\t\tesac\n"
0.27.9 by Martin von Gagern
Remove suppression of alternate switches for the same option.
242
        cases += "\t\t;;\n"
0.27.36 by Martin von Gagern
List versions of bzr and plugins.
243
244
    bzr_version = bzrlib.version_string
245
    if not plugins:
246
        bzr_version += "."
247
    else:
248
        bzr_version += " and the following plugins:"
249
        for plugin in sorted(plugins):
250
            pv = bzrlib.plugin.plugins()[plugin].__version__
251
            if pv == 'unknown':
252
                pv = ''
253
            else:
254
                pv = ' ' + pv
255
                bzr_version += "\n# %s%s" % (plugin, pv)
256
0.27.7 by Martin von Gagern
Introduce --function-only option
257
    if function_only:
258
        template = fun
259
    else:
260
        template = head + fun + tail
0.27.40 by Martin von Gagern
Restore compatibility with Python 2.4.
261
    if debug:
262
        perhaps_debug_output = debug_output
263
    else:
264
        perhaps_debug_output = ''
0.27.12 by Martin von Gagern
Take user-configured aliases into account.
265
    out.write(template % {"cmds": " ".join(cmds),
0.27.2 by Martin von Gagern
First programmatic generation of completions.
266
                          "cases": cases,
0.27.4 by Martin von Gagern
Introduce --function-name switch. (LP #439829)
267
                          "function_name": function_name,
0.27.18 by Martin von Gagern
Add global options in all cases
268
                          "version": __version__,
269
                          "global_options": global_options,
0.27.40 by Martin von Gagern
Restore compatibility with Python 2.4.
270
                          "debug": perhaps_debug_output,
0.27.36 by Martin von Gagern
List versions of bzr and plugins.
271
                          "bzr_version": bzr_version,
0.27.4 by Martin von Gagern
Introduce --function-name switch. (LP #439829)
272
                          })
0.27.2 by Martin von Gagern
First programmatic generation of completions.
273
274
if __name__ == '__main__':
275
276
    import sys
277
    import locale
0.27.32 by Martin von Gagern
Added OptionParser for script usage.
278
    import optparse
279
    from meta import __version__
280
0.27.38 by Martin von Gagern
Add --plugin switch to selectively include plugins.
281
    def plugin_callback(option, opt, value, parser):
282
        values = parser.values.selected_plugins
283
        if value == '-':
284
            del values[:]
285
        else:
286
            values.append(value)
287
0.27.32 by Martin von Gagern
Added OptionParser for script usage.
288
    parser = optparse.OptionParser(usage="%prog [-f NAME] [-o]",
289
                                   version="%%prog %s" % __version__)
290
    parser.add_option("--function-name", "-f", metavar="NAME",
291
                      help="Name of the generated function (default: _bzr)")
292
    parser.add_option("--function-only", "-o", action="store_true",
293
                      help="Generate only the shell function, don't enable it")
294
    parser.add_option("--debug", action="store_true",
295
                      help=optparse.SUPPRESS_HELP)
0.27.37 by Martin von Gagern
Introduce --no-plugins option to script execution mode.
296
    parser.add_option("--no-plugins", action="store_true",
297
                      help="Don't load any bzr plugins")
0.27.38 by Martin von Gagern
Add --plugin switch to selectively include plugins.
298
    parser.add_option("--plugin", metavar="NAME", type="string",
299
                      dest="selected_plugins", default=[],
300
                      action="callback", callback=plugin_callback,
301
                      help="Enable completions for the selected plugin"
302
                      + " (default: all plugins)")
0.27.32 by Martin von Gagern
Added OptionParser for script usage.
303
    (opts, args) = parser.parse_args()
304
    if args:
305
        parser.error("script does not take positional arguments")
306
    kwargs = dict()
307
    for name, value in opts.__dict__.iteritems():
308
        if value is not None:
309
            kwargs[name] = value
0.27.2 by Martin von Gagern
First programmatic generation of completions.
310
311
    locale.setlocale(locale.LC_ALL, '')
0.27.37 by Martin von Gagern
Introduce --no-plugins option to script execution mode.
312
    if not kwargs.get('no_plugins', False):
313
        plugin.load_plugins()
0.27.2 by Martin von Gagern
First programmatic generation of completions.
314
    commands.install_bzr_command_hooks()
0.27.32 by Martin von Gagern
Added OptionParser for script usage.
315
    bash_completion_function(sys.stdout, **kwargs)