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