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