~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/commands.py

  • Committer: Martin Pool
  • Date: 2005-08-30 03:14:42 UTC
  • Revision ID: mbp@sourcefrog.net-20050830031442-445c7b00640b967c
- accept -- to terminate options
  (patch from jblack)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#! /usr/bin/python
2
 
 
3
 
 
4
 
# Copyright (C) 2004, 2005 by Martin Pool
5
 
# Copyright (C) 2005 by Canonical Ltd
6
 
 
 
1
# Copyright (C) 2004, 2005 by Canonical Ltd
7
2
 
8
3
# This program is free software; you can redistribute it and/or modify
9
4
# it under the terms of the GNU General Public License as published by
19
14
# along with this program; if not, write to the Free Software
20
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21
16
 
22
 
"""Bazaar-NG -- a free distributed version-control tool
23
 
 
24
 
**WARNING: THIS IS AN UNSTABLE DEVELOPMENT VERSION**
25
 
 
26
 
Current limitation include:
27
 
 
28
 
* Metadata format is not stable yet -- you may need to
29
 
  discard history in the future.
30
 
 
31
 
* No handling of subdirectories, symlinks or any non-text files.
32
 
 
33
 
* Insufficient error handling.
34
 
 
35
 
* Many commands unimplemented or partially implemented.
36
 
 
37
 
* Space-inefficient storage.
38
 
 
39
 
* No merge operators yet.
40
 
 
41
 
Interesting commands::
42
 
 
43
 
  bzr help
44
 
       Show summary help screen
45
 
  bzr version
46
 
       Show software version/licence/non-warranty.
47
 
  bzr init
48
 
       Start versioning the current directory
49
 
  bzr add FILE...
50
 
       Make files versioned.
51
 
  bzr log
52
 
       Show revision history.
53
 
  bzr diff
54
 
       Show changes from last revision to working copy.
55
 
  bzr commit -m 'MESSAGE'
56
 
       Store current state as new revision.
57
 
  bzr export REVNO DESTINATION
58
 
       Export the branch state at a previous version.
59
 
  bzr status
60
 
       Show summary of pending changes.
61
 
  bzr remove FILE...
62
 
       Make a file not versioned.
63
 
"""
64
 
 
65
 
# not currently working:
66
 
#  bzr info
67
 
#       Show some information about this branch.
68
 
 
69
 
 
70
 
 
71
 
__copyright__ = "Copyright 2005 Canonical Development Ltd."
72
 
__author__ = "Martin Pool <mbp@canonical.com>"
73
 
__docformat__ = "restructuredtext en"
74
 
__version__ = '0.0.0'
75
 
 
76
 
 
77
 
import sys, os, random, time, sha, sets, types, re, shutil, tempfile
78
 
import traceback, socket, fnmatch, difflib
79
 
from os import path
80
 
from sets import Set
81
 
from pprint import pprint
82
 
from stat import *
83
 
from glob import glob
 
17
 
 
18
# TODO: Split the command framework away from the actual commands.
 
19
 
 
20
# TODO: probably should say which arguments are candidates for glob
 
21
# expansion on windows and do that at the command level.
 
22
 
 
23
# TODO: Help messages for options.
 
24
 
 
25
# TODO: Define arguments by objects, rather than just using names.
 
26
# Those objects can specify the expected type of the argument, which
 
27
# would help with validation and shell completion.
 
28
 
 
29
 
 
30
# TODO: Help messages for options.
 
31
 
 
32
# TODO: Define arguments by objects, rather than just using names.
 
33
# Those objects can specify the expected type of the argument, which
 
34
# would help with validation and shell completion.
 
35
 
 
36
 
 
37
import sys
 
38
import os
84
39
 
85
40
import bzrlib
86
 
from bzrlib.store import ImmutableStore
87
 
from bzrlib.trace import mutter, note, log_error
88
 
from bzrlib.errors import bailout, BzrError
89
 
from bzrlib.osutils import quotefn, pumpfile, isdir, isfile
90
 
from bzrlib.tree import RevisionTree, EmptyTree, WorkingTree, Tree
91
 
from bzrlib.revision import Revision
92
 
from bzrlib import Branch, Inventory, InventoryEntry, ScratchBranch, BZRDIR, \
93
 
     format_date
94
 
 
95
 
BZR_DIFF_FORMAT = "## Bazaar-NG diff, format 0 ##\n"
96
 
BZR_PATCHNAME_FORMAT = 'cset:sha1:%s'
97
 
 
98
 
## standard representation
99
 
NONE_STRING = '(none)'
100
 
EMPTY = 'empty'
101
 
 
102
 
 
103
 
## TODO: Perhaps a different version of inventory commands that
104
 
## returns iterators...
105
 
 
106
 
## TODO: Perhaps an AtomicFile class that writes to a temporary file and then renames.
107
 
 
108
 
## TODO: Some kind of locking on branches.  Perhaps there should be a
109
 
## parameter to the branch object saying whether we want a read or
110
 
## write lock; release it from destructor.  Perhaps don't even need a
111
 
## read lock to look at immutable objects?
112
 
 
113
 
## TODO: Perhaps make UUIDs predictable in test mode to make it easier
114
 
## to compare output?
115
 
 
116
 
## TODO: Some kind of global code to generate the right Branch object
117
 
## to work on.  Almost, but not quite all, commands need one, and it
118
 
## can be taken either from their parameters or their working
119
 
## directory.
120
 
 
121
 
## TODO: rename command, needed soon: check destination doesn't exist
122
 
## either in working copy or tree; move working copy; update
123
 
## inventory; write out
124
 
 
125
 
## TODO: move command; check destination is a directory and will not
126
 
## clash; move it.
127
 
 
128
 
## TODO: command to show renames, one per line, as to->from
129
 
 
130
 
 
131
 
 
132
 
 
133
 
def cmd_status(all=False):
 
41
import bzrlib.trace
 
42
from bzrlib.trace import mutter, note, log_error, warning
 
43
from bzrlib.errors import BzrError, BzrCheckError, BzrCommandError
 
44
from bzrlib.branch import find_branch
 
45
from bzrlib import BZRDIR
 
46
 
 
47
 
 
48
plugin_cmds = {}
 
49
 
 
50
 
 
51
def register_command(cmd):
 
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
    else:
 
63
        log_error('Two plugins defined the same command: %r' % k)
 
64
        log_error('Not loading the one in %r' % sys.modules[cmd.__module__])
 
65
 
 
66
 
 
67
def _squish_command_name(cmd):
 
68
    return 'cmd_' + cmd.replace('-', '_')
 
69
 
 
70
 
 
71
def _unsquish_command_name(cmd):
 
72
    assert cmd.startswith("cmd_")
 
73
    return cmd[4:].replace('_','-')
 
74
 
 
75
 
 
76
def _parse_revision_str(revstr):
 
77
    """This handles a revision string -> revno.
 
78
 
 
79
    This always returns a list.  The list will have one element for 
 
80
 
 
81
    It supports integers directly, but everything else it
 
82
    defers for passing to Branch.get_revision_info()
 
83
 
 
84
    >>> _parse_revision_str('234')
 
85
    [234]
 
86
    >>> _parse_revision_str('234..567')
 
87
    [234, 567]
 
88
    >>> _parse_revision_str('..')
 
89
    [None, None]
 
90
    >>> _parse_revision_str('..234')
 
91
    [None, 234]
 
92
    >>> _parse_revision_str('234..')
 
93
    [234, None]
 
94
    >>> _parse_revision_str('234..456..789') # Maybe this should be an error
 
95
    [234, 456, 789]
 
96
    >>> _parse_revision_str('234....789') # Error?
 
97
    [234, None, 789]
 
98
    >>> _parse_revision_str('revid:test@other.com-234234')
 
99
    ['revid:test@other.com-234234']
 
100
    >>> _parse_revision_str('revid:test@other.com-234234..revid:test@other.com-234235')
 
101
    ['revid:test@other.com-234234', 'revid:test@other.com-234235']
 
102
    >>> _parse_revision_str('revid:test@other.com-234234..23')
 
103
    ['revid:test@other.com-234234', 23]
 
104
    >>> _parse_revision_str('date:2005-04-12')
 
105
    ['date:2005-04-12']
 
106
    >>> _parse_revision_str('date:2005-04-12 12:24:33')
 
107
    ['date:2005-04-12 12:24:33']
 
108
    >>> _parse_revision_str('date:2005-04-12T12:24:33')
 
109
    ['date:2005-04-12T12:24:33']
 
110
    >>> _parse_revision_str('date:2005-04-12,12:24:33')
 
111
    ['date:2005-04-12,12:24:33']
 
112
    >>> _parse_revision_str('-5..23')
 
113
    [-5, 23]
 
114
    >>> _parse_revision_str('-5')
 
115
    [-5]
 
116
    >>> _parse_revision_str('123a')
 
117
    ['123a']
 
118
    >>> _parse_revision_str('abc')
 
119
    ['abc']
 
120
    """
 
121
    import re
 
122
    old_format_re = re.compile('\d*:\d*')
 
123
    m = old_format_re.match(revstr)
 
124
    if m:
 
125
        warning('Colon separator for revision numbers is deprecated.'
 
126
                ' Use .. instead')
 
127
        revs = []
 
128
        for rev in revstr.split(':'):
 
129
            if rev:
 
130
                revs.append(int(rev))
 
131
            else:
 
132
                revs.append(None)
 
133
        return revs
 
134
    revs = []
 
135
    for x in revstr.split('..'):
 
136
        if not x:
 
137
            revs.append(None)
 
138
        else:
 
139
            try:
 
140
                revs.append(int(x))
 
141
            except ValueError:
 
142
                revs.append(x)
 
143
    return revs
 
144
 
 
145
 
 
146
def get_merge_type(typestring):
 
147
    """Attempt to find the merge class/factory associated with a string."""
 
148
    from merge import merge_types
 
149
    try:
 
150
        return merge_types[typestring][0]
 
151
    except KeyError:
 
152
        templ = '%s%%7s: %%s' % (' '*12)
 
153
        lines = [templ % (f[0], f[1][1]) for f in merge_types.iteritems()]
 
154
        type_list = '\n'.join(lines)
 
155
        msg = "No known merge type %s. Supported types are:\n%s" %\
 
156
            (typestring, type_list)
 
157
        raise BzrCommandError(msg)
 
158
    
 
159
 
 
160
def get_merge_type(typestring):
 
161
    """Attempt to find the merge class/factory associated with a string."""
 
162
    from merge import merge_types
 
163
    try:
 
164
        return merge_types[typestring][0]
 
165
    except KeyError:
 
166
        templ = '%s%%7s: %%s' % (' '*12)
 
167
        lines = [templ % (f[0], f[1][1]) for f in merge_types.iteritems()]
 
168
        type_list = '\n'.join(lines)
 
169
        msg = "No known merge type %s. Supported types are:\n%s" %\
 
170
            (typestring, type_list)
 
171
        raise BzrCommandError(msg)
 
172
    
 
173
 
 
174
 
 
175
def _get_cmd_dict(plugins_override=True):
 
176
    d = {}
 
177
    for k, v in globals().iteritems():
 
178
        if k.startswith("cmd_"):
 
179
            d[_unsquish_command_name(k)] = v
 
180
    # If we didn't load plugins, the plugin_cmds dict will be empty
 
181
    if plugins_override:
 
182
        d.update(plugin_cmds)
 
183
    else:
 
184
        d2 = plugin_cmds.copy()
 
185
        d2.update(d)
 
186
        d = d2
 
187
    return d
 
188
 
 
189
    
 
190
def get_all_cmds(plugins_override=True):
 
191
    """Return canonical name and class for all registered commands."""
 
192
    for k, v in _get_cmd_dict(plugins_override=plugins_override).iteritems():
 
193
        yield k,v
 
194
 
 
195
 
 
196
def get_cmd_class(cmd, plugins_override=True):
 
197
    """Return the canonical name and command class for a command.
 
198
    """
 
199
    cmd = str(cmd)                      # not unicode
 
200
 
 
201
    # first look up this command under the specified name
 
202
    cmds = _get_cmd_dict(plugins_override=plugins_override)
 
203
    mutter("all commands: %r", cmds.keys())
 
204
    try:
 
205
        return cmd, cmds[cmd]
 
206
    except KeyError:
 
207
        pass
 
208
 
 
209
    # look for any command which claims this as an alias
 
210
    for cmdname, cmdclass in cmds.iteritems():
 
211
        if cmd in cmdclass.aliases:
 
212
            return cmdname, cmdclass
 
213
 
 
214
    cmdclass = ExternalCommand.find_command(cmd)
 
215
    if cmdclass:
 
216
        return cmd, cmdclass
 
217
 
 
218
    raise BzrCommandError("unknown command %r" % cmd)
 
219
 
 
220
 
 
221
class Command(object):
 
222
    """Base class for commands.
 
223
 
 
224
    The docstring for an actual command should give a single-line
 
225
    summary, then a complete description of the command.  A grammar
 
226
    description will be inserted.
 
227
 
 
228
    takes_args
 
229
        List of argument forms, marked with whether they are optional,
 
230
        repeated, etc.
 
231
 
 
232
    takes_options
 
233
        List of options that may be given for this command.
 
234
 
 
235
    hidden
 
236
        If true, this command isn't advertised.
 
237
    """
 
238
    aliases = []
 
239
    
 
240
    takes_args = []
 
241
    takes_options = []
 
242
 
 
243
    hidden = False
 
244
    
 
245
    def __init__(self, options, arguments):
 
246
        """Construct and run the command.
 
247
 
 
248
        Sets self.status to the return value of run()."""
 
249
        assert isinstance(options, dict)
 
250
        assert isinstance(arguments, dict)
 
251
        cmdargs = options.copy()
 
252
        cmdargs.update(arguments)
 
253
        if self.__doc__ == Command.__doc__:
 
254
            from warnings import warn
 
255
            warn("No help message set for %r" % self)
 
256
        self.status = self.run(**cmdargs)
 
257
        if self.status is None:
 
258
            self.status = 0
 
259
 
 
260
    
 
261
    def run(self):
 
262
        """Override this in sub-classes.
 
263
 
 
264
        This is invoked with the options and arguments bound to
 
265
        keyword parameters.
 
266
 
 
267
        Return 0 or None if the command was successful, or a shell
 
268
        error code if not.
 
269
        """
 
270
        return 0
 
271
 
 
272
 
 
273
class ExternalCommand(Command):
 
274
    """Class to wrap external commands.
 
275
 
 
276
    We cheat a little here, when get_cmd_class() calls us we actually
 
277
    give it back an object we construct that has the appropriate path,
 
278
    help, options etc for the specified command.
 
279
 
 
280
    When run_bzr() tries to instantiate that 'class' it gets caught by
 
281
    the __call__ method, which we override to call the Command.__init__
 
282
    method. That then calls our run method which is pretty straight
 
283
    forward.
 
284
 
 
285
    The only wrinkle is that we have to map bzr's dictionary of options
 
286
    and arguments back into command line options and arguments for the
 
287
    script.
 
288
    """
 
289
 
 
290
    def find_command(cls, cmd):
 
291
        import os.path
 
292
        bzrpath = os.environ.get('BZRPATH', '')
 
293
 
 
294
        for dir in bzrpath.split(os.pathsep):
 
295
            path = os.path.join(dir, cmd)
 
296
            if os.path.isfile(path):
 
297
                return ExternalCommand(path)
 
298
 
 
299
        return None
 
300
 
 
301
    find_command = classmethod(find_command)
 
302
 
 
303
    def __init__(self, path):
 
304
        self.path = path
 
305
 
 
306
        pipe = os.popen('%s --bzr-usage' % path, 'r')
 
307
        self.takes_options = pipe.readline().split()
 
308
 
 
309
        for opt in self.takes_options:
 
310
            if not opt in OPTIONS:
 
311
                raise BzrError("Unknown option '%s' returned by external command %s"
 
312
                               % (opt, path))
 
313
 
 
314
        # TODO: Is there any way to check takes_args is valid here?
 
315
        self.takes_args = pipe.readline().split()
 
316
 
 
317
        if pipe.close() is not None:
 
318
            raise BzrError("Failed funning '%s --bzr-usage'" % path)
 
319
 
 
320
        pipe = os.popen('%s --bzr-help' % path, 'r')
 
321
        self.__doc__ = pipe.read()
 
322
        if pipe.close() is not None:
 
323
            raise BzrError("Failed funning '%s --bzr-help'" % path)
 
324
 
 
325
    def __call__(self, options, arguments):
 
326
        Command.__init__(self, options, arguments)
 
327
        return self
 
328
 
 
329
    def run(self, **kargs):
 
330
        opts = []
 
331
        args = []
 
332
 
 
333
        keys = kargs.keys()
 
334
        keys.sort()
 
335
        for name in keys:
 
336
            optname = name.replace('_','-')
 
337
            value = kargs[name]
 
338
            if OPTIONS.has_key(optname):
 
339
                # it's an option
 
340
                opts.append('--%s' % optname)
 
341
                if value is not None and value is not True:
 
342
                    opts.append(str(value))
 
343
            else:
 
344
                # it's an arg, or arg list
 
345
                if type(value) is not list:
 
346
                    value = [value]
 
347
                for v in value:
 
348
                    if v is not None:
 
349
                        args.append(str(v))
 
350
 
 
351
        self.status = os.spawnv(os.P_WAIT, self.path, [self.path] + opts + args)
 
352
        return self.status
 
353
 
 
354
 
 
355
class cmd_status(Command):
134
356
    """Display status summary.
135
357
 
136
 
    For each file there is a single line giving its file state and name.
137
 
    The name is that in the current revision unless it is deleted or
138
 
    missing, in which case the old name is shown.
139
 
 
140
 
    :todo: Don't show unchanged files unless ``--all`` is given?
141
 
    """
142
 
    Branch('.').show_status(show_all=all)
143
 
 
144
 
 
145
 
 
146
 
######################################################################
147
 
# examining history
148
 
def cmd_get_revision(revision_id):
149
 
    Branch('.').get_revision(revision_id).write_xml(sys.stdout)
150
 
 
151
 
 
152
 
def cmd_get_file_text(text_id):
153
 
    """Get contents of a file by hash."""
154
 
    sf = Branch('.').text_store[text_id]
155
 
    pumpfile(sf, sys.stdout)
156
 
 
157
 
 
158
 
 
159
 
######################################################################
160
 
# commands
161
 
    
162
 
 
163
 
def cmd_revno():
164
 
    """Show number of revisions on this branch"""
165
 
    print Branch('.').revno()
166
 
    
167
 
 
168
 
    
169
 
def cmd_add(file_list, verbose=False):
 
358
    This reports on versioned and unknown files, reporting them
 
359
    grouped by state.  Possible states are:
 
360
 
 
361
    added
 
362
        Versioned in the working copy but not in the previous revision.
 
363
 
 
364
    removed
 
365
        Versioned in the previous revision but removed or deleted
 
366
        in the working copy.
 
367
 
 
368
    renamed
 
369
        Path of this file changed from the previous revision;
 
370
        the text may also have changed.  This includes files whose
 
371
        parent directory was renamed.
 
372
 
 
373
    modified
 
374
        Text has changed since the previous revision.
 
375
 
 
376
    unchanged
 
377
        Nothing about this file has changed since the previous revision.
 
378
        Only shown with --all.
 
379
 
 
380
    unknown
 
381
        Not versioned and not matching an ignore pattern.
 
382
 
 
383
    To see ignored files use 'bzr ignored'.  For details in the
 
384
    changes to file texts, use 'bzr diff'.
 
385
 
 
386
    If no arguments are specified, the status of the entire working
 
387
    directory is shown.  Otherwise, only the status of the specified
 
388
    files or directories is reported.  If a directory is given, status
 
389
    is reported for everything inside that directory.
 
390
 
 
391
    If a revision is specified, the changes since that revision are shown.
 
392
    """
 
393
    takes_args = ['file*']
 
394
    takes_options = ['all', 'show-ids', 'revision']
 
395
    aliases = ['st', 'stat']
 
396
    
 
397
    def run(self, all=False, show_ids=False, file_list=None):
 
398
        if file_list:
 
399
            b = find_branch(file_list[0])
 
400
            file_list = [b.relpath(x) for x in file_list]
 
401
            # special case: only one path was given and it's the root
 
402
            # of the branch
 
403
            if file_list == ['']:
 
404
                file_list = None
 
405
        else:
 
406
            b = find_branch('.')
 
407
            
 
408
        from bzrlib.status import show_status
 
409
        show_status(b, show_unchanged=all, show_ids=show_ids,
 
410
                    specific_files=file_list)
 
411
 
 
412
 
 
413
class cmd_cat_revision(Command):
 
414
    """Write out metadata for a revision."""
 
415
 
 
416
    hidden = True
 
417
    takes_args = ['revision_id']
 
418
    
 
419
    def run(self, revision_id):
 
420
        from bzrlib.xml import pack_xml
 
421
        pack_xml(find_branch('.').get_revision(revision_id), sys.stdout)
 
422
 
 
423
 
 
424
class cmd_revno(Command):
 
425
    """Show current revision number.
 
426
 
 
427
    This is equal to the number of revisions on this branch."""
 
428
    def run(self):
 
429
        print find_branch('.').revno()
 
430
 
 
431
class cmd_revision_info(Command):
 
432
    """Show revision number and revision id for a given revision identifier.
 
433
    """
 
434
    hidden = True
 
435
    takes_args = ['revision_info*']
 
436
    takes_options = ['revision']
 
437
    def run(self, revision=None, revision_info_list=None):
 
438
        from bzrlib.branch import find_branch
 
439
 
 
440
        revs = []
 
441
        if revision is not None:
 
442
            revs.extend(revision)
 
443
        if revision_info_list is not None:
 
444
            revs.extend(revision_info_list)
 
445
        if len(revs) == 0:
 
446
            raise BzrCommandError('You must supply a revision identifier')
 
447
 
 
448
        b = find_branch('.')
 
449
 
 
450
        for rev in revs:
 
451
            print '%4d %s' % b.get_revision_info(rev)
 
452
 
 
453
    
 
454
class cmd_add(Command):
170
455
    """Add specified files or directories.
171
456
 
172
457
    In non-recursive mode, all the named items are added, regardless
179
464
    whether already versioned or not, are searched for files or
180
465
    subdirectories that are neither versioned or ignored, and these
181
466
    are added.  This search proceeds recursively into versioned
182
 
    directories.
 
467
    directories.  If no names are given '.' is assumed.
183
468
 
184
 
    Therefore simply saying 'bzr add .' will version all files that
 
469
    Therefore simply saying 'bzr add' will version all files that
185
470
    are currently unknown.
186
 
    """
187
 
    if True:
188
 
        bzrlib.add.smart_add(file_list, verbose)
189
 
    else:
190
 
        # old way
191
 
        assert file_list
192
 
        b = Branch(file_list[0], find_root=True)
193
 
        b.add([b.relpath(f) for f in file_list], verbose=verbose)
194
 
 
195
 
    
196
 
 
197
 
def cmd_relpath(filename):
198
 
    print Branch(filename).relpath(filename)
199
 
 
200
 
 
201
 
def cmd_inventory(revision=None):
202
 
    """Show inventory of the current working copy."""
203
 
    ## TODO: Also optionally show a previous inventory
204
 
    ## TODO: Format options
205
 
    b = Branch('.')
206
 
    if revision == None:
 
471
 
 
472
    TODO: Perhaps adding a file whose directly is not versioned should
 
473
    recursively add that parent, rather than giving an error?
 
474
    """
 
475
    takes_args = ['file*']
 
476
    takes_options = ['verbose', 'no-recurse']
 
477
    
 
478
    def run(self, file_list, verbose=False, no_recurse=False):
 
479
        from bzrlib.add import smart_add, _PrintAddCallback
 
480
        recurse = not no_recurse
 
481
        smart_add(file_list, verbose, not no_recurse,
 
482
                  callback=_PrintAddCallback)
 
483
 
 
484
 
 
485
 
 
486
class cmd_mkdir(Command):
 
487
    """Create a new versioned directory.
 
488
 
 
489
    This is equivalent to creating the directory and then adding it.
 
490
    """
 
491
    takes_args = ['dir+']
 
492
 
 
493
    def run(self, dir_list):
 
494
        b = None
 
495
        
 
496
        for d in dir_list:
 
497
            os.mkdir(d)
 
498
            if not b:
 
499
                b = find_branch(d)
 
500
            b.add([d])
 
501
            print 'added', d
 
502
 
 
503
 
 
504
class cmd_relpath(Command):
 
505
    """Show path of a file relative to root"""
 
506
    takes_args = ['filename']
 
507
    hidden = True
 
508
    
 
509
    def run(self, filename):
 
510
        print find_branch(filename).relpath(filename)
 
511
 
 
512
 
 
513
 
 
514
class cmd_inventory(Command):
 
515
    """Show inventory of the current working copy or a revision."""
 
516
    takes_options = ['revision', 'show-ids']
 
517
    
 
518
    def run(self, revision=None, show_ids=False):
 
519
        b = find_branch('.')
 
520
        if revision == None:
 
521
            inv = b.read_working_inventory()
 
522
        else:
 
523
            if len(revision) > 1:
 
524
                raise BzrCommandError('bzr inventory --revision takes'
 
525
                    ' exactly one revision identifier')
 
526
            inv = b.get_revision_inventory(b.lookup_revision(revision[0]))
 
527
 
 
528
        for path, entry in inv.entries():
 
529
            if show_ids:
 
530
                print '%-50s %s' % (path, entry.file_id)
 
531
            else:
 
532
                print path
 
533
 
 
534
 
 
535
class cmd_move(Command):
 
536
    """Move files to a different directory.
 
537
 
 
538
    examples:
 
539
        bzr move *.txt doc
 
540
 
 
541
    The destination must be a versioned directory in the same branch.
 
542
    """
 
543
    takes_args = ['source$', 'dest']
 
544
    def run(self, source_list, dest):
 
545
        b = find_branch('.')
 
546
 
 
547
        # TODO: glob expansion on windows?
 
548
        b.move([b.relpath(s) for s in source_list], b.relpath(dest))
 
549
 
 
550
 
 
551
class cmd_rename(Command):
 
552
    """Change the name of an entry.
 
553
 
 
554
    examples:
 
555
      bzr rename frob.c frobber.c
 
556
      bzr rename src/frob.c lib/frob.c
 
557
 
 
558
    It is an error if the destination name exists.
 
559
 
 
560
    See also the 'move' command, which moves files into a different
 
561
    directory without changing their name.
 
562
 
 
563
    TODO: Some way to rename multiple files without invoking bzr for each
 
564
    one?"""
 
565
    takes_args = ['from_name', 'to_name']
 
566
    
 
567
    def run(self, from_name, to_name):
 
568
        b = find_branch('.')
 
569
        b.rename_one(b.relpath(from_name), b.relpath(to_name))
 
570
 
 
571
 
 
572
 
 
573
class cmd_mv(Command):
 
574
    """Move or rename a file.
 
575
 
 
576
    usage:
 
577
        bzr mv OLDNAME NEWNAME
 
578
        bzr mv SOURCE... DESTINATION
 
579
 
 
580
    If the last argument is a versioned directory, all the other names
 
581
    are moved into it.  Otherwise, there must be exactly two arguments
 
582
    and the file is changed to a new name, which must not already exist.
 
583
 
 
584
    Files cannot be moved between branches.
 
585
    """
 
586
    takes_args = ['names*']
 
587
    def run(self, names_list):
 
588
        if len(names_list) < 2:
 
589
            raise BzrCommandError("missing file argument")
 
590
        b = find_branch(names_list[0])
 
591
 
 
592
        rel_names = [b.relpath(x) for x in names_list]
 
593
        
 
594
        if os.path.isdir(names_list[-1]):
 
595
            # move into existing directory
 
596
            for pair in b.move(rel_names[:-1], rel_names[-1]):
 
597
                print "%s => %s" % pair
 
598
        else:
 
599
            if len(names_list) != 2:
 
600
                raise BzrCommandError('to mv multiple files the destination '
 
601
                                      'must be a versioned directory')
 
602
            for pair in b.move(rel_names[0], rel_names[1]):
 
603
                print "%s => %s" % pair
 
604
            
 
605
    
 
606
 
 
607
 
 
608
class cmd_pull(Command):
 
609
    """Pull any changes from another branch into the current one.
 
610
 
 
611
    If the location is omitted, the last-used location will be used.
 
612
    Both the revision history and the working directory will be
 
613
    updated.
 
614
 
 
615
    This command only works on branches that have not diverged.  Branches are
 
616
    considered diverged if both branches have had commits without first
 
617
    pulling from the other.
 
618
 
 
619
    If branches have diverged, you can use 'bzr merge' to pull the text changes
 
620
    from one into the other.
 
621
    """
 
622
    takes_args = ['location?']
 
623
 
 
624
    def run(self, location=None):
 
625
        from bzrlib.merge import merge
 
626
        import tempfile
 
627
        from shutil import rmtree
 
628
        import errno
 
629
        from bzrlib.branch import pull_loc
 
630
        
 
631
        br_to = find_branch('.')
 
632
        stored_loc = None
 
633
        try:
 
634
            stored_loc = br_to.controlfile("x-pull", "rb").read().rstrip('\n')
 
635
        except IOError, e:
 
636
            if e.errno != errno.ENOENT:
 
637
                raise
 
638
        if location is None:
 
639
            if stored_loc is None:
 
640
                raise BzrCommandError("No pull location known or specified.")
 
641
            else:
 
642
                print "Using last location: %s" % stored_loc
 
643
                location = stored_loc
 
644
        cache_root = tempfile.mkdtemp()
 
645
        from bzrlib.branch import DivergedBranches
 
646
        br_from = find_branch(location)
 
647
        location = pull_loc(br_from)
 
648
        old_revno = br_to.revno()
 
649
        try:
 
650
            from branch import find_cached_branch, DivergedBranches
 
651
            br_from = find_cached_branch(location, cache_root)
 
652
            location = pull_loc(br_from)
 
653
            old_revno = br_to.revno()
 
654
            try:
 
655
                br_to.update_revisions(br_from)
 
656
            except DivergedBranches:
 
657
                raise BzrCommandError("These branches have diverged."
 
658
                    "  Try merge.")
 
659
                
 
660
            merge(('.', -1), ('.', old_revno), check_clean=False)
 
661
            if location != stored_loc:
 
662
                br_to.controlfile("x-pull", "wb").write(location + "\n")
 
663
        finally:
 
664
            rmtree(cache_root)
 
665
 
 
666
 
 
667
 
 
668
class cmd_branch(Command):
 
669
    """Create a new copy of a branch.
 
670
 
 
671
    If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
 
672
    be used.  In other words, "branch ../foo/bar" will attempt to create ./bar.
 
673
 
 
674
    To retrieve the branch as of a particular revision, supply the --revision
 
675
    parameter, as in "branch foo/bar -r 5".
 
676
    """
 
677
    takes_args = ['from_location', 'to_location?']
 
678
    takes_options = ['revision']
 
679
    aliases = ['get', 'clone']
 
680
 
 
681
    def run(self, from_location, to_location=None, revision=None):
 
682
        from bzrlib.branch import copy_branch, find_cached_branch
 
683
        import tempfile
 
684
        import errno
 
685
        from shutil import rmtree
 
686
        cache_root = tempfile.mkdtemp()
 
687
        try:
 
688
            if revision is None:
 
689
                revision = [None]
 
690
            elif len(revision) > 1:
 
691
                raise BzrCommandError(
 
692
                    'bzr branch --revision takes exactly 1 revision value')
 
693
            try:
 
694
                br_from = find_cached_branch(from_location, cache_root)
 
695
            except OSError, e:
 
696
                if e.errno == errno.ENOENT:
 
697
                    raise BzrCommandError('Source location "%s" does not'
 
698
                                          ' exist.' % to_location)
 
699
                else:
 
700
                    raise
 
701
            if to_location is None:
 
702
                to_location = os.path.basename(from_location.rstrip("/\\"))
 
703
            try:
 
704
                os.mkdir(to_location)
 
705
            except OSError, e:
 
706
                if e.errno == errno.EEXIST:
 
707
                    raise BzrCommandError('Target directory "%s" already'
 
708
                                          ' exists.' % to_location)
 
709
                if e.errno == errno.ENOENT:
 
710
                    raise BzrCommandError('Parent of "%s" does not exist.' %
 
711
                                          to_location)
 
712
                else:
 
713
                    raise
 
714
            try:
 
715
                copy_branch(br_from, to_location, revision[0])
 
716
            except bzrlib.errors.NoSuchRevision:
 
717
                rmtree(to_location)
 
718
                msg = "The branch %s has no revision %d." % (from_location, revision[0])
 
719
                raise BzrCommandError(msg)
 
720
        finally:
 
721
            rmtree(cache_root)
 
722
 
 
723
 
 
724
class cmd_renames(Command):
 
725
    """Show list of renamed files.
 
726
 
 
727
    TODO: Option to show renames between two historical versions.
 
728
 
 
729
    TODO: Only show renames under dir, rather than in the whole branch.
 
730
    """
 
731
    takes_args = ['dir?']
 
732
 
 
733
    def run(self, dir='.'):
 
734
        b = find_branch(dir)
 
735
        old_inv = b.basis_tree().inventory
 
736
        new_inv = b.read_working_inventory()
 
737
 
 
738
        renames = list(bzrlib.tree.find_renames(old_inv, new_inv))
 
739
        renames.sort()
 
740
        for old_name, new_name in renames:
 
741
            print "%s => %s" % (old_name, new_name)        
 
742
 
 
743
 
 
744
class cmd_info(Command):
 
745
    """Show statistical information about a branch."""
 
746
    takes_args = ['branch?']
 
747
    
 
748
    def run(self, branch=None):
 
749
        import info
 
750
 
 
751
        b = find_branch(branch)
 
752
        info.show_info(b)
 
753
 
 
754
 
 
755
class cmd_remove(Command):
 
756
    """Make a file unversioned.
 
757
 
 
758
    This makes bzr stop tracking changes to a versioned file.  It does
 
759
    not delete the working copy.
 
760
    """
 
761
    takes_args = ['file+']
 
762
    takes_options = ['verbose']
 
763
    
 
764
    def run(self, file_list, verbose=False):
 
765
        b = find_branch(file_list[0])
 
766
        b.remove([b.relpath(f) for f in file_list], verbose=verbose)
 
767
 
 
768
 
 
769
class cmd_file_id(Command):
 
770
    """Print file_id of a particular file or directory.
 
771
 
 
772
    The file_id is assigned when the file is first added and remains the
 
773
    same through all revisions where the file exists, even when it is
 
774
    moved or renamed.
 
775
    """
 
776
    hidden = True
 
777
    takes_args = ['filename']
 
778
    def run(self, filename):
 
779
        b = find_branch(filename)
 
780
        i = b.inventory.path2id(b.relpath(filename))
 
781
        if i == None:
 
782
            raise BzrError("%r is not a versioned file" % filename)
 
783
        else:
 
784
            print i
 
785
 
 
786
 
 
787
class cmd_file_path(Command):
 
788
    """Print path of file_ids to a file or directory.
 
789
 
 
790
    This prints one line for each directory down to the target,
 
791
    starting at the branch root."""
 
792
    hidden = True
 
793
    takes_args = ['filename']
 
794
    def run(self, filename):
 
795
        b = find_branch(filename)
 
796
        inv = b.inventory
 
797
        fid = inv.path2id(b.relpath(filename))
 
798
        if fid == None:
 
799
            raise BzrError("%r is not a versioned file" % filename)
 
800
        for fip in inv.get_idpath(fid):
 
801
            print fip
 
802
 
 
803
 
 
804
class cmd_revision_history(Command):
 
805
    """Display list of revision ids on this branch."""
 
806
    hidden = True
 
807
    def run(self):
 
808
        for patchid in find_branch('.').revision_history():
 
809
            print patchid
 
810
 
 
811
 
 
812
class cmd_directories(Command):
 
813
    """Display list of versioned directories in this branch."""
 
814
    def run(self):
 
815
        for name, ie in find_branch('.').read_working_inventory().directories():
 
816
            if name == '':
 
817
                print '.'
 
818
            else:
 
819
                print name
 
820
 
 
821
 
 
822
class cmd_init(Command):
 
823
    """Make a directory into a versioned branch.
 
824
 
 
825
    Use this to create an empty branch, or before importing an
 
826
    existing project.
 
827
 
 
828
    Recipe for importing a tree of files:
 
829
        cd ~/project
 
830
        bzr init
 
831
        bzr add -v .
 
832
        bzr status
 
833
        bzr commit -m 'imported project'
 
834
    """
 
835
    def run(self):
 
836
        from bzrlib.branch import Branch
 
837
        Branch('.', init=True)
 
838
 
 
839
 
 
840
class cmd_diff(Command):
 
841
    """Show differences in working tree.
 
842
    
 
843
    If files are listed, only the changes in those files are listed.
 
844
    Otherwise, all changes for the tree are listed.
 
845
 
 
846
    TODO: Allow diff across branches.
 
847
 
 
848
    TODO: Option to use external diff command; could be GNU diff, wdiff,
 
849
          or a graphical diff.
 
850
 
 
851
    TODO: Python difflib is not exactly the same as unidiff; should
 
852
          either fix it up or prefer to use an external diff.
 
853
 
 
854
    TODO: If a directory is given, diff everything under that.
 
855
 
 
856
    TODO: Selected-file diff is inefficient and doesn't show you
 
857
          deleted files.
 
858
 
 
859
    TODO: This probably handles non-Unix newlines poorly.
 
860
 
 
861
    examples:
 
862
        bzr diff
 
863
        bzr diff -r1
 
864
        bzr diff -r1:2
 
865
    """
 
866
    
 
867
    takes_args = ['file*']
 
868
    takes_options = ['revision', 'diff-options']
 
869
    aliases = ['di', 'dif']
 
870
 
 
871
    def run(self, revision=None, file_list=None, diff_options=None):
 
872
        from bzrlib.diff import show_diff
 
873
 
 
874
        if file_list:
 
875
            b = find_branch(file_list[0])
 
876
            file_list = [b.relpath(f) for f in file_list]
 
877
            if file_list == ['']:
 
878
                # just pointing to top-of-tree
 
879
                file_list = None
 
880
        else:
 
881
            b = find_branch('.')
 
882
 
 
883
        if revision is not None:
 
884
            if len(revision) == 1:
 
885
                show_diff(b, revision[0], specific_files=file_list,
 
886
                          external_diff_options=diff_options)
 
887
            elif len(revision) == 2:
 
888
                show_diff(b, revision[0], specific_files=file_list,
 
889
                          external_diff_options=diff_options,
 
890
                          revision2=revision[1])
 
891
            else:
 
892
                raise BzrCommandError('bzr diff --revision takes exactly one or two revision identifiers')
 
893
        else:
 
894
            show_diff(b, None, specific_files=file_list,
 
895
                      external_diff_options=diff_options)
 
896
 
 
897
        
 
898
 
 
899
 
 
900
class cmd_deleted(Command):
 
901
    """List files deleted in the working tree.
 
902
 
 
903
    TODO: Show files deleted since a previous revision, or between two revisions.
 
904
    """
 
905
    def run(self, show_ids=False):
 
906
        b = find_branch('.')
 
907
        old = b.basis_tree()
 
908
        new = b.working_tree()
 
909
 
 
910
        ## TODO: Much more efficient way to do this: read in new
 
911
        ## directories with readdir, rather than stating each one.  Same
 
912
        ## level of effort but possibly much less IO.  (Or possibly not,
 
913
        ## if the directories are very large...)
 
914
 
 
915
        for path, ie in old.inventory.iter_entries():
 
916
            if not new.has_id(ie.file_id):
 
917
                if show_ids:
 
918
                    print '%-50s %s' % (path, ie.file_id)
 
919
                else:
 
920
                    print path
 
921
 
 
922
 
 
923
class cmd_modified(Command):
 
924
    """List files modified in working tree."""
 
925
    hidden = True
 
926
    def run(self):
 
927
        from bzrlib.delta import compare_trees
 
928
 
 
929
        b = find_branch('.')
 
930
        td = compare_trees(b.basis_tree(), b.working_tree())
 
931
 
 
932
        for path, id, kind in td.modified:
 
933
            print path
 
934
 
 
935
 
 
936
 
 
937
class cmd_added(Command):
 
938
    """List files added in working tree."""
 
939
    hidden = True
 
940
    def run(self):
 
941
        b = find_branch('.')
 
942
        wt = b.working_tree()
 
943
        basis_inv = b.basis_tree().inventory
 
944
        inv = wt.inventory
 
945
        for file_id in inv:
 
946
            if file_id in basis_inv:
 
947
                continue
 
948
            path = inv.id2path(file_id)
 
949
            if not os.access(b.abspath(path), os.F_OK):
 
950
                continue
 
951
            print path
 
952
                
 
953
        
 
954
 
 
955
class cmd_root(Command):
 
956
    """Show the tree root directory.
 
957
 
 
958
    The root is the nearest enclosing directory with a .bzr control
 
959
    directory."""
 
960
    takes_args = ['filename?']
 
961
    def run(self, filename=None):
 
962
        """Print the branch root."""
 
963
        b = find_branch(filename)
 
964
        print getattr(b, 'base', None) or getattr(b, 'baseurl')
 
965
 
 
966
 
 
967
class cmd_log(Command):
 
968
    """Show log of this branch.
 
969
 
 
970
    To request a range of logs, you can use the command -r begin:end
 
971
    -r revision requests a specific revision, -r :end or -r begin: are
 
972
    also valid.
 
973
 
 
974
    --message allows you to give a regular expression, which will be evaluated
 
975
    so that only matching entries will be displayed.
 
976
 
 
977
    TODO: Make --revision support uuid: and hash: [future tag:] notation.
 
978
  
 
979
    """
 
980
 
 
981
    takes_args = ['filename?']
 
982
    takes_options = ['forward', 'timezone', 'verbose', 'show-ids', 'revision',
 
983
                     'long', 'message', 'short',]
 
984
    
 
985
    def run(self, filename=None, timezone='original',
 
986
            verbose=False,
 
987
            show_ids=False,
 
988
            forward=False,
 
989
            revision=None,
 
990
            message=None,
 
991
            long=False,
 
992
            short=False):
 
993
        from bzrlib.branch import find_branch
 
994
        from bzrlib.log import log_formatter, show_log
 
995
        import codecs
 
996
 
 
997
        direction = (forward and 'forward') or 'reverse'
 
998
        
 
999
        if filename:
 
1000
            b = find_branch(filename)
 
1001
            fp = b.relpath(filename)
 
1002
            if fp:
 
1003
                file_id = b.read_working_inventory().path2id(fp)
 
1004
            else:
 
1005
                file_id = None  # points to branch root
 
1006
        else:
 
1007
            b = find_branch('.')
 
1008
            file_id = None
 
1009
 
 
1010
        if revision is None:
 
1011
            rev1 = None
 
1012
            rev2 = None
 
1013
        elif len(revision) == 1:
 
1014
            rev1 = rev2 = b.get_revision_info(revision[0])[0]
 
1015
        elif len(revision) == 2:
 
1016
            rev1 = b.get_revision_info(revision[0])[0]
 
1017
            rev2 = b.get_revision_info(revision[1])[0]
 
1018
        else:
 
1019
            raise BzrCommandError('bzr log --revision takes one or two values.')
 
1020
 
 
1021
        if rev1 == 0:
 
1022
            rev1 = None
 
1023
        if rev2 == 0:
 
1024
            rev2 = None
 
1025
 
 
1026
        mutter('encoding log as %r' % bzrlib.user_encoding)
 
1027
 
 
1028
        # use 'replace' so that we don't abort if trying to write out
 
1029
        # in e.g. the default C locale.
 
1030
        outf = codecs.getwriter(bzrlib.user_encoding)(sys.stdout, errors='replace')
 
1031
 
 
1032
        if not short:
 
1033
            log_format = 'long'
 
1034
        else:
 
1035
            log_format = 'short'
 
1036
        lf = log_formatter(log_format,
 
1037
                           show_ids=show_ids,
 
1038
                           to_file=outf,
 
1039
                           show_timezone=timezone)
 
1040
 
 
1041
        show_log(b,
 
1042
                 lf,
 
1043
                 file_id,
 
1044
                 verbose=verbose,
 
1045
                 direction=direction,
 
1046
                 start_revision=rev1,
 
1047
                 end_revision=rev2,
 
1048
                 search=message)
 
1049
 
 
1050
 
 
1051
 
 
1052
class cmd_touching_revisions(Command):
 
1053
    """Return revision-ids which affected a particular file.
 
1054
 
 
1055
    A more user-friendly interface is "bzr log FILE"."""
 
1056
    hidden = True
 
1057
    takes_args = ["filename"]
 
1058
    def run(self, filename):
 
1059
        b = find_branch(filename)
207
1060
        inv = b.read_working_inventory()
208
 
    else:
209
 
        inv = b.get_revision_inventory(b.lookup_revision(revision))
210
 
        
211
 
    for path, entry in inv.iter_entries():
212
 
        print '%-50s %s' % (entry.file_id, path)
213
 
 
214
 
 
215
 
 
216
 
def cmd_info():
217
 
    b = Branch('.')
218
 
    print 'branch format:', b.controlfile('branch-format', 'r').readline().rstrip('\n')
219
 
 
220
 
    def plural(n, base='', pl=None):
221
 
        if n == 1:
222
 
            return base
223
 
        elif pl is not None:
224
 
            return pl
225
 
        else:
226
 
            return 's'
227
 
 
228
 
    count_version_dirs = 0
229
 
 
230
 
    count_status = {'A': 0, 'D': 0, 'M': 0, 'R': 0, '?': 0, 'I': 0, '.': 0}
231
 
    for st_tup in bzrlib.diff_trees(b.basis_tree(), b.working_tree()):
232
 
        fs = st_tup[0]
233
 
        count_status[fs] += 1
234
 
        if fs not in ['I', '?'] and st_tup[4] == 'directory':
235
 
            count_version_dirs += 1
236
 
 
237
 
    print
238
 
    print 'in the working tree:'
239
 
    for name, fs in (('unchanged', '.'),
240
 
                     ('modified', 'M'), ('added', 'A'), ('removed', 'D'),
241
 
                     ('renamed', 'R'), ('unknown', '?'), ('ignored', 'I'),
242
 
                     ):
243
 
        print '  %5d %s' % (count_status[fs], name)
244
 
    print '  %5d versioned subdirector%s' % (count_version_dirs,
245
 
                                             plural(count_version_dirs, 'y', 'ies'))
246
 
 
247
 
    print
248
 
    print 'branch history:'
249
 
    history = b.revision_history()
250
 
    revno = len(history)
251
 
    print '  %5d revision%s' % (revno, plural(revno))
252
 
    committers = Set()
253
 
    for rev in history:
254
 
        committers.add(b.get_revision(rev).committer)
255
 
    print '  %5d committer%s' % (len(committers), plural(len(committers)))
256
 
    if revno > 0:
257
 
        firstrev = b.get_revision(history[0])
258
 
        age = int((time.time() - firstrev.timestamp) / 3600 / 24)
259
 
        print '  %5d day%s old' % (age, plural(age))
260
 
        print '  first revision: %s' % format_date(firstrev.timestamp,
261
 
                                                 firstrev.timezone)
262
 
 
263
 
        lastrev = b.get_revision(history[-1])
264
 
        print '  latest revision: %s' % format_date(lastrev.timestamp,
265
 
                                                    lastrev.timezone)
266
 
        
267
 
    
268
 
 
269
 
 
270
 
def cmd_remove(file_list, verbose=False):
271
 
    b = Branch(file_list[0])
272
 
    b.remove([b.relpath(f) for f in file_list], verbose=verbose)
273
 
 
274
 
 
275
 
 
276
 
def cmd_file_id(filename):
277
 
    b = Branch(filename)
278
 
    i = b.inventory.path2id(b.relpath(filename))
279
 
    if i is None:
280
 
        bailout("%s is not a versioned file" % filename)
281
 
    else:
282
 
        print i
283
 
 
284
 
 
285
 
def cmd_find_filename(fileid):
286
 
    n = find_filename(fileid)
287
 
    if n is None:
288
 
        bailout("%s is not a live file id" % fileid)
289
 
    else:
290
 
        print n
291
 
 
292
 
 
293
 
def cmd_revision_history():
294
 
    for patchid in Branch('.').revision_history():
295
 
        print patchid
296
 
 
297
 
 
298
 
 
299
 
def cmd_init():
300
 
    # TODO: Check we're not already in a working directory?  At the
301
 
    # moment you'll get an ugly error.
302
 
    
303
 
    # TODO: What if we're in a subdirectory of a branch?  Would like
304
 
    # to allow that, but then the parent may need to understand that
305
 
    # the children have disappeared, or should they be versioned in
306
 
    # both?
307
 
 
308
 
    # TODO: Take an argument/option for branch name.
309
 
    Branch('.', init=True)
310
 
 
311
 
 
312
 
def cmd_diff(revision=None):
313
 
    """Show diff from basis to working copy.
314
 
 
315
 
    :todo: Take one or two revision arguments, look up those trees,
316
 
           and diff them.
317
 
 
318
 
    :todo: Allow diff across branches.
319
 
 
320
 
    :todo: Mangle filenames in diff to be more relevant.
321
 
 
322
 
    :todo: Shouldn't be in the cmd function.
323
 
    """
324
 
 
325
 
    b = Branch('.')
326
 
 
327
 
    if revision == None:
328
 
        old_tree = b.basis_tree()
329
 
    else:
330
 
        old_tree = b.revision_tree(b.lookup_revision(revision))
331
 
        
332
 
    new_tree = b.working_tree()
333
 
    old_inv = old_tree.inventory
334
 
    new_inv = new_tree.inventory
335
 
 
336
 
    # TODO: Options to control putting on a prefix or suffix, perhaps as a format string
337
 
    old_label = ''
338
 
    new_label = ''
339
 
 
340
 
    DEVNULL = '/dev/null'
341
 
    # Windows users, don't panic about this filename -- it is a
342
 
    # special signal to GNU patch that the file should be created or
343
 
    # deleted respectively.
344
 
 
345
 
    # TODO: Generation of pseudo-diffs for added/deleted files could
346
 
    # be usefully made into a much faster special case.
347
 
 
348
 
    # TODO: Better to return them in sorted order I think.
349
 
    
350
 
    for file_state, fid, old_name, new_name, kind in bzrlib.diff_trees(old_tree, new_tree):
351
 
        d = None
352
 
 
353
 
        # Don't show this by default; maybe do it if an option is passed
354
 
        # idlabel = '      {%s}' % fid
355
 
        idlabel = ''
356
 
 
357
 
        # FIXME: Something about the diff format makes patch unhappy
358
 
        # with newly-added files.
359
 
 
360
 
        def diffit(*a, **kw):
361
 
            sys.stdout.writelines(difflib.unified_diff(*a, **kw))
362
 
            print
363
 
        
364
 
        if file_state in ['.', '?', 'I']:
365
 
            continue
366
 
        elif file_state == 'A':
367
 
            print '*** added %s %r' % (kind, new_name)
368
 
            if kind == 'file':
369
 
                diffit([],
370
 
                       new_tree.get_file(fid).readlines(),
371
 
                       fromfile=DEVNULL,
372
 
                       tofile=new_label + new_name + idlabel)
373
 
        elif file_state == 'D':
374
 
            assert isinstance(old_name, types.StringTypes)
375
 
            print '*** deleted %s %r' % (kind, old_name)
376
 
            if kind == 'file':
377
 
                diffit(old_tree.get_file(fid).readlines(), [],
378
 
                       fromfile=old_label + old_name + idlabel,
379
 
                       tofile=DEVNULL)
380
 
        elif file_state in ['M', 'R']:
381
 
            if file_state == 'M':
382
 
                assert kind == 'file'
383
 
                assert old_name == new_name
384
 
                print '*** modified %s %r' % (kind, new_name)
385
 
            elif file_state == 'R':
386
 
                print '*** renamed %s %r => %r' % (kind, old_name, new_name)
387
 
 
388
 
            if kind == 'file':
389
 
                diffit(old_tree.get_file(fid).readlines(),
390
 
                       new_tree.get_file(fid).readlines(),
391
 
                       fromfile=old_label + old_name + idlabel,
392
 
                       tofile=new_label + new_name)
393
 
        else:
394
 
            bailout("can't represent state %s {%s}" % (file_state, fid))
395
 
 
396
 
 
397
 
 
398
 
def cmd_root(filename=None):
399
 
    """Print the branch root."""
400
 
    print bzrlib.branch.find_branch_root(filename)
401
 
    
402
 
 
403
 
def cmd_log(timezone='original'):
404
 
    """Show log of this branch.
405
 
 
406
 
    :todo: Options for utc; to show ids; to limit range; etc.
407
 
    """
408
 
    Branch('.').write_log(show_timezone=timezone)
409
 
 
410
 
 
411
 
def cmd_ls(revision=None, verbose=False):
 
1061
        file_id = inv.path2id(b.relpath(filename))
 
1062
        for revno, revision_id, what in bzrlib.log.find_touching_revisions(b, file_id):
 
1063
            print "%6d %s" % (revno, what)
 
1064
 
 
1065
 
 
1066
class cmd_ls(Command):
412
1067
    """List files in a tree.
413
1068
 
414
 
    :todo: Take a revision or remote path and list that tree instead.
415
 
    """
416
 
    b = Branch('.')
417
 
    if revision == None:
418
 
        tree = b.working_tree()
419
 
    else:
420
 
        tree = b.revision_tree(b.lookup_revision(revision))
421
 
        
422
 
    for fp, fc, kind, fid in tree.list_files():
423
 
        if verbose:
424
 
            if kind == 'directory':
425
 
                kindch = '/'
426
 
            elif kind == 'file':
427
 
                kindch = ''
428
 
            else:
429
 
                kindch = '???'
430
 
                
431
 
            print '%-8s %s%s' % (fc, fp, kindch)
432
 
        else:
433
 
            print fp
434
 
    
435
 
    
436
 
 
437
 
def cmd_unknowns():
438
 
    """List unknown files"""
439
 
    for f in Branch('.').unknowns():
440
 
        print quotefn(f)
441
 
 
442
 
 
443
 
def cmd_lookup_revision(revno):
444
 
    try:
445
 
        revno = int(revno)
446
 
    except ValueError:
447
 
        bailout("usage: lookup-revision REVNO",
448
 
                ["REVNO is a non-negative revision number for this branch"])
449
 
 
450
 
    print Branch('.').lookup_revision(revno) or NONE_STRING
451
 
 
452
 
 
453
 
 
454
 
def cmd_export(revno, dest):
455
 
    """Export past revision to destination directory."""
456
 
    b = Branch('.')
457
 
    rh = b.lookup_revision(int(revno))
458
 
    t = b.revision_tree(rh)
459
 
    t.export(dest)
460
 
 
461
 
 
462
 
 
463
 
######################################################################
464
 
# internal/test commands
465
 
 
466
 
 
467
 
def cmd_uuid():
468
 
    """Print a newly-generated UUID."""
469
 
    print bzrlib.osutils.uuid()
470
 
 
471
 
 
472
 
 
473
 
def cmd_local_time_offset():
474
 
    print bzrlib.osutils.local_time_offset()
475
 
 
476
 
 
477
 
 
478
 
def cmd_commit(message=None, verbose=False):
479
 
    if not message:
480
 
        bailout("please specify a commit message")
481
 
    Branch('.').commit(message, verbose=verbose)
482
 
 
483
 
 
484
 
def cmd_check():
485
 
    """Check consistency of the branch."""
486
 
    check()
487
 
 
488
 
 
489
 
def cmd_is(pred, *rest):
490
 
    """Test whether PREDICATE is true."""
491
 
    try:
492
 
        cmd_handler = globals()['assert_' + pred.replace('-', '_')]
493
 
    except KeyError:
494
 
        bailout("unknown predicate: %s" % quotefn(pred))
495
 
        
496
 
    try:
497
 
        cmd_handler(*rest)
498
 
    except BzrCheckError:
499
 
        # by default we don't print the message so that this can
500
 
        # be used from shell scripts without producing noise
501
 
        sys.exit(1)
502
 
 
503
 
 
504
 
def cmd_username():
505
 
    print bzrlib.osutils.username()
506
 
 
507
 
 
508
 
def cmd_user_email():
509
 
    print bzrlib.osutils.user_email()
510
 
 
511
 
 
512
 
def cmd_gen_revision_id():
513
 
    import time
514
 
    print bzrlib.branch._gen_revision_id(time.time())
515
 
 
516
 
 
517
 
def cmd_selftest(verbose=False):
 
1069
    TODO: Take a revision or remote path and list that tree instead.
 
1070
    """
 
1071
    hidden = True
 
1072
    def run(self, revision=None, verbose=False):
 
1073
        b = find_branch('.')
 
1074
        if revision == None:
 
1075
            tree = b.working_tree()
 
1076
        else:
 
1077
            tree = b.revision_tree(b.lookup_revision(revision))
 
1078
 
 
1079
        for fp, fc, kind, fid in tree.list_files():
 
1080
            if verbose:
 
1081
                if kind == 'directory':
 
1082
                    kindch = '/'
 
1083
                elif kind == 'file':
 
1084
                    kindch = ''
 
1085
                else:
 
1086
                    kindch = '???'
 
1087
 
 
1088
                print '%-8s %s%s' % (fc, fp, kindch)
 
1089
            else:
 
1090
                print fp
 
1091
 
 
1092
 
 
1093
 
 
1094
class cmd_unknowns(Command):
 
1095
    """List unknown files."""
 
1096
    def run(self):
 
1097
        from bzrlib.osutils import quotefn
 
1098
        for f in find_branch('.').unknowns():
 
1099
            print quotefn(f)
 
1100
 
 
1101
 
 
1102
 
 
1103
class cmd_ignore(Command):
 
1104
    """Ignore a command or pattern.
 
1105
 
 
1106
    To remove patterns from the ignore list, edit the .bzrignore file.
 
1107
 
 
1108
    If the pattern contains a slash, it is compared to the whole path
 
1109
    from the branch root.  Otherwise, it is comapred to only the last
 
1110
    component of the path.
 
1111
 
 
1112
    Ignore patterns are case-insensitive on case-insensitive systems.
 
1113
 
 
1114
    Note: wildcards must be quoted from the shell on Unix.
 
1115
 
 
1116
    examples:
 
1117
        bzr ignore ./Makefile
 
1118
        bzr ignore '*.class'
 
1119
    """
 
1120
    takes_args = ['name_pattern']
 
1121
    
 
1122
    def run(self, name_pattern):
 
1123
        from bzrlib.atomicfile import AtomicFile
 
1124
        import os.path
 
1125
 
 
1126
        b = find_branch('.')
 
1127
        ifn = b.abspath('.bzrignore')
 
1128
 
 
1129
        if os.path.exists(ifn):
 
1130
            f = open(ifn, 'rt')
 
1131
            try:
 
1132
                igns = f.read().decode('utf-8')
 
1133
            finally:
 
1134
                f.close()
 
1135
        else:
 
1136
            igns = ''
 
1137
 
 
1138
        # TODO: If the file already uses crlf-style termination, maybe
 
1139
        # we should use that for the newly added lines?
 
1140
 
 
1141
        if igns and igns[-1] != '\n':
 
1142
            igns += '\n'
 
1143
        igns += name_pattern + '\n'
 
1144
 
 
1145
        try:
 
1146
            f = AtomicFile(ifn, 'wt')
 
1147
            f.write(igns.encode('utf-8'))
 
1148
            f.commit()
 
1149
        finally:
 
1150
            f.close()
 
1151
 
 
1152
        inv = b.working_tree().inventory
 
1153
        if inv.path2id('.bzrignore'):
 
1154
            mutter('.bzrignore is already versioned')
 
1155
        else:
 
1156
            mutter('need to make new .bzrignore file versioned')
 
1157
            b.add(['.bzrignore'])
 
1158
 
 
1159
 
 
1160
 
 
1161
class cmd_ignored(Command):
 
1162
    """List ignored files and the patterns that matched them.
 
1163
 
 
1164
    See also: bzr ignore"""
 
1165
    def run(self):
 
1166
        tree = find_branch('.').working_tree()
 
1167
        for path, file_class, kind, file_id in tree.list_files():
 
1168
            if file_class != 'I':
 
1169
                continue
 
1170
            ## XXX: Slightly inefficient since this was already calculated
 
1171
            pat = tree.is_ignored(path)
 
1172
            print '%-50s %s' % (path, pat)
 
1173
 
 
1174
 
 
1175
class cmd_lookup_revision(Command):
 
1176
    """Lookup the revision-id from a revision-number
 
1177
 
 
1178
    example:
 
1179
        bzr lookup-revision 33
 
1180
    """
 
1181
    hidden = True
 
1182
    takes_args = ['revno']
 
1183
    
 
1184
    def run(self, revno):
 
1185
        try:
 
1186
            revno = int(revno)
 
1187
        except ValueError:
 
1188
            raise BzrCommandError("not a valid revision-number: %r" % revno)
 
1189
 
 
1190
        print find_branch('.').lookup_revision(revno)
 
1191
 
 
1192
 
 
1193
class cmd_export(Command):
 
1194
    """Export past revision to destination directory.
 
1195
 
 
1196
    If no revision is specified this exports the last committed revision.
 
1197
 
 
1198
    Format may be an "exporter" name, such as tar, tgz, tbz2.  If none is
 
1199
    given, try to find the format with the extension. If no extension
 
1200
    is found exports to a directory (equivalent to --format=dir).
 
1201
 
 
1202
    Root may be the top directory for tar, tgz and tbz2 formats. If none
 
1203
    is given, the top directory will be the root name of the file."""
 
1204
    # TODO: list known exporters
 
1205
    takes_args = ['dest']
 
1206
    takes_options = ['revision', 'format', 'root']
 
1207
    def run(self, dest, revision=None, format=None, root=None):
 
1208
        import os.path
 
1209
        b = find_branch('.')
 
1210
        if revision is None:
 
1211
            rev_id = b.last_patch()
 
1212
        else:
 
1213
            if len(revision) != 1:
 
1214
                raise BzrError('bzr export --revision takes exactly 1 argument')
 
1215
            revno, rev_id = b.get_revision_info(revision[0])
 
1216
        t = b.revision_tree(rev_id)
 
1217
        root, ext = os.path.splitext(dest)
 
1218
        if not format:
 
1219
            if ext in (".tar",):
 
1220
                format = "tar"
 
1221
            elif ext in (".gz", ".tgz"):
 
1222
                format = "tgz"
 
1223
            elif ext in (".bz2", ".tbz2"):
 
1224
                format = "tbz2"
 
1225
            else:
 
1226
                format = "dir"
 
1227
        t.export(dest, format, root)
 
1228
 
 
1229
 
 
1230
class cmd_cat(Command):
 
1231
    """Write a file's text from a previous revision."""
 
1232
 
 
1233
    takes_options = ['revision']
 
1234
    takes_args = ['filename']
 
1235
 
 
1236
    def run(self, filename, revision=None):
 
1237
        if revision == None:
 
1238
            raise BzrCommandError("bzr cat requires a revision number")
 
1239
        elif len(revision) != 1:
 
1240
            raise BzrCommandError("bzr cat --revision takes exactly one number")
 
1241
        b = find_branch('.')
 
1242
        b.print_file(b.relpath(filename), revision[0])
 
1243
 
 
1244
 
 
1245
class cmd_local_time_offset(Command):
 
1246
    """Show the offset in seconds from GMT to local time."""
 
1247
    hidden = True    
 
1248
    def run(self):
 
1249
        print bzrlib.osutils.local_time_offset()
 
1250
 
 
1251
 
 
1252
 
 
1253
class cmd_commit(Command):
 
1254
    """Commit changes into a new revision.
 
1255
    
 
1256
    If no arguments are given, the entire tree is committed.
 
1257
 
 
1258
    If selected files are specified, only changes to those files are
 
1259
    committed.  If a directory is specified then the directory and everything 
 
1260
    within it is committed.
 
1261
 
 
1262
    A selected-file commit may fail in some cases where the committed
 
1263
    tree would be invalid, such as trying to commit a file in a
 
1264
    newly-added directory that is not itself committed.
 
1265
 
 
1266
    TODO: Run hooks on tree to-be-committed, and after commit.
 
1267
 
 
1268
    TODO: Strict commit that fails if there are unknown or deleted files.
 
1269
    """
 
1270
    takes_args = ['selected*']
 
1271
    takes_options = ['message', 'file', 'verbose', 'unchanged']
 
1272
    aliases = ['ci', 'checkin']
 
1273
 
 
1274
    # TODO: Give better message for -s, --summary, used by tla people
 
1275
    
 
1276
    def run(self, message=None, file=None, verbose=True, selected_list=None,
 
1277
            unchanged=False):
 
1278
        from bzrlib.errors import PointlessCommit
 
1279
        from bzrlib.osutils import get_text_message
 
1280
 
 
1281
        ## Warning: shadows builtin file()
 
1282
        if not message and not file:
 
1283
            # FIXME: Ugly; change status code to send to a provided function?
 
1284
            
 
1285
            import cStringIO
 
1286
            stdout = sys.stdout
 
1287
            catcher = cStringIO.StringIO()
 
1288
            sys.stdout = catcher
 
1289
            cmd_status({"file_list":selected_list}, {})
 
1290
            info = catcher.getvalue()
 
1291
            sys.stdout = stdout
 
1292
            message = get_text_message(info)
 
1293
            
 
1294
            if message is None:
 
1295
                raise BzrCommandError("please specify a commit message",
 
1296
                                      ["use either --message or --file"])
 
1297
        elif message and file:
 
1298
            raise BzrCommandError("please specify either --message or --file")
 
1299
        
 
1300
        if file:
 
1301
            import codecs
 
1302
            message = codecs.open(file, 'rt', bzrlib.user_encoding).read()
 
1303
 
 
1304
        b = find_branch('.')
 
1305
        if selected_list:
 
1306
            selected_list = [b.relpath(s) for s in selected_list]
 
1307
            
 
1308
        try:
 
1309
            b.commit(message, verbose=verbose,
 
1310
                     specific_files=selected_list,
 
1311
                     allow_pointless=unchanged)
 
1312
        except PointlessCommit:
 
1313
            # FIXME: This should really happen before the file is read in;
 
1314
            # perhaps prepare the commit; get the message; then actually commit
 
1315
            raise BzrCommandError("no changes to commit",
 
1316
                                  ["use --unchanged to commit anyhow"])
 
1317
 
 
1318
 
 
1319
class cmd_check(Command):
 
1320
    """Validate consistency of branch history.
 
1321
 
 
1322
    This command checks various invariants about the branch storage to
 
1323
    detect data corruption or bzr bugs.
 
1324
 
 
1325
    If given the --update flag, it will update some optional fields
 
1326
    to help ensure data consistency.
 
1327
    """
 
1328
    takes_args = ['dir?']
 
1329
 
 
1330
    def run(self, dir='.'):
 
1331
        from bzrlib.check import check
 
1332
 
 
1333
        check(find_branch(dir))
 
1334
 
 
1335
 
 
1336
class cmd_scan_cache(Command):
 
1337
    hidden = True
 
1338
    def run(self):
 
1339
        from bzrlib.hashcache import HashCache
 
1340
        import os
 
1341
 
 
1342
        c = HashCache('.')
 
1343
        c.read()
 
1344
        c.scan()
 
1345
            
 
1346
        print '%6d stats' % c.stat_count
 
1347
        print '%6d in hashcache' % len(c._cache)
 
1348
        print '%6d files removed from cache' % c.removed_count
 
1349
        print '%6d hashes updated' % c.update_count
 
1350
        print '%6d files changed too recently to cache' % c.danger_count
 
1351
 
 
1352
        if c.needs_write:
 
1353
            c.write()
 
1354
            
 
1355
 
 
1356
 
 
1357
class cmd_upgrade(Command):
 
1358
    """Upgrade branch storage to current format.
 
1359
 
 
1360
    The check command or bzr developers may sometimes advise you to run
 
1361
    this command.
 
1362
    """
 
1363
    takes_args = ['dir?']
 
1364
 
 
1365
    def run(self, dir='.'):
 
1366
        from bzrlib.upgrade import upgrade
 
1367
        upgrade(find_branch(dir))
 
1368
 
 
1369
 
 
1370
 
 
1371
class cmd_whoami(Command):
 
1372
    """Show bzr user id."""
 
1373
    takes_options = ['email']
 
1374
    
 
1375
    def run(self, email=False):
 
1376
        try:
 
1377
            b = bzrlib.branch.find_branch('.')
 
1378
        except:
 
1379
            b = None
 
1380
        
 
1381
        if email:
 
1382
            print bzrlib.osutils.user_email(b)
 
1383
        else:
 
1384
            print bzrlib.osutils.username(b)
 
1385
 
 
1386
 
 
1387
class cmd_selftest(Command):
518
1388
    """Run internal test suite"""
519
 
    ## -v, if present, is seen by doctest; the argument is just here
520
 
    ## so our parser doesn't complain
521
 
 
522
 
    ## TODO: --verbose option
523
 
 
524
 
    failures, tests = 0, 0
525
 
    
526
 
    import doctest, bzrlib.store, bzrlib.tests
527
 
    bzrlib.trace.verbose = False
528
 
 
529
 
    for m in bzrlib.store, bzrlib.inventory, bzrlib.branch, bzrlib.osutils, \
530
 
        bzrlib.tree, bzrlib.tests, bzrlib.commands, bzrlib.add:
531
 
        mf, mt = doctest.testmod(m)
532
 
        failures += mf
533
 
        tests += mt
534
 
        print '%-40s %3d tests' % (m.__name__, mt),
535
 
        if mf:
536
 
            print '%3d FAILED!' % mf
537
 
        else:
538
 
            print
539
 
 
540
 
    print '%-40s %3d tests' % ('total', tests),
541
 
    if failures:
542
 
        print '%3d FAILED!' % failures
543
 
    else:
544
 
        print
545
 
 
546
 
 
547
 
 
548
 
# deprecated
549
 
cmd_doctest = cmd_selftest
550
 
 
551
 
 
552
 
######################################################################
553
 
# help
554
 
 
555
 
 
556
 
def cmd_help():
557
 
    # TODO: Specific help for particular commands
558
 
    print __doc__
559
 
 
560
 
 
561
 
def cmd_version():
562
 
    print "bzr (bazaar-ng) %s" % __version__
563
 
    print __copyright__
 
1389
    hidden = True
 
1390
    takes_options = ['verbose', 'pattern']
 
1391
    def run(self, verbose=False, pattern=".*"):
 
1392
        import bzrlib.ui
 
1393
        from bzrlib.selftest import selftest
 
1394
        # we don't want progress meters from the tests to go to the
 
1395
        # real output; and we don't want log messages cluttering up
 
1396
        # the real logs.
 
1397
        save_ui = bzrlib.ui.ui_factory
 
1398
        bzrlib.trace.info('running tests...')
 
1399
        try:
 
1400
            bzrlib.ui.ui_factory = bzrlib.ui.SilentUIFactory()
 
1401
            result = selftest(verbose=verbose, pattern=pattern)
 
1402
            if result:
 
1403
                bzrlib.trace.info('tests passed')
 
1404
            else:
 
1405
                bzrlib.trace.info('tests failed')
 
1406
            return int(not result)
 
1407
        finally:
 
1408
            bzrlib.ui.ui_factory = save_ui
 
1409
 
 
1410
 
 
1411
class cmd_version(Command):
 
1412
    """Show version of bzr."""
 
1413
    def run(self):
 
1414
        show_version()
 
1415
 
 
1416
def show_version():
 
1417
    print "bzr (bazaar-ng) %s" % bzrlib.__version__
 
1418
    # is bzrlib itself in a branch?
 
1419
    bzrrev = bzrlib.get_bzr_revision()
 
1420
    if bzrrev:
 
1421
        print "  (bzr checkout, revision %d {%s})" % bzrrev
 
1422
    print bzrlib.__copyright__
564
1423
    print "http://bazaar-ng.org/"
565
1424
    print
566
 
    print \
567
 
"""bzr comes with ABSOLUTELY NO WARRANTY.  bzr is free software, and
568
 
you may use, modify and redistribute it under the terms of the GNU 
569
 
General Public License version 2 or later."""
570
 
 
571
 
 
572
 
def cmd_rocks():
 
1425
    print "bzr comes with ABSOLUTELY NO WARRANTY.  bzr is free software, and"
 
1426
    print "you may use, modify and redistribute it under the terms of the GNU"
 
1427
    print "General Public License version 2 or later."
 
1428
 
 
1429
 
 
1430
class cmd_rocks(Command):
573
1431
    """Statement of optimism."""
574
 
    print "it sure does!"
575
 
 
576
 
 
577
 
 
578
 
######################################################################
579
 
# main routine
 
1432
    hidden = True
 
1433
    def run(self):
 
1434
        print "it sure does!"
 
1435
 
 
1436
def parse_spec(spec):
 
1437
    """
 
1438
    >>> parse_spec(None)
 
1439
    [None, None]
 
1440
    >>> parse_spec("./")
 
1441
    ['./', None]
 
1442
    >>> parse_spec("../@")
 
1443
    ['..', -1]
 
1444
    >>> parse_spec("../f/@35")
 
1445
    ['../f', 35]
 
1446
    >>> parse_spec('./@revid:john@arbash-meinel.com-20050711044610-3ca0327c6a222f67')
 
1447
    ['.', 'revid:john@arbash-meinel.com-20050711044610-3ca0327c6a222f67']
 
1448
    """
 
1449
    if spec is None:
 
1450
        return [None, None]
 
1451
    if '/@' in spec:
 
1452
        parsed = spec.split('/@')
 
1453
        assert len(parsed) == 2
 
1454
        if parsed[1] == "":
 
1455
            parsed[1] = -1
 
1456
        else:
 
1457
            try:
 
1458
                parsed[1] = int(parsed[1])
 
1459
            except ValueError:
 
1460
                pass # We can allow stuff like ./@revid:blahblahblah
 
1461
            else:
 
1462
                assert parsed[1] >=0
 
1463
    else:
 
1464
        parsed = [spec, None]
 
1465
    return parsed
 
1466
 
 
1467
 
 
1468
 
 
1469
class cmd_find_merge_base(Command):
 
1470
    """Find and print a base revision for merging two branches.
 
1471
 
 
1472
    TODO: Options to specify revisions on either side, as if
 
1473
          merging only part of the history.
 
1474
    """
 
1475
    takes_args = ['branch', 'other']
 
1476
    hidden = True
 
1477
    
 
1478
    def run(self, branch, other):
 
1479
        branch1 = find_branch(branch)
 
1480
        branch2 = find_branch(other)
 
1481
 
 
1482
        base_revno, base_revid = branch1.common_ancestor(branch2)
 
1483
 
 
1484
        if base_revno is None:
 
1485
            raise bzrlib.errors.UnrelatedBranches()
 
1486
 
 
1487
        print 'merge base is revision %s' % base_revid
 
1488
        print ' r%-6d in %s' % (base_revno, branch)
 
1489
 
 
1490
        other_revno = branch2.revision_id_to_revno(base_revid)
 
1491
        
 
1492
        print ' r%-6d in %s' % (other_revno, other)
 
1493
 
 
1494
 
 
1495
 
 
1496
class cmd_merge(Command):
 
1497
    """Perform a three-way merge.
 
1498
    
 
1499
    The branch is the branch you will merge from.  By default, it will merge
 
1500
    the latest revision.  If you specify a revision, that revision will be
 
1501
    merged.  If you specify two revisions, the first will be used as a BASE, 
 
1502
    and the second one as OTHER.  Revision numbers are always relative to the
 
1503
    specified branch.
 
1504
    
 
1505
    Examples:
 
1506
 
 
1507
    To merge the latest revision from bzr.dev
 
1508
    bzr merge ../bzr.dev
 
1509
 
 
1510
    To merge changes up to and including revision 82 from bzr.dev
 
1511
    bzr merge -r 82 ../bzr.dev
 
1512
 
 
1513
    To merge the changes introduced by 82, without previous changes:
 
1514
    bzr merge -r 81..82 ../bzr.dev
 
1515
    
 
1516
    merge refuses to run if there are any uncommitted changes, unless
 
1517
    --force is given.
 
1518
    """
 
1519
    takes_args = ['branch?']
 
1520
    takes_options = ['revision', 'force', 'merge-type']
 
1521
 
 
1522
    def run(self, branch='.', revision=None, force=False, 
 
1523
            merge_type=None):
 
1524
        from bzrlib.merge import merge
 
1525
        from bzrlib.merge_core import ApplyMerge3
 
1526
        if merge_type is None:
 
1527
            merge_type = ApplyMerge3
 
1528
 
 
1529
        if revision is None or len(revision) < 1:
 
1530
            base = [None, None]
 
1531
            other = (branch, -1)
 
1532
        else:
 
1533
            if len(revision) == 1:
 
1534
                other = (branch, revision[0])
 
1535
                base = (None, None)
 
1536
            else:
 
1537
                assert len(revision) == 2
 
1538
                if None in revision:
 
1539
                    raise BzrCommandError(
 
1540
                        "Merge doesn't permit that revision specifier.")
 
1541
                base = (branch, revision[0])
 
1542
                other = (branch, revision[1])
 
1543
            
 
1544
        merge(other, base, check_clean=(not force), merge_type=merge_type)
 
1545
 
 
1546
 
 
1547
class cmd_revert(Command):
 
1548
    """Reverse all changes since the last commit.
 
1549
 
 
1550
    Only versioned files are affected.  Specify filenames to revert only 
 
1551
    those files.  By default, any files that are changed will be backed up
 
1552
    first.  Backup files have a '~' appended to their name.
 
1553
    """
 
1554
    takes_options = ['revision', 'no-backup']
 
1555
    takes_args = ['file*']
 
1556
    aliases = ['merge-revert']
 
1557
 
 
1558
    def run(self, revision=None, no_backup=False, file_list=None):
 
1559
        from bzrlib.merge import merge
 
1560
        from bzrlib.branch import Branch
 
1561
        if file_list is not None:
 
1562
            if len(file_list) == 0:
 
1563
                raise BzrCommandError("No files specified")
 
1564
        if revision is None:
 
1565
            revision = [-1]
 
1566
        elif len(revision) != 1:
 
1567
            raise BzrCommandError('bzr revert --revision takes exactly 1 argument')
 
1568
        merge(('.', revision[0]), parse_spec('.'),
 
1569
              check_clean=False,
 
1570
              ignore_zero=True,
 
1571
              backup_files=not no_backup,
 
1572
              file_list=file_list)
 
1573
        if not file_list:
 
1574
            Branch('.').set_pending_merges([])
 
1575
 
 
1576
 
 
1577
class cmd_assert_fail(Command):
 
1578
    """Test reporting of assertion failures"""
 
1579
    hidden = True
 
1580
    def run(self):
 
1581
        assert False, "always fails"
 
1582
 
 
1583
 
 
1584
class cmd_help(Command):
 
1585
    """Show help on a command or other topic.
 
1586
 
 
1587
    For a list of all available commands, say 'bzr help commands'."""
 
1588
    takes_options = ['long']
 
1589
    takes_args = ['topic?']
 
1590
    aliases = ['?']
 
1591
    
 
1592
    def run(self, topic=None, long=False):
 
1593
        import help
 
1594
        if topic is None and long:
 
1595
            topic = "commands"
 
1596
        help.help(topic)
 
1597
 
 
1598
 
 
1599
class cmd_shell_complete(Command):
 
1600
    """Show appropriate completions for context.
 
1601
 
 
1602
    For a list of all available commands, say 'bzr shell-complete'."""
 
1603
    takes_args = ['context?']
 
1604
    aliases = ['s-c']
 
1605
    hidden = True
 
1606
    
 
1607
    def run(self, context=None):
 
1608
        import shellcomplete
 
1609
        shellcomplete.shellcomplete(context)
 
1610
 
 
1611
 
 
1612
class cmd_missing(Command):
 
1613
    """What is missing in this branch relative to other branch.
 
1614
    """
 
1615
    takes_args = ['remote?']
 
1616
    aliases = ['mis', 'miss']
 
1617
    # We don't have to add quiet to the list, because 
 
1618
    # unknown options are parsed as booleans
 
1619
    takes_options = ['verbose', 'quiet']
 
1620
 
 
1621
    def run(self, remote=None, verbose=False, quiet=False):
 
1622
        from bzrlib.branch import find_branch, DivergedBranches
 
1623
        from bzrlib.errors import BzrCommandError
 
1624
        from bzrlib.missing import get_parent, show_missing
 
1625
 
 
1626
        if verbose and quiet:
 
1627
            raise BzrCommandError('Cannot pass both quiet and verbose')
 
1628
 
 
1629
        b = find_branch('.')
 
1630
        parent = get_parent(b)
 
1631
        if remote is None:
 
1632
            if parent is None:
 
1633
                raise BzrCommandError("No missing location known or specified.")
 
1634
            else:
 
1635
                if not quiet:
 
1636
                    print "Using last location: %s" % parent
 
1637
                remote = parent
 
1638
        elif parent is None:
 
1639
            # We only update x-pull if it did not exist, missing should not change the parent
 
1640
            b.controlfile('x-pull', 'wb').write(remote + '\n')
 
1641
        br_remote = find_branch(remote)
 
1642
 
 
1643
        return show_missing(b, br_remote, verbose=verbose, quiet=quiet)
 
1644
 
 
1645
 
 
1646
 
 
1647
class cmd_plugins(Command):
 
1648
    """List plugins"""
 
1649
    hidden = True
 
1650
    def run(self):
 
1651
        import bzrlib.plugin
 
1652
        from inspect import getdoc
 
1653
        from pprint import pprint
 
1654
        for plugin in bzrlib.plugin.all_plugins:
 
1655
            if hasattr(plugin, '__path__'):
 
1656
                print plugin.__path__[0]
 
1657
            else:
 
1658
                print `plugin`
 
1659
            d = getdoc(plugin)
 
1660
            if d:
 
1661
                print '\t', d.split('\n')[0]
 
1662
 
 
1663
        #pprint(bzrlib.plugin.all_plugins)
 
1664
 
580
1665
 
581
1666
 
582
1667
# list of all available options; the rhs can be either None for an
584
1669
# the type.
585
1670
OPTIONS = {
586
1671
    'all':                    None,
 
1672
    'diff-options':           str,
587
1673
    'help':                   None,
 
1674
    'file':                   unicode,
 
1675
    'force':                  None,
 
1676
    'format':                 unicode,
 
1677
    'forward':                None,
588
1678
    'message':                unicode,
589
 
    'revision':               int,
 
1679
    'no-recurse':             None,
 
1680
    'profile':                None,
 
1681
    'revision':               _parse_revision_str,
 
1682
    'short':                  None,
590
1683
    'show-ids':               None,
591
1684
    'timezone':               str,
592
1685
    'verbose':                None,
593
1686
    'version':                None,
 
1687
    'email':                  None,
 
1688
    'unchanged':              None,
 
1689
    'update':                 None,
 
1690
    'long':                   None,
 
1691
    'root':                   str,
 
1692
    'no-backup':              None,
 
1693
    'merge-type':             get_merge_type,
 
1694
    'pattern':                str,
594
1695
    }
595
1696
 
596
1697
SHORT_OPTIONS = {
 
1698
    'F':                      'file', 
 
1699
    'h':                      'help',
597
1700
    'm':                      'message',
598
1701
    'r':                      'revision',
599
1702
    'v':                      'verbose',
 
1703
    'l':                      'long',
600
1704
}
601
1705
 
602
 
# List of options that apply to particular commands; commands not
603
 
# listed take none.
604
 
cmd_options = {
605
 
    'add':                    ['verbose'],
606
 
    'commit':                 ['message', 'verbose'],
607
 
    'diff':                   ['revision'],
608
 
    'inventory':              ['revision'],
609
 
    'log':                    ['show-ids', 'timezone'],
610
 
    'ls':                     ['revision', 'verbose'],
611
 
    'remove':                 ['verbose'],
612
 
    'status':                 ['all'],
613
 
    }
614
 
 
615
 
 
616
 
cmd_args = {
617
 
    'init':                   [],
618
 
    'add':                    ['file+'],
619
 
    'commit':                 [],
620
 
    'diff':                   [],
621
 
    'file-id':                ['filename'],
622
 
    'root':                   ['filename?'],
623
 
    'relpath':                ['filename'],
624
 
    'get-file-text':          ['text_id'],
625
 
    'get-inventory':          ['inventory_id'],
626
 
    'get-revision':           ['revision_id'],
627
 
    'get-revision-inventory': ['revision_id'],
628
 
    'log':                    [],
629
 
    'lookup-revision':        ['revno'],
630
 
    'export':                 ['revno', 'dest'],
631
 
    'remove':                 ['file+'],
632
 
    'status':                 [],
633
 
    }
634
 
 
635
1706
 
636
1707
def parse_args(argv):
637
1708
    """Parse command line.
643
1714
 
644
1715
    >>> parse_args('--help'.split())
645
1716
    ([], {'help': True})
 
1717
    >>> parse_args('help -- --invalidcmd'.split())
 
1718
    (['help', '--invalidcmd'], {})
646
1719
    >>> parse_args('--version'.split())
647
1720
    ([], {'version': True})
648
1721
    >>> parse_args('status --all'.split())
649
1722
    (['status'], {'all': True})
650
1723
    >>> parse_args('commit --message=biter'.split())
651
1724
    (['commit'], {'message': u'biter'})
 
1725
    >>> parse_args('log -r 500'.split())
 
1726
    (['log'], {'revision': [500]})
 
1727
    >>> parse_args('log -r500..600'.split())
 
1728
    (['log'], {'revision': [500, 600]})
 
1729
    >>> parse_args('log -vr500..600'.split())
 
1730
    (['log'], {'verbose': True, 'revision': [500, 600]})
 
1731
    >>> parse_args('log -rv500..600'.split()) #the r takes an argument
 
1732
    (['log'], {'revision': ['v500', 600]})
652
1733
    """
653
1734
    args = []
654
1735
    opts = {}
655
1736
 
656
 
    # TODO: Maybe handle '--' to end options?
657
 
 
 
1737
    argsover = False
658
1738
    while argv:
659
1739
        a = argv.pop(0)
660
 
        if a[0] == '-':
 
1740
        if not argsover and a[0] == '-':
 
1741
            # option names must not be unicode
 
1742
            a = str(a)
661
1743
            optarg = None
662
1744
            if a[1] == '-':
 
1745
                if a == '--':
 
1746
                    # We've received a standalone -- No more flags
 
1747
                    argsover = True
 
1748
                    continue
663
1749
                mutter("  got option %r" % a)
664
1750
                if '=' in a:
665
1751
                    optname, optarg = a[2:].split('=', 1)
666
1752
                else:
667
1753
                    optname = a[2:]
668
1754
                if optname not in OPTIONS:
669
 
                    bailout('unknown long option %r' % a)
 
1755
                    raise BzrError('unknown long option %r' % a)
670
1756
            else:
671
1757
                shortopt = a[1:]
672
 
                if shortopt not in SHORT_OPTIONS:
673
 
                    bailout('unknown short option %r' % a)
674
 
                optname = SHORT_OPTIONS[shortopt]
 
1758
                if shortopt in SHORT_OPTIONS:
 
1759
                    # Multi-character options must have a space to delimit
 
1760
                    # their value
 
1761
                    optname = SHORT_OPTIONS[shortopt]
 
1762
                else:
 
1763
                    # Single character short options, can be chained,
 
1764
                    # and have their value appended to their name
 
1765
                    shortopt = a[1:2]
 
1766
                    if shortopt not in SHORT_OPTIONS:
 
1767
                        # We didn't find the multi-character name, and we
 
1768
                        # didn't find the single char name
 
1769
                        raise BzrError('unknown short option %r' % a)
 
1770
                    optname = SHORT_OPTIONS[shortopt]
 
1771
 
 
1772
                    if a[2:]:
 
1773
                        # There are extra things on this option
 
1774
                        # see if it is the value, or if it is another
 
1775
                        # short option
 
1776
                        optargfn = OPTIONS[optname]
 
1777
                        if optargfn is None:
 
1778
                            # This option does not take an argument, so the
 
1779
                            # next entry is another short option, pack it back
 
1780
                            # into the list
 
1781
                            argv.insert(0, '-' + a[2:])
 
1782
                        else:
 
1783
                            # This option takes an argument, so pack it
 
1784
                            # into the array
 
1785
                            optarg = a[2:]
675
1786
            
676
1787
            if optname in opts:
677
1788
                # XXX: Do we ever want to support this, e.g. for -r?
678
 
                bailout('repeated option %r' % a)
 
1789
                raise BzrError('repeated option %r' % a)
679
1790
                
680
1791
            optargfn = OPTIONS[optname]
681
1792
            if optargfn:
682
1793
                if optarg == None:
683
1794
                    if not argv:
684
 
                        bailout('option %r needs an argument' % a)
 
1795
                        raise BzrError('option %r needs an argument' % a)
685
1796
                    else:
686
1797
                        optarg = argv.pop(0)
687
1798
                opts[optname] = optargfn(optarg)
688
 
                mutter("    option argument %r" % opts[optname])
689
1799
            else:
690
1800
                if optarg != None:
691
 
                    bailout('option %r takes no argument' % optname)
 
1801
                    raise BzrError('option %r takes no argument' % optname)
692
1802
                opts[optname] = True
693
1803
        else:
694
1804
            args.append(a)
697
1807
 
698
1808
 
699
1809
 
700
 
def _match_args(cmd, args):
701
 
    """Check non-option arguments match required pattern.
702
1810
 
703
 
    >>> _match_args('status', ['asdasdsadasd'])
704
 
    Traceback (most recent call last):
705
 
    ...
706
 
    BzrError: ("extra arguments to command status: ['asdasdsadasd']", [])
707
 
    >>> _match_args('add', ['asdasdsadasd'])
708
 
    {'file_list': ['asdasdsadasd']}
709
 
    >>> _match_args('add', 'abc def gj'.split())
710
 
    {'file_list': ['abc', 'def', 'gj']}
711
 
    """
712
 
    # match argument pattern
713
 
    argform = cmd_args.get(cmd, [])
 
1811
def _match_argform(cmd, takes_args, args):
714
1812
    argdict = {}
715
 
    # TODO: Need a way to express 'cp SRC... DEST', where it matches
716
 
    # all but one.
717
1813
 
718
 
    # step through args and argform, allowing appropriate 0-many matches
719
 
    for ap in argform:
 
1814
    # step through args and takes_args, allowing appropriate 0-many matches
 
1815
    for ap in takes_args:
720
1816
        argname = ap[:-1]
721
1817
        if ap[-1] == '?':
722
1818
            if args:
723
1819
                argdict[argname] = args.pop(0)
724
 
        elif ap[-1] == '*':
725
 
            assert 0
 
1820
        elif ap[-1] == '*': # all remaining arguments
 
1821
            if args:
 
1822
                argdict[argname + '_list'] = args[:]
 
1823
                args = []
 
1824
            else:
 
1825
                argdict[argname + '_list'] = None
726
1826
        elif ap[-1] == '+':
727
1827
            if not args:
728
 
                bailout("command %r needs one or more %s"
 
1828
                raise BzrCommandError("command %r needs one or more %s"
729
1829
                        % (cmd, argname.upper()))
730
1830
            else:
731
1831
                argdict[argname + '_list'] = args[:]
732
1832
                args = []
 
1833
        elif ap[-1] == '$': # all but one
 
1834
            if len(args) < 2:
 
1835
                raise BzrCommandError("command %r needs one or more %s"
 
1836
                        % (cmd, argname.upper()))
 
1837
            argdict[argname + '_list'] = args[:-1]
 
1838
            args[:-1] = []                
733
1839
        else:
734
1840
            # just a plain arg
735
1841
            argname = ap
736
1842
            if not args:
737
 
                bailout("command %r requires argument %s"
 
1843
                raise BzrCommandError("command %r requires argument %s"
738
1844
                        % (cmd, argname.upper()))
739
1845
            else:
740
1846
                argdict[argname] = args.pop(0)
741
1847
            
742
1848
    if args:
743
 
        bailout("extra arguments to command %s: %r"
744
 
                % (cmd, args))
 
1849
        raise BzrCommandError("extra argument to command %s: %s"
 
1850
                              % (cmd, args[0]))
745
1851
 
746
1852
    return argdict
747
1853
 
751
1857
    """Execute a command.
752
1858
 
753
1859
    This is similar to main(), but without all the trappings for
754
 
    logging and error handling.
 
1860
    logging and error handling.  
 
1861
    
 
1862
    argv
 
1863
       The command-line arguments, without the program name from argv[0]
 
1864
    
 
1865
    Returns a command status or raises an exception.
 
1866
 
 
1867
    Special master options: these must come before the command because
 
1868
    they control how the command is interpreted.
 
1869
 
 
1870
    --no-plugins
 
1871
        Do not load plugin modules at all
 
1872
 
 
1873
    --builtin
 
1874
        Only use builtin commands.  (Plugins are still allowed to change
 
1875
        other behaviour.)
 
1876
 
 
1877
    --profile
 
1878
        Run under the Python profiler.
755
1879
    """
756
 
    try:
757
 
        args, opts = parse_args(argv[1:])
758
 
        if 'help' in opts:
759
 
            # TODO: pass down other arguments in case they asked for
760
 
            # help on a command name?
761
 
            cmd_help()
762
 
            return 0
763
 
        elif 'version' in opts:
764
 
            cmd_version()
765
 
            return 0
766
 
        cmd = args.pop(0)
767
 
    except IndexError:
768
 
        log_error('usage: bzr COMMAND\n')
769
 
        log_error('  try "bzr help"\n')
770
 
        return 1
771
 
            
772
 
    try:
773
 
        cmd_handler = globals()['cmd_' + cmd.replace('-', '_')]
774
 
    except KeyError:
775
 
        bailout("unknown command " + `cmd`)
776
 
 
777
 
    # TODO: special --profile option to turn on the Python profiler
 
1880
    
 
1881
    argv = [a.decode(bzrlib.user_encoding) for a in argv]
 
1882
 
 
1883
    opt_profile = opt_no_plugins = opt_builtin = False
 
1884
 
 
1885
    # --no-plugins is handled specially at a very early stage. We need
 
1886
    # to load plugins before doing other command parsing so that they
 
1887
    # can override commands, but this needs to happen first.
 
1888
 
 
1889
    for a in argv[:]:
 
1890
        if a == '--profile':
 
1891
            opt_profile = True
 
1892
        elif a == '--no-plugins':
 
1893
            opt_no_plugins = True
 
1894
        elif a == '--builtin':
 
1895
            opt_builtin = True
 
1896
        else:
 
1897
            break
 
1898
        argv.remove(a)
 
1899
 
 
1900
    if not opt_no_plugins:
 
1901
        from bzrlib.plugin import load_plugins
 
1902
        load_plugins()
 
1903
 
 
1904
    args, opts = parse_args(argv)
 
1905
 
 
1906
    if 'help' in opts:
 
1907
        from bzrlib.help import help
 
1908
        if args:
 
1909
            help(args[0])
 
1910
        else:
 
1911
            help()
 
1912
        return 0            
 
1913
        
 
1914
    if 'version' in opts:
 
1915
        show_version()
 
1916
        return 0
 
1917
    
 
1918
    if not args:
 
1919
        from bzrlib.help import help
 
1920
        help(None)
 
1921
        return 0
 
1922
    
 
1923
    cmd = str(args.pop(0))
 
1924
 
 
1925
    canonical_cmd, cmd_class = \
 
1926
                   get_cmd_class(cmd, plugins_override=not opt_builtin)
778
1927
 
779
1928
    # check options are reasonable
780
 
    allowed = cmd_options.get(cmd, [])
 
1929
    allowed = cmd_class.takes_options
781
1930
    for oname in opts:
782
1931
        if oname not in allowed:
783
 
            bailout("option %r is not allowed for command %r"
784
 
                    % (oname, cmd))
785
 
 
786
 
    cmdargs = _match_args(cmd, args)
787
 
    cmdargs.update(opts)
788
 
 
789
 
    ret = cmd_handler(**cmdargs) or 0
790
 
 
 
1932
            raise BzrCommandError("option '--%s' is not allowed for command %r"
 
1933
                                  % (oname, cmd))
 
1934
 
 
1935
    # mix arguments and options into one dictionary
 
1936
    cmdargs = _match_argform(cmd, cmd_class.takes_args, args)
 
1937
    cmdopts = {}
 
1938
    for k, v in opts.items():
 
1939
        cmdopts[k.replace('-', '_')] = v
 
1940
 
 
1941
    if opt_profile:
 
1942
        import hotshot, tempfile
 
1943
        pffileno, pfname = tempfile.mkstemp()
 
1944
        try:
 
1945
            prof = hotshot.Profile(pfname)
 
1946
            ret = prof.runcall(cmd_class, cmdopts, cmdargs) or 0
 
1947
            prof.close()
 
1948
 
 
1949
            import hotshot.stats
 
1950
            stats = hotshot.stats.load(pfname)
 
1951
            #stats.strip_dirs()
 
1952
            stats.sort_stats('time')
 
1953
            ## XXX: Might like to write to stderr or the trace file instead but
 
1954
            ## print_stats seems hardcoded to stdout
 
1955
            stats.print_stats(20)
 
1956
            
 
1957
            return ret.status
 
1958
 
 
1959
        finally:
 
1960
            os.close(pffileno)
 
1961
            os.remove(pfname)
 
1962
    else:
 
1963
        return cmd_class(cmdopts, cmdargs).status 
791
1964
 
792
1965
 
793
1966
def main(argv):
794
 
    ## TODO: Handle command-line options; probably know what options are valid for
795
 
    ## each command
796
 
 
797
 
    ## TODO: If the arguments are wrong, give a usage message rather
798
 
    ## than just a backtrace.
799
 
 
800
 
    bzrlib.trace.create_tracefile(argv)
801
 
    
 
1967
    import bzrlib.ui
 
1968
    bzrlib.trace.log_startup(argv)
 
1969
    bzrlib.ui.ui_factory = bzrlib.ui.TextUIFactory()
 
1970
 
802
1971
    try:
803
 
        ret = run_bzr(argv)
804
 
        return ret
 
1972
        try:
 
1973
            return run_bzr(argv[1:])
 
1974
        finally:
 
1975
            # do this here inside the exception wrappers to catch EPIPE
 
1976
            sys.stdout.flush()
 
1977
    except BzrCommandError, e:
 
1978
        # command line syntax error, etc
 
1979
        log_error(str(e))
 
1980
        return 1
805
1981
    except BzrError, e:
806
 
        log_error('bzr: error: ' + e.args[0] + '\n')
807
 
        if len(e.args) > 1:
808
 
            for h in e.args[1]:
809
 
                log_error('  ' + h + '\n')
 
1982
        bzrlib.trace.log_exception()
810
1983
        return 1
 
1984
    except AssertionError, e:
 
1985
        bzrlib.trace.log_exception('assertion failed: ' + str(e))
 
1986
        return 3
 
1987
    except KeyboardInterrupt, e:
 
1988
        bzrlib.trace.note('interrupted')
 
1989
        return 2
811
1990
    except Exception, e:
812
 
        log_error('bzr: exception: %s\n' % e)
813
 
        log_error('    see .bzr.log for details\n')
814
 
        traceback.print_exc(None, bzrlib.trace._tracefile)
815
 
        traceback.print_exc(None, sys.stderr)
816
 
        return 1
817
 
 
818
 
    # TODO: Maybe nicer handling of IOError?
819
 
 
 
1991
        import errno
 
1992
        if (isinstance(e, IOError) 
 
1993
            and hasattr(e, 'errno')
 
1994
            and e.errno == errno.EPIPE):
 
1995
            bzrlib.trace.note('broken pipe')
 
1996
            return 2
 
1997
        else:
 
1998
            bzrlib.trace.log_exception()
 
1999
            return 2
820
2000
 
821
2001
 
822
2002
if __name__ == '__main__':
823
2003
    sys.exit(main(sys.argv))
824
 
    ##import profile
825
 
    ##profile.run('main(sys.argv)')
826