~abentley/bzrtools/bzrtools.dev

« back to all changes in this revision

Viewing changes to shell.py

  • Committer: Aaron Bentley
  • Date: 2013-08-20 03:02:43 UTC
  • Revision ID: aaron@aaronbentley.com-20130820030243-r8v1xfbcnd8f10p4
Fix zap command for 2.6/7

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
# Copyright (C) 2004, 2005 Aaron Bentley
2
 
# <aaron.bentley@utoronto.ca>
 
2
# <aaron@aaronbentley.com>
3
3
#
4
4
#    This program is free software; you can redistribute it and/or modify
5
5
#    it under the terms of the GNU General Public License as published by
18
18
import cmd
19
19
from itertools import chain
20
20
import os
21
 
import readline
 
21
try:
 
22
    import readline
 
23
except ImportError:
 
24
    _has_readline = False
 
25
else:
 
26
    _has_readline = True
22
27
import shlex
 
28
import stat
23
29
import string
24
30
import sys
25
31
 
 
32
from bzrlib import osutils, trace
26
33
from bzrlib.branch import Branch
27
 
from bzrlib.commands import get_cmd_object, get_all_cmds, get_alias
 
34
from bzrlib.config import config_dir, ensure_config_dir_exists
 
35
from bzrlib.commands import get_cmd_object, all_command_names, get_alias
28
36
from bzrlib.errors import BzrError
 
37
from bzrlib.workingtree import WorkingTree
29
38
 
30
39
import terminal
31
40
 
64
73
 
65
74
    def get_completions_or_raise(self):
66
75
        if self.command is None:
67
 
            iter = (c+" " for c in iter_command_names() if
68
 
                    c not in COMPLETION_BLACKLIST)
 
76
            if '/' in self.text:
 
77
                iter = iter_executables(self.text)
 
78
            else:
 
79
                iter = (c+" " for c in iter_command_names() if
 
80
                        c not in COMPLETION_BLACKLIST)
69
81
            return list(filter_completions(iter, self.text))
70
82
        if self.prev_opt is None:
71
83
            completions = self.get_option_completions()
75
87
            else:
76
88
                iter = iter_file_completions(self.text)
77
89
                completions.extend(filter_completions(iter, self.text))
78
 
            return completions 
 
90
            return completions
79
91
 
80
92
 
81
93
class PromptCmd(cmd.Cmd):
 
94
 
82
95
    def __init__(self):
83
96
        cmd.Cmd.__init__(self)
84
97
        self.prompt = "bzr> "
89
102
        self.set_title()
90
103
        self.set_prompt()
91
104
        self.identchars += '-'
92
 
        self.history_file = os.path.expanduser("~/.bazaar/shell-history")
93
 
        readline.set_completer_delims(string.whitespace)
94
 
        if os.access(self.history_file, os.R_OK) and \
95
 
            os.path.isfile(self.history_file):
96
 
            readline.read_history_file(self.history_file)
 
105
        ensure_config_dir_exists()
 
106
        self.history_file = osutils.pathjoin(config_dir(), 'shell-history')
 
107
        whitespace = ''.join(c for c in string.whitespace if c < chr(127))
 
108
        if _has_readline:
 
109
            readline.set_completer_delims(whitespace)
 
110
            if os.access(self.history_file, os.R_OK) and \
 
111
                os.path.isfile(self.history_file):
 
112
                readline.read_history_file(self.history_file)
97
113
        self.cwd = os.getcwd()
98
114
 
99
115
    def write_history(self):
100
 
        readline.write_history_file(self.history_file)
 
116
        if _has_readline:
 
117
            readline.write_history_file(self.history_file)
101
118
 
102
119
    def do_quit(self, args):
103
120
        self.write_history()
117
134
    def set_prompt(self):
118
135
        if self.tree is not None:
119
136
            try:
120
 
                prompt_data = (self.tree.branch.nick, self.tree.branch.revno(), 
121
 
                               self.tree.branch.relpath('.'))
 
137
                prompt_data = (self.tree.branch.nick, self.tree.branch.revno(),
 
138
                               self.tree.relpath('.'))
122
139
                prompt = " %s:%d/%s" % prompt_data
123
140
            except:
124
141
                prompt = ""
159
176
        self.default("help "+line)
160
177
 
161
178
    def default(self, line):
162
 
        args = shlex.split(line)
 
179
        try:
 
180
            args = shlex.split(line)
 
181
        except ValueError, e:
 
182
            print 'Parse error:', e
 
183
            return
 
184
 
163
185
        alias_args = get_alias(args[0])
164
186
        if alias_args is not None:
165
187
            args[0] = alias_args.pop(0)
166
 
            
 
188
 
167
189
        commandname = args.pop(0)
168
190
        for char in ('|', '<', '>'):
169
191
            commandname = commandname.split(char)[0]
177
199
            return os.system(line)
178
200
 
179
201
        try:
180
 
            if too_complicated(line):
 
202
            is_qbzr = cmd_obj.__module__.startswith('bzrlib.plugins.qbzr.')
 
203
            if too_complicated(line) or is_qbzr:
181
204
                return os.system("bzr "+line)
182
205
            else:
183
206
                return (cmd_obj.run_argv_aliases(args, alias_args) or 0)
184
207
        except BzrError, e:
 
208
            trace.log_exception_quietly()
185
209
            print e
186
210
        except KeyboardInterrupt, e:
187
211
            print "Interrupted"
188
212
        except Exception, e:
189
 
#            print "Unhandled error:\n%s" % errors.exception_str(e)
 
213
            trace.log_exception_quietly()
190
214
            print "Unhandled error:\n%s" % (e)
191
215
 
192
216
 
195
219
 
196
220
    def completedefault(self, text, line, begidx, endidx):
197
221
        """Perform completion for native commands.
198
 
        
 
222
 
199
223
        :param text: The text to complete
200
224
        :type text: str
201
225
        :param line: The entire line to complete
211
235
        return CompletionContext(text, command=cmd).get_completions()
212
236
 
213
237
 
214
 
def run_shell():
 
238
def run_shell(directory=None):
215
239
    try:
 
240
        if not directory is None:
 
241
            os.chdir(directory)
216
242
        prompt = PromptCmd()
217
 
        try:
218
 
            prompt.cmdloop()
219
 
        finally:
220
 
            prompt.write_history()
 
243
        while True:
 
244
            try:
 
245
                try:
 
246
                    prompt.cmdloop()
 
247
                except KeyboardInterrupt:
 
248
                    print
 
249
            finally:
 
250
                prompt.write_history()
221
251
    except StopIteration:
222
252
        pass
223
253
 
271
301
 
272
302
 
273
303
def iter_command_names(hidden=False):
274
 
    for real_cmd_name, cmd_class in get_all_cmds():
275
 
        if not hidden and cmd_class.hidden:
 
304
    for real_cmd_name in all_command_names():
 
305
        cmd_obj = get_cmd_object(real_cmd_name)
 
306
        if not hidden and cmd_obj.hidden:
276
307
            continue
277
 
        for name in [real_cmd_name] + cmd_class.aliases:
 
308
        for name in [real_cmd_name] + cmd_obj.aliases:
278
309
            # Don't complete on aliases that are prefixes of the canonical name
279
310
            if name == real_cmd_name or not real_cmd_name.startswith(name):
280
311
                yield name
281
312
 
282
313
 
 
314
def iter_executables(path):
 
315
    dirname, partial = os.path.split(path)
 
316
    for filename in os.listdir(dirname):
 
317
        if not filename.startswith(partial):
 
318
            continue
 
319
        fullpath = os.path.join(dirname, filename)
 
320
        mode=os.lstat(fullpath)[stat.ST_MODE]
 
321
        if stat.S_ISREG(mode) and 0111 & mode:
 
322
            yield fullpath + ' '
 
323
 
 
324
 
283
325
def filter_completions(iter, arg):
284
326
    return (c for c in iter if c.startswith(arg))
285
327