~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/commands.py

  • Committer: aaron.bentley at utoronto
  • Date: 2005-08-25 02:30:04 UTC
  • mto: (1092.1.41) (1185.3.4)
  • mto: This revision was merged to the branch mainline in revision 1139.
  • Revision ID: aaron.bentley@utoronto.ca-20050825023004-581548615ae1066d
Made revert clear pending-merges

Show diffs side-by-side

added added

removed removed

Lines of Context:
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
 
18
 
 
19
 
import sys, os
 
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
import sys
 
24
import os
20
25
 
21
26
import bzrlib
22
 
from bzrlib.trace import mutter, note, log_error
23
 
from bzrlib.errors import bailout, BzrError, BzrCheckError, BzrCommandError
24
 
from bzrlib.osutils import quotefn
25
 
from bzrlib import Branch, Inventory, InventoryEntry, BZRDIR, \
26
 
     format_date
 
27
from bzrlib.trace import mutter, note, log_error, warning
 
28
from bzrlib.errors import BzrError, BzrCheckError, BzrCommandError
 
29
from bzrlib.branch import find_branch
 
30
from bzrlib import BZRDIR
 
31
 
 
32
 
 
33
plugin_cmds = {}
 
34
 
 
35
 
 
36
def register_command(cmd):
 
37
    "Utility function to help register a command"
 
38
    global plugin_cmds
 
39
    k = cmd.__name__
 
40
    if k.startswith("cmd_"):
 
41
        k_unsquished = _unsquish_command_name(k)
 
42
    else:
 
43
        k_unsquished = k
 
44
    if not plugin_cmds.has_key(k_unsquished):
 
45
        plugin_cmds[k_unsquished] = cmd
 
46
    else:
 
47
        log_error('Two plugins defined the same command: %r' % k)
 
48
        log_error('Not loading the one in %r' % sys.modules[cmd.__module__])
27
49
 
28
50
 
29
51
def _squish_command_name(cmd):
34
56
    assert cmd.startswith("cmd_")
35
57
    return cmd[4:].replace('_','-')
36
58
 
 
59
 
37
60
def _parse_revision_str(revstr):
38
 
    """This handles a revision string -> revno. 
39
 
 
40
 
    There are several possibilities:
41
 
 
42
 
        '234'       -> 234
43
 
        '234:345'   -> [234, 345]
44
 
        ':234'      -> [None, 234]
45
 
        '234:'      -> [234, None]
46
 
 
47
 
    In the future we will also support:
48
 
        'uuid:blah-blah-blah'   -> ?
49
 
        'hash:blahblahblah'     -> ?
50
 
        potentially:
51
 
        'tag:mytag'             -> ?
 
61
    """This handles a revision string -> revno.
 
62
 
 
63
    This always returns a list.  The list will have one element for 
 
64
 
 
65
    It supports integers directly, but everything else it
 
66
    defers for passing to Branch.get_revision_info()
 
67
 
 
68
    >>> _parse_revision_str('234')
 
69
    [234]
 
70
    >>> _parse_revision_str('234..567')
 
71
    [234, 567]
 
72
    >>> _parse_revision_str('..')
 
73
    [None, None]
 
74
    >>> _parse_revision_str('..234')
 
75
    [None, 234]
 
76
    >>> _parse_revision_str('234..')
 
77
    [234, None]
 
78
    >>> _parse_revision_str('234..456..789') # Maybe this should be an error
 
79
    [234, 456, 789]
 
80
    >>> _parse_revision_str('234....789') # Error?
 
81
    [234, None, 789]
 
82
    >>> _parse_revision_str('revid:test@other.com-234234')
 
83
    ['revid:test@other.com-234234']
 
84
    >>> _parse_revision_str('revid:test@other.com-234234..revid:test@other.com-234235')
 
85
    ['revid:test@other.com-234234', 'revid:test@other.com-234235']
 
86
    >>> _parse_revision_str('revid:test@other.com-234234..23')
 
87
    ['revid:test@other.com-234234', 23]
 
88
    >>> _parse_revision_str('date:2005-04-12')
 
89
    ['date:2005-04-12']
 
90
    >>> _parse_revision_str('date:2005-04-12 12:24:33')
 
91
    ['date:2005-04-12 12:24:33']
 
92
    >>> _parse_revision_str('date:2005-04-12T12:24:33')
 
93
    ['date:2005-04-12T12:24:33']
 
94
    >>> _parse_revision_str('date:2005-04-12,12:24:33')
 
95
    ['date:2005-04-12,12:24:33']
 
96
    >>> _parse_revision_str('-5..23')
 
97
    [-5, 23]
 
98
    >>> _parse_revision_str('-5')
 
99
    [-5]
 
100
    >>> _parse_revision_str('123a')
 
101
    ['123a']
 
102
    >>> _parse_revision_str('abc')
 
103
    ['abc']
52
104
    """
53
 
    if revstr.find(':') != -1:
54
 
        revs = revstr.split(':')
55
 
        if len(revs) > 2:
56
 
            raise ValueError('More than 2 pieces not supported for --revision: %r' % revstr)
57
 
 
58
 
        if not revs[0]:
59
 
            revs[0] = None
60
 
        else:
61
 
            revs[0] = int(revs[0])
62
 
 
63
 
        if not revs[1]:
64
 
            revs[1] = None
65
 
        else:
66
 
            revs[1] = int(revs[1])
67
 
    else:
68
 
        revs = int(revstr)
 
105
    import re
 
106
    old_format_re = re.compile('\d*:\d*')
 
107
    m = old_format_re.match(revstr)
 
108
    if m:
 
109
        warning('Colon separator for revision numbers is deprecated.'
 
110
                ' Use .. instead')
 
111
        revs = []
 
112
        for rev in revstr.split(':'):
 
113
            if rev:
 
114
                revs.append(int(rev))
 
115
            else:
 
116
                revs.append(None)
 
117
        return revs
 
118
    revs = []
 
119
    for x in revstr.split('..'):
 
120
        if not x:
 
121
            revs.append(None)
 
122
        else:
 
123
            try:
 
124
                revs.append(int(x))
 
125
            except ValueError:
 
126
                revs.append(x)
69
127
    return revs
70
128
 
71
 
def _find_plugins():
72
 
    """Find all python files which are plugins, and load their commands
73
 
    to add to the list of "all commands"
74
 
 
75
 
    The environment variable BZRPATH is considered a delimited set of
76
 
    paths to look through. Each entry is searched for *.py files.
77
 
    If a directory is found, it is also searched, but they are 
78
 
    not searched recursively. This allows you to revctl the plugins.
79
 
    
80
 
    Inside the plugin should be a series of cmd_* function, which inherit from
81
 
    the bzrlib.commands.Command class.
82
 
    """
83
 
    bzrpath = os.environ.get('BZRPLUGINPATH', '')
84
 
 
85
 
    plugin_cmds = {} 
86
 
    if not bzrpath:
87
 
        return plugin_cmds
88
 
    _platform_extensions = {
89
 
        'win32':'.pyd',
90
 
        'cygwin':'.dll',
91
 
        'darwin':'.dylib',
92
 
        'linux2':'.so'
93
 
        }
94
 
    if _platform_extensions.has_key(sys.platform):
95
 
        platform_extension = _platform_extensions[sys.platform]
96
 
    else:
97
 
        platform_extension = None
98
 
    for d in bzrpath.split(os.pathsep):
99
 
        plugin_names = {} # This should really be a set rather than a dict
100
 
        for f in os.listdir(d):
101
 
            if f.endswith('.py'):
102
 
                f = f[:-3]
103
 
            elif f.endswith('.pyc') or f.endswith('.pyo'):
104
 
                f = f[:-4]
105
 
            elif platform_extension and f.endswith(platform_extension):
106
 
                f = f[:-len(platform_extension)]
107
 
                if f.endswidth('module'):
108
 
                    f = f[:-len('module')]
109
 
            else:
110
 
                continue
111
 
            if not plugin_names.has_key(f):
112
 
                plugin_names[f] = True
113
 
 
114
 
        plugin_names = plugin_names.keys()
115
 
        plugin_names.sort()
116
 
        try:
117
 
            sys.path.insert(0, d)
118
 
            for name in plugin_names:
119
 
                try:
120
 
                    old_module = None
121
 
                    try:
122
 
                        if sys.modules.has_key(name):
123
 
                            old_module = sys.modules[name]
124
 
                            del sys.modules[name]
125
 
                        plugin = __import__(name, locals())
126
 
                        for k in dir(plugin):
127
 
                            if k.startswith('cmd_'):
128
 
                                k_unsquished = _unsquish_command_name(k)
129
 
                                if not plugin_cmds.has_key(k_unsquished):
130
 
                                    plugin_cmds[k_unsquished] = getattr(plugin, k)
131
 
                                else:
132
 
                                    log_error('Two plugins defined the same command: %r' % k)
133
 
                                    log_error('Not loading the one in %r in dir %r' % (name, d))
134
 
                    finally:
135
 
                        if old_module:
136
 
                            sys.modules[name] = old_module
137
 
                except ImportError, e:
138
 
                    log_error('Unable to load plugin: %r from %r\n%s' % (name, d, e))
139
 
        finally:
140
 
            sys.path.pop(0)
141
 
    return plugin_cmds
142
 
 
143
 
def _get_cmd_dict(include_plugins=True):
 
129
 
 
130
def get_merge_type(typestring):
 
131
    """Attempt to find the merge class/factory associated with a string."""
 
132
    from merge import merge_types
 
133
    try:
 
134
        return merge_types[typestring][0]
 
135
    except KeyError:
 
136
        templ = '%s%%7s: %%s' % (' '*12)
 
137
        lines = [templ % (f[0], f[1][1]) for f in merge_types.iteritems()]
 
138
        type_list = '\n'.join(lines)
 
139
        msg = "No known merge type %s. Supported types are:\n%s" %\
 
140
            (typestring, type_list)
 
141
        raise BzrCommandError(msg)
 
142
    
 
143
 
 
144
def get_merge_type(typestring):
 
145
    """Attempt to find the merge class/factory associated with a string."""
 
146
    from merge import merge_types
 
147
    try:
 
148
        return merge_types[typestring][0]
 
149
    except KeyError:
 
150
        templ = '%s%%7s: %%s' % (' '*12)
 
151
        lines = [templ % (f[0], f[1][1]) for f in merge_types.iteritems()]
 
152
        type_list = '\n'.join(lines)
 
153
        msg = "No known merge type %s. Supported types are:\n%s" %\
 
154
            (typestring, type_list)
 
155
        raise BzrCommandError(msg)
 
156
    
 
157
 
 
158
 
 
159
def _get_cmd_dict(plugins_override=True):
144
160
    d = {}
145
161
    for k, v in globals().iteritems():
146
162
        if k.startswith("cmd_"):
147
163
            d[_unsquish_command_name(k)] = v
148
 
    if include_plugins:
149
 
        d.update(_find_plugins())
 
164
    # If we didn't load plugins, the plugin_cmds dict will be empty
 
165
    if plugins_override:
 
166
        d.update(plugin_cmds)
 
167
    else:
 
168
        d2 = plugin_cmds.copy()
 
169
        d2.update(d)
 
170
        d = d2
150
171
    return d
 
172
 
151
173
    
152
 
def get_all_cmds(include_plugins=True):
 
174
def get_all_cmds(plugins_override=True):
153
175
    """Return canonical name and class for all registered commands."""
154
 
    for k, v in _get_cmd_dict(include_plugins=include_plugins).iteritems():
 
176
    for k, v in _get_cmd_dict(plugins_override=plugins_override).iteritems():
155
177
        yield k,v
156
178
 
157
179
 
158
 
def get_cmd_class(cmd,include_plugins=True):
 
180
def get_cmd_class(cmd, plugins_override=True):
159
181
    """Return the canonical name and command class for a command.
160
182
    """
161
183
    cmd = str(cmd)                      # not unicode
162
184
 
163
185
    # first look up this command under the specified name
164
 
    cmds = _get_cmd_dict(include_plugins=include_plugins)
 
186
    cmds = _get_cmd_dict(plugins_override=plugins_override)
165
187
    try:
166
188
        return cmd, cmds[cmd]
167
189
    except KeyError:
211
233
        assert isinstance(arguments, dict)
212
234
        cmdargs = options.copy()
213
235
        cmdargs.update(arguments)
214
 
        assert self.__doc__ != Command.__doc__, \
215
 
               ("No help message set for %r" % self)
 
236
        if self.__doc__ == Command.__doc__:
 
237
            from warnings import warn
 
238
            warn("No help message set for %r" % self)
216
239
        self.status = self.run(**cmdargs)
 
240
        if self.status is None:
 
241
            self.status = 0
217
242
 
218
243
    
219
244
    def run(self):
231
256
class ExternalCommand(Command):
232
257
    """Class to wrap external commands.
233
258
 
234
 
    We cheat a little here, when get_cmd_class() calls us we actually give it back
235
 
    an object we construct that has the appropriate path, help, options etc for the
236
 
    specified command.
237
 
 
238
 
    When run_bzr() tries to instantiate that 'class' it gets caught by the __call__
239
 
    method, which we override to call the Command.__init__ method. That then calls
240
 
    our run method which is pretty straight forward.
241
 
 
242
 
    The only wrinkle is that we have to map bzr's dictionary of options and arguments
243
 
    back into command line options and arguments for the script.
 
259
    We cheat a little here, when get_cmd_class() calls us we actually
 
260
    give it back an object we construct that has the appropriate path,
 
261
    help, options etc for the specified command.
 
262
 
 
263
    When run_bzr() tries to instantiate that 'class' it gets caught by
 
264
    the __call__ method, which we override to call the Command.__init__
 
265
    method. That then calls our run method which is pretty straight
 
266
    forward.
 
267
 
 
268
    The only wrinkle is that we have to map bzr's dictionary of options
 
269
    and arguments back into command line options and arguments for the
 
270
    script.
244
271
    """
245
272
 
246
273
    def find_command(cls, cmd):
259
286
    def __init__(self, path):
260
287
        self.path = path
261
288
 
262
 
        # TODO: If either of these fail, we should detect that and
263
 
        # assume that path is not really a bzr plugin after all.
264
 
 
265
289
        pipe = os.popen('%s --bzr-usage' % path, 'r')
266
290
        self.takes_options = pipe.readline().split()
 
291
 
 
292
        for opt in self.takes_options:
 
293
            if not opt in OPTIONS:
 
294
                raise BzrError("Unknown option '%s' returned by external command %s"
 
295
                               % (opt, path))
 
296
 
 
297
        # TODO: Is there any way to check takes_args is valid here?
267
298
        self.takes_args = pipe.readline().split()
268
 
        pipe.close()
 
299
 
 
300
        if pipe.close() is not None:
 
301
            raise BzrError("Failed funning '%s --bzr-usage'" % path)
269
302
 
270
303
        pipe = os.popen('%s --bzr-help' % path, 'r')
271
304
        self.__doc__ = pipe.read()
272
 
        pipe.close()
 
305
        if pipe.close() is not None:
 
306
            raise BzrError("Failed funning '%s --bzr-help'" % path)
273
307
 
274
308
    def __call__(self, options, arguments):
275
309
        Command.__init__(self, options, arguments)
282
316
        keys = kargs.keys()
283
317
        keys.sort()
284
318
        for name in keys:
 
319
            optname = name.replace('_','-')
285
320
            value = kargs[name]
286
 
            if OPTIONS.has_key(name):
 
321
            if OPTIONS.has_key(optname):
287
322
                # it's an option
288
 
                opts.append('--%s' % name)
 
323
                opts.append('--%s' % optname)
289
324
                if value is not None and value is not True:
290
325
                    opts.append(str(value))
291
326
            else:
335
370
    directory is shown.  Otherwise, only the status of the specified
336
371
    files or directories is reported.  If a directory is given, status
337
372
    is reported for everything inside that directory.
 
373
 
 
374
    If a revision is specified, the changes since that revision are shown.
338
375
    """
339
376
    takes_args = ['file*']
340
 
    takes_options = ['all', 'show-ids']
 
377
    takes_options = ['all', 'show-ids', 'revision']
341
378
    aliases = ['st', 'stat']
342
379
    
343
380
    def run(self, all=False, show_ids=False, file_list=None):
344
381
        if file_list:
345
 
            b = Branch(file_list[0])
 
382
            b = find_branch(file_list[0])
346
383
            file_list = [b.relpath(x) for x in file_list]
347
384
            # special case: only one path was given and it's the root
348
385
            # of the branch
349
386
            if file_list == ['']:
350
387
                file_list = None
351
388
        else:
352
 
            b = Branch('.')
353
 
        import status
354
 
        status.show_status(b, show_unchanged=all, show_ids=show_ids,
355
 
                           specific_files=file_list)
 
389
            b = find_branch('.')
 
390
            
 
391
        from bzrlib.status import show_status
 
392
        show_status(b, show_unchanged=all, show_ids=show_ids,
 
393
                    specific_files=file_list)
356
394
 
357
395
 
358
396
class cmd_cat_revision(Command):
362
400
    takes_args = ['revision_id']
363
401
    
364
402
    def run(self, revision_id):
365
 
        Branch('.').get_revision(revision_id).write_xml(sys.stdout)
 
403
        from bzrlib.xml import pack_xml
 
404
        pack_xml(find_branch('.').get_revision(revision_id), sys.stdout)
366
405
 
367
406
 
368
407
class cmd_revno(Command):
370
409
 
371
410
    This is equal to the number of revisions on this branch."""
372
411
    def run(self):
373
 
        print Branch('.').revno()
 
412
        print find_branch('.').revno()
 
413
 
 
414
class cmd_revision_info(Command):
 
415
    """Show revision number and revision id for a given revision identifier.
 
416
    """
 
417
    hidden = True
 
418
    takes_args = ['revision_info*']
 
419
    takes_options = ['revision']
 
420
    def run(self, revision=None, revision_info_list=None):
 
421
        from bzrlib.branch import find_branch
 
422
 
 
423
        revs = []
 
424
        if revision is not None:
 
425
            revs.extend(revision)
 
426
        if revision_info_list is not None:
 
427
            revs.extend(revision_info_list)
 
428
        if len(revs) == 0:
 
429
            raise BzrCommandError('You must supply a revision identifier')
 
430
 
 
431
        b = find_branch('.')
 
432
 
 
433
        for rev in revs:
 
434
            print '%4d %s' % b.get_revision_info(rev)
374
435
 
375
436
    
376
437
class cmd_add(Command):
386
447
    whether already versioned or not, are searched for files or
387
448
    subdirectories that are neither versioned or ignored, and these
388
449
    are added.  This search proceeds recursively into versioned
389
 
    directories.
 
450
    directories.  If no names are given '.' is assumed.
390
451
 
391
 
    Therefore simply saying 'bzr add .' will version all files that
 
452
    Therefore simply saying 'bzr add' will version all files that
392
453
    are currently unknown.
393
454
 
394
455
    TODO: Perhaps adding a file whose directly is not versioned should
395
456
    recursively add that parent, rather than giving an error?
396
457
    """
397
 
    takes_args = ['file+']
 
458
    takes_args = ['file*']
398
459
    takes_options = ['verbose', 'no-recurse']
399
460
    
400
461
    def run(self, file_list, verbose=False, no_recurse=False):
401
 
        bzrlib.add.smart_add(file_list, verbose, not no_recurse)
 
462
        from bzrlib.add import smart_add
 
463
        smart_add(file_list, verbose, not no_recurse)
 
464
 
 
465
 
 
466
 
 
467
class cmd_mkdir(Command):
 
468
    """Create a new versioned directory.
 
469
 
 
470
    This is equivalent to creating the directory and then adding it.
 
471
    """
 
472
    takes_args = ['dir+']
 
473
 
 
474
    def run(self, dir_list):
 
475
        b = None
 
476
        
 
477
        for d in dir_list:
 
478
            os.mkdir(d)
 
479
            if not b:
 
480
                b = find_branch(d)
 
481
            b.add([d], verbose=True)
402
482
 
403
483
 
404
484
class cmd_relpath(Command):
407
487
    hidden = True
408
488
    
409
489
    def run(self, filename):
410
 
        print Branch(filename).relpath(filename)
 
490
        print find_branch(filename).relpath(filename)
411
491
 
412
492
 
413
493
 
416
496
    takes_options = ['revision', 'show-ids']
417
497
    
418
498
    def run(self, revision=None, show_ids=False):
419
 
        b = Branch('.')
 
499
        b = find_branch('.')
420
500
        if revision == None:
421
501
            inv = b.read_working_inventory()
422
502
        else:
423
 
            inv = b.get_revision_inventory(b.lookup_revision(revision))
 
503
            if len(revision) > 1:
 
504
                raise BzrCommandError('bzr inventory --revision takes'
 
505
                    ' exactly one revision identifier')
 
506
            inv = b.get_revision_inventory(b.lookup_revision(revision[0]))
424
507
 
425
508
        for path, entry in inv.entries():
426
509
            if show_ids:
439
522
    """
440
523
    takes_args = ['source$', 'dest']
441
524
    def run(self, source_list, dest):
442
 
        b = Branch('.')
 
525
        b = find_branch('.')
443
526
 
 
527
        # TODO: glob expansion on windows?
444
528
        b.move([b.relpath(s) for s in source_list], b.relpath(dest))
445
529
 
446
530
 
461
545
    takes_args = ['from_name', 'to_name']
462
546
    
463
547
    def run(self, from_name, to_name):
464
 
        b = Branch('.')
 
548
        b = find_branch('.')
465
549
        b.rename_one(b.relpath(from_name), b.relpath(to_name))
466
550
 
467
551
 
468
552
 
 
553
class cmd_mv(Command):
 
554
    """Move or rename a file.
 
555
 
 
556
    usage:
 
557
        bzr mv OLDNAME NEWNAME
 
558
        bzr mv SOURCE... DESTINATION
 
559
 
 
560
    If the last argument is a versioned directory, all the other names
 
561
    are moved into it.  Otherwise, there must be exactly two arguments
 
562
    and the file is changed to a new name, which must not already exist.
 
563
 
 
564
    Files cannot be moved between branches.
 
565
    """
 
566
    takes_args = ['names*']
 
567
    def run(self, names_list):
 
568
        if len(names_list) < 2:
 
569
            raise BzrCommandError("missing file argument")
 
570
        b = find_branch(names_list[0])
 
571
 
 
572
        rel_names = [b.relpath(x) for x in names_list]
 
573
        
 
574
        if os.path.isdir(names_list[-1]):
 
575
            # move into existing directory
 
576
            b.move(rel_names[:-1], rel_names[-1])
 
577
        else:
 
578
            if len(names_list) != 2:
 
579
                raise BzrCommandError('to mv multiple files the destination '
 
580
                                      'must be a versioned directory')
 
581
            b.move(rel_names[0], rel_names[1])
 
582
            
 
583
    
469
584
 
470
585
 
471
586
class cmd_pull(Command):
486
601
 
487
602
    def run(self, location=None):
488
603
        from bzrlib.merge import merge
 
604
        import tempfile
 
605
        from shutil import rmtree
489
606
        import errno
490
607
        
491
 
        br_to = Branch('.')
 
608
        br_to = find_branch('.')
492
609
        stored_loc = None
493
610
        try:
494
611
            stored_loc = br_to.controlfile("x-pull", "rb").read().rstrip('\n')
495
612
        except IOError, e:
496
 
            if errno == errno.ENOENT:
 
613
            if e.errno != errno.ENOENT:
497
614
                raise
498
615
        if location is None:
499
 
            location = stored_loc
500
 
        if location is None:
501
 
            raise BzrCommandError("No pull location known or specified.")
502
 
        from branch import find_branch, DivergedBranches
 
616
            if stored_loc is None:
 
617
                raise BzrCommandError("No pull location known or specified.")
 
618
            else:
 
619
                print "Using last location: %s" % stored_loc
 
620
                location = stored_loc
 
621
        cache_root = tempfile.mkdtemp()
 
622
        from bzrlib.branch import DivergedBranches
503
623
        br_from = find_branch(location)
504
624
        location = pull_loc(br_from)
505
625
        old_revno = br_to.revno()
506
626
        try:
507
 
            br_to.update_revisions(br_from)
508
 
        except DivergedBranches:
509
 
            raise BzrCommandError("These branches have diverged.  Try merge.")
510
 
            
511
 
        merge(('.', -1), ('.', old_revno), check_clean=False)
512
 
        if location != stored_loc:
513
 
            br_to.controlfile("x-pull", "wb").write(location + "\n")
 
627
            from branch import find_cached_branch, DivergedBranches
 
628
            br_from = find_cached_branch(location, cache_root)
 
629
            location = pull_loc(br_from)
 
630
            old_revno = br_to.revno()
 
631
            try:
 
632
                br_to.update_revisions(br_from)
 
633
            except DivergedBranches:
 
634
                raise BzrCommandError("These branches have diverged."
 
635
                    "  Try merge.")
 
636
                
 
637
            merge(('.', -1), ('.', old_revno), check_clean=False)
 
638
            if location != stored_loc:
 
639
                br_to.controlfile("x-pull", "wb").write(location + "\n")
 
640
        finally:
 
641
            rmtree(cache_root)
514
642
 
515
643
 
516
644
 
517
645
class cmd_branch(Command):
518
646
    """Create a new copy of a branch.
519
647
 
520
 
    If the TO_LOCATION is omitted, the last component of the
521
 
    FROM_LOCATION will be used.  In other words,
522
 
    "branch ../foo/bar" will attempt to create ./bar.
 
648
    If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
 
649
    be used.  In other words, "branch ../foo/bar" will attempt to create ./bar.
 
650
 
 
651
    To retrieve the branch as of a particular revision, supply the --revision
 
652
    parameter, as in "branch foo/bar -r 5".
523
653
    """
524
654
    takes_args = ['from_location', 'to_location?']
 
655
    takes_options = ['revision']
 
656
    aliases = ['get', 'clone']
525
657
 
526
 
    def run(self, from_location, to_location=None):
 
658
    def run(self, from_location, to_location=None, revision=None):
527
659
        import errno
528
660
        from bzrlib.merge import merge
529
 
        
530
 
        if to_location is None:
531
 
            to_location = os.path.basename(from_location)
532
 
            # FIXME: If there's a trailing slash, keep removing them
533
 
            # until we find the right bit
534
 
 
535
 
        try:
536
 
            os.mkdir(to_location)
537
 
        except OSError, e:
538
 
            if e.errno == errno.EEXIST:
539
 
                raise BzrCommandError('Target directory "%s" already exists.' %
540
 
                                      to_location)
541
 
            if e.errno == errno.ENOENT:
542
 
                raise BzrCommandError('Parent of "%s" does not exist.' %
543
 
                                      to_location)
544
 
            else:
545
 
                raise
546
 
        br_to = Branch(to_location, init=True)
547
 
        from branch import find_branch, DivergedBranches
548
 
        try:
549
 
            br_from = find_branch(from_location)
550
 
        except OSError, e:
551
 
            if e.errno == errno.ENOENT:
552
 
                raise BzrCommandError('Source location "%s" does not exist.' %
553
 
                                      to_location)
554
 
            else:
555
 
                raise
556
 
 
557
 
        from_location = pull_loc(br_from)
558
 
        br_to.update_revisions(br_from)
559
 
        merge((to_location, -1), (to_location, 0), this_dir=to_location,
560
 
              check_clean=False)
561
 
        br_to.controlfile("x-pull", "wb").write(from_location + "\n")
 
661
        from bzrlib.branch import DivergedBranches, \
 
662
             find_cached_branch, Branch
 
663
        from shutil import rmtree
 
664
        from meta_store import CachedStore
 
665
        import tempfile
 
666
        cache_root = tempfile.mkdtemp()
 
667
 
 
668
        if revision is None:
 
669
            revision = [None]
 
670
        elif len(revision) > 1:
 
671
            raise BzrCommandError('bzr branch --revision takes exactly 1 revision value')
 
672
 
 
673
        try:
 
674
            try:
 
675
                br_from = find_cached_branch(from_location, cache_root)
 
676
            except OSError, e:
 
677
                if e.errno == errno.ENOENT:
 
678
                    raise BzrCommandError('Source location "%s" does not'
 
679
                                          ' exist.' % to_location)
 
680
                else:
 
681
                    raise
 
682
 
 
683
            if to_location is None:
 
684
                to_location = os.path.basename(from_location.rstrip("/\\"))
 
685
 
 
686
            try:
 
687
                os.mkdir(to_location)
 
688
            except OSError, e:
 
689
                if e.errno == errno.EEXIST:
 
690
                    raise BzrCommandError('Target directory "%s" already'
 
691
                                          ' exists.' % to_location)
 
692
                if e.errno == errno.ENOENT:
 
693
                    raise BzrCommandError('Parent of "%s" does not exist.' %
 
694
                                          to_location)
 
695
                else:
 
696
                    raise
 
697
            br_to = Branch(to_location, init=True)
 
698
 
 
699
            br_to.set_root_id(br_from.get_root_id())
 
700
 
 
701
            if revision:
 
702
                if revision[0] is None:
 
703
                    revno = br_from.revno()
 
704
                else:
 
705
                    revno, rev_id = br_from.get_revision_info(revision[0])
 
706
                try:
 
707
                    br_to.update_revisions(br_from, stop_revision=revno)
 
708
                except bzrlib.errors.NoSuchRevision:
 
709
                    rmtree(to_location)
 
710
                    msg = "The branch %s has no revision %d." % (from_location,
 
711
                                                                 revno)
 
712
                    raise BzrCommandError(msg)
 
713
            
 
714
            merge((to_location, -1), (to_location, 0), this_dir=to_location,
 
715
                  check_clean=False, ignore_zero=True)
 
716
            from_location = pull_loc(br_from)
 
717
            br_to.controlfile("x-pull", "wb").write(from_location + "\n")
 
718
        finally:
 
719
            rmtree(cache_root)
562
720
 
563
721
 
564
722
def pull_loc(branch):
581
739
    takes_args = ['dir?']
582
740
 
583
741
    def run(self, dir='.'):
584
 
        b = Branch(dir)
 
742
        b = find_branch(dir)
585
743
        old_inv = b.basis_tree().inventory
586
744
        new_inv = b.read_working_inventory()
587
745
 
598
756
    def run(self, branch=None):
599
757
        import info
600
758
 
601
 
        from branch import find_branch
602
759
        b = find_branch(branch)
603
760
        info.show_info(b)
604
761
 
613
770
    takes_options = ['verbose']
614
771
    
615
772
    def run(self, file_list, verbose=False):
616
 
        b = Branch(file_list[0])
 
773
        b = find_branch(file_list[0])
617
774
        b.remove([b.relpath(f) for f in file_list], verbose=verbose)
618
775
 
619
776
 
627
784
    hidden = True
628
785
    takes_args = ['filename']
629
786
    def run(self, filename):
630
 
        b = Branch(filename)
 
787
        b = find_branch(filename)
631
788
        i = b.inventory.path2id(b.relpath(filename))
632
789
        if i == None:
633
 
            bailout("%r is not a versioned file" % filename)
 
790
            raise BzrError("%r is not a versioned file" % filename)
634
791
        else:
635
792
            print i
636
793
 
643
800
    hidden = True
644
801
    takes_args = ['filename']
645
802
    def run(self, filename):
646
 
        b = Branch(filename)
 
803
        b = find_branch(filename)
647
804
        inv = b.inventory
648
805
        fid = inv.path2id(b.relpath(filename))
649
806
        if fid == None:
650
 
            bailout("%r is not a versioned file" % filename)
 
807
            raise BzrError("%r is not a versioned file" % filename)
651
808
        for fip in inv.get_idpath(fid):
652
809
            print fip
653
810
 
656
813
    """Display list of revision ids on this branch."""
657
814
    hidden = True
658
815
    def run(self):
659
 
        for patchid in Branch('.').revision_history():
 
816
        for patchid in find_branch('.').revision_history():
660
817
            print patchid
661
818
 
662
819
 
663
820
class cmd_directories(Command):
664
821
    """Display list of versioned directories in this branch."""
665
822
    def run(self):
666
 
        for name, ie in Branch('.').read_working_inventory().directories():
 
823
        for name, ie in find_branch('.').read_working_inventory().directories():
667
824
            if name == '':
668
825
                print '.'
669
826
            else:
684
841
        bzr commit -m 'imported project'
685
842
    """
686
843
    def run(self):
 
844
        from bzrlib.branch import Branch
687
845
        Branch('.', init=True)
688
846
 
689
847
 
693
851
    If files are listed, only the changes in those files are listed.
694
852
    Otherwise, all changes for the tree are listed.
695
853
 
696
 
    TODO: Given two revision arguments, show the difference between them.
697
 
 
698
854
    TODO: Allow diff across branches.
699
855
 
700
856
    TODO: Option to use external diff command; could be GNU diff, wdiff,
709
865
          deleted files.
710
866
 
711
867
    TODO: This probably handles non-Unix newlines poorly.
 
868
 
 
869
    examples:
 
870
        bzr diff
 
871
        bzr diff -r1
 
872
        bzr diff -r1:2
712
873
    """
713
874
    
714
875
    takes_args = ['file*']
717
878
 
718
879
    def run(self, revision=None, file_list=None, diff_options=None):
719
880
        from bzrlib.diff import show_diff
720
 
        from bzrlib import find_branch
721
881
 
722
882
        if file_list:
723
883
            b = find_branch(file_list[0])
726
886
                # just pointing to top-of-tree
727
887
                file_list = None
728
888
        else:
729
 
            b = Branch('.')
730
 
    
731
 
        show_diff(b, revision, specific_files=file_list,
732
 
                  external_diff_options=diff_options)
 
889
            b = find_branch('.')
733
890
 
 
891
        if revision is not None:
 
892
            if len(revision) == 1:
 
893
                show_diff(b, revision[0], specific_files=file_list,
 
894
                          external_diff_options=diff_options)
 
895
            elif len(revision) == 2:
 
896
                show_diff(b, revision[0], specific_files=file_list,
 
897
                          external_diff_options=diff_options,
 
898
                          revision2=revision[1])
 
899
            else:
 
900
                raise BzrCommandError('bzr diff --revision takes exactly one or two revision identifiers')
 
901
        else:
 
902
            show_diff(b, None, specific_files=file_list,
 
903
                      external_diff_options=diff_options)
734
904
 
735
905
        
736
906
 
741
911
    TODO: Show files deleted since a previous revision, or between two revisions.
742
912
    """
743
913
    def run(self, show_ids=False):
744
 
        b = Branch('.')
 
914
        b = find_branch('.')
745
915
        old = b.basis_tree()
746
916
        new = b.working_tree()
747
917
 
762
932
    """List files modified in working tree."""
763
933
    hidden = True
764
934
    def run(self):
765
 
        import statcache
766
 
        b = Branch('.')
767
 
        inv = b.read_working_inventory()
768
 
        sc = statcache.update_cache(b, inv)
769
 
        basis = b.basis_tree()
770
 
        basis_inv = basis.inventory
771
 
        
772
 
        # We used to do this through iter_entries(), but that's slow
773
 
        # when most of the files are unmodified, as is usually the
774
 
        # case.  So instead we iterate by inventory entry, and only
775
 
        # calculate paths as necessary.
776
 
 
777
 
        for file_id in basis_inv:
778
 
            cacheentry = sc.get(file_id)
779
 
            if not cacheentry:                 # deleted
780
 
                continue
781
 
            ie = basis_inv[file_id]
782
 
            if cacheentry[statcache.SC_SHA1] != ie.text_sha1:
783
 
                path = inv.id2path(file_id)
784
 
                print path
 
935
        from bzrlib.delta import compare_trees
 
936
 
 
937
        b = find_branch('.')
 
938
        td = compare_trees(b.basis_tree(), b.working_tree())
 
939
 
 
940
        for path, id, kind in td.modified:
 
941
            print path
785
942
 
786
943
 
787
944
 
789
946
    """List files added in working tree."""
790
947
    hidden = True
791
948
    def run(self):
792
 
        b = Branch('.')
 
949
        b = find_branch('.')
793
950
        wt = b.working_tree()
794
951
        basis_inv = b.basis_tree().inventory
795
952
        inv = wt.inventory
811
968
    takes_args = ['filename?']
812
969
    def run(self, filename=None):
813
970
        """Print the branch root."""
814
 
        from branch import find_branch
815
971
        b = find_branch(filename)
816
972
        print getattr(b, 'base', None) or getattr(b, 'baseurl')
817
973
 
823
979
    -r revision requests a specific revision, -r :end or -r begin: are
824
980
    also valid.
825
981
 
 
982
    --message allows you to give a regular expression, which will be evaluated
 
983
    so that only matching entries will be displayed.
 
984
 
826
985
    TODO: Make --revision support uuid: and hash: [future tag:] notation.
827
986
  
828
987
    """
829
988
 
830
989
    takes_args = ['filename?']
831
 
    takes_options = ['forward', 'timezone', 'verbose', 'show-ids', 'revision']
 
990
    takes_options = ['forward', 'timezone', 'verbose', 'show-ids', 'revision',
 
991
                     'long', 'message', 'short',]
832
992
    
833
993
    def run(self, filename=None, timezone='original',
834
994
            verbose=False,
835
995
            show_ids=False,
836
996
            forward=False,
837
 
            revision=None):
838
 
        from bzrlib import show_log, find_branch
 
997
            revision=None,
 
998
            message=None,
 
999
            long=False,
 
1000
            short=False):
 
1001
        from bzrlib.branch import find_branch
 
1002
        from bzrlib.log import log_formatter, show_log
839
1003
        import codecs
840
1004
 
841
1005
        direction = (forward and 'forward') or 'reverse'
851
1015
            b = find_branch('.')
852
1016
            file_id = None
853
1017
 
854
 
        if revision == None:
855
 
            revision = [None, None]
856
 
        elif isinstance(revision, int):
857
 
            revision = [revision, revision]
 
1018
        if revision is None:
 
1019
            rev1 = None
 
1020
            rev2 = None
 
1021
        elif len(revision) == 1:
 
1022
            rev1 = rev2 = b.get_revision_info(revision[0])[0]
 
1023
        elif len(revision) == 2:
 
1024
            rev1 = b.get_revision_info(revision[0])[0]
 
1025
            rev2 = b.get_revision_info(revision[1])[0]
858
1026
        else:
859
 
            # pair of revisions?
860
 
            pass
861
 
            
862
 
        assert len(revision) == 2
 
1027
            raise BzrCommandError('bzr log --revision takes one or two values.')
 
1028
 
 
1029
        if rev1 == 0:
 
1030
            rev1 = None
 
1031
        if rev2 == 0:
 
1032
            rev2 = None
863
1033
 
864
1034
        mutter('encoding log as %r' % bzrlib.user_encoding)
865
1035
 
867
1037
        # in e.g. the default C locale.
868
1038
        outf = codecs.getwriter(bzrlib.user_encoding)(sys.stdout, errors='replace')
869
1039
 
870
 
        show_log(b, file_id,
871
 
                 show_timezone=timezone,
 
1040
        if not short:
 
1041
            log_format = 'long'
 
1042
        else:
 
1043
            log_format = 'short'
 
1044
        lf = log_formatter(log_format,
 
1045
                           show_ids=show_ids,
 
1046
                           to_file=outf,
 
1047
                           show_timezone=timezone)
 
1048
 
 
1049
        show_log(b,
 
1050
                 lf,
 
1051
                 file_id,
872
1052
                 verbose=verbose,
873
 
                 show_ids=show_ids,
874
 
                 to_file=outf,
875
1053
                 direction=direction,
876
 
                 start_revision=revision[0],
877
 
                 end_revision=revision[1])
 
1054
                 start_revision=rev1,
 
1055
                 end_revision=rev2,
 
1056
                 search=message)
878
1057
 
879
1058
 
880
1059
 
885
1064
    hidden = True
886
1065
    takes_args = ["filename"]
887
1066
    def run(self, filename):
888
 
        b = Branch(filename)
 
1067
        b = find_branch(filename)
889
1068
        inv = b.read_working_inventory()
890
1069
        file_id = inv.path2id(b.relpath(filename))
891
1070
        for revno, revision_id, what in bzrlib.log.find_touching_revisions(b, file_id):
899
1078
    """
900
1079
    hidden = True
901
1080
    def run(self, revision=None, verbose=False):
902
 
        b = Branch('.')
 
1081
        b = find_branch('.')
903
1082
        if revision == None:
904
1083
            tree = b.working_tree()
905
1084
        else:
923
1102
class cmd_unknowns(Command):
924
1103
    """List unknown files."""
925
1104
    def run(self):
926
 
        for f in Branch('.').unknowns():
 
1105
        from bzrlib.osutils import quotefn
 
1106
        for f in find_branch('.').unknowns():
927
1107
            print quotefn(f)
928
1108
 
929
1109
 
951
1131
        from bzrlib.atomicfile import AtomicFile
952
1132
        import os.path
953
1133
 
954
 
        b = Branch('.')
 
1134
        b = find_branch('.')
955
1135
        ifn = b.abspath('.bzrignore')
956
1136
 
957
1137
        if os.path.exists(ifn):
991
1171
 
992
1172
    See also: bzr ignore"""
993
1173
    def run(self):
994
 
        tree = Branch('.').working_tree()
 
1174
        tree = find_branch('.').working_tree()
995
1175
        for path, file_class, kind, file_id in tree.list_files():
996
1176
            if file_class != 'I':
997
1177
                continue
1015
1195
        except ValueError:
1016
1196
            raise BzrCommandError("not a valid revision-number: %r" % revno)
1017
1197
 
1018
 
        print Branch('.').lookup_revision(revno)
 
1198
        print find_branch('.').lookup_revision(revno)
1019
1199
 
1020
1200
 
1021
1201
class cmd_export(Command):
1022
1202
    """Export past revision to destination directory.
1023
1203
 
1024
 
    If no revision is specified this exports the last committed revision."""
 
1204
    If no revision is specified this exports the last committed revision.
 
1205
 
 
1206
    Format may be an "exporter" name, such as tar, tgz, tbz2.  If none is
 
1207
    given, try to find the format with the extension. If no extension
 
1208
    is found exports to a directory (equivalent to --format=dir).
 
1209
 
 
1210
    Root may be the top directory for tar, tgz and tbz2 formats. If none
 
1211
    is given, the top directory will be the root name of the file."""
 
1212
    # TODO: list known exporters
1025
1213
    takes_args = ['dest']
1026
 
    takes_options = ['revision']
1027
 
    def run(self, dest, revision=None):
1028
 
        b = Branch('.')
1029
 
        if revision == None:
1030
 
            rh = b.revision_history()[-1]
 
1214
    takes_options = ['revision', 'format', 'root']
 
1215
    def run(self, dest, revision=None, format=None, root=None):
 
1216
        import os.path
 
1217
        b = find_branch('.')
 
1218
        if revision is None:
 
1219
            rev_id = b.last_patch()
1031
1220
        else:
1032
 
            rh = b.lookup_revision(int(revision))
1033
 
        t = b.revision_tree(rh)
1034
 
        t.export(dest)
 
1221
            if len(revision) != 1:
 
1222
                raise BzrError('bzr export --revision takes exactly 1 argument')
 
1223
            revno, rev_id = b.get_revision_info(revision[0])
 
1224
        t = b.revision_tree(rev_id)
 
1225
        root, ext = os.path.splitext(dest)
 
1226
        if not format:
 
1227
            if ext in (".tar",):
 
1228
                format = "tar"
 
1229
            elif ext in (".gz", ".tgz"):
 
1230
                format = "tgz"
 
1231
            elif ext in (".bz2", ".tbz2"):
 
1232
                format = "tbz2"
 
1233
            else:
 
1234
                format = "dir"
 
1235
        t.export(dest, format, root)
1035
1236
 
1036
1237
 
1037
1238
class cmd_cat(Command):
1043
1244
    def run(self, filename, revision=None):
1044
1245
        if revision == None:
1045
1246
            raise BzrCommandError("bzr cat requires a revision number")
1046
 
        b = Branch('.')
1047
 
        b.print_file(b.relpath(filename), int(revision))
 
1247
        elif len(revision) != 1:
 
1248
            raise BzrCommandError("bzr cat --revision takes exactly one number")
 
1249
        b = find_branch('.')
 
1250
        b.print_file(b.relpath(filename), revision[0])
1048
1251
 
1049
1252
 
1050
1253
class cmd_local_time_offset(Command):
1057
1260
 
1058
1261
class cmd_commit(Command):
1059
1262
    """Commit changes into a new revision.
 
1263
    
 
1264
    If no arguments are given, the entire tree is committed.
1060
1265
 
1061
1266
    If selected files are specified, only changes to those files are
1062
 
    committed.  If a directory is specified then its contents are also
1063
 
    committed.
 
1267
    committed.  If a directory is specified then the directory and everything 
 
1268
    within it is committed.
1064
1269
 
1065
1270
    A selected-file commit may fail in some cases where the committed
1066
1271
    tree would be invalid, such as trying to commit a file in a
1071
1276
    TODO: Strict commit that fails if there are unknown or deleted files.
1072
1277
    """
1073
1278
    takes_args = ['selected*']
1074
 
    takes_options = ['message', 'file', 'verbose']
 
1279
    takes_options = ['message', 'file', 'verbose', 'unchanged']
1075
1280
    aliases = ['ci', 'checkin']
1076
1281
 
1077
 
    def run(self, message=None, file=None, verbose=True, selected_list=None):
1078
 
        from bzrlib.commit import commit
 
1282
    # TODO: Give better message for -s, --summary, used by tla people
 
1283
    
 
1284
    def run(self, message=None, file=None, verbose=True, selected_list=None,
 
1285
            unchanged=False):
 
1286
        from bzrlib.errors import PointlessCommit
 
1287
        from bzrlib.osutils import get_text_message
1079
1288
 
1080
1289
        ## Warning: shadows builtin file()
1081
1290
        if not message and not file:
1082
 
            raise BzrCommandError("please specify a commit message",
1083
 
                                  ["use either --message or --file"])
 
1291
            # FIXME: Ugly; change status code to send to a provided function?
 
1292
            
 
1293
            import cStringIO
 
1294
            stdout = sys.stdout
 
1295
            catcher = cStringIO.StringIO()
 
1296
            sys.stdout = catcher
 
1297
            cmd_status({"file_list":selected_list}, {})
 
1298
            info = catcher.getvalue()
 
1299
            sys.stdout = stdout
 
1300
            message = get_text_message(info)
 
1301
            
 
1302
            if message is None:
 
1303
                raise BzrCommandError("please specify a commit message",
 
1304
                                      ["use either --message or --file"])
1084
1305
        elif message and file:
1085
1306
            raise BzrCommandError("please specify either --message or --file")
1086
1307
        
1088
1309
            import codecs
1089
1310
            message = codecs.open(file, 'rt', bzrlib.user_encoding).read()
1090
1311
 
1091
 
        b = Branch('.')
1092
 
        commit(b, message, verbose=verbose, specific_files=selected_list)
 
1312
        b = find_branch('.')
 
1313
        if selected_list:
 
1314
            selected_list = [b.relpath(s) for s in selected_list]
 
1315
            
 
1316
        try:
 
1317
            b.commit(message, verbose=verbose,
 
1318
                     specific_files=selected_list,
 
1319
                     allow_pointless=unchanged)
 
1320
        except PointlessCommit:
 
1321
            # FIXME: This should really happen before the file is read in;
 
1322
            # perhaps prepare the commit; get the message; then actually commit
 
1323
            raise BzrCommandError("no changes to commit",
 
1324
                                  ["use --unchanged to commit anyhow"])
1093
1325
 
1094
1326
 
1095
1327
class cmd_check(Command):
1097
1329
 
1098
1330
    This command checks various invariants about the branch storage to
1099
1331
    detect data corruption or bzr bugs.
1100
 
    """
1101
 
    takes_args = ['dir?']
1102
 
    def run(self, dir='.'):
1103
 
        import bzrlib.check
1104
 
        bzrlib.check.check(Branch(dir))
 
1332
 
 
1333
    If given the --update flag, it will update some optional fields
 
1334
    to help ensure data consistency.
 
1335
    """
 
1336
    takes_args = ['dir?']
 
1337
 
 
1338
    def run(self, dir='.'):
 
1339
        from bzrlib.check import check
 
1340
        check(find_branch(dir))
 
1341
 
 
1342
 
 
1343
 
 
1344
class cmd_scan_cache(Command):
 
1345
    hidden = True
 
1346
    def run(self):
 
1347
        from bzrlib.hashcache import HashCache
 
1348
        import os
 
1349
 
 
1350
        c = HashCache('.')
 
1351
        c.read()
 
1352
        c.scan()
 
1353
            
 
1354
        print '%6d stats' % c.stat_count
 
1355
        print '%6d in hashcache' % len(c._cache)
 
1356
        print '%6d files removed from cache' % c.removed_count
 
1357
        print '%6d hashes updated' % c.update_count
 
1358
        print '%6d files changed too recently to cache' % c.danger_count
 
1359
 
 
1360
        if c.needs_write:
 
1361
            c.write()
 
1362
            
 
1363
 
 
1364
 
 
1365
class cmd_upgrade(Command):
 
1366
    """Upgrade branch storage to current format.
 
1367
 
 
1368
    This should normally be used only after the check command tells
 
1369
    you to run it.
 
1370
    """
 
1371
    takes_args = ['dir?']
 
1372
 
 
1373
    def run(self, dir='.'):
 
1374
        from bzrlib.upgrade import upgrade
 
1375
        upgrade(find_branch(dir))
1105
1376
 
1106
1377
 
1107
1378
 
1119
1390
class cmd_selftest(Command):
1120
1391
    """Run internal test suite"""
1121
1392
    hidden = True
1122
 
    def run(self):
 
1393
    takes_options = ['verbose']
 
1394
    def run(self, verbose=False):
1123
1395
        from bzrlib.selftest import selftest
1124
 
        if selftest():
1125
 
            return 0
1126
 
        else:
1127
 
            return 1
1128
 
 
 
1396
        return int(not selftest(verbose=verbose))
1129
1397
 
1130
1398
 
1131
1399
class cmd_version(Command):
1163
1431
    ['..', -1]
1164
1432
    >>> parse_spec("../f/@35")
1165
1433
    ['../f', 35]
 
1434
    >>> parse_spec('./@revid:john@arbash-meinel.com-20050711044610-3ca0327c6a222f67')
 
1435
    ['.', 'revid:john@arbash-meinel.com-20050711044610-3ca0327c6a222f67']
1166
1436
    """
1167
1437
    if spec is None:
1168
1438
        return [None, None]
1172
1442
        if parsed[1] == "":
1173
1443
            parsed[1] = -1
1174
1444
        else:
1175
 
            parsed[1] = int(parsed[1])
1176
 
            assert parsed[1] >=0
 
1445
            try:
 
1446
                parsed[1] = int(parsed[1])
 
1447
            except ValueError:
 
1448
                pass # We can allow stuff like ./@revid:blahblahblah
 
1449
            else:
 
1450
                assert parsed[1] >=0
1177
1451
    else:
1178
1452
        parsed = [spec, None]
1179
1453
    return parsed
1181
1455
 
1182
1456
 
1183
1457
class cmd_merge(Command):
1184
 
    """Perform a three-way merge of trees.
1185
 
    
1186
 
    The SPEC parameters are working tree or revision specifiers.  Working trees
1187
 
    are specified using standard paths or urls.  No component of a directory
1188
 
    path may begin with '@'.
1189
 
    
1190
 
    Working tree examples: '.', '..', 'foo@', but NOT 'foo/@bar'
1191
 
 
1192
 
    Revisions are specified using a dirname/@revno pair, where dirname is the
1193
 
    branch directory and revno is the revision within that branch.  If no revno
1194
 
    is specified, the latest revision is used.
1195
 
 
1196
 
    Revision examples: './@127', 'foo/@', '../@1'
1197
 
 
1198
 
    The OTHER_SPEC parameter is required.  If the BASE_SPEC parameter is
1199
 
    not supplied, the common ancestor of OTHER_SPEC the current branch is used
1200
 
    as the BASE.
1201
 
 
 
1458
    """Perform a three-way merge.
 
1459
    
 
1460
    The branch is the branch you will merge from.  By default, it will merge
 
1461
    the latest revision.  If you specify a revision, that revision will be
 
1462
    merged.  If you specify two revisions, the first will be used as a BASE, 
 
1463
    and the second one as OTHER.  Revision numbers are always relative to the
 
1464
    specified branch.
 
1465
    
 
1466
    Examples:
 
1467
 
 
1468
    To merge the latest revision from bzr.dev
 
1469
    bzr merge ../bzr.dev
 
1470
 
 
1471
    To merge changes up to and including revision 82 from bzr.dev
 
1472
    bzr merge -r 82 ../bzr.dev
 
1473
 
 
1474
    To merge the changes introduced by 82, without previous changes:
 
1475
    bzr merge -r 81..82 ../bzr.dev
 
1476
    
1202
1477
    merge refuses to run if there are any uncommitted changes, unless
1203
1478
    --force is given.
1204
1479
    """
1205
 
    takes_args = ['other_spec', 'base_spec?']
1206
 
    takes_options = ['force']
 
1480
    takes_args = ['branch?']
 
1481
    takes_options = ['revision', 'force', 'merge-type']
1207
1482
 
1208
 
    def run(self, other_spec, base_spec=None, force=False):
 
1483
    def run(self, branch='.', revision=None, force=False, 
 
1484
            merge_type=None):
1209
1485
        from bzrlib.merge import merge
1210
 
        merge(parse_spec(other_spec), parse_spec(base_spec),
1211
 
              check_clean=(not force))
 
1486
        from bzrlib.merge_core import ApplyMerge3
 
1487
        if merge_type is None:
 
1488
            merge_type = ApplyMerge3
 
1489
 
 
1490
        if revision is None or len(revision) < 1:
 
1491
            base = [None, None]
 
1492
            other = (branch, -1)
 
1493
        else:
 
1494
            if len(revision) == 1:
 
1495
                other = (branch, revision[0])
 
1496
                base = (None, None)
 
1497
            else:
 
1498
                assert len(revision) == 2
 
1499
                if None in revision:
 
1500
                    raise BzrCommandError(
 
1501
                        "Merge doesn't permit that revision specifier.")
 
1502
                base = (branch, revision[0])
 
1503
                other = (branch, revision[1])
 
1504
            
 
1505
        merge(other, base, check_clean=(not force), merge_type=merge_type)
1212
1506
 
1213
1507
 
1214
1508
class cmd_revert(Command):
1215
1509
    """Reverse all changes since the last commit.
1216
1510
 
1217
 
    Only versioned files are affected.
1218
 
 
1219
 
    TODO: Store backups of any files that will be reverted, so
1220
 
          that the revert can be undone.          
 
1511
    Only versioned files are affected.  Specify filenames to revert only 
 
1512
    those files.  By default, any files that are changed will be backed up
 
1513
    first.  Backup files have a '~' appended to their name.
1221
1514
    """
1222
 
    takes_options = ['revision']
 
1515
    takes_options = ['revision', 'no-backup']
 
1516
    takes_args = ['file*']
 
1517
    aliases = ['merge-revert']
1223
1518
 
1224
 
    def run(self, revision=-1):
 
1519
    def run(self, revision=None, no_backup=False, file_list=None):
1225
1520
        from bzrlib.merge import merge
1226
 
        merge(('.', revision), parse_spec('.'),
 
1521
        from bzrlib.branch import Branch
 
1522
        if file_list is not None:
 
1523
            if len(file_list) == 0:
 
1524
                raise BzrCommandError("No files specified")
 
1525
        if revision is None:
 
1526
            revision = [-1]
 
1527
        elif len(revision) != 1:
 
1528
            raise BzrCommandError('bzr revert --revision takes exactly 1 argument')
 
1529
        merge(('.', revision[0]), parse_spec('.'),
1227
1530
              check_clean=False,
1228
 
              ignore_zero=True)
 
1531
              ignore_zero=True,
 
1532
              backup_files=not no_backup,
 
1533
              file_list=file_list)
 
1534
        if not file_list:
 
1535
            Branch('.').set_pending_merges([])
1229
1536
 
1230
1537
 
1231
1538
class cmd_assert_fail(Command):
1247
1554
        help.help(topic)
1248
1555
 
1249
1556
 
1250
 
class cmd_update_stat_cache(Command):
1251
 
    """Update stat-cache mapping inodes to SHA-1 hashes.
1252
 
 
1253
 
    For testing only."""
 
1557
 
 
1558
 
 
1559
class cmd_missing(Command):
 
1560
    """What is missing in this branch relative to other branch.
 
1561
    """
 
1562
    takes_args = ['remote?']
 
1563
    aliases = ['mis', 'miss']
 
1564
    # We don't have to add quiet to the list, because 
 
1565
    # unknown options are parsed as booleans
 
1566
    takes_options = ['verbose', 'quiet']
 
1567
 
 
1568
    def run(self, remote=None, verbose=False, quiet=False):
 
1569
        from bzrlib.branch import find_branch, DivergedBranches
 
1570
        from bzrlib.errors import BzrCommandError
 
1571
        from bzrlib.missing import get_parent, show_missing
 
1572
 
 
1573
        if verbose and quiet:
 
1574
            raise BzrCommandError('Cannot pass both quiet and verbose')
 
1575
 
 
1576
        b = find_branch('.')
 
1577
        parent = get_parent(b)
 
1578
        if remote is None:
 
1579
            if parent is None:
 
1580
                raise BzrCommandError("No missing location known or specified.")
 
1581
            else:
 
1582
                if not quiet:
 
1583
                    print "Using last location: %s" % parent
 
1584
                remote = parent
 
1585
        elif parent is None:
 
1586
            # We only update x-pull if it did not exist, missing should not change the parent
 
1587
            b.controlfile('x-pull', 'wb').write(remote + '\n')
 
1588
        br_remote = find_branch(remote)
 
1589
 
 
1590
        return show_missing(b, br_remote, verbose=verbose, quiet=quiet)
 
1591
 
 
1592
 
 
1593
class cmd_plugins(Command):
 
1594
    """List plugins"""
1254
1595
    hidden = True
1255
1596
    def run(self):
1256
 
        import statcache
1257
 
        b = Branch('.')
1258
 
        statcache.update_cache(b.base, b.read_working_inventory())
 
1597
        import bzrlib.plugin
 
1598
        from inspect import getdoc
 
1599
        from pprint import pprint
 
1600
        for plugin in bzrlib.plugin.all_plugins:
 
1601
            print plugin.__path__[0]
 
1602
            d = getdoc(plugin)
 
1603
            if d:
 
1604
                print '\t', d.split('\n')[0]
 
1605
 
 
1606
        #pprint(bzrlib.plugin.all_plugins)
1259
1607
 
1260
1608
 
1261
1609
 
1268
1616
    'help':                   None,
1269
1617
    'file':                   unicode,
1270
1618
    'force':                  None,
 
1619
    'format':                 unicode,
1271
1620
    'forward':                None,
1272
1621
    'message':                unicode,
1273
1622
    'no-recurse':             None,
1274
1623
    'profile':                None,
1275
1624
    'revision':               _parse_revision_str,
 
1625
    'short':                  None,
1276
1626
    'show-ids':               None,
1277
1627
    'timezone':               str,
1278
1628
    'verbose':                None,
1279
1629
    'version':                None,
1280
1630
    'email':                  None,
 
1631
    'unchanged':              None,
 
1632
    'update':                 None,
 
1633
    'long':                   None,
 
1634
    'root':                   str,
 
1635
    'no-backup':              None,
 
1636
    'merge-type':             get_merge_type,
1281
1637
    }
1282
1638
 
1283
1639
SHORT_OPTIONS = {
1286
1642
    'm':                      'message',
1287
1643
    'r':                      'revision',
1288
1644
    'v':                      'verbose',
 
1645
    'l':                      'long',
1289
1646
}
1290
1647
 
1291
1648
 
1305
1662
    (['status'], {'all': True})
1306
1663
    >>> parse_args('commit --message=biter'.split())
1307
1664
    (['commit'], {'message': u'biter'})
 
1665
    >>> parse_args('log -r 500'.split())
 
1666
    (['log'], {'revision': [500]})
 
1667
    >>> parse_args('log -r500..600'.split())
 
1668
    (['log'], {'revision': [500, 600]})
 
1669
    >>> parse_args('log -vr500..600'.split())
 
1670
    (['log'], {'verbose': True, 'revision': [500, 600]})
 
1671
    >>> parse_args('log -rv500..600'.split()) #the r takes an argument
 
1672
    (['log'], {'revision': ['v500', 600]})
1308
1673
    """
1309
1674
    args = []
1310
1675
    opts = {}
1324
1689
                else:
1325
1690
                    optname = a[2:]
1326
1691
                if optname not in OPTIONS:
1327
 
                    bailout('unknown long option %r' % a)
 
1692
                    raise BzrError('unknown long option %r' % a)
1328
1693
            else:
1329
1694
                shortopt = a[1:]
1330
 
                if shortopt not in SHORT_OPTIONS:
1331
 
                    bailout('unknown short option %r' % a)
1332
 
                optname = SHORT_OPTIONS[shortopt]
 
1695
                if shortopt in SHORT_OPTIONS:
 
1696
                    # Multi-character options must have a space to delimit
 
1697
                    # their value
 
1698
                    optname = SHORT_OPTIONS[shortopt]
 
1699
                else:
 
1700
                    # Single character short options, can be chained,
 
1701
                    # and have their value appended to their name
 
1702
                    shortopt = a[1:2]
 
1703
                    if shortopt not in SHORT_OPTIONS:
 
1704
                        # We didn't find the multi-character name, and we
 
1705
                        # didn't find the single char name
 
1706
                        raise BzrError('unknown short option %r' % a)
 
1707
                    optname = SHORT_OPTIONS[shortopt]
 
1708
 
 
1709
                    if a[2:]:
 
1710
                        # There are extra things on this option
 
1711
                        # see if it is the value, or if it is another
 
1712
                        # short option
 
1713
                        optargfn = OPTIONS[optname]
 
1714
                        if optargfn is None:
 
1715
                            # This option does not take an argument, so the
 
1716
                            # next entry is another short option, pack it back
 
1717
                            # into the list
 
1718
                            argv.insert(0, '-' + a[2:])
 
1719
                        else:
 
1720
                            # This option takes an argument, so pack it
 
1721
                            # into the array
 
1722
                            optarg = a[2:]
1333
1723
            
1334
1724
            if optname in opts:
1335
1725
                # XXX: Do we ever want to support this, e.g. for -r?
1336
 
                bailout('repeated option %r' % a)
 
1726
                raise BzrError('repeated option %r' % a)
1337
1727
                
1338
1728
            optargfn = OPTIONS[optname]
1339
1729
            if optargfn:
1340
1730
                if optarg == None:
1341
1731
                    if not argv:
1342
 
                        bailout('option %r needs an argument' % a)
 
1732
                        raise BzrError('option %r needs an argument' % a)
1343
1733
                    else:
1344
1734
                        optarg = argv.pop(0)
1345
1735
                opts[optname] = optargfn(optarg)
1346
1736
            else:
1347
1737
                if optarg != None:
1348
 
                    bailout('option %r takes no argument' % optname)
 
1738
                    raise BzrError('option %r takes no argument' % optname)
1349
1739
                opts[optname] = True
1350
1740
        else:
1351
1741
            args.append(a)
1405
1795
 
1406
1796
    This is similar to main(), but without all the trappings for
1407
1797
    logging and error handling.  
 
1798
    
 
1799
    argv
 
1800
       The command-line arguments, without the program name from argv[0]
 
1801
    
 
1802
    Returns a command status or raises an exception.
 
1803
 
 
1804
    Special master options: these must come before the command because
 
1805
    they control how the command is interpreted.
 
1806
 
 
1807
    --no-plugins
 
1808
        Do not load plugin modules at all
 
1809
 
 
1810
    --builtin
 
1811
        Only use builtin commands.  (Plugins are still allowed to change
 
1812
        other behaviour.)
 
1813
 
 
1814
    --profile
 
1815
        Run under the Python profiler.
1408
1816
    """
 
1817
    
1409
1818
    argv = [a.decode(bzrlib.user_encoding) for a in argv]
 
1819
 
 
1820
    opt_profile = opt_no_plugins = opt_builtin = False
 
1821
 
 
1822
    # --no-plugins is handled specially at a very early stage. We need
 
1823
    # to load plugins before doing other command parsing so that they
 
1824
    # can override commands, but this needs to happen first.
 
1825
 
 
1826
    for a in argv[:]:
 
1827
        if a == '--profile':
 
1828
            opt_profile = True
 
1829
        elif a == '--no-plugins':
 
1830
            opt_no_plugins = True
 
1831
        elif a == '--builtin':
 
1832
            opt_builtin = True
 
1833
        else:
 
1834
            break
 
1835
        argv.remove(a)
 
1836
 
 
1837
    if not opt_no_plugins:
 
1838
        from bzrlib.plugin import load_plugins
 
1839
        load_plugins()
 
1840
 
 
1841
    args, opts = parse_args(argv)
 
1842
 
 
1843
    if 'help' in opts:
 
1844
        from bzrlib.help import help
 
1845
        if args:
 
1846
            help(args[0])
 
1847
        else:
 
1848
            help()
 
1849
        return 0            
 
1850
        
 
1851
    if 'version' in opts:
 
1852
        show_version()
 
1853
        return 0
1410
1854
    
1411
 
    include_plugins=True
1412
 
    try:
1413
 
        args, opts = parse_args(argv[1:])
1414
 
        if 'help' in opts:
1415
 
            import help
1416
 
            if args:
1417
 
                help.help(args[0])
1418
 
            else:
1419
 
                help.help()
1420
 
            return 0
1421
 
        elif 'version' in opts:
1422
 
            show_version()
1423
 
            return 0
1424
 
        elif args and args[0] == 'builtin':
1425
 
            include_plugins=False
1426
 
            args = args[1:]
1427
 
        cmd = str(args.pop(0))
1428
 
    except IndexError:
1429
 
        import help
1430
 
        help.help()
 
1855
    if not args:
 
1856
        print >>sys.stderr, "please try 'bzr help' for help"
1431
1857
        return 1
1432
 
          
1433
 
 
1434
 
    canonical_cmd, cmd_class = get_cmd_class(cmd,include_plugins=include_plugins)
1435
 
 
1436
 
    # global option
1437
 
    if 'profile' in opts:
1438
 
        profile = True
1439
 
        del opts['profile']
1440
 
    else:
1441
 
        profile = False
 
1858
    
 
1859
    cmd = str(args.pop(0))
 
1860
 
 
1861
    canonical_cmd, cmd_class = \
 
1862
                   get_cmd_class(cmd, plugins_override=not opt_builtin)
1442
1863
 
1443
1864
    # check options are reasonable
1444
1865
    allowed = cmd_class.takes_options
1453
1874
    for k, v in opts.items():
1454
1875
        cmdopts[k.replace('-', '_')] = v
1455
1876
 
1456
 
    if profile:
 
1877
    if opt_profile:
1457
1878
        import hotshot, tempfile
1458
1879
        pffileno, pfname = tempfile.mkstemp()
1459
1880
        try:
1480
1901
 
1481
1902
def _report_exception(summary, quiet=False):
1482
1903
    import traceback
 
1904
    
1483
1905
    log_error('bzr: ' + summary)
1484
1906
    bzrlib.trace.log_exception()
1485
1907
 
 
1908
    if os.environ.get('BZR_DEBUG'):
 
1909
        traceback.print_exc()
 
1910
 
1486
1911
    if not quiet:
 
1912
        sys.stderr.write('\n')
1487
1913
        tb = sys.exc_info()[2]
1488
1914
        exinfo = traceback.extract_tb(tb)
1489
1915
        if exinfo:
1493
1919
 
1494
1920
 
1495
1921
def main(argv):
1496
 
    import errno
1497
1922
    
1498
 
    bzrlib.open_tracefile(argv)
 
1923
    bzrlib.trace.open_tracefile(argv)
1499
1924
 
1500
1925
    try:
1501
1926
        try:
1502
1927
            try:
1503
 
                return run_bzr(argv)
 
1928
                return run_bzr(argv[1:])
1504
1929
            finally:
1505
1930
                # do this here inside the exception wrappers to catch EPIPE
1506
1931
                sys.stdout.flush()
1507
1932
        except BzrError, e:
1508
1933
            quiet = isinstance(e, (BzrCommandError))
1509
 
            _report_exception('error: ' + e.args[0], quiet=quiet)
 
1934
            _report_exception('error: ' + str(e), quiet=quiet)
1510
1935
            if len(e.args) > 1:
1511
1936
                for h in e.args[1]:
1512
1937
                    # some explanation or hints
1522
1947
            _report_exception('interrupted', quiet=True)
1523
1948
            return 2
1524
1949
        except Exception, e:
 
1950
            import errno
1525
1951
            quiet = False
1526
1952
            if (isinstance(e, IOError) 
1527
1953
                and hasattr(e, 'errno')