~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/commands.py

  • Committer: Martin Pool
  • Date: 2005-07-22 19:54:37 UTC
  • Revision ID: mbp@sourcefrog.net-20050722195437-d7548eab2e4f75c1
doc

Show diffs side-by-side

added added

removed removed

Lines of Context:
19
19
import sys, os
20
20
 
21
21
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
 
22
from bzrlib.trace import mutter, note, log_error, warning
 
23
from bzrlib.errors import BzrError, BzrCheckError, BzrCommandError
 
24
from bzrlib.branch import find_branch
 
25
from bzrlib import BZRDIR
 
26
 
 
27
 
 
28
plugin_cmds = {}
 
29
 
 
30
 
 
31
def register_command(cmd):
 
32
    "Utility function to help register a command"
 
33
    global plugin_cmds
 
34
    k = cmd.__name__
 
35
    if k.startswith("cmd_"):
 
36
        k_unsquished = _unsquish_command_name(k)
 
37
    else:
 
38
        k_unsquished = k
 
39
    if not plugin_cmds.has_key(k_unsquished):
 
40
        plugin_cmds[k_unsquished] = cmd
 
41
    else:
 
42
        log_error('Two plugins defined the same command: %r' % k)
 
43
        log_error('Not loading the one in %r' % sys.modules[cmd.__module__])
27
44
 
28
45
 
29
46
def _squish_command_name(cmd):
34
51
    assert cmd.startswith("cmd_")
35
52
    return cmd[4:].replace('_','-')
36
53
 
 
54
 
37
55
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'             -> ?
 
56
    """This handles a revision string -> revno.
 
57
 
 
58
    This always returns a list.  The list will have one element for 
 
59
 
 
60
    It supports integers directly, but everything else it
 
61
    defers for passing to Branch.get_revision_info()
 
62
 
 
63
    >>> _parse_revision_str('234')
 
64
    [234]
 
65
    >>> _parse_revision_str('234..567')
 
66
    [234, 567]
 
67
    >>> _parse_revision_str('..')
 
68
    [None, None]
 
69
    >>> _parse_revision_str('..234')
 
70
    [None, 234]
 
71
    >>> _parse_revision_str('234..')
 
72
    [234, None]
 
73
    >>> _parse_revision_str('234..456..789') # Maybe this should be an error
 
74
    [234, 456, 789]
 
75
    >>> _parse_revision_str('234....789') # Error?
 
76
    [234, None, 789]
 
77
    >>> _parse_revision_str('revid:test@other.com-234234')
 
78
    ['revid:test@other.com-234234']
 
79
    >>> _parse_revision_str('revid:test@other.com-234234..revid:test@other.com-234235')
 
80
    ['revid:test@other.com-234234', 'revid:test@other.com-234235']
 
81
    >>> _parse_revision_str('revid:test@other.com-234234..23')
 
82
    ['revid:test@other.com-234234', 23]
 
83
    >>> _parse_revision_str('date:2005-04-12')
 
84
    ['date:2005-04-12']
 
85
    >>> _parse_revision_str('date:2005-04-12 12:24:33')
 
86
    ['date:2005-04-12 12:24:33']
 
87
    >>> _parse_revision_str('date:2005-04-12T12:24:33')
 
88
    ['date:2005-04-12T12:24:33']
 
89
    >>> _parse_revision_str('date:2005-04-12,12:24:33')
 
90
    ['date:2005-04-12,12:24:33']
 
91
    >>> _parse_revision_str('-5..23')
 
92
    [-5, 23]
 
93
    >>> _parse_revision_str('-5')
 
94
    [-5]
 
95
    >>> _parse_revision_str('123a')
 
96
    ['123a']
 
97
    >>> _parse_revision_str('abc')
 
98
    ['abc']
52
99
    """
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)
 
100
    import re
 
101
    old_format_re = re.compile('\d*:\d*')
 
102
    m = old_format_re.match(revstr)
 
103
    if m:
 
104
        warning('Colon separator for revision numbers is deprecated.'
 
105
                ' Use .. instead')
 
106
        revs = []
 
107
        for rev in revstr.split(':'):
 
108
            if rev:
 
109
                revs.append(int(rev))
 
110
            else:
 
111
                revs.append(None)
 
112
        return revs
 
113
    revs = []
 
114
    for x in revstr.split('..'):
 
115
        if not x:
 
116
            revs.append(None)
 
117
        else:
 
118
            try:
 
119
                revs.append(int(x))
 
120
            except ValueError:
 
121
                revs.append(x)
69
122
    return revs
70
123
 
71
 
def get_all_cmds():
72
 
    """Return canonical name and class for all registered commands."""
 
124
 
 
125
 
 
126
def _get_cmd_dict(plugins_override=True):
 
127
    d = {}
73
128
    for k, v in globals().iteritems():
74
129
        if k.startswith("cmd_"):
75
 
            yield _unsquish_command_name(k), v
76
 
 
77
 
def get_cmd_class(cmd):
 
130
            d[_unsquish_command_name(k)] = v
 
131
    # If we didn't load plugins, the plugin_cmds dict will be empty
 
132
    if plugins_override:
 
133
        d.update(plugin_cmds)
 
134
    else:
 
135
        d2 = plugin_cmds.copy()
 
136
        d2.update(d)
 
137
        d = d2
 
138
    return d
 
139
 
 
140
    
 
141
def get_all_cmds(plugins_override=True):
 
142
    """Return canonical name and class for all registered commands."""
 
143
    for k, v in _get_cmd_dict(plugins_override=plugins_override).iteritems():
 
144
        yield k,v
 
145
 
 
146
 
 
147
def get_cmd_class(cmd, plugins_override=True):
78
148
    """Return the canonical name and command class for a command.
79
149
    """
80
150
    cmd = str(cmd)                      # not unicode
81
151
 
82
152
    # first look up this command under the specified name
 
153
    cmds = _get_cmd_dict(plugins_override=plugins_override)
83
154
    try:
84
 
        return cmd, globals()[_squish_command_name(cmd)]
 
155
        return cmd, cmds[cmd]
85
156
    except KeyError:
86
157
        pass
87
158
 
88
159
    # look for any command which claims this as an alias
89
 
    for cmdname, cmdclass in get_all_cmds():
 
160
    for cmdname, cmdclass in cmds.iteritems():
90
161
        if cmd in cmdclass.aliases:
91
162
            return cmdname, cmdclass
92
163
 
165
236
        import os.path
166
237
        bzrpath = os.environ.get('BZRPATH', '')
167
238
 
168
 
        for dir in bzrpath.split(':'):
 
239
        for dir in bzrpath.split(os.pathsep):
169
240
            path = os.path.join(dir, cmd)
170
241
            if os.path.isfile(path):
171
242
                return ExternalCommand(path)
177
248
    def __init__(self, path):
178
249
        self.path = path
179
250
 
180
 
        # TODO: If either of these fail, we should detect that and
181
 
        # assume that path is not really a bzr plugin after all.
182
 
 
183
251
        pipe = os.popen('%s --bzr-usage' % path, 'r')
184
252
        self.takes_options = pipe.readline().split()
 
253
 
 
254
        for opt in self.takes_options:
 
255
            if not opt in OPTIONS:
 
256
                raise BzrError("Unknown option '%s' returned by external command %s"
 
257
                               % (opt, path))
 
258
 
 
259
        # TODO: Is there any way to check takes_args is valid here?
185
260
        self.takes_args = pipe.readline().split()
186
 
        pipe.close()
 
261
 
 
262
        if pipe.close() is not None:
 
263
            raise BzrError("Failed funning '%s --bzr-usage'" % path)
187
264
 
188
265
        pipe = os.popen('%s --bzr-help' % path, 'r')
189
266
        self.__doc__ = pipe.read()
190
 
        pipe.close()
 
267
        if pipe.close() is not None:
 
268
            raise BzrError("Failed funning '%s --bzr-help'" % path)
191
269
 
192
270
    def __call__(self, options, arguments):
193
271
        Command.__init__(self, options, arguments)
200
278
        keys = kargs.keys()
201
279
        keys.sort()
202
280
        for name in keys:
 
281
            optname = name.replace('_','-')
203
282
            value = kargs[name]
204
 
            if OPTIONS.has_key(name):
 
283
            if OPTIONS.has_key(optname):
205
284
                # it's an option
206
 
                opts.append('--%s' % name)
 
285
                opts.append('--%s' % optname)
207
286
                if value is not None and value is not True:
208
287
                    opts.append(str(value))
209
288
            else:
253
332
    directory is shown.  Otherwise, only the status of the specified
254
333
    files or directories is reported.  If a directory is given, status
255
334
    is reported for everything inside that directory.
 
335
 
 
336
    If a revision is specified, the changes since that revision are shown.
256
337
    """
257
338
    takes_args = ['file*']
258
 
    takes_options = ['all', 'show-ids']
 
339
    takes_options = ['all', 'show-ids', 'revision']
259
340
    aliases = ['st', 'stat']
260
341
    
261
342
    def run(self, all=False, show_ids=False, file_list=None):
262
343
        if file_list:
263
 
            b = Branch(file_list[0])
 
344
            b = find_branch(file_list[0])
264
345
            file_list = [b.relpath(x) for x in file_list]
265
346
            # special case: only one path was given and it's the root
266
347
            # of the branch
267
348
            if file_list == ['']:
268
349
                file_list = None
269
350
        else:
270
 
            b = Branch('.')
271
 
        import status
272
 
        status.show_status(b, show_unchanged=all, show_ids=show_ids,
273
 
                           specific_files=file_list)
 
351
            b = find_branch('.')
 
352
            
 
353
        from bzrlib.status import show_status
 
354
        show_status(b, show_unchanged=all, show_ids=show_ids,
 
355
                    specific_files=file_list)
274
356
 
275
357
 
276
358
class cmd_cat_revision(Command):
280
362
    takes_args = ['revision_id']
281
363
    
282
364
    def run(self, revision_id):
283
 
        Branch('.').get_revision(revision_id).write_xml(sys.stdout)
 
365
        from bzrlib.xml import pack_xml
 
366
        pack_xml(find_branch('.').get_revision(revision_id), sys.stdout)
284
367
 
285
368
 
286
369
class cmd_revno(Command):
288
371
 
289
372
    This is equal to the number of revisions on this branch."""
290
373
    def run(self):
291
 
        print Branch('.').revno()
 
374
        print find_branch('.').revno()
 
375
 
 
376
class cmd_revision_info(Command):
 
377
    """Show revision number and revision id for a given revision identifier.
 
378
    """
 
379
    hidden = True
 
380
    takes_args = ['revision_info*']
 
381
    takes_options = ['revision']
 
382
    def run(self, revision=None, revision_info_list=None):
 
383
        from bzrlib.branch import find_branch
 
384
 
 
385
        revs = []
 
386
        if revision is not None:
 
387
            revs.extend(revision)
 
388
        if revision_info_list is not None:
 
389
            revs.extend(revision_info_list)
 
390
        if len(revs) == 0:
 
391
            raise BzrCommandError('You must supply a revision identifier')
 
392
 
 
393
        b = find_branch('.')
 
394
 
 
395
        for rev in revs:
 
396
            print '%4d %s' % b.get_revision_info(rev)
292
397
 
293
398
    
294
399
class cmd_add(Command):
316
421
    takes_options = ['verbose', 'no-recurse']
317
422
    
318
423
    def run(self, file_list, verbose=False, no_recurse=False):
319
 
        bzrlib.add.smart_add(file_list, verbose, not no_recurse)
 
424
        from bzrlib.add import smart_add
 
425
        smart_add(file_list, verbose, not no_recurse)
 
426
 
 
427
 
 
428
 
 
429
class cmd_mkdir(Command):
 
430
    """Create a new versioned directory.
 
431
 
 
432
    This is equivalent to creating the directory and then adding it.
 
433
    """
 
434
    takes_args = ['dir+']
 
435
 
 
436
    def run(self, dir_list):
 
437
        b = None
 
438
        
 
439
        for d in dir_list:
 
440
            os.mkdir(d)
 
441
            if not b:
 
442
                b = find_branch(d)
 
443
            b.add([d], verbose=True)
320
444
 
321
445
 
322
446
class cmd_relpath(Command):
325
449
    hidden = True
326
450
    
327
451
    def run(self, filename):
328
 
        print Branch(filename).relpath(filename)
 
452
        print find_branch(filename).relpath(filename)
329
453
 
330
454
 
331
455
 
334
458
    takes_options = ['revision', 'show-ids']
335
459
    
336
460
    def run(self, revision=None, show_ids=False):
337
 
        b = Branch('.')
 
461
        b = find_branch('.')
338
462
        if revision == None:
339
463
            inv = b.read_working_inventory()
340
464
        else:
341
 
            inv = b.get_revision_inventory(b.lookup_revision(revision))
 
465
            if len(revision) > 1:
 
466
                raise BzrCommandError('bzr inventory --revision takes'
 
467
                    ' exactly one revision identifier')
 
468
            inv = b.get_revision_inventory(b.lookup_revision(revision[0]))
342
469
 
343
470
        for path, entry in inv.entries():
344
471
            if show_ids:
357
484
    """
358
485
    takes_args = ['source$', 'dest']
359
486
    def run(self, source_list, dest):
360
 
        b = Branch('.')
 
487
        b = find_branch('.')
361
488
 
362
489
        b.move([b.relpath(s) for s in source_list], b.relpath(dest))
363
490
 
379
506
    takes_args = ['from_name', 'to_name']
380
507
    
381
508
    def run(self, from_name, to_name):
382
 
        b = Branch('.')
 
509
        b = find_branch('.')
383
510
        b.rename_one(b.relpath(from_name), b.relpath(to_name))
384
511
 
385
512
 
404
531
 
405
532
    def run(self, location=None):
406
533
        from bzrlib.merge import merge
 
534
        import tempfile
 
535
        from shutil import rmtree
407
536
        import errno
408
537
        
409
 
        br_to = Branch('.')
 
538
        br_to = find_branch('.')
410
539
        stored_loc = None
411
540
        try:
412
541
            stored_loc = br_to.controlfile("x-pull", "rb").read().rstrip('\n')
413
542
        except IOError, e:
414
 
            if errno == errno.ENOENT:
 
543
            if e.errno != errno.ENOENT:
415
544
                raise
416
545
        if location is None:
417
 
            location = stored_loc
418
 
        if location is None:
419
 
            raise BzrCommandError("No pull location known or specified.")
420
 
        from branch import find_branch, DivergedBranches
 
546
            if stored_loc is None:
 
547
                raise BzrCommandError("No pull location known or specified.")
 
548
            else:
 
549
                print "Using last location: %s" % stored_loc
 
550
                location = stored_loc
 
551
        cache_root = tempfile.mkdtemp()
 
552
        from bzrlib.branch import DivergedBranches
421
553
        br_from = find_branch(location)
422
554
        location = pull_loc(br_from)
423
555
        old_revno = br_to.revno()
424
556
        try:
425
 
            br_to.update_revisions(br_from)
426
 
        except DivergedBranches:
427
 
            raise BzrCommandError("These branches have diverged.  Try merge.")
428
 
            
429
 
        merge(('.', -1), ('.', old_revno))
430
 
        if location != stored_loc:
431
 
            br_to.controlfile("x-pull", "wb").write(location + "\n")
 
557
            from branch import find_cached_branch, DivergedBranches
 
558
            br_from = find_cached_branch(location, cache_root)
 
559
            location = pull_loc(br_from)
 
560
            old_revno = br_to.revno()
 
561
            try:
 
562
                br_to.update_revisions(br_from)
 
563
            except DivergedBranches:
 
564
                raise BzrCommandError("These branches have diverged."
 
565
                    "  Try merge.")
 
566
                
 
567
            merge(('.', -1), ('.', old_revno), check_clean=False)
 
568
            if location != stored_loc:
 
569
                br_to.controlfile("x-pull", "wb").write(location + "\n")
 
570
        finally:
 
571
            rmtree(cache_root)
432
572
 
433
573
 
434
574
 
435
575
class cmd_branch(Command):
436
576
    """Create a new copy of a branch.
437
577
 
438
 
    If the TO_LOCATION is omitted, the last component of the
439
 
    FROM_LOCATION will be used.  In other words,
440
 
    "branch ../foo/bar" will attempt to create ./bar.
 
578
    If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
 
579
    be used.  In other words, "branch ../foo/bar" will attempt to create ./bar.
 
580
 
 
581
    To retrieve the branch as of a particular revision, supply the --revision
 
582
    parameter, as in "branch foo/bar -r 5".
441
583
    """
442
584
    takes_args = ['from_location', 'to_location?']
 
585
    takes_options = ['revision']
443
586
 
444
 
    def run(self, from_location, to_location=None):
 
587
    def run(self, from_location, to_location=None, revision=None):
445
588
        import errno
446
589
        from bzrlib.merge import merge
447
 
        
448
 
        if to_location is None:
449
 
            to_location = os.path.basename(from_location)
450
 
            # FIXME: If there's a trailing slash, keep removing them
451
 
            # until we find the right bit
452
 
 
453
 
        try:
454
 
            os.mkdir(to_location)
455
 
        except OSError, e:
456
 
            if e.errno == errno.EEXIST:
457
 
                raise BzrCommandError('Target directory "%s" already exists.' %
458
 
                                      to_location)
459
 
            if e.errno == errno.ENOENT:
460
 
                raise BzrCommandError('Parent of "%s" does not exist.' %
461
 
                                      to_location)
462
 
            else:
463
 
                raise
464
 
        br_to = Branch(to_location, init=True)
465
 
        from branch import find_branch, DivergedBranches
466
 
        try:
467
 
            br_from = find_branch(from_location)
468
 
        except OSError, e:
469
 
            if e.errno == errno.ENOENT:
470
 
                raise BzrCommandError('Source location "%s" does not exist.' %
471
 
                                      to_location)
472
 
            else:
473
 
                raise
474
 
 
475
 
        from_location = pull_loc(br_from)
476
 
        br_to.update_revisions(br_from)
477
 
        merge((to_location, -1), (to_location, 0), this_dir=to_location,
478
 
              check_clean=False)
479
 
        br_to.controlfile("x-pull", "wb").write(from_location + "\n")
 
590
        from bzrlib.branch import DivergedBranches, NoSuchRevision, \
 
591
             find_cached_branch, Branch
 
592
        from shutil import rmtree
 
593
        from meta_store import CachedStore
 
594
        import tempfile
 
595
        cache_root = tempfile.mkdtemp()
 
596
 
 
597
        if revision is None:
 
598
            revision = [None]
 
599
        elif len(revision) > 1:
 
600
            raise BzrCommandError('bzr branch --revision takes exactly 1 revision value')
 
601
 
 
602
        try:
 
603
            try:
 
604
                br_from = find_cached_branch(from_location, cache_root)
 
605
            except OSError, e:
 
606
                if e.errno == errno.ENOENT:
 
607
                    raise BzrCommandError('Source location "%s" does not'
 
608
                                          ' exist.' % to_location)
 
609
                else:
 
610
                    raise
 
611
 
 
612
            if to_location is None:
 
613
                to_location = os.path.basename(from_location.rstrip("/\\"))
 
614
 
 
615
            try:
 
616
                os.mkdir(to_location)
 
617
            except OSError, e:
 
618
                if e.errno == errno.EEXIST:
 
619
                    raise BzrCommandError('Target directory "%s" already'
 
620
                                          ' exists.' % to_location)
 
621
                if e.errno == errno.ENOENT:
 
622
                    raise BzrCommandError('Parent of "%s" does not exist.' %
 
623
                                          to_location)
 
624
                else:
 
625
                    raise
 
626
            br_to = Branch(to_location, init=True)
 
627
 
 
628
            br_to.set_root_id(br_from.get_root_id())
 
629
 
 
630
            if revision:
 
631
                if revision[0] is None:
 
632
                    revno = br_from.revno()
 
633
                else:
 
634
                    revno, rev_id = br_from.get_revision_info(revision[0])
 
635
                try:
 
636
                    br_to.update_revisions(br_from, stop_revision=revno)
 
637
                except NoSuchRevision:
 
638
                    rmtree(to_location)
 
639
                    msg = "The branch %s has no revision %d." % (from_location,
 
640
                                                                 revno)
 
641
                    raise BzrCommandError(msg)
 
642
            
 
643
            merge((to_location, -1), (to_location, 0), this_dir=to_location,
 
644
                  check_clean=False, ignore_zero=True)
 
645
            from_location = pull_loc(br_from)
 
646
            br_to.controlfile("x-pull", "wb").write(from_location + "\n")
 
647
        finally:
 
648
            rmtree(cache_root)
480
649
 
481
650
 
482
651
def pull_loc(branch):
499
668
    takes_args = ['dir?']
500
669
 
501
670
    def run(self, dir='.'):
502
 
        b = Branch(dir)
 
671
        b = find_branch(dir)
503
672
        old_inv = b.basis_tree().inventory
504
673
        new_inv = b.read_working_inventory()
505
674
 
516
685
    def run(self, branch=None):
517
686
        import info
518
687
 
519
 
        from branch import find_branch
520
688
        b = find_branch(branch)
521
689
        info.show_info(b)
522
690
 
531
699
    takes_options = ['verbose']
532
700
    
533
701
    def run(self, file_list, verbose=False):
534
 
        b = Branch(file_list[0])
 
702
        b = find_branch(file_list[0])
535
703
        b.remove([b.relpath(f) for f in file_list], verbose=verbose)
536
704
 
537
705
 
545
713
    hidden = True
546
714
    takes_args = ['filename']
547
715
    def run(self, filename):
548
 
        b = Branch(filename)
 
716
        b = find_branch(filename)
549
717
        i = b.inventory.path2id(b.relpath(filename))
550
718
        if i == None:
551
 
            bailout("%r is not a versioned file" % filename)
 
719
            raise BzrError("%r is not a versioned file" % filename)
552
720
        else:
553
721
            print i
554
722
 
561
729
    hidden = True
562
730
    takes_args = ['filename']
563
731
    def run(self, filename):
564
 
        b = Branch(filename)
 
732
        b = find_branch(filename)
565
733
        inv = b.inventory
566
734
        fid = inv.path2id(b.relpath(filename))
567
735
        if fid == None:
568
 
            bailout("%r is not a versioned file" % filename)
 
736
            raise BzrError("%r is not a versioned file" % filename)
569
737
        for fip in inv.get_idpath(fid):
570
738
            print fip
571
739
 
574
742
    """Display list of revision ids on this branch."""
575
743
    hidden = True
576
744
    def run(self):
577
 
        for patchid in Branch('.').revision_history():
 
745
        for patchid in find_branch('.').revision_history():
578
746
            print patchid
579
747
 
580
748
 
581
749
class cmd_directories(Command):
582
750
    """Display list of versioned directories in this branch."""
583
751
    def run(self):
584
 
        for name, ie in Branch('.').read_working_inventory().directories():
 
752
        for name, ie in find_branch('.').read_working_inventory().directories():
585
753
            if name == '':
586
754
                print '.'
587
755
            else:
602
770
        bzr commit -m 'imported project'
603
771
    """
604
772
    def run(self):
 
773
        from bzrlib.branch import Branch
605
774
        Branch('.', init=True)
606
775
 
607
776
 
631
800
    
632
801
    takes_args = ['file*']
633
802
    takes_options = ['revision', 'diff-options']
634
 
    aliases = ['di']
 
803
    aliases = ['di', 'dif']
635
804
 
636
805
    def run(self, revision=None, file_list=None, diff_options=None):
637
806
        from bzrlib.diff import show_diff
638
 
        from bzrlib import find_branch
639
807
 
640
808
        if file_list:
641
809
            b = find_branch(file_list[0])
644
812
                # just pointing to top-of-tree
645
813
                file_list = None
646
814
        else:
647
 
            b = Branch('.')
 
815
            b = find_branch('.')
 
816
 
 
817
        # TODO: Make show_diff support taking 2 arguments
 
818
        base_rev = None
 
819
        if revision is not None:
 
820
            if len(revision) != 1:
 
821
                raise BzrCommandError('bzr diff --revision takes exactly one revision identifier')
 
822
            base_rev = revision[0]
648
823
    
649
 
        show_diff(b, revision, specific_files=file_list,
 
824
        show_diff(b, base_rev, specific_files=file_list,
650
825
                  external_diff_options=diff_options)
651
826
 
652
827
 
659
834
    TODO: Show files deleted since a previous revision, or between two revisions.
660
835
    """
661
836
    def run(self, show_ids=False):
662
 
        b = Branch('.')
 
837
        b = find_branch('.')
663
838
        old = b.basis_tree()
664
839
        new = b.working_tree()
665
840
 
680
855
    """List files modified in working tree."""
681
856
    hidden = True
682
857
    def run(self):
683
 
        import statcache
684
 
        b = Branch('.')
685
 
        inv = b.read_working_inventory()
686
 
        sc = statcache.update_cache(b, inv)
687
 
        basis = b.basis_tree()
688
 
        basis_inv = basis.inventory
689
 
        
690
 
        # We used to do this through iter_entries(), but that's slow
691
 
        # when most of the files are unmodified, as is usually the
692
 
        # case.  So instead we iterate by inventory entry, and only
693
 
        # calculate paths as necessary.
694
 
 
695
 
        for file_id in basis_inv:
696
 
            cacheentry = sc.get(file_id)
697
 
            if not cacheentry:                 # deleted
698
 
                continue
699
 
            ie = basis_inv[file_id]
700
 
            if cacheentry[statcache.SC_SHA1] != ie.text_sha1:
701
 
                path = inv.id2path(file_id)
702
 
                print path
 
858
        from bzrlib.diff import compare_trees
 
859
 
 
860
        b = find_branch('.')
 
861
        td = compare_trees(b.basis_tree(), b.working_tree())
 
862
 
 
863
        for path, id, kind in td.modified:
 
864
            print path
703
865
 
704
866
 
705
867
 
707
869
    """List files added in working tree."""
708
870
    hidden = True
709
871
    def run(self):
710
 
        b = Branch('.')
 
872
        b = find_branch('.')
711
873
        wt = b.working_tree()
712
874
        basis_inv = b.basis_tree().inventory
713
875
        inv = wt.inventory
729
891
    takes_args = ['filename?']
730
892
    def run(self, filename=None):
731
893
        """Print the branch root."""
732
 
        from branch import find_branch
733
894
        b = find_branch(filename)
734
895
        print getattr(b, 'base', None) or getattr(b, 'baseurl')
735
896
 
741
902
    -r revision requests a specific revision, -r :end or -r begin: are
742
903
    also valid.
743
904
 
 
905
    --message allows you to give a regular expression, which will be evaluated
 
906
    so that only matching entries will be displayed.
 
907
 
744
908
    TODO: Make --revision support uuid: and hash: [future tag:] notation.
745
909
  
746
910
    """
747
911
 
748
912
    takes_args = ['filename?']
749
 
    takes_options = ['forward', 'timezone', 'verbose', 'show-ids', 'revision']
 
913
    takes_options = ['forward', 'timezone', 'verbose', 'show-ids', 'revision','long', 'message']
750
914
    
751
915
    def run(self, filename=None, timezone='original',
752
916
            verbose=False,
753
917
            show_ids=False,
754
918
            forward=False,
755
 
            revision=None):
756
 
        from bzrlib import show_log, find_branch
 
919
            revision=None,
 
920
            message=None,
 
921
            long=False):
 
922
        from bzrlib.branch import find_branch
 
923
        from bzrlib.log import log_formatter, show_log
757
924
        import codecs
758
925
 
759
926
        direction = (forward and 'forward') or 'reverse'
769
936
            b = find_branch('.')
770
937
            file_id = None
771
938
 
772
 
        if revision == None:
773
 
            revision = [None, None]
774
 
        elif isinstance(revision, int):
775
 
            revision = [revision, revision]
 
939
        if revision is None:
 
940
            rev1 = None
 
941
            rev2 = None
 
942
        elif len(revision) == 1:
 
943
            rev1 = rev2 = b.get_revision_info(revision[0])[0]
 
944
        elif len(revision) == 2:
 
945
            rev1 = b.get_revision_info(revision[0])[0]
 
946
            rev2 = b.get_revision_info(revision[1])[0]
776
947
        else:
777
 
            # pair of revisions?
778
 
            pass
779
 
            
780
 
        assert len(revision) == 2
 
948
            raise BzrCommandError('bzr log --revision takes one or two values.')
 
949
 
 
950
        if rev1 == 0:
 
951
            rev1 = None
 
952
        if rev2 == 0:
 
953
            rev2 = None
781
954
 
782
955
        mutter('encoding log as %r' % bzrlib.user_encoding)
783
956
 
785
958
        # in e.g. the default C locale.
786
959
        outf = codecs.getwriter(bzrlib.user_encoding)(sys.stdout, errors='replace')
787
960
 
788
 
        show_log(b, file_id,
789
 
                 show_timezone=timezone,
 
961
        if long:
 
962
            log_format = 'long'
 
963
        else:
 
964
            log_format = 'short'
 
965
        lf = log_formatter(log_format,
 
966
                           show_ids=show_ids,
 
967
                           to_file=outf,
 
968
                           show_timezone=timezone)
 
969
 
 
970
        show_log(b,
 
971
                 lf,
 
972
                 file_id,
790
973
                 verbose=verbose,
791
 
                 show_ids=show_ids,
792
 
                 to_file=outf,
793
974
                 direction=direction,
794
 
                 start_revision=revision[0],
795
 
                 end_revision=revision[1])
 
975
                 start_revision=rev1,
 
976
                 end_revision=rev2,
 
977
                 search=message)
796
978
 
797
979
 
798
980
 
803
985
    hidden = True
804
986
    takes_args = ["filename"]
805
987
    def run(self, filename):
806
 
        b = Branch(filename)
 
988
        b = find_branch(filename)
807
989
        inv = b.read_working_inventory()
808
990
        file_id = inv.path2id(b.relpath(filename))
809
991
        for revno, revision_id, what in bzrlib.log.find_touching_revisions(b, file_id):
817
999
    """
818
1000
    hidden = True
819
1001
    def run(self, revision=None, verbose=False):
820
 
        b = Branch('.')
 
1002
        b = find_branch('.')
821
1003
        if revision == None:
822
1004
            tree = b.working_tree()
823
1005
        else:
839
1021
 
840
1022
 
841
1023
class cmd_unknowns(Command):
842
 
    """List unknown files"""
 
1024
    """List unknown files."""
843
1025
    def run(self):
844
 
        for f in Branch('.').unknowns():
 
1026
        from bzrlib.osutils import quotefn
 
1027
        for f in find_branch('.').unknowns():
845
1028
            print quotefn(f)
846
1029
 
847
1030
 
848
1031
 
849
1032
class cmd_ignore(Command):
850
 
    """Ignore a command or pattern
 
1033
    """Ignore a command or pattern.
851
1034
 
852
1035
    To remove patterns from the ignore list, edit the .bzrignore file.
853
1036
 
869
1052
        from bzrlib.atomicfile import AtomicFile
870
1053
        import os.path
871
1054
 
872
 
        b = Branch('.')
 
1055
        b = find_branch('.')
873
1056
        ifn = b.abspath('.bzrignore')
874
1057
 
875
1058
        if os.path.exists(ifn):
909
1092
 
910
1093
    See also: bzr ignore"""
911
1094
    def run(self):
912
 
        tree = Branch('.').working_tree()
 
1095
        tree = find_branch('.').working_tree()
913
1096
        for path, file_class, kind, file_id in tree.list_files():
914
1097
            if file_class != 'I':
915
1098
                continue
933
1116
        except ValueError:
934
1117
            raise BzrCommandError("not a valid revision-number: %r" % revno)
935
1118
 
936
 
        print Branch('.').lookup_revision(revno)
 
1119
        print find_branch('.').lookup_revision(revno)
937
1120
 
938
1121
 
939
1122
class cmd_export(Command):
940
1123
    """Export past revision to destination directory.
941
1124
 
942
 
    If no revision is specified this exports the last committed revision."""
 
1125
    If no revision is specified this exports the last committed revision.
 
1126
 
 
1127
    Format may be an "exporter" name, such as tar, tgz, tbz2.  If none is
 
1128
    given, try to find the format with the extension. If no extension
 
1129
    is found exports to a directory (equivalent to --format=dir).
 
1130
 
 
1131
    Root may be the top directory for tar, tgz and tbz2 formats. If none
 
1132
    is given, the top directory will be the root name of the file."""
 
1133
    # TODO: list known exporters
943
1134
    takes_args = ['dest']
944
 
    takes_options = ['revision']
945
 
    def run(self, dest, revision=None):
946
 
        b = Branch('.')
947
 
        if revision == None:
948
 
            rh = b.revision_history()[-1]
 
1135
    takes_options = ['revision', 'format', 'root']
 
1136
    def run(self, dest, revision=None, format=None, root=None):
 
1137
        import os.path
 
1138
        b = find_branch('.')
 
1139
        if revision is None:
 
1140
            rev_id = b.last_patch()
949
1141
        else:
950
 
            rh = b.lookup_revision(int(revision))
951
 
        t = b.revision_tree(rh)
952
 
        t.export(dest)
 
1142
            if len(revision) != 1:
 
1143
                raise BzrError('bzr export --revision takes exactly 1 argument')
 
1144
            revno, rev_id = b.get_revision_info(revision[0])
 
1145
        t = b.revision_tree(rev_id)
 
1146
        root, ext = os.path.splitext(dest)
 
1147
        if not format:
 
1148
            if ext in (".tar",):
 
1149
                format = "tar"
 
1150
            elif ext in (".gz", ".tgz"):
 
1151
                format = "tgz"
 
1152
            elif ext in (".bz2", ".tbz2"):
 
1153
                format = "tbz2"
 
1154
            else:
 
1155
                format = "dir"
 
1156
        t.export(dest, format, root)
953
1157
 
954
1158
 
955
1159
class cmd_cat(Command):
961
1165
    def run(self, filename, revision=None):
962
1166
        if revision == None:
963
1167
            raise BzrCommandError("bzr cat requires a revision number")
964
 
        b = Branch('.')
965
 
        b.print_file(b.relpath(filename), int(revision))
 
1168
        elif len(revision) != 1:
 
1169
            raise BzrCommandError("bzr cat --revision takes exactly one number")
 
1170
        b = find_branch('.')
 
1171
        b.print_file(b.relpath(filename), revision[0])
966
1172
 
967
1173
 
968
1174
class cmd_local_time_offset(Command):
989
1195
    TODO: Strict commit that fails if there are unknown or deleted files.
990
1196
    """
991
1197
    takes_args = ['selected*']
992
 
    takes_options = ['message', 'file', 'verbose']
 
1198
    takes_options = ['message', 'file', 'verbose', 'unchanged']
993
1199
    aliases = ['ci', 'checkin']
994
1200
 
995
 
    def run(self, message=None, file=None, verbose=True, selected_list=None):
996
 
        from bzrlib.commit import commit
 
1201
    def run(self, message=None, file=None, verbose=True, selected_list=None,
 
1202
            unchanged=False):
 
1203
        from bzrlib.errors import PointlessCommit
 
1204
        from bzrlib.osutils import get_text_message
997
1205
 
998
1206
        ## Warning: shadows builtin file()
999
1207
        if not message and not file:
1000
 
            raise BzrCommandError("please specify a commit message",
1001
 
                                  ["use either --message or --file"])
 
1208
            import cStringIO
 
1209
            stdout = sys.stdout
 
1210
            catcher = cStringIO.StringIO()
 
1211
            sys.stdout = catcher
 
1212
            cmd_status({"file_list":selected_list}, {})
 
1213
            info = catcher.getvalue()
 
1214
            sys.stdout = stdout
 
1215
            message = get_text_message(info)
 
1216
            
 
1217
            if message is None:
 
1218
                raise BzrCommandError("please specify a commit message",
 
1219
                                      ["use either --message or --file"])
1002
1220
        elif message and file:
1003
1221
            raise BzrCommandError("please specify either --message or --file")
1004
1222
        
1006
1224
            import codecs
1007
1225
            message = codecs.open(file, 'rt', bzrlib.user_encoding).read()
1008
1226
 
1009
 
        b = Branch('.')
1010
 
        commit(b, message, verbose=verbose, specific_files=selected_list)
 
1227
        b = find_branch('.')
 
1228
 
 
1229
        try:
 
1230
            b.commit(message, verbose=verbose,
 
1231
                     specific_files=selected_list,
 
1232
                     allow_pointless=unchanged)
 
1233
        except PointlessCommit:
 
1234
            # FIXME: This should really happen before the file is read in;
 
1235
            # perhaps prepare the commit; get the message; then actually commit
 
1236
            raise BzrCommandError("no changes to commit",
 
1237
                                  ["use --unchanged to commit anyhow"])
1011
1238
 
1012
1239
 
1013
1240
class cmd_check(Command):
1015
1242
 
1016
1243
    This command checks various invariants about the branch storage to
1017
1244
    detect data corruption or bzr bugs.
1018
 
    """
1019
 
    takes_args = ['dir?']
1020
 
    def run(self, dir='.'):
1021
 
        import bzrlib.check
1022
 
        bzrlib.check.check(Branch(dir))
 
1245
 
 
1246
    If given the --update flag, it will update some optional fields
 
1247
    to help ensure data consistency.
 
1248
    """
 
1249
    takes_args = ['dir?']
 
1250
 
 
1251
    def run(self, dir='.'):
 
1252
        from bzrlib.check import check
 
1253
        check(find_branch(dir))
 
1254
 
 
1255
 
 
1256
 
 
1257
class cmd_scan_cache(Command):
 
1258
    hidden = True
 
1259
    def run(self):
 
1260
        from bzrlib.hashcache import HashCache
 
1261
        import os
 
1262
 
 
1263
        c = HashCache('.')
 
1264
        c.read()
 
1265
        c.scan()
 
1266
            
 
1267
        print '%6d stats' % c.stat_count
 
1268
        print '%6d in hashcache' % len(c._cache)
 
1269
        print '%6d files removed from cache' % c.removed_count
 
1270
        print '%6d hashes updated' % c.update_count
 
1271
        print '%6d files changed too recently to cache' % c.danger_count
 
1272
 
 
1273
        if c.needs_write:
 
1274
            c.write()
 
1275
            
 
1276
 
 
1277
 
 
1278
class cmd_upgrade(Command):
 
1279
    """Upgrade branch storage to current format.
 
1280
 
 
1281
    This should normally be used only after the check command tells
 
1282
    you to run it.
 
1283
    """
 
1284
    takes_args = ['dir?']
 
1285
 
 
1286
    def run(self, dir='.'):
 
1287
        from bzrlib.upgrade import upgrade
 
1288
        upgrade(find_branch(dir))
1023
1289
 
1024
1290
 
1025
1291
 
1039
1305
    hidden = True
1040
1306
    def run(self):
1041
1307
        from bzrlib.selftest import selftest
1042
 
        if selftest():
1043
 
            return 0
1044
 
        else:
1045
 
            return 1
1046
 
 
 
1308
        return int(not selftest())
1047
1309
 
1048
1310
 
1049
1311
class cmd_version(Command):
1050
 
    """Show version of bzr"""
 
1312
    """Show version of bzr."""
1051
1313
    def run(self):
1052
1314
        show_version()
1053
1315
 
1081
1343
    ['..', -1]
1082
1344
    >>> parse_spec("../f/@35")
1083
1345
    ['../f', 35]
 
1346
    >>> parse_spec('./@revid:john@arbash-meinel.com-20050711044610-3ca0327c6a222f67')
 
1347
    ['.', 'revid:john@arbash-meinel.com-20050711044610-3ca0327c6a222f67']
1084
1348
    """
1085
1349
    if spec is None:
1086
1350
        return [None, None]
1090
1354
        if parsed[1] == "":
1091
1355
            parsed[1] = -1
1092
1356
        else:
1093
 
            parsed[1] = int(parsed[1])
1094
 
            assert parsed[1] >=0
 
1357
            try:
 
1358
                parsed[1] = int(parsed[1])
 
1359
            except ValueError:
 
1360
                pass # We can allow stuff like ./@revid:blahblahblah
 
1361
            else:
 
1362
                assert parsed[1] >=0
1095
1363
    else:
1096
1364
        parsed = [spec, None]
1097
1365
    return parsed
1129
1397
              check_clean=(not force))
1130
1398
 
1131
1399
 
 
1400
 
1132
1401
class cmd_revert(Command):
 
1402
    """Restore selected files from a previous revision.
 
1403
    """
 
1404
    takes_args = ['file+']
 
1405
    def run(self, file_list):
 
1406
        from bzrlib.branch import find_branch
 
1407
        
 
1408
        if not file_list:
 
1409
            file_list = ['.']
 
1410
            
 
1411
        b = find_branch(file_list[0])
 
1412
 
 
1413
        b.revert([b.relpath(f) for f in file_list])
 
1414
 
 
1415
 
 
1416
class cmd_merge_revert(Command):
1133
1417
    """Reverse all changes since the last commit.
1134
1418
 
1135
1419
    Only versioned files are affected.
1139
1423
    """
1140
1424
    takes_options = ['revision']
1141
1425
 
1142
 
    def run(self, revision=-1):
1143
 
        merge(('.', revision), parse_spec('.'),
 
1426
    def run(self, revision=None):
 
1427
        from bzrlib.merge import merge
 
1428
        if revision is None:
 
1429
            revision = [-1]
 
1430
        elif len(revision) != 1:
 
1431
            raise BzrCommandError('bzr merge-revert --revision takes exactly 1 argument')
 
1432
        merge(('.', revision[0]), parse_spec('.'),
1144
1433
              check_clean=False,
1145
1434
              ignore_zero=True)
1146
1435
 
1164
1453
        help.help(topic)
1165
1454
 
1166
1455
 
1167
 
class cmd_update_stat_cache(Command):
1168
 
    """Update stat-cache mapping inodes to SHA-1 hashes.
1169
 
 
1170
 
    For testing only."""
 
1456
 
 
1457
 
 
1458
class cmd_plugins(Command):
 
1459
    """List plugins"""
1171
1460
    hidden = True
1172
1461
    def run(self):
1173
 
        import statcache
1174
 
        b = Branch('.')
1175
 
        statcache.update_cache(b.base, b.read_working_inventory())
 
1462
        import bzrlib.plugin
 
1463
        from inspect import getdoc
 
1464
        from pprint import pprint
 
1465
        for plugin in bzrlib.plugin.all_plugins:
 
1466
            print plugin.__path__[0]
 
1467
            d = getdoc(plugin)
 
1468
            if d:
 
1469
                print '\t', d.split('\n')[0]
 
1470
 
 
1471
        #pprint(bzrlib.plugin.all_plugins)
1176
1472
 
1177
1473
 
1178
1474
 
1185
1481
    'help':                   None,
1186
1482
    'file':                   unicode,
1187
1483
    'force':                  None,
 
1484
    'format':                 unicode,
1188
1485
    'forward':                None,
1189
1486
    'message':                unicode,
1190
1487
    'no-recurse':             None,
1195
1492
    'verbose':                None,
1196
1493
    'version':                None,
1197
1494
    'email':                  None,
 
1495
    'unchanged':              None,
 
1496
    'update':                 None,
 
1497
    'long':                   None,
 
1498
    'root':                   str,
1198
1499
    }
1199
1500
 
1200
1501
SHORT_OPTIONS = {
1203
1504
    'm':                      'message',
1204
1505
    'r':                      'revision',
1205
1506
    'v':                      'verbose',
 
1507
    'l':                      'long',
1206
1508
}
1207
1509
 
1208
1510
 
1222
1524
    (['status'], {'all': True})
1223
1525
    >>> parse_args('commit --message=biter'.split())
1224
1526
    (['commit'], {'message': u'biter'})
 
1527
    >>> parse_args('log -r 500'.split())
 
1528
    (['log'], {'revision': [500]})
 
1529
    >>> parse_args('log -r500..600'.split())
 
1530
    (['log'], {'revision': [500, 600]})
 
1531
    >>> parse_args('log -vr500..600'.split())
 
1532
    (['log'], {'verbose': True, 'revision': [500, 600]})
 
1533
    >>> parse_args('log -rv500..600'.split()) #the r takes an argument
 
1534
    (['log'], {'revision': ['v500', 600]})
1225
1535
    """
1226
1536
    args = []
1227
1537
    opts = {}
1241
1551
                else:
1242
1552
                    optname = a[2:]
1243
1553
                if optname not in OPTIONS:
1244
 
                    bailout('unknown long option %r' % a)
 
1554
                    raise BzrError('unknown long option %r' % a)
1245
1555
            else:
1246
1556
                shortopt = a[1:]
1247
 
                if shortopt not in SHORT_OPTIONS:
1248
 
                    bailout('unknown short option %r' % a)
1249
 
                optname = SHORT_OPTIONS[shortopt]
 
1557
                if shortopt in SHORT_OPTIONS:
 
1558
                    # Multi-character options must have a space to delimit
 
1559
                    # their value
 
1560
                    optname = SHORT_OPTIONS[shortopt]
 
1561
                else:
 
1562
                    # Single character short options, can be chained,
 
1563
                    # and have their value appended to their name
 
1564
                    shortopt = a[1:2]
 
1565
                    if shortopt not in SHORT_OPTIONS:
 
1566
                        # We didn't find the multi-character name, and we
 
1567
                        # didn't find the single char name
 
1568
                        raise BzrError('unknown short option %r' % a)
 
1569
                    optname = SHORT_OPTIONS[shortopt]
 
1570
 
 
1571
                    if a[2:]:
 
1572
                        # There are extra things on this option
 
1573
                        # see if it is the value, or if it is another
 
1574
                        # short option
 
1575
                        optargfn = OPTIONS[optname]
 
1576
                        if optargfn is None:
 
1577
                            # This option does not take an argument, so the
 
1578
                            # next entry is another short option, pack it back
 
1579
                            # into the list
 
1580
                            argv.insert(0, '-' + a[2:])
 
1581
                        else:
 
1582
                            # This option takes an argument, so pack it
 
1583
                            # into the array
 
1584
                            optarg = a[2:]
1250
1585
            
1251
1586
            if optname in opts:
1252
1587
                # XXX: Do we ever want to support this, e.g. for -r?
1253
 
                bailout('repeated option %r' % a)
 
1588
                raise BzrError('repeated option %r' % a)
1254
1589
                
1255
1590
            optargfn = OPTIONS[optname]
1256
1591
            if optargfn:
1257
1592
                if optarg == None:
1258
1593
                    if not argv:
1259
 
                        bailout('option %r needs an argument' % a)
 
1594
                        raise BzrError('option %r needs an argument' % a)
1260
1595
                    else:
1261
1596
                        optarg = argv.pop(0)
1262
1597
                opts[optname] = optargfn(optarg)
1263
1598
            else:
1264
1599
                if optarg != None:
1265
 
                    bailout('option %r takes no argument' % optname)
 
1600
                    raise BzrError('option %r takes no argument' % optname)
1266
1601
                opts[optname] = True
1267
1602
        else:
1268
1603
            args.append(a)
1316
1651
    return argdict
1317
1652
 
1318
1653
 
 
1654
def _parse_master_args(argv):
 
1655
    """Parse the arguments that always go with the original command.
 
1656
    These are things like bzr --no-plugins, etc.
 
1657
 
 
1658
    There are now 2 types of option flags. Ones that come *before* the command,
 
1659
    and ones that come *after* the command.
 
1660
    Ones coming *before* the command are applied against all possible commands.
 
1661
    And are generally applied before plugins are loaded.
 
1662
 
 
1663
    The current list are:
 
1664
        --builtin   Allow plugins to load, but don't let them override builtin commands,
 
1665
                    they will still be allowed if they do not override a builtin.
 
1666
        --no-plugins    Don't load any plugins. This lets you get back to official source
 
1667
                        behavior.
 
1668
        --profile   Enable the hotspot profile before running the command.
 
1669
                    For backwards compatibility, this is also a non-master option.
 
1670
        --version   Spit out the version of bzr that is running and exit.
 
1671
                    This is also a non-master option.
 
1672
        --help      Run help and exit, also a non-master option (I think that should stay, though)
 
1673
 
 
1674
    >>> argv, opts = _parse_master_args(['bzr', '--test'])
 
1675
    Traceback (most recent call last):
 
1676
    ...
 
1677
    BzrCommandError: Invalid master option: 'test'
 
1678
    >>> argv, opts = _parse_master_args(['bzr', '--version', 'command'])
 
1679
    >>> print argv
 
1680
    ['command']
 
1681
    >>> print opts['version']
 
1682
    True
 
1683
    >>> argv, opts = _parse_master_args(['bzr', '--profile', 'command', '--more-options'])
 
1684
    >>> print argv
 
1685
    ['command', '--more-options']
 
1686
    >>> print opts['profile']
 
1687
    True
 
1688
    >>> argv, opts = _parse_master_args(['bzr', '--no-plugins', 'command'])
 
1689
    >>> print argv
 
1690
    ['command']
 
1691
    >>> print opts['no-plugins']
 
1692
    True
 
1693
    >>> print opts['profile']
 
1694
    False
 
1695
    >>> argv, opts = _parse_master_args(['bzr', 'command', '--profile'])
 
1696
    >>> print argv
 
1697
    ['command', '--profile']
 
1698
    >>> print opts['profile']
 
1699
    False
 
1700
    """
 
1701
    master_opts = {'builtin':False,
 
1702
        'no-plugins':False,
 
1703
        'version':False,
 
1704
        'profile':False,
 
1705
        'help':False
 
1706
    }
 
1707
 
 
1708
    # This is the point where we could hook into argv[0] to determine
 
1709
    # what front-end is supposed to be run
 
1710
    # For now, we are just ignoring it.
 
1711
    cmd_name = argv.pop(0)
 
1712
    for arg in argv[:]:
 
1713
        if arg[:2] != '--': # at the first non-option, we return the rest
 
1714
            break
 
1715
        arg = arg[2:] # Remove '--'
 
1716
        if arg not in master_opts:
 
1717
            # We could say that this is not an error, that we should
 
1718
            # just let it be handled by the main section instead
 
1719
            raise BzrCommandError('Invalid master option: %r' % arg)
 
1720
        argv.pop(0) # We are consuming this entry
 
1721
        master_opts[arg] = True
 
1722
    return argv, master_opts
 
1723
 
 
1724
 
1319
1725
 
1320
1726
def run_bzr(argv):
1321
1727
    """Execute a command.
1326
1732
    argv = [a.decode(bzrlib.user_encoding) for a in argv]
1327
1733
    
1328
1734
    try:
1329
 
        args, opts = parse_args(argv[1:])
 
1735
        # some options like --builtin and --no-plugins have special effects
 
1736
        argv, master_opts = _parse_master_args(argv)
 
1737
        if not master_opts['no-plugins']:
 
1738
            from bzrlib.plugin import load_plugins
 
1739
            load_plugins()
 
1740
 
 
1741
        args, opts = parse_args(argv)
 
1742
 
 
1743
        if master_opts['help']:
 
1744
            from bzrlib.help import help
 
1745
            if argv:
 
1746
                help(argv[0])
 
1747
            else:
 
1748
                help()
 
1749
            return 0            
 
1750
            
1330
1751
        if 'help' in opts:
1331
 
            import help
 
1752
            from bzrlib.help import help
1332
1753
            if args:
1333
 
                help.help(args[0])
 
1754
                help(args[0])
1334
1755
            else:
1335
 
                help.help()
 
1756
                help()
1336
1757
            return 0
1337
1758
        elif 'version' in opts:
1338
1759
            show_version()
1339
1760
            return 0
 
1761
        elif args and args[0] == 'builtin':
 
1762
            include_plugins=False
 
1763
            args = args[1:]
1340
1764
        cmd = str(args.pop(0))
1341
1765
    except IndexError:
1342
1766
        import help
1344
1768
        return 1
1345
1769
          
1346
1770
 
1347
 
    canonical_cmd, cmd_class = get_cmd_class(cmd)
 
1771
    plugins_override = not (master_opts['builtin'])
 
1772
    canonical_cmd, cmd_class = get_cmd_class(cmd, plugins_override=plugins_override)
1348
1773
 
1349
 
    # global option
 
1774
    profile = master_opts['profile']
 
1775
    # For backwards compatibility, I would rather stick with --profile being a
 
1776
    # master/global option
1350
1777
    if 'profile' in opts:
1351
1778
        profile = True
1352
1779
        del opts['profile']
1353
 
    else:
1354
 
        profile = False
1355
1780
 
1356
1781
    # check options are reasonable
1357
1782
    allowed = cmd_class.takes_options
1406
1831
 
1407
1832
 
1408
1833
def main(argv):
1409
 
    import errno
1410
1834
    
1411
 
    bzrlib.open_tracefile(argv)
 
1835
    bzrlib.trace.open_tracefile(argv)
1412
1836
 
1413
1837
    try:
1414
1838
        try:
1435
1859
            _report_exception('interrupted', quiet=True)
1436
1860
            return 2
1437
1861
        except Exception, e:
 
1862
            import errno
1438
1863
            quiet = False
1439
1864
            if (isinstance(e, IOError) 
1440
1865
                and hasattr(e, 'errno')