~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/commands.py

  • Committer: mbp at sourcefrog
  • Date: 2005-04-11 02:44:45 UTC
  • Revision ID: mbp@sourcefrog.net-20050411024445-a2d4fa7e39309d2300533a6a
- Experiments in inventory performance

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2004, 2005 by Canonical Ltd
 
1
# Copyright (C) 2004, 2005 by Martin Pool
 
2
# Copyright (C) 2005 by Canonical Ltd
 
3
 
2
4
 
3
5
# This program is free software; you can redistribute it and/or modify
4
6
# it under the terms of the GNU General Public License as published by
14
16
# along with this program; if not, write to the Free Software
15
17
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
18
 
17
 
 
18
 
# TODO: probably should say which arguments are candidates for glob
19
 
# expansion on windows and do that at the command level.
20
 
 
21
 
# TODO: Help messages for options.
22
 
 
23
 
# TODO: Define arguments by objects, rather than just using names.
24
 
# Those objects can specify the expected type of the argument, which
25
 
# would help with validation and shell completion.
26
 
 
27
 
# TODO: "--profile=cum", to change sort order.  Is there any value in leaving
28
 
# the profile output behind so it can be interactively examined?
29
 
 
30
 
import sys
31
 
import os
32
 
from warnings import warn
 
19
"""Bazaar-NG -- a free distributed version-control tool
 
20
 
 
21
**WARNING: THIS IS AN UNSTABLE DEVELOPMENT VERSION**
 
22
 
 
23
Current limitation include:
 
24
 
 
25
* Metadata format is not stable yet -- you may need to
 
26
  discard history in the future.
 
27
 
 
28
* Insufficient error handling.
 
29
 
 
30
* Many commands unimplemented or partially implemented.
 
31
 
 
32
* Space-inefficient storage.
 
33
 
 
34
* No merge operators yet.
 
35
 
 
36
Interesting commands::
 
37
 
 
38
  bzr help [COMMAND]
 
39
       Show help screen
 
40
  bzr version
 
41
       Show software version/licence/non-warranty.
 
42
  bzr init
 
43
       Start versioning the current directory
 
44
  bzr add FILE...
 
45
       Make files versioned.
 
46
  bzr log
 
47
       Show revision history.
 
48
  bzr diff [FILE...]
 
49
       Show changes from last revision to working copy.
 
50
  bzr commit -m 'MESSAGE'
 
51
       Store current state as new revision.
 
52
  bzr export REVNO DESTINATION
 
53
       Export the branch state at a previous version.
 
54
  bzr status
 
55
       Show summary of pending changes.
 
56
  bzr remove FILE...
 
57
       Make a file not versioned.
 
58
  bzr info
 
59
       Show statistics about this branch.
 
60
"""
 
61
 
 
62
 
 
63
 
 
64
 
 
65
import sys, os, time, types, shutil, tempfile, traceback, fnmatch, difflib, os.path
 
66
from sets import Set
 
67
from pprint import pprint
 
68
from stat import *
 
69
from glob import glob
33
70
from inspect import getdoc
34
 
import errno
35
71
 
36
72
import bzrlib
37
 
import bzrlib.trace
38
 
from bzrlib.trace import mutter, note, log_error, warning
39
 
from bzrlib.errors import (BzrError, 
40
 
                           BzrCheckError,
41
 
                           BzrCommandError,
42
 
                           BzrOptionError,
43
 
                           NotBranchError)
44
 
from bzrlib.revisionspec import RevisionSpec
45
 
from bzrlib import BZRDIR
46
 
from bzrlib.option import Option
47
 
 
48
 
plugin_cmds = {}
49
 
 
50
 
 
51
 
def register_command(cmd, decorate=False):
52
 
    "Utility function to help register a command"
53
 
    global plugin_cmds
54
 
    k = cmd.__name__
55
 
    if k.startswith("cmd_"):
56
 
        k_unsquished = _unsquish_command_name(k)
57
 
    else:
58
 
        k_unsquished = k
59
 
    if not plugin_cmds.has_key(k_unsquished):
60
 
        plugin_cmds[k_unsquished] = cmd
61
 
        mutter('registered plugin command %s', k_unsquished)      
62
 
        if decorate and k_unsquished in builtin_command_names():
63
 
            return _builtin_commands()[k_unsquished]
64
 
    elif decorate:
65
 
        result = plugin_cmds[k_unsquished]
66
 
        plugin_cmds[k_unsquished] = cmd
67
 
        return result
68
 
    else:
69
 
        log_error('Two plugins defined the same command: %r' % k)
70
 
        log_error('Not loading the one in %r' % sys.modules[cmd.__module__])
71
 
 
72
 
 
73
 
def _squish_command_name(cmd):
74
 
    return 'cmd_' + cmd.replace('-', '_')
75
 
 
76
 
 
77
 
def _unsquish_command_name(cmd):
78
 
    assert cmd.startswith("cmd_")
79
 
    return cmd[4:].replace('_','-')
80
 
 
81
 
 
82
 
def _builtin_commands():
83
 
    import bzrlib.builtins
84
 
    r = {}
85
 
    builtins = bzrlib.builtins.__dict__
86
 
    for name in builtins:
87
 
        if name.startswith("cmd_"):
88
 
            real_name = _unsquish_command_name(name)        
89
 
            r[real_name] = builtins[name]
90
 
    return r
91
 
 
92
 
            
93
 
 
94
 
def builtin_command_names():
95
 
    """Return list of builtin command names."""
96
 
    return _builtin_commands().keys()
97
 
    
98
 
 
99
 
def plugin_command_names():
100
 
    return plugin_cmds.keys()
101
 
 
102
 
 
103
 
def _get_cmd_dict(plugins_override=True):
104
 
    """Return name->class mapping for all commands."""
105
 
    d = _builtin_commands()
106
 
    if plugins_override:
107
 
        d.update(plugin_cmds)
108
 
    return d
109
 
 
110
 
    
111
 
def get_all_cmds(plugins_override=True):
112
 
    """Return canonical name and class for all registered commands."""
113
 
    for k, v in _get_cmd_dict(plugins_override=plugins_override).iteritems():
114
 
        yield k,v
115
 
 
116
 
 
117
 
def get_cmd_object(cmd_name, plugins_override=True):
118
 
    """Return the canonical name and command class for a command.
119
 
 
120
 
    plugins_override
121
 
        If true, plugin commands can override builtins.
122
 
    """
123
 
    from bzrlib.externalcommand import ExternalCommand
124
 
 
125
 
    cmd_name = str(cmd_name)            # not unicode
126
 
 
127
 
    # first look up this command under the specified name
128
 
    cmds = _get_cmd_dict(plugins_override=plugins_override)
129
 
    try:
130
 
        return cmds[cmd_name]()
131
 
    except KeyError:
132
 
        pass
133
 
 
134
 
    # look for any command which claims this as an alias
135
 
    for real_cmd_name, cmd_class in cmds.iteritems():
136
 
        if cmd_name in cmd_class.aliases:
137
 
            return cmd_class()
138
 
 
139
 
    cmd_obj = ExternalCommand.find_command(cmd_name)
140
 
    if cmd_obj:
141
 
        return cmd_obj
142
 
 
143
 
    raise BzrCommandError("unknown command %r" % cmd_name)
144
 
 
145
 
 
146
 
class Command(object):
147
 
    """Base class for commands.
148
 
 
149
 
    Commands are the heart of the command-line bzr interface.
150
 
 
151
 
    The command object mostly handles the mapping of command-line
152
 
    parameters into one or more bzrlib operations, and of the results
153
 
    into textual output.
154
 
 
155
 
    Commands normally don't have any state.  All their arguments are
156
 
    passed in to the run method.  (Subclasses may take a different
157
 
    policy if the behaviour of the instance needs to depend on e.g. a
158
 
    shell plugin and not just its Python class.)
159
 
 
160
 
    The docstring for an actual command should give a single-line
161
 
    summary, then a complete description of the command.  A grammar
162
 
    description will be inserted.
163
 
 
164
 
    aliases
165
 
        Other accepted names for this command.
166
 
 
167
 
    takes_args
168
 
        List of argument forms, marked with whether they are optional,
169
 
        repeated, etc.
170
 
 
171
 
    takes_options
172
 
        List of options that may be given for this command.  These can
173
 
        be either strings, referring to globally-defined options,
174
 
        or option objects.  Retrieve through options().
175
 
 
176
 
    hidden
177
 
        If true, this command isn't advertised.  This is typically
178
 
        for commands intended for expert users.
179
 
    """
180
 
    aliases = []
181
 
    takes_args = []
182
 
    takes_options = []
183
 
 
184
 
    hidden = False
185
 
    
186
 
    def __init__(self):
187
 
        """Construct an instance of this command."""
188
 
        if self.__doc__ == Command.__doc__:
189
 
            warn("No help message set for %r" % self)
190
 
 
191
 
    def options(self):
192
 
        """Return dict of valid options for this command.
193
 
 
194
 
        Maps from long option name to option object."""
195
 
        r = dict()
196
 
        r['help'] = Option.OPTIONS['help']
197
 
        for o in self.takes_options:
198
 
            if not isinstance(o, Option):
199
 
                o = Option.OPTIONS[o]
200
 
            r[o.name] = o
201
 
        return r
202
 
 
203
 
    def run_argv(self, argv):
204
 
        """Parse command line and run."""
205
 
        args, opts = parse_args(self, argv)
206
 
        if 'help' in opts:  # e.g. bzr add --help
207
 
            from bzrlib.help import help_on_command
208
 
            help_on_command(self.name())
209
 
            return 0
210
 
        # XXX: This should be handled by the parser
211
 
        allowed_names = self.options().keys()
212
 
        for oname in opts:
213
 
            if oname not in allowed_names:
214
 
                raise BzrCommandError("option '--%s' is not allowed for command %r"
215
 
                                      % (oname, self.name()))
216
 
        # mix arguments and options into one dictionary
217
 
        cmdargs = _match_argform(self.name(), self.takes_args, args)
218
 
        cmdopts = {}
219
 
        for k, v in opts.items():
220
 
            cmdopts[k.replace('-', '_')] = v
221
 
 
222
 
        all_cmd_args = cmdargs.copy()
223
 
        all_cmd_args.update(cmdopts)
224
 
 
225
 
        return self.run(**all_cmd_args)
226
 
    
227
 
    def run(self):
228
 
        """Actually run the command.
229
 
 
230
 
        This is invoked with the options and arguments bound to
231
 
        keyword parameters.
232
 
 
233
 
        Return 0 or None if the command was successful, or a non-zero
234
 
        shell error code if not.  It's OK for this method to allow
235
 
        an exception to raise up.
236
 
        """
237
 
        raise NotImplementedError()
238
 
 
239
 
 
240
 
    def help(self):
241
 
        """Return help message for this class."""
242
 
        if self.__doc__ is Command.__doc__:
243
 
            return None
244
 
        return getdoc(self)
245
 
 
246
 
    def name(self):
247
 
        return _unsquish_command_name(self.__class__.__name__)
248
 
 
249
 
 
250
 
def parse_spec(spec):
251
 
    """
252
 
    >>> parse_spec(None)
253
 
    [None, None]
254
 
    >>> parse_spec("./")
255
 
    ['./', None]
256
 
    >>> parse_spec("../@")
257
 
    ['..', -1]
258
 
    >>> parse_spec("../f/@35")
259
 
    ['../f', 35]
260
 
    >>> parse_spec('./@revid:john@arbash-meinel.com-20050711044610-3ca0327c6a222f67')
261
 
    ['.', 'revid:john@arbash-meinel.com-20050711044610-3ca0327c6a222f67']
262
 
    """
263
 
    if spec is None:
264
 
        return [None, None]
265
 
    if '/@' in spec:
266
 
        parsed = spec.split('/@')
267
 
        assert len(parsed) == 2
268
 
        if parsed[1] == "":
269
 
            parsed[1] = -1
270
 
        else:
271
 
            try:
272
 
                parsed[1] = int(parsed[1])
273
 
            except ValueError:
274
 
                pass # We can allow stuff like ./@revid:blahblahblah
275
 
            else:
276
 
                assert parsed[1] >=0
277
 
    else:
278
 
        parsed = [spec, None]
279
 
    return parsed
280
 
 
281
 
def parse_args(command, argv):
 
73
from bzrlib.store import ImmutableStore
 
74
from bzrlib.trace import mutter, note, log_error
 
75
from bzrlib.errors import bailout, BzrError, BzrCheckError
 
76
from bzrlib.osutils import quotefn, pumpfile, isdir, isfile
 
77
from bzrlib.tree import RevisionTree, EmptyTree, WorkingTree, Tree
 
78
from bzrlib.revision import Revision
 
79
from bzrlib import Branch, Inventory, InventoryEntry, ScratchBranch, BZRDIR, \
 
80
     format_date
 
81
 
 
82
BZR_DIFF_FORMAT = "## Bazaar-NG diff, format 0 ##\n"
 
83
BZR_PATCHNAME_FORMAT = 'cset:sha1:%s'
 
84
 
 
85
## standard representation
 
86
NONE_STRING = '(none)'
 
87
EMPTY = 'empty'
 
88
 
 
89
 
 
90
## TODO: Perhaps a different version of inventory commands that
 
91
## returns iterators...
 
92
 
 
93
## TODO: Perhaps an AtomicFile class that writes to a temporary file and then renames.
 
94
 
 
95
## TODO: Some kind of locking on branches.  Perhaps there should be a
 
96
## parameter to the branch object saying whether we want a read or
 
97
## write lock; release it from destructor.  Perhaps don't even need a
 
98
## read lock to look at immutable objects?
 
99
 
 
100
## TODO: Perhaps make UUIDs predictable in test mode to make it easier
 
101
## to compare output?
 
102
 
 
103
## TODO: Some kind of global code to generate the right Branch object
 
104
## to work on.  Almost, but not quite all, commands need one, and it
 
105
## can be taken either from their parameters or their working
 
106
## directory.
 
107
 
 
108
## TODO: rename command, needed soon: check destination doesn't exist
 
109
## either in working copy or tree; move working copy; update
 
110
## inventory; write out
 
111
 
 
112
## TODO: move command; check destination is a directory and will not
 
113
## clash; move it.
 
114
 
 
115
## TODO: command to show renames, one per line, as to->from
 
116
 
 
117
 
 
118
 
 
119
 
 
120
def cmd_status(all=False):
 
121
    """Display status summary.
 
122
 
 
123
    For each file there is a single line giving its file state and name.
 
124
    The name is that in the current revision unless it is deleted or
 
125
    missing, in which case the old name is shown.
 
126
 
 
127
    :todo: Don't show unchanged files unless ``--all`` is given?
 
128
    """
 
129
    #import bzrlib.status
 
130
    #bzrlib.status.tree_status(Branch('.'))
 
131
    Branch('.').show_status(show_all=all)
 
132
 
 
133
 
 
134
 
 
135
######################################################################
 
136
# examining history
 
137
def cmd_get_revision(revision_id):
 
138
    Branch('.').get_revision(revision_id).write_xml(sys.stdout)
 
139
 
 
140
 
 
141
def cmd_get_file_text(text_id):
 
142
    """Get contents of a file by hash."""
 
143
    sf = Branch('.').text_store[text_id]
 
144
    pumpfile(sf, sys.stdout)
 
145
 
 
146
 
 
147
 
 
148
######################################################################
 
149
# commands
 
150
    
 
151
 
 
152
def cmd_revno():
 
153
    """Show number of revisions on this branch"""
 
154
    print Branch('.').revno()
 
155
    
 
156
 
 
157
    
 
158
def cmd_add(file_list, verbose=False):
 
159
    """Add specified files or directories.
 
160
 
 
161
    In non-recursive mode, all the named items are added, regardless
 
162
    of whether they were previously ignored.  A warning is given if
 
163
    any of the named files are already versioned.
 
164
 
 
165
    In recursive mode (the default), files are treated the same way
 
166
    but the behaviour for directories is different.  Directories that
 
167
    are already versioned do not give a warning.  All directories,
 
168
    whether already versioned or not, are searched for files or
 
169
    subdirectories that are neither versioned or ignored, and these
 
170
    are added.  This search proceeds recursively into versioned
 
171
    directories.
 
172
 
 
173
    Therefore simply saying 'bzr add .' will version all files that
 
174
    are currently unknown.
 
175
    """
 
176
    bzrlib.add.smart_add(file_list, verbose)
 
177
    
 
178
 
 
179
def cmd_relpath(filename):
 
180
    """Show path of file relative to root"""
 
181
    print Branch(filename).relpath(filename)
 
182
 
 
183
 
 
184
 
 
185
def cmd_inventory(revision=None):
 
186
    """Show inventory of the current working copy."""
 
187
    ## TODO: Also optionally show a previous inventory
 
188
    ## TODO: Format options
 
189
    b = Branch('.')
 
190
    if revision == None:
 
191
        inv = b.read_working_inventory()
 
192
    else:
 
193
        inv = b.get_revision_inventory(b.lookup_revision(revision))
 
194
        
 
195
    for path, entry in inv.iter_entries():
 
196
        print '%-50s %s' % (entry.file_id, path)
 
197
 
 
198
 
 
199
 
 
200
# TODO: Maybe a 'mv' command that has the combined move/rename
 
201
# special behaviour of Unix?
 
202
 
 
203
def cmd_move(source_list, dest):
 
204
    b = Branch('.')
 
205
 
 
206
    b.move([b.relpath(s) for s in source_list], b.relpath(dest))
 
207
 
 
208
 
 
209
 
 
210
def cmd_rename(from_name, to_name):
 
211
    """Change the name of an entry.
 
212
 
 
213
    usage: bzr rename FROM_NAME TO_NAME
 
214
 
 
215
    examples:
 
216
      bzr rename frob.c frobber.c
 
217
      bzr rename src/frob.c lib/frob.c
 
218
 
 
219
    It is an error if the destination name exists.
 
220
 
 
221
    See also the 'move' command, which moves files into a different
 
222
    directory without changing their name.
 
223
 
 
224
    TODO: Some way to rename multiple files without invoking bzr for each
 
225
    one?"""
 
226
    b = Branch('.')
 
227
    b.rename_one(b.relpath(from_name), b.relpath(to_name))
 
228
    
 
229
 
 
230
 
 
231
 
 
232
def cmd_renames(dir='.'):
 
233
    """Show list of renamed files.
 
234
 
 
235
    usage: bzr renames [BRANCH]
 
236
 
 
237
    TODO: Option to show renames between two historical versions.
 
238
 
 
239
    TODO: Only show renames under dir, rather than in the whole branch.
 
240
    """
 
241
    b = Branch(dir)
 
242
    old_inv = b.basis_tree().inventory
 
243
    new_inv = b.read_working_inventory()
 
244
    
 
245
    renames = list(bzrlib.tree.find_renames(old_inv, new_inv))
 
246
    renames.sort()
 
247
    for old_name, new_name in renames:
 
248
        print "%s => %s" % (old_name, new_name)        
 
249
 
 
250
 
 
251
 
 
252
def cmd_info():
 
253
    """info: Show statistical information for this branch
 
254
 
 
255
    usage: bzr info"""
 
256
    import info
 
257
    info.show_info(Branch('.'))        
 
258
    
 
259
 
 
260
 
 
261
def cmd_remove(file_list, verbose=False):
 
262
    b = Branch(file_list[0])
 
263
    b.remove([b.relpath(f) for f in file_list], verbose=verbose)
 
264
 
 
265
 
 
266
 
 
267
def cmd_file_id(filename):
 
268
    """Print file_id of a particular file or directory.
 
269
 
 
270
    usage: bzr file-id FILE
 
271
 
 
272
    The file_id is assigned when the file is first added and remains the
 
273
    same through all revisions where the file exists, even when it is
 
274
    moved or renamed.
 
275
    """
 
276
    b = Branch(filename)
 
277
    i = b.inventory.path2id(b.relpath(filename))
 
278
    if i == None:
 
279
        bailout("%r is not a versioned file" % filename)
 
280
    else:
 
281
        print i
 
282
 
 
283
 
 
284
def cmd_file_id_path(filename):
 
285
    """Print path of file_ids to a file or directory.
 
286
 
 
287
    usage: bzr file-id-path FILE
 
288
 
 
289
    This prints one line for each directory down to the target,
 
290
    starting at the branch root."""
 
291
    b = Branch(filename)
 
292
    inv = b.inventory
 
293
    fid = inv.path2id(b.relpath(filename))
 
294
    if fid == None:
 
295
        bailout("%r is not a versioned file" % filename)
 
296
    for fip in inv.get_idpath(fid):
 
297
        print fip
 
298
 
 
299
 
 
300
def cmd_revision_history():
 
301
    for patchid in Branch('.').revision_history():
 
302
        print patchid
 
303
 
 
304
 
 
305
def cmd_directories():
 
306
    for name, ie in Branch('.').read_working_inventory().directories():
 
307
        if name == '':
 
308
            print '.'
 
309
        else:
 
310
            print name
 
311
 
 
312
 
 
313
def cmd_missing():
 
314
    for name, ie in Branch('.').working_tree().missing():
 
315
        print name
 
316
 
 
317
 
 
318
def cmd_init():
 
319
    # TODO: Check we're not already in a working directory?  At the
 
320
    # moment you'll get an ugly error.
 
321
    
 
322
    # TODO: What if we're in a subdirectory of a branch?  Would like
 
323
    # to allow that, but then the parent may need to understand that
 
324
    # the children have disappeared, or should they be versioned in
 
325
    # both?
 
326
 
 
327
    # TODO: Take an argument/option for branch name.
 
328
    Branch('.', init=True)
 
329
 
 
330
 
 
331
def cmd_diff(revision=None, file_list=None):
 
332
    """bzr diff: Show differences in working tree.
 
333
    
 
334
    usage: bzr diff [-r REV] [FILE...]
 
335
 
 
336
    --revision REV
 
337
         Show changes since REV, rather than predecessor.
 
338
 
 
339
    If files are listed, only the changes in those files are listed.
 
340
    Otherwise, all changes for the tree are listed.
 
341
 
 
342
    TODO: Given two revision arguments, show the difference between them.
 
343
 
 
344
    TODO: Allow diff across branches.
 
345
 
 
346
    TODO: Option to use external diff command; could be GNU diff, wdiff,
 
347
          or a graphical diff.
 
348
 
 
349
    TODO: If a directory is given, diff everything under that.
 
350
 
 
351
    TODO: Selected-file diff is inefficient and doesn't show you deleted files.
 
352
"""
 
353
 
 
354
    ## TODO: Shouldn't be in the cmd function.
 
355
 
 
356
    b = Branch('.')
 
357
 
 
358
    if revision == None:
 
359
        old_tree = b.basis_tree()
 
360
    else:
 
361
        old_tree = b.revision_tree(b.lookup_revision(revision))
 
362
        
 
363
    new_tree = b.working_tree()
 
364
 
 
365
    # TODO: Options to control putting on a prefix or suffix, perhaps as a format string
 
366
    old_label = ''
 
367
    new_label = ''
 
368
 
 
369
    DEVNULL = '/dev/null'
 
370
    # Windows users, don't panic about this filename -- it is a
 
371
    # special signal to GNU patch that the file should be created or
 
372
    # deleted respectively.
 
373
 
 
374
    # TODO: Generation of pseudo-diffs for added/deleted files could
 
375
    # be usefully made into a much faster special case.
 
376
 
 
377
    # TODO: Better to return them in sorted order I think.
 
378
 
 
379
    # FIXME: If given a file list, compare only those files rather
 
380
    # than comparing everything and then throwing stuff away.
 
381
    
 
382
    for file_state, fid, old_name, new_name, kind in bzrlib.diff_trees(old_tree, new_tree):
 
383
 
 
384
        if file_list and new_name not in file_list:
 
385
            continue
 
386
        
 
387
        # Don't show this by default; maybe do it if an option is passed
 
388
        # idlabel = '      {%s}' % fid
 
389
        idlabel = ''
 
390
 
 
391
        # FIXME: Something about the diff format makes patch unhappy
 
392
        # with newly-added files.
 
393
 
 
394
        def diffit(oldlines, newlines, **kw):
 
395
            # FIXME: difflib is wrong if there is no trailing newline.
 
396
 
 
397
            # Special workaround for Python2.3, where difflib fails if
 
398
            # both sequences are empty.
 
399
            if oldlines or newlines:
 
400
                sys.stdout.writelines(difflib.unified_diff(oldlines, newlines, **kw))
 
401
            print
 
402
        
 
403
        if file_state in ['.', '?', 'I']:
 
404
            continue
 
405
        elif file_state == 'A':
 
406
            print '*** added %s %r' % (kind, new_name)
 
407
            if kind == 'file':
 
408
                diffit([],
 
409
                       new_tree.get_file(fid).readlines(),
 
410
                       fromfile=DEVNULL,
 
411
                       tofile=new_label + new_name + idlabel)
 
412
        elif file_state == 'D':
 
413
            assert isinstance(old_name, types.StringTypes)
 
414
            print '*** deleted %s %r' % (kind, old_name)
 
415
            if kind == 'file':
 
416
                diffit(old_tree.get_file(fid).readlines(), [],
 
417
                       fromfile=old_label + old_name + idlabel,
 
418
                       tofile=DEVNULL)
 
419
        elif file_state in ['M', 'R']:
 
420
            if file_state == 'M':
 
421
                assert kind == 'file'
 
422
                assert old_name == new_name
 
423
                print '*** modified %s %r' % (kind, new_name)
 
424
            elif file_state == 'R':
 
425
                print '*** renamed %s %r => %r' % (kind, old_name, new_name)
 
426
 
 
427
            if kind == 'file':
 
428
                diffit(old_tree.get_file(fid).readlines(),
 
429
                       new_tree.get_file(fid).readlines(),
 
430
                       fromfile=old_label + old_name + idlabel,
 
431
                       tofile=new_label + new_name)
 
432
        else:
 
433
            bailout("can't represent state %s {%s}" % (file_state, fid))
 
434
 
 
435
 
 
436
 
 
437
def cmd_deleted(show_ids=False):
 
438
    """List files deleted in the working tree.
 
439
 
 
440
    TODO: Show files deleted since a previous revision, or between two revisions.
 
441
    """
 
442
    b = Branch('.')
 
443
    old = b.basis_tree()
 
444
    new = b.working_tree()
 
445
 
 
446
    ## TODO: Much more efficient way to do this: read in new
 
447
    ## directories with readdir, rather than stating each one.  Same
 
448
    ## level of effort but possibly much less IO.  (Or possibly not,
 
449
    ## if the directories are very large...)
 
450
 
 
451
    for path, ie in old.inventory.iter_entries():
 
452
        if not new.has_id(ie.file_id):
 
453
            if show_ids:
 
454
                print '%-50s %s' % (path, ie.file_id)
 
455
            else:
 
456
                print path
 
457
 
 
458
 
 
459
 
 
460
def cmd_parse_inventory():
 
461
    import cElementTree
 
462
    
 
463
    cElementTree.ElementTree().parse(file('.bzr/inventory'))
 
464
 
 
465
 
 
466
 
 
467
def cmd_load_inventory():
 
468
    """Load inventory for timing purposes"""
 
469
    Branch('.').basis_tree().inventory
 
470
 
 
471
 
 
472
def cmd_dump_inventory():
 
473
    Branch('.').read_working_inventory().write_xml(sys.stdout)
 
474
 
 
475
 
 
476
def cmd_dump_new_inventory():
 
477
    import bzrlib.newinventory
 
478
    inv = Branch('.').basis_tree().inventory
 
479
    bzrlib.newinventory.write_inventory(inv, sys.stdout)
 
480
 
 
481
 
 
482
def cmd_load_new_inventory():
 
483
    import bzrlib.newinventory
 
484
    bzrlib.newinventory.read_new_inventory(sys.stdin)
 
485
                
 
486
    
 
487
def cmd_dump_slacker_inventory():
 
488
    import bzrlib.newinventory
 
489
    inv = Branch('.').basis_tree().inventory
 
490
    bzrlib.newinventory.write_slacker_inventory(inv, sys.stdout)
 
491
 
 
492
 
 
493
 
 
494
def cmd_dump_text_inventory():
 
495
    import bzrlib.textinv
 
496
    inv = Branch('.').basis_tree().inventory
 
497
    bzrlib.textinv.write_text_inventory(inv, sys.stdout)
 
498
 
 
499
 
 
500
def cmd_load_text_inventory():
 
501
    import bzrlib.textinv
 
502
    inv = bzrlib.textinv.read_text_inventory(sys.stdin)
 
503
    print 'loaded %d entries' % len(inv)
 
504
    
 
505
    
 
506
 
 
507
def cmd_root(filename=None):
 
508
    """Print the branch root."""
 
509
    print bzrlib.branch.find_branch_root(filename)
 
510
    
 
511
 
 
512
def cmd_log(timezone='original'):
 
513
    """Show log of this branch.
 
514
 
 
515
    :todo: Options for utc; to show ids; to limit range; etc.
 
516
    """
 
517
    Branch('.').write_log(show_timezone=timezone)
 
518
 
 
519
 
 
520
def cmd_ls(revision=None, verbose=False):
 
521
    """List files in a tree.
 
522
 
 
523
    :todo: Take a revision or remote path and list that tree instead.
 
524
    """
 
525
    b = Branch('.')
 
526
    if revision == None:
 
527
        tree = b.working_tree()
 
528
    else:
 
529
        tree = b.revision_tree(b.lookup_revision(revision))
 
530
        
 
531
    for fp, fc, kind, fid in tree.list_files():
 
532
        if verbose:
 
533
            if kind == 'directory':
 
534
                kindch = '/'
 
535
            elif kind == 'file':
 
536
                kindch = ''
 
537
            else:
 
538
                kindch = '???'
 
539
                
 
540
            print '%-8s %s%s' % (fc, fp, kindch)
 
541
        else:
 
542
            print fp
 
543
    
 
544
    
 
545
 
 
546
def cmd_unknowns():
 
547
    """List unknown files"""
 
548
    for f in Branch('.').unknowns():
 
549
        print quotefn(f)
 
550
 
 
551
 
 
552
 
 
553
def cmd_ignored():
 
554
    """List ignored files and the patterns that matched them.
 
555
      """
 
556
    tree = Branch('.').working_tree()
 
557
    for path, file_class, kind, file_id in tree.list_files():
 
558
        if file_class != 'I':
 
559
            continue
 
560
        ## XXX: Slightly inefficient since this was already calculated
 
561
        pat = tree.is_ignored(path)
 
562
        print '%-50s %s' % (path, pat)
 
563
 
 
564
 
 
565
def cmd_lookup_revision(revno):
 
566
    try:
 
567
        revno = int(revno)
 
568
    except ValueError:
 
569
        bailout("usage: lookup-revision REVNO",
 
570
                ["REVNO is a non-negative revision number for this branch"])
 
571
 
 
572
    print Branch('.').lookup_revision(revno) or NONE_STRING
 
573
 
 
574
 
 
575
 
 
576
def cmd_export(revno, dest):
 
577
    """Export past revision to destination directory."""
 
578
    b = Branch('.')
 
579
    rh = b.lookup_revision(int(revno))
 
580
    t = b.revision_tree(rh)
 
581
    t.export(dest)
 
582
 
 
583
def cmd_cat(revision, filename):
 
584
    """Print file to stdout."""
 
585
    b = Branch('.')
 
586
    b.print_file(b.relpath(filename), int(revision))
 
587
 
 
588
 
 
589
######################################################################
 
590
# internal/test commands
 
591
 
 
592
 
 
593
def cmd_uuid():
 
594
    """Print a newly-generated UUID."""
 
595
    print bzrlib.osutils.uuid()
 
596
 
 
597
 
 
598
 
 
599
def cmd_local_time_offset():
 
600
    print bzrlib.osutils.local_time_offset()
 
601
 
 
602
 
 
603
 
 
604
def cmd_commit(message=None, verbose=False):
 
605
    """Commit changes to a new revision.
 
606
 
 
607
    --message MESSAGE
 
608
        Description of changes in this revision; free form text.
 
609
        It is recommended that the first line be a single-sentence
 
610
        summary.
 
611
    --verbose
 
612
        Show status of changed files,
 
613
 
 
614
    TODO: Commit only selected files.
 
615
 
 
616
    TODO: Run hooks on tree to-be-committed, and after commit.
 
617
 
 
618
    TODO: Strict commit that fails if there are unknown or deleted files.
 
619
    """
 
620
 
 
621
    if not message:
 
622
        bailout("please specify a commit message")
 
623
    Branch('.').commit(message, verbose=verbose)
 
624
 
 
625
 
 
626
def cmd_check(dir='.'):
 
627
    """check: Consistency check of branch history.
 
628
 
 
629
    usage: bzr check [-v] [BRANCH]
 
630
 
 
631
    options:
 
632
      --verbose, -v         Show progress of checking.
 
633
 
 
634
    This command checks various invariants about the branch storage to
 
635
    detect data corruption or bzr bugs.
 
636
    """
 
637
    import bzrlib.check
 
638
    bzrlib.check.check(Branch(dir, find_root=False))
 
639
 
 
640
 
 
641
def cmd_is(pred, *rest):
 
642
    """Test whether PREDICATE is true."""
 
643
    try:
 
644
        cmd_handler = globals()['assert_' + pred.replace('-', '_')]
 
645
    except KeyError:
 
646
        bailout("unknown predicate: %s" % quotefn(pred))
 
647
        
 
648
    try:
 
649
        cmd_handler(*rest)
 
650
    except BzrCheckError:
 
651
        # by default we don't print the message so that this can
 
652
        # be used from shell scripts without producing noise
 
653
        sys.exit(1)
 
654
 
 
655
 
 
656
def cmd_username():
 
657
    print bzrlib.osutils.username()
 
658
 
 
659
 
 
660
def cmd_user_email():
 
661
    print bzrlib.osutils.user_email()
 
662
 
 
663
 
 
664
def cmd_gen_revision_id():
 
665
    print bzrlib.branch._gen_revision_id(time.time())
 
666
 
 
667
 
 
668
def cmd_selftest():
 
669
    """Run internal test suite"""
 
670
    ## -v, if present, is seen by doctest; the argument is just here
 
671
    ## so our parser doesn't complain
 
672
 
 
673
    ## TODO: --verbose option
 
674
 
 
675
    failures, tests = 0, 0
 
676
    
 
677
    import doctest, bzrlib.store, bzrlib.tests
 
678
    bzrlib.trace.verbose = False
 
679
 
 
680
    for m in bzrlib.store, bzrlib.inventory, bzrlib.branch, bzrlib.osutils, \
 
681
        bzrlib.tree, bzrlib.tests, bzrlib.commands, bzrlib.add:
 
682
        mf, mt = doctest.testmod(m)
 
683
        failures += mf
 
684
        tests += mt
 
685
        print '%-40s %3d tests' % (m.__name__, mt),
 
686
        if mf:
 
687
            print '%3d FAILED!' % mf
 
688
        else:
 
689
            print
 
690
 
 
691
    print '%-40s %3d tests' % ('total', tests),
 
692
    if failures:
 
693
        print '%3d FAILED!' % failures
 
694
    else:
 
695
        print
 
696
 
 
697
 
 
698
 
 
699
# deprecated
 
700
cmd_doctest = cmd_selftest
 
701
 
 
702
 
 
703
######################################################################
 
704
# help
 
705
 
 
706
 
 
707
def cmd_help(topic=None):
 
708
    if topic == None:
 
709
        print __doc__
 
710
        return
 
711
 
 
712
    # otherwise, maybe the name of a command?
 
713
    try:
 
714
        cmdfn = globals()['cmd_' + topic.replace('-', '_')]
 
715
    except KeyError:
 
716
        bailout("no help for %r" % topic)
 
717
 
 
718
    doc = getdoc(cmdfn)
 
719
    if doc == None:
 
720
        bailout("sorry, no detailed help yet for %r" % topic)
 
721
 
 
722
    print doc
 
723
        
 
724
 
 
725
 
 
726
 
 
727
def cmd_version():
 
728
    print "bzr (bazaar-ng) %s" % bzrlib.__version__
 
729
    print bzrlib.__copyright__
 
730
    print "http://bazaar-ng.org/"
 
731
    print
 
732
    print \
 
733
"""bzr comes with ABSOLUTELY NO WARRANTY.  bzr is free software, and
 
734
you may use, modify and redistribute it under the terms of the GNU 
 
735
General Public License version 2 or later."""
 
736
 
 
737
 
 
738
def cmd_rocks():
 
739
    """Statement of optimism."""
 
740
    print "it sure does!"
 
741
 
 
742
 
 
743
 
 
744
######################################################################
 
745
# main routine
 
746
 
 
747
 
 
748
# list of all available options; the rhs can be either None for an
 
749
# option that takes no argument, or a constructor function that checks
 
750
# the type.
 
751
OPTIONS = {
 
752
    'all':                    None,
 
753
    'help':                   None,
 
754
    'message':                unicode,
 
755
    'profile':                None,
 
756
    'revision':               int,
 
757
    'show-ids':               None,
 
758
    'timezone':               str,
 
759
    'verbose':                None,
 
760
    'version':                None,
 
761
    }
 
762
 
 
763
SHORT_OPTIONS = {
 
764
    'm':                      'message',
 
765
    'r':                      'revision',
 
766
    'v':                      'verbose',
 
767
}
 
768
 
 
769
# List of options that apply to particular commands; commands not
 
770
# listed take none.
 
771
cmd_options = {
 
772
    'add':                    ['verbose'],
 
773
    'cat':                    ['revision'],
 
774
    'commit':                 ['message', 'verbose'],
 
775
    'deleted':                ['show-ids'],
 
776
    'diff':                   ['revision'],
 
777
    'inventory':              ['revision'],
 
778
    'log':                    ['timezone'],
 
779
    'ls':                     ['revision', 'verbose'],
 
780
    'remove':                 ['verbose'],
 
781
    'status':                 ['all'],
 
782
    }
 
783
 
 
784
 
 
785
cmd_args = {
 
786
    'add':                    ['file+'],
 
787
    'cat':                    ['filename'],
 
788
    'commit':                 [],
 
789
    'diff':                   ['file*'],
 
790
    'export':                 ['revno', 'dest'],
 
791
    'file-id':                ['filename'],
 
792
    'file-id-path':           ['filename'],
 
793
    'get-file-text':          ['text_id'],
 
794
    'get-inventory':          ['inventory_id'],
 
795
    'get-revision':           ['revision_id'],
 
796
    'get-revision-inventory': ['revision_id'],
 
797
    'help':                   ['topic?'],
 
798
    'init':                   [],
 
799
    'log':                    [],
 
800
    'lookup-revision':        ['revno'],
 
801
    'move':                   ['source$', 'dest'],
 
802
    'relpath':                ['filename'],
 
803
    'remove':                 ['file+'],
 
804
    'rename':                 ['from_name', 'to_name'],
 
805
    'renames':                ['dir?'],
 
806
    'root':                   ['filename?'],
 
807
    'status':                 [],
 
808
    }
 
809
 
 
810
 
 
811
def parse_args(argv):
282
812
    """Parse command line.
283
813
    
284
814
    Arguments and options are parsed at this level before being passed
285
815
    down to specific command handlers.  This routine knows, from a
286
816
    lookup table, something about the available options, what optargs
287
817
    they take, and which commands will accept them.
 
818
 
 
819
    >>> parse_args('--help'.split())
 
820
    ([], {'help': True})
 
821
    >>> parse_args('--version'.split())
 
822
    ([], {'version': True})
 
823
    >>> parse_args('status --all'.split())
 
824
    (['status'], {'all': True})
 
825
    >>> parse_args('commit --message=biter'.split())
 
826
    (['commit'], {'message': u'biter'})
288
827
    """
289
 
    # TODO: chop up this beast; make it a method of the Command
290
828
    args = []
291
829
    opts = {}
292
830
 
293
 
    cmd_options = command.options()
294
 
    argsover = False
 
831
    # TODO: Maybe handle '--' to end options?
 
832
 
295
833
    while argv:
296
834
        a = argv.pop(0)
297
 
        if argsover:
298
 
            args.append(a)
299
 
            continue
300
 
        elif a == '--':
301
 
            # We've received a standalone -- No more flags
302
 
            argsover = True
303
 
            continue
304
835
        if a[0] == '-':
305
 
            # option names must not be unicode
306
 
            a = str(a)
307
836
            optarg = None
308
837
            if a[1] == '-':
309
 
                mutter("  got option %r", a)
 
838
                mutter("  got option %r" % a)
310
839
                if '=' in a:
311
840
                    optname, optarg = a[2:].split('=', 1)
312
841
                else:
313
842
                    optname = a[2:]
314
 
                if optname not in cmd_options:
315
 
                    raise BzrOptionError('unknown long option %r for command %s'
316
 
                        % (a, command.name()))
 
843
                if optname not in OPTIONS:
 
844
                    bailout('unknown long option %r' % a)
317
845
            else:
318
846
                shortopt = a[1:]
319
 
                if shortopt in Option.SHORT_OPTIONS:
320
 
                    # Multi-character options must have a space to delimit
321
 
                    # their value
322
 
                    # ^^^ what does this mean? mbp 20051014
323
 
                    optname = Option.SHORT_OPTIONS[shortopt].name
324
 
                else:
325
 
                    # Single character short options, can be chained,
326
 
                    # and have their value appended to their name
327
 
                    shortopt = a[1:2]
328
 
                    if shortopt not in Option.SHORT_OPTIONS:
329
 
                        # We didn't find the multi-character name, and we
330
 
                        # didn't find the single char name
331
 
                        raise BzrError('unknown short option %r' % a)
332
 
                    optname = Option.SHORT_OPTIONS[shortopt].name
333
 
 
334
 
                    if a[2:]:
335
 
                        # There are extra things on this option
336
 
                        # see if it is the value, or if it is another
337
 
                        # short option
338
 
                        optargfn = Option.OPTIONS[optname].type
339
 
                        if optargfn is None:
340
 
                            # This option does not take an argument, so the
341
 
                            # next entry is another short option, pack it back
342
 
                            # into the list
343
 
                            argv.insert(0, '-' + a[2:])
344
 
                        else:
345
 
                            # This option takes an argument, so pack it
346
 
                            # into the array
347
 
                            optarg = a[2:]
 
847
                if shortopt not in SHORT_OPTIONS:
 
848
                    bailout('unknown short option %r' % a)
 
849
                optname = SHORT_OPTIONS[shortopt]
348
850
            
349
851
            if optname in opts:
350
852
                # XXX: Do we ever want to support this, e.g. for -r?
351
 
                raise BzrError('repeated option %r' % a)
 
853
                bailout('repeated option %r' % a)
352
854
                
353
 
            option_obj = cmd_options[optname]
354
 
            optargfn = option_obj.type
 
855
            optargfn = OPTIONS[optname]
355
856
            if optargfn:
356
857
                if optarg == None:
357
858
                    if not argv:
358
 
                        raise BzrError('option %r needs an argument' % a)
 
859
                        bailout('option %r needs an argument' % a)
359
860
                    else:
360
861
                        optarg = argv.pop(0)
361
862
                opts[optname] = optargfn(optarg)
362
863
            else:
363
864
                if optarg != None:
364
 
                    raise BzrError('option %r takes no argument' % optname)
 
865
                    bailout('option %r takes no argument' % optname)
365
866
                opts[optname] = True
366
867
        else:
367
868
            args.append(a)
 
869
 
368
870
    return args, opts
369
871
 
370
872
 
371
 
def _match_argform(cmd, takes_args, args):
 
873
 
 
874
def _match_args(cmd, args):
 
875
    """Check non-option arguments match required pattern.
 
876
 
 
877
    >>> _match_args('status', ['asdasdsadasd'])
 
878
    Traceback (most recent call last):
 
879
    ...
 
880
    BzrError: ("extra arguments to command status: ['asdasdsadasd']", [])
 
881
    >>> _match_args('add', ['asdasdsadasd'])
 
882
    {'file_list': ['asdasdsadasd']}
 
883
    >>> _match_args('add', 'abc def gj'.split())
 
884
    {'file_list': ['abc', 'def', 'gj']}
 
885
    """
 
886
    # match argument pattern
 
887
    argform = cmd_args.get(cmd, [])
372
888
    argdict = {}
 
889
    # TODO: Need a way to express 'cp SRC... DEST', where it matches
 
890
    # all but one.
373
891
 
374
 
    # step through args and takes_args, allowing appropriate 0-many matches
375
 
    for ap in takes_args:
 
892
    # step through args and argform, allowing appropriate 0-many matches
 
893
    for ap in argform:
376
894
        argname = ap[:-1]
377
895
        if ap[-1] == '?':
378
896
            if args:
385
903
                argdict[argname + '_list'] = None
386
904
        elif ap[-1] == '+':
387
905
            if not args:
388
 
                raise BzrCommandError("command %r needs one or more %s"
 
906
                bailout("command %r needs one or more %s"
389
907
                        % (cmd, argname.upper()))
390
908
            else:
391
909
                argdict[argname + '_list'] = args[:]
392
910
                args = []
393
911
        elif ap[-1] == '$': # all but one
394
912
            if len(args) < 2:
395
 
                raise BzrCommandError("command %r needs one or more %s"
 
913
                bailout("command %r needs one or more %s"
396
914
                        % (cmd, argname.upper()))
397
915
            argdict[argname + '_list'] = args[:-1]
398
916
            args[:-1] = []                
400
918
            # just a plain arg
401
919
            argname = ap
402
920
            if not args:
403
 
                raise BzrCommandError("command %r requires argument %s"
 
921
                bailout("command %r requires argument %s"
404
922
                        % (cmd, argname.upper()))
405
923
            else:
406
924
                argdict[argname] = args.pop(0)
407
925
            
408
926
    if args:
409
 
        raise BzrCommandError("extra argument to command %s: %s"
410
 
                              % (cmd, args[0]))
 
927
        bailout("extra arguments to command %s: %r"
 
928
                % (cmd, args))
411
929
 
412
930
    return argdict
413
931
 
414
932
 
415
933
 
416
 
def apply_profiled(the_callable, *args, **kwargs):
417
 
    import hotshot
418
 
    import tempfile
419
 
    import hotshot.stats
420
 
    pffileno, pfname = tempfile.mkstemp()
421
 
    try:
422
 
        prof = hotshot.Profile(pfname)
423
 
        try:
424
 
            ret = prof.runcall(the_callable, *args, **kwargs) or 0
425
 
        finally:
426
 
            prof.close()
427
 
        stats = hotshot.stats.load(pfname)
428
 
        stats.strip_dirs()
429
 
        stats.sort_stats('cum')   # 'time'
430
 
        ## XXX: Might like to write to stderr or the trace file instead but
431
 
        ## print_stats seems hardcoded to stdout
432
 
        stats.print_stats(20)
433
 
        return ret
434
 
    finally:
435
 
        os.close(pffileno)
436
 
        os.remove(pfname)
437
 
 
438
 
 
439
934
def run_bzr(argv):
440
935
    """Execute a command.
441
936
 
442
937
    This is similar to main(), but without all the trappings for
443
 
    logging and error handling.  
444
 
    
445
 
    argv
446
 
       The command-line arguments, without the program name from argv[0]
447
 
    
448
 
    Returns a command status or raises an exception.
449
 
 
450
 
    Special master options: these must come before the command because
451
 
    they control how the command is interpreted.
452
 
 
453
 
    --no-plugins
454
 
        Do not load plugin modules at all
455
 
 
456
 
    --builtin
457
 
        Only use builtin commands.  (Plugins are still allowed to change
458
 
        other behaviour.)
459
 
 
460
 
    --profile
461
 
        Run under the Python profiler.
 
938
    logging and error handling.
462
939
    """
463
 
    argv = [a.decode(bzrlib.user_encoding) for a in argv]
464
 
 
465
 
    opt_profile = opt_no_plugins = opt_builtin = False
466
 
 
467
 
    # --no-plugins is handled specially at a very early stage. We need
468
 
    # to load plugins before doing other command parsing so that they
469
 
    # can override commands, but this needs to happen first.
470
 
 
471
 
    for a in argv:
472
 
        if a == '--profile':
473
 
            opt_profile = True
474
 
        elif a == '--no-plugins':
475
 
            opt_no_plugins = True
476
 
        elif a == '--builtin':
477
 
            opt_builtin = True
478
 
        else:
479
 
            break
480
 
        argv.remove(a)
481
 
 
482
 
    if (not argv) or (argv[0] == '--help'):
483
 
        from bzrlib.help import help
484
 
        if len(argv) > 1:
485
 
            help(argv[1])
486
 
        else:
487
 
            help()
488
 
        return 0
489
 
 
490
 
    if argv[0] == '--version':
491
 
        from bzrlib.builtins import show_version
492
 
        show_version()
493
 
        return 0
494
 
        
495
 
    if not opt_no_plugins:
496
 
        from bzrlib.plugin import load_plugins
497
 
        load_plugins()
498
 
 
499
 
    cmd = str(argv.pop(0))
500
 
 
501
 
    cmd_obj = get_cmd_object(cmd, plugins_override=not opt_builtin)
502
 
 
503
 
    if opt_profile:
504
 
        ret = apply_profiled(cmd_obj.run_argv, argv)
505
 
    else:
506
 
        ret = cmd_obj.run_argv(argv)
507
 
    return ret or 0
508
 
 
509
 
def display_command(func):
510
 
    def ignore_pipe(*args, **kwargs):
511
 
        try:
512
 
            return func(*args, **kwargs)
513
 
        except IOError, e:
514
 
            if e.errno != errno.EPIPE:
515
 
                raise
516
 
        except KeyboardInterrupt:
517
 
            pass
518
 
    return ignore_pipe
 
940
    try:
 
941
        args, opts = parse_args(argv[1:])
 
942
        if 'help' in opts:
 
943
            # TODO: pass down other arguments in case they asked for
 
944
            # help on a command name?
 
945
            if args:
 
946
                cmd_help(args[0])
 
947
            else:
 
948
                cmd_help()
 
949
            return 0
 
950
        elif 'version' in opts:
 
951
            cmd_version()
 
952
            return 0
 
953
        cmd = args.pop(0)
 
954
    except IndexError:
 
955
        log_error('usage: bzr COMMAND\n')
 
956
        log_error('  try "bzr help"\n')
 
957
        return 1
 
958
 
 
959
    try:
 
960
        cmd_handler = globals()['cmd_' + cmd.replace('-', '_')]
 
961
    except KeyError:
 
962
        bailout("unknown command " + `cmd`)
 
963
 
 
964
    # global option
 
965
    if 'profile' in opts:
 
966
        profile = True
 
967
        del opts['profile']
 
968
    else:
 
969
        profile = False
 
970
 
 
971
    # check options are reasonable
 
972
    allowed = cmd_options.get(cmd, [])
 
973
    for oname in opts:
 
974
        if oname not in allowed:
 
975
            bailout("option %r is not allowed for command %r"
 
976
                    % (oname, cmd))
 
977
 
 
978
    # TODO: give an error if there are any mandatory options which are
 
979
    # not specified?  Or maybe there shouldn't be any "mandatory
 
980
    # options" (it is an oxymoron)
 
981
 
 
982
    # mix arguments and options into one dictionary
 
983
    cmdargs = _match_args(cmd, args)
 
984
    for k, v in opts.items():
 
985
        cmdargs[k.replace('-', '_')] = v
 
986
 
 
987
    if profile:
 
988
        import hotshot
 
989
        prof = hotshot.Profile('.bzr.profile')
 
990
        ret = prof.runcall(cmd_handler, **cmdargs) or 0
 
991
        prof.close()
 
992
 
 
993
        import hotshot.stats
 
994
        stats = hotshot.stats.load('.bzr.profile')
 
995
        #stats.strip_dirs()
 
996
        stats.sort_stats('time')
 
997
        stats.print_stats(20)
 
998
 
 
999
        return ret
 
1000
    else:
 
1001
        return cmd_handler(**cmdargs) or 0
 
1002
 
 
1003
 
519
1004
 
520
1005
def main(argv):
521
 
    import bzrlib.ui
522
 
    bzrlib.trace.log_startup(argv)
523
 
    bzrlib.ui.ui_factory = bzrlib.ui.TextUIFactory()
524
 
 
525
 
    return run_bzr_catch_errors(argv[1:])
526
 
 
527
 
 
528
 
def run_bzr_catch_errors(argv):
 
1006
    ## TODO: Handle command-line options; probably know what options are valid for
 
1007
    ## each command
 
1008
 
 
1009
    ## TODO: If the arguments are wrong, give a usage message rather
 
1010
    ## than just a backtrace.
 
1011
 
 
1012
    bzrlib.trace.create_tracefile(argv)
 
1013
    
529
1014
    try:
530
 
        try:
531
 
            return run_bzr(argv)
532
 
        finally:
533
 
            # do this here inside the exception wrappers to catch EPIPE
534
 
            sys.stdout.flush()
535
 
    except BzrCommandError, e:
536
 
        # command line syntax error, etc
537
 
        log_error(str(e))
538
 
        return 1
 
1015
        ret = run_bzr(argv)
 
1016
        return ret
539
1017
    except BzrError, e:
540
 
        bzrlib.trace.log_exception()
 
1018
        log_error('bzr: error: ' + e.args[0] + '\n')
 
1019
        if len(e.args) > 1:
 
1020
            for h in e.args[1]:
 
1021
                log_error('  ' + h + '\n')
 
1022
        traceback.print_exc(None, bzrlib.trace._tracefile)
 
1023
        log_error('(see $HOME/.bzr.log for debug information)\n')
541
1024
        return 1
542
 
    except AssertionError, e:
543
 
        bzrlib.trace.log_exception('assertion failed: ' + str(e))
544
 
        return 3
545
 
    except KeyboardInterrupt, e:
546
 
        bzrlib.trace.log_exception('interrupted')
547
 
        return 2
548
1025
    except Exception, e:
549
 
        import errno
550
 
        if (isinstance(e, IOError) 
551
 
            and hasattr(e, 'errno')
552
 
            and e.errno == errno.EPIPE):
553
 
            bzrlib.trace.note('broken pipe')
554
 
            return 2
555
 
        else:
556
 
            ## import pdb
557
 
            ## pdb.pm()
558
 
            bzrlib.trace.log_exception()
559
 
            return 2
 
1026
        log_error('bzr: exception: %s\n' % e)
 
1027
        log_error('(see $HOME/.bzr.log for debug information)\n')
 
1028
        traceback.print_exc(None, bzrlib.trace._tracefile)
 
1029
        ## traceback.print_exc(None, sys.stderr)
 
1030
        return 1
 
1031
 
 
1032
    ## TODO: Trap AssertionError
 
1033
 
 
1034
    # TODO: Maybe nicer handling of IOError especially for broken pipe.
 
1035
 
 
1036
 
560
1037
 
561
1038
if __name__ == '__main__':
562
1039
    sys.exit(main(sys.argv))
 
1040
    ##import profile
 
1041
    ##profile.run('main(sys.argv)')
 
1042