~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/commands.py

  • Committer: Martin Pool
  • Date: 2005-07-07 10:22:02 UTC
  • Revision ID: mbp@sourcefrog.net-20050707102201-2d2a13a25098b101
- rearrange and clear up merged weave

Show diffs side-by-side

added added

removed removed

Lines of Context:
16
16
 
17
17
 
18
18
 
19
 
import sys, os, time, os.path
20
 
from sets import Set
 
19
import sys, os
21
20
 
22
21
import bzrlib
23
22
from bzrlib.trace import mutter, note, log_error
24
 
from bzrlib.errors import bailout, BzrError, BzrCheckError, BzrCommandError
25
 
from bzrlib.osutils import quotefn, pumpfile, isdir, isfile
26
 
from bzrlib.tree import RevisionTree, EmptyTree, Tree
27
 
from bzrlib.revision import Revision
28
 
from bzrlib import Branch, Inventory, InventoryEntry, ScratchBranch, BZRDIR, \
29
 
     format_date
 
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__])
30
44
 
31
45
 
32
46
def _squish_command_name(cmd):
37
51
    assert cmd.startswith("cmd_")
38
52
    return cmd[4:].replace('_','-')
39
53
 
40
 
def get_all_cmds():
41
 
    """Return canonical name and class for all registered commands."""
 
54
def _parse_revision_str(revstr):
 
55
    """This handles a revision string -> revno. 
 
56
 
 
57
    There are several possibilities:
 
58
 
 
59
        '234'       -> 234
 
60
        '234:345'   -> [234, 345]
 
61
        ':234'      -> [None, 234]
 
62
        '234:'      -> [234, None]
 
63
 
 
64
    In the future we will also support:
 
65
        'uuid:blah-blah-blah'   -> ?
 
66
        'hash:blahblahblah'     -> ?
 
67
        potentially:
 
68
        'tag:mytag'             -> ?
 
69
    """
 
70
    if revstr.find(':') != -1:
 
71
        revs = revstr.split(':')
 
72
        if len(revs) > 2:
 
73
            raise ValueError('More than 2 pieces not supported for --revision: %r' % revstr)
 
74
 
 
75
        if not revs[0]:
 
76
            revs[0] = None
 
77
        else:
 
78
            revs[0] = int(revs[0])
 
79
 
 
80
        if not revs[1]:
 
81
            revs[1] = None
 
82
        else:
 
83
            revs[1] = int(revs[1])
 
84
    else:
 
85
        revs = int(revstr)
 
86
    return revs
 
87
 
 
88
 
 
89
 
 
90
def _get_cmd_dict(plugins_override=True):
 
91
    d = {}
42
92
    for k, v in globals().iteritems():
43
93
        if k.startswith("cmd_"):
44
 
            yield _unsquish_command_name(k), v
45
 
 
46
 
def get_cmd_class(cmd):
 
94
            d[_unsquish_command_name(k)] = v
 
95
    # If we didn't load plugins, the plugin_cmds dict will be empty
 
96
    if plugins_override:
 
97
        d.update(plugin_cmds)
 
98
    else:
 
99
        d2 = plugin_cmds.copy()
 
100
        d2.update(d)
 
101
        d = d2
 
102
    return d
 
103
 
 
104
    
 
105
def get_all_cmds(plugins_override=True):
 
106
    """Return canonical name and class for all registered commands."""
 
107
    for k, v in _get_cmd_dict(plugins_override=plugins_override).iteritems():
 
108
        yield k,v
 
109
 
 
110
 
 
111
def get_cmd_class(cmd, plugins_override=True):
47
112
    """Return the canonical name and command class for a command.
48
113
    """
49
114
    cmd = str(cmd)                      # not unicode
50
115
 
51
116
    # first look up this command under the specified name
 
117
    cmds = _get_cmd_dict(plugins_override=plugins_override)
52
118
    try:
53
 
        return cmd, globals()[_squish_command_name(cmd)]
 
119
        return cmd, cmds[cmd]
54
120
    except KeyError:
55
121
        pass
56
122
 
57
123
    # look for any command which claims this as an alias
58
 
    for cmdname, cmdclass in get_all_cmds():
 
124
    for cmdname, cmdclass in cmds.iteritems():
59
125
        if cmd in cmdclass.aliases:
60
126
            return cmdname, cmdclass
61
127
 
66
132
    raise BzrCommandError("unknown command %r" % cmd)
67
133
 
68
134
 
69
 
class Command:
 
135
class Command(object):
70
136
    """Base class for commands.
71
137
 
72
138
    The docstring for an actual command should give a single-line
131
197
    """
132
198
 
133
199
    def find_command(cls, cmd):
 
200
        import os.path
134
201
        bzrpath = os.environ.get('BZRPATH', '')
135
202
 
136
 
        for dir in bzrpath.split(':'):
 
203
        for dir in bzrpath.split(os.pathsep):
137
204
            path = os.path.join(dir, cmd)
138
205
            if os.path.isfile(path):
139
206
                return ExternalCommand(path)
145
212
    def __init__(self, path):
146
213
        self.path = path
147
214
 
148
 
        # TODO: If either of these fail, we should detect that and
149
 
        # assume that path is not really a bzr plugin after all.
150
 
 
151
215
        pipe = os.popen('%s --bzr-usage' % path, 'r')
152
216
        self.takes_options = pipe.readline().split()
 
217
 
 
218
        for opt in self.takes_options:
 
219
            if not opt in OPTIONS:
 
220
                raise BzrError("Unknown option '%s' returned by external command %s"
 
221
                               % (opt, path))
 
222
 
 
223
        # TODO: Is there any way to check takes_args is valid here?
153
224
        self.takes_args = pipe.readline().split()
154
 
        pipe.close()
 
225
 
 
226
        if pipe.close() is not None:
 
227
            raise BzrError("Failed funning '%s --bzr-usage'" % path)
155
228
 
156
229
        pipe = os.popen('%s --bzr-help' % path, 'r')
157
230
        self.__doc__ = pipe.read()
158
 
        pipe.close()
 
231
        if pipe.close() is not None:
 
232
            raise BzrError("Failed funning '%s --bzr-help'" % path)
159
233
 
160
234
    def __call__(self, options, arguments):
161
235
        Command.__init__(self, options, arguments)
168
242
        keys = kargs.keys()
169
243
        keys.sort()
170
244
        for name in keys:
 
245
            optname = name.replace('_','-')
171
246
            value = kargs[name]
172
 
            if OPTIONS.has_key(name):
 
247
            if OPTIONS.has_key(optname):
173
248
                # it's an option
174
 
                opts.append('--%s' % name)
 
249
                opts.append('--%s' % optname)
175
250
                if value is not None and value is not True:
176
251
                    opts.append(str(value))
177
252
            else:
228
303
    
229
304
    def run(self, all=False, show_ids=False, file_list=None):
230
305
        if file_list:
231
 
            b = Branch(file_list[0], lock_mode='r')
 
306
            b = find_branch(file_list[0])
232
307
            file_list = [b.relpath(x) for x in file_list]
233
308
            # special case: only one path was given and it's the root
234
309
            # of the branch
235
310
            if file_list == ['']:
236
311
                file_list = None
237
312
        else:
238
 
            b = Branch('.', lock_mode='r')
 
313
            b = find_branch('.')
239
314
        import status
240
315
        status.show_status(b, show_unchanged=all, show_ids=show_ids,
241
316
                           specific_files=file_list)
248
323
    takes_args = ['revision_id']
249
324
    
250
325
    def run(self, revision_id):
251
 
        Branch('.').get_revision(revision_id).write_xml(sys.stdout)
 
326
        from bzrlib.xml import pack_xml
 
327
        pack_xml(find_branch('.').get_revision(revision_id), sys.stdout)
252
328
 
253
329
 
254
330
class cmd_revno(Command):
256
332
 
257
333
    This is equal to the number of revisions on this branch."""
258
334
    def run(self):
259
 
        print Branch('.').revno()
 
335
        print find_branch('.').revno()
260
336
 
261
337
    
262
338
class cmd_add(Command):
281
357
    recursively add that parent, rather than giving an error?
282
358
    """
283
359
    takes_args = ['file+']
284
 
    takes_options = ['verbose']
 
360
    takes_options = ['verbose', 'no-recurse']
285
361
    
286
 
    def run(self, file_list, verbose=False):
287
 
        bzrlib.add.smart_add(file_list, verbose)
 
362
    def run(self, file_list, verbose=False, no_recurse=False):
 
363
        from bzrlib.add import smart_add
 
364
        smart_add(file_list, verbose, not no_recurse)
 
365
 
 
366
 
 
367
 
 
368
class cmd_mkdir(Command):
 
369
    """Create a new versioned directory.
 
370
 
 
371
    This is equivalent to creating the directory and then adding it.
 
372
    """
 
373
    takes_args = ['dir+']
 
374
 
 
375
    def run(self, dir_list):
 
376
        b = None
 
377
        
 
378
        for d in dir_list:
 
379
            os.mkdir(d)
 
380
            if not b:
 
381
                b = find_branch(d)
 
382
            b.add([d], verbose=True)
288
383
 
289
384
 
290
385
class cmd_relpath(Command):
291
386
    """Show path of a file relative to root"""
292
387
    takes_args = ['filename']
 
388
    hidden = True
293
389
    
294
390
    def run(self, filename):
295
 
        print Branch(filename).relpath(filename)
 
391
        print find_branch(filename).relpath(filename)
296
392
 
297
393
 
298
394
 
299
395
class cmd_inventory(Command):
300
396
    """Show inventory of the current working copy or a revision."""
301
 
    takes_options = ['revision']
 
397
    takes_options = ['revision', 'show-ids']
302
398
    
303
 
    def run(self, revision=None):
304
 
        b = Branch('.')
 
399
    def run(self, revision=None, show_ids=False):
 
400
        b = find_branch('.')
305
401
        if revision == None:
306
402
            inv = b.read_working_inventory()
307
403
        else:
308
404
            inv = b.get_revision_inventory(b.lookup_revision(revision))
309
405
 
310
 
        for path, entry in inv.iter_entries():
311
 
            print '%-50s %s' % (entry.file_id, path)
 
406
        for path, entry in inv.entries():
 
407
            if show_ids:
 
408
                print '%-50s %s' % (path, entry.file_id)
 
409
            else:
 
410
                print path
312
411
 
313
412
 
314
413
class cmd_move(Command):
321
420
    """
322
421
    takes_args = ['source$', 'dest']
323
422
    def run(self, source_list, dest):
324
 
        b = Branch('.')
 
423
        b = find_branch('.')
325
424
 
326
425
        b.move([b.relpath(s) for s in source_list], b.relpath(dest))
327
426
 
343
442
    takes_args = ['from_name', 'to_name']
344
443
    
345
444
    def run(self, from_name, to_name):
346
 
        b = Branch('.')
 
445
        b = find_branch('.')
347
446
        b.rename_one(b.relpath(from_name), b.relpath(to_name))
348
447
 
349
448
 
350
449
 
 
450
 
 
451
 
 
452
class cmd_pull(Command):
 
453
    """Pull any changes from another branch into the current one.
 
454
 
 
455
    If the location is omitted, the last-used location will be used.
 
456
    Both the revision history and the working directory will be
 
457
    updated.
 
458
 
 
459
    This command only works on branches that have not diverged.  Branches are
 
460
    considered diverged if both branches have had commits without first
 
461
    pulling from the other.
 
462
 
 
463
    If branches have diverged, you can use 'bzr merge' to pull the text changes
 
464
    from one into the other.
 
465
    """
 
466
    takes_args = ['location?']
 
467
 
 
468
    def run(self, location=None):
 
469
        from bzrlib.merge import merge
 
470
        import tempfile
 
471
        from shutil import rmtree
 
472
        import errno
 
473
        
 
474
        br_to = find_branch('.')
 
475
        stored_loc = None
 
476
        try:
 
477
            stored_loc = br_to.controlfile("x-pull", "rb").read().rstrip('\n')
 
478
        except IOError, e:
 
479
            if e.errno != errno.ENOENT:
 
480
                raise
 
481
        if location is None:
 
482
            if stored_loc is None:
 
483
                raise BzrCommandError("No pull location known or specified.")
 
484
            else:
 
485
                print "Using last location: %s" % stored_loc
 
486
                location = stored_loc
 
487
        cache_root = tempfile.mkdtemp()
 
488
        from bzrlib.branch import DivergedBranches
 
489
        br_from = find_branch(location)
 
490
        location = pull_loc(br_from)
 
491
        old_revno = br_to.revno()
 
492
        try:
 
493
            from branch import find_cached_branch, DivergedBranches
 
494
            br_from = find_cached_branch(location, cache_root)
 
495
            location = pull_loc(br_from)
 
496
            old_revno = br_to.revno()
 
497
            try:
 
498
                br_to.update_revisions(br_from)
 
499
            except DivergedBranches:
 
500
                raise BzrCommandError("These branches have diverged."
 
501
                    "  Try merge.")
 
502
                
 
503
            merge(('.', -1), ('.', old_revno), check_clean=False)
 
504
            if location != stored_loc:
 
505
                br_to.controlfile("x-pull", "wb").write(location + "\n")
 
506
        finally:
 
507
            rmtree(cache_root)
 
508
 
 
509
 
 
510
 
 
511
class cmd_branch(Command):
 
512
    """Create a new copy of a branch.
 
513
 
 
514
    If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
 
515
    be used.  In other words, "branch ../foo/bar" will attempt to create ./bar.
 
516
 
 
517
    To retrieve the branch as of a particular revision, supply the --revision
 
518
    parameter, as in "branch foo/bar -r 5".
 
519
    """
 
520
    takes_args = ['from_location', 'to_location?']
 
521
    takes_options = ['revision']
 
522
 
 
523
    def run(self, from_location, to_location=None, revision=None):
 
524
        import errno
 
525
        from bzrlib.merge import merge
 
526
        from bzrlib.branch import DivergedBranches, NoSuchRevision, \
 
527
             find_cached_branch, Branch
 
528
        from shutil import rmtree
 
529
        from meta_store import CachedStore
 
530
        import tempfile
 
531
        cache_root = tempfile.mkdtemp()
 
532
        try:
 
533
            try:
 
534
                br_from = find_cached_branch(from_location, cache_root)
 
535
            except OSError, e:
 
536
                if e.errno == errno.ENOENT:
 
537
                    raise BzrCommandError('Source location "%s" does not'
 
538
                                          ' exist.' % to_location)
 
539
                else:
 
540
                    raise
 
541
 
 
542
            if to_location is None:
 
543
                to_location = os.path.basename(from_location.rstrip("/\\"))
 
544
 
 
545
            try:
 
546
                os.mkdir(to_location)
 
547
            except OSError, e:
 
548
                if e.errno == errno.EEXIST:
 
549
                    raise BzrCommandError('Target directory "%s" already'
 
550
                                          ' exists.' % to_location)
 
551
                if e.errno == errno.ENOENT:
 
552
                    raise BzrCommandError('Parent of "%s" does not exist.' %
 
553
                                          to_location)
 
554
                else:
 
555
                    raise
 
556
            br_to = Branch(to_location, init=True)
 
557
 
 
558
            try:
 
559
                br_to.update_revisions(br_from, stop_revision=revision)
 
560
            except NoSuchRevision:
 
561
                rmtree(to_location)
 
562
                msg = "The branch %s has no revision %d." % (from_location,
 
563
                                                             revision)
 
564
                raise BzrCommandError(msg)
 
565
            merge((to_location, -1), (to_location, 0), this_dir=to_location,
 
566
                  check_clean=False, ignore_zero=True)
 
567
            from_location = pull_loc(br_from)
 
568
            br_to.controlfile("x-pull", "wb").write(from_location + "\n")
 
569
        finally:
 
570
            rmtree(cache_root)
 
571
 
 
572
 
 
573
def pull_loc(branch):
 
574
    # TODO: Should perhaps just make attribute be 'base' in
 
575
    # RemoteBranch and Branch?
 
576
    if hasattr(branch, "baseurl"):
 
577
        return branch.baseurl
 
578
    else:
 
579
        return branch.base
 
580
 
 
581
 
 
582
 
351
583
class cmd_renames(Command):
352
584
    """Show list of renamed files.
353
585
 
358
590
    takes_args = ['dir?']
359
591
 
360
592
    def run(self, dir='.'):
361
 
        b = Branch(dir)
 
593
        b = find_branch(dir)
362
594
        old_inv = b.basis_tree().inventory
363
595
        new_inv = b.read_working_inventory()
364
596
 
375
607
    def run(self, branch=None):
376
608
        import info
377
609
 
378
 
        from branch import find_branch
379
610
        b = find_branch(branch)
380
611
        info.show_info(b)
381
612
 
390
621
    takes_options = ['verbose']
391
622
    
392
623
    def run(self, file_list, verbose=False):
393
 
        b = Branch(file_list[0])
 
624
        b = find_branch(file_list[0])
394
625
        b.remove([b.relpath(f) for f in file_list], verbose=verbose)
395
626
 
396
627
 
404
635
    hidden = True
405
636
    takes_args = ['filename']
406
637
    def run(self, filename):
407
 
        b = Branch(filename)
 
638
        b = find_branch(filename)
408
639
        i = b.inventory.path2id(b.relpath(filename))
409
640
        if i == None:
410
 
            bailout("%r is not a versioned file" % filename)
 
641
            raise BzrError("%r is not a versioned file" % filename)
411
642
        else:
412
643
            print i
413
644
 
420
651
    hidden = True
421
652
    takes_args = ['filename']
422
653
    def run(self, filename):
423
 
        b = Branch(filename)
 
654
        b = find_branch(filename)
424
655
        inv = b.inventory
425
656
        fid = inv.path2id(b.relpath(filename))
426
657
        if fid == None:
427
 
            bailout("%r is not a versioned file" % filename)
 
658
            raise BzrError("%r is not a versioned file" % filename)
428
659
        for fip in inv.get_idpath(fid):
429
660
            print fip
430
661
 
431
662
 
432
663
class cmd_revision_history(Command):
433
664
    """Display list of revision ids on this branch."""
 
665
    hidden = True
434
666
    def run(self):
435
 
        for patchid in Branch('.').revision_history():
 
667
        for patchid in find_branch('.').revision_history():
436
668
            print patchid
437
669
 
438
670
 
439
671
class cmd_directories(Command):
440
672
    """Display list of versioned directories in this branch."""
441
673
    def run(self):
442
 
        for name, ie in Branch('.').read_working_inventory().directories():
 
674
        for name, ie in find_branch('.').read_working_inventory().directories():
443
675
            if name == '':
444
676
                print '.'
445
677
            else:
460
692
        bzr commit -m 'imported project'
461
693
    """
462
694
    def run(self):
 
695
        from bzrlib.branch import Branch
463
696
        Branch('.', init=True)
464
697
 
465
698
 
488
721
    """
489
722
    
490
723
    takes_args = ['file*']
491
 
    takes_options = ['revision']
492
 
    aliases = ['di']
 
724
    takes_options = ['revision', 'diff-options']
 
725
    aliases = ['di', 'dif']
493
726
 
494
 
    def run(self, revision=None, file_list=None):
 
727
    def run(self, revision=None, file_list=None, diff_options=None):
495
728
        from bzrlib.diff import show_diff
 
729
 
 
730
        if file_list:
 
731
            b = find_branch(file_list[0])
 
732
            file_list = [b.relpath(f) for f in file_list]
 
733
            if file_list == ['']:
 
734
                # just pointing to top-of-tree
 
735
                file_list = None
 
736
        else:
 
737
            b = find_branch('.')
496
738
    
497
 
        show_diff(Branch('.'), revision, specific_files=file_list)
 
739
        show_diff(b, revision, specific_files=file_list,
 
740
                  external_diff_options=diff_options)
498
741
 
499
742
 
500
743
        
506
749
    TODO: Show files deleted since a previous revision, or between two revisions.
507
750
    """
508
751
    def run(self, show_ids=False):
509
 
        b = Branch('.')
 
752
        b = find_branch('.')
510
753
        old = b.basis_tree()
511
754
        new = b.working_tree()
512
755
 
527
770
    """List files modified in working tree."""
528
771
    hidden = True
529
772
    def run(self):
530
 
        import statcache
531
 
        b = Branch('.')
 
773
        from bzrlib.statcache import update_cache, SC_SHA1
 
774
        b = find_branch('.')
532
775
        inv = b.read_working_inventory()
533
 
        sc = statcache.update_cache(b, inv)
 
776
        sc = update_cache(b, inv)
534
777
        basis = b.basis_tree()
535
778
        basis_inv = basis.inventory
536
779
        
544
787
            if not cacheentry:                 # deleted
545
788
                continue
546
789
            ie = basis_inv[file_id]
547
 
            if cacheentry[statcache.SC_SHA1] != ie.text_sha1:
 
790
            if cacheentry[SC_SHA1] != ie.text_sha1:
548
791
                path = inv.id2path(file_id)
549
792
                print path
550
793
 
554
797
    """List files added in working tree."""
555
798
    hidden = True
556
799
    def run(self):
557
 
        b = Branch('.')
 
800
        b = find_branch('.')
558
801
        wt = b.working_tree()
559
802
        basis_inv = b.basis_tree().inventory
560
803
        inv = wt.inventory
576
819
    takes_args = ['filename?']
577
820
    def run(self, filename=None):
578
821
        """Print the branch root."""
579
 
        from branch import find_branch
580
822
        b = find_branch(filename)
581
823
        print getattr(b, 'base', None) or getattr(b, 'baseurl')
582
824
 
584
826
class cmd_log(Command):
585
827
    """Show log of this branch.
586
828
 
587
 
    TODO: Option to limit range.
 
829
    To request a range of logs, you can use the command -r begin:end
 
830
    -r revision requests a specific revision, -r :end or -r begin: are
 
831
    also valid.
588
832
 
589
 
    TODO: Perhaps show most-recent first with an option for last.
 
833
    TODO: Make --revision support uuid: and hash: [future tag:] notation.
 
834
  
590
835
    """
 
836
 
591
837
    takes_args = ['filename?']
592
 
    takes_options = ['timezone', 'verbose', 'show-ids']
593
 
    def run(self, filename=None, timezone='original', verbose=False, show_ids=False):
594
 
        from branch import find_branch
595
 
        b = find_branch((filename or '.'), lock_mode='r')
 
838
    takes_options = ['forward', 'timezone', 'verbose', 'show-ids', 'revision','long']
 
839
    
 
840
    def run(self, filename=None, timezone='original',
 
841
            verbose=False,
 
842
            show_ids=False,
 
843
            forward=False,
 
844
            revision=None,
 
845
            long=False):
 
846
        from bzrlib.branch import find_branch
 
847
        from bzrlib.log import log_formatter, show_log
 
848
        import codecs
 
849
 
 
850
        direction = (forward and 'forward') or 'reverse'
 
851
        
596
852
        if filename:
597
 
            filename = b.relpath(filename)
598
 
        bzrlib.show_log(b, filename,
599
 
                        show_timezone=timezone,
600
 
                        verbose=verbose,
601
 
                        show_ids=show_ids)
 
853
            b = find_branch(filename)
 
854
            fp = b.relpath(filename)
 
855
            if fp:
 
856
                file_id = b.read_working_inventory().path2id(fp)
 
857
            else:
 
858
                file_id = None  # points to branch root
 
859
        else:
 
860
            b = find_branch('.')
 
861
            file_id = None
 
862
 
 
863
        if revision == None:
 
864
            revision = [None, None]
 
865
        elif isinstance(revision, int):
 
866
            revision = [revision, revision]
 
867
        else:
 
868
            # pair of revisions?
 
869
            pass
 
870
            
 
871
        assert len(revision) == 2
 
872
 
 
873
        mutter('encoding log as %r' % bzrlib.user_encoding)
 
874
 
 
875
        # use 'replace' so that we don't abort if trying to write out
 
876
        # in e.g. the default C locale.
 
877
        outf = codecs.getwriter(bzrlib.user_encoding)(sys.stdout, errors='replace')
 
878
 
 
879
        if long:
 
880
            log_format = 'long'
 
881
        else:
 
882
            log_format = 'short'
 
883
        lf = log_formatter(log_format,
 
884
                           show_ids=show_ids,
 
885
                           to_file=outf,
 
886
                           show_timezone=timezone)
 
887
 
 
888
        show_log(b,
 
889
                 lf,
 
890
                 file_id,
 
891
                 verbose=verbose,
 
892
                 direction=direction,
 
893
                 start_revision=revision[0],
 
894
                 end_revision=revision[1])
602
895
 
603
896
 
604
897
 
605
898
class cmd_touching_revisions(Command):
606
 
    """Return revision-ids which affected a particular file."""
 
899
    """Return revision-ids which affected a particular file.
 
900
 
 
901
    A more user-friendly interface is "bzr log FILE"."""
607
902
    hidden = True
608
903
    takes_args = ["filename"]
609
904
    def run(self, filename):
610
 
        b = Branch(filename, lock_mode='r')
 
905
        b = find_branch(filename)
611
906
        inv = b.read_working_inventory()
612
907
        file_id = inv.path2id(b.relpath(filename))
613
908
        for revno, revision_id, what in bzrlib.log.find_touching_revisions(b, file_id):
621
916
    """
622
917
    hidden = True
623
918
    def run(self, revision=None, verbose=False):
624
 
        b = Branch('.')
 
919
        b = find_branch('.')
625
920
        if revision == None:
626
921
            tree = b.working_tree()
627
922
        else:
643
938
 
644
939
 
645
940
class cmd_unknowns(Command):
646
 
    """List unknown files"""
 
941
    """List unknown files."""
647
942
    def run(self):
648
 
        for f in Branch('.').unknowns():
 
943
        from bzrlib.osutils import quotefn
 
944
        for f in find_branch('.').unknowns():
649
945
            print quotefn(f)
650
946
 
651
947
 
652
948
 
653
949
class cmd_ignore(Command):
654
 
    """Ignore a command or pattern
 
950
    """Ignore a command or pattern.
655
951
 
656
952
    To remove patterns from the ignore list, edit the .bzrignore file.
657
953
 
671
967
    
672
968
    def run(self, name_pattern):
673
969
        from bzrlib.atomicfile import AtomicFile
674
 
        import codecs
 
970
        import os.path
675
971
 
676
 
        b = Branch('.')
 
972
        b = find_branch('.')
677
973
        ifn = b.abspath('.bzrignore')
678
974
 
679
 
        # FIXME: probably doesn't handle non-ascii patterns
680
 
 
681
975
        if os.path.exists(ifn):
682
 
            f = b.controlfile(ifn, 'rt')
683
 
            igns = f.read()
684
 
            f.close()
 
976
            f = open(ifn, 'rt')
 
977
            try:
 
978
                igns = f.read().decode('utf-8')
 
979
            finally:
 
980
                f.close()
685
981
        else:
686
982
            igns = ''
687
983
 
 
984
        # TODO: If the file already uses crlf-style termination, maybe
 
985
        # we should use that for the newly added lines?
 
986
 
688
987
        if igns and igns[-1] != '\n':
689
988
            igns += '\n'
690
989
        igns += name_pattern + '\n'
691
990
 
692
 
        f = AtomicFile(ifn, 'wt')
693
 
        f.write(igns)
694
 
        f.commit()
 
991
        try:
 
992
            f = AtomicFile(ifn, 'wt')
 
993
            f.write(igns.encode('utf-8'))
 
994
            f.commit()
 
995
        finally:
 
996
            f.close()
695
997
 
696
998
        inv = b.working_tree().inventory
697
999
        if inv.path2id('.bzrignore'):
707
1009
 
708
1010
    See also: bzr ignore"""
709
1011
    def run(self):
710
 
        tree = Branch('.').working_tree()
 
1012
        tree = find_branch('.').working_tree()
711
1013
        for path, file_class, kind, file_id in tree.list_files():
712
1014
            if file_class != 'I':
713
1015
                continue
731
1033
        except ValueError:
732
1034
            raise BzrCommandError("not a valid revision-number: %r" % revno)
733
1035
 
734
 
        print Branch('.').lookup_revision(revno)
 
1036
        print find_branch('.').lookup_revision(revno)
735
1037
 
736
1038
 
737
1039
class cmd_export(Command):
738
1040
    """Export past revision to destination directory.
739
1041
 
740
 
    If no revision is specified this exports the last committed revision."""
 
1042
    If no revision is specified this exports the last committed revision.
 
1043
 
 
1044
    Format may be an "exporter" name, such as tar, tgz, tbz2.  If none is
 
1045
    given, exports to a directory (equivalent to --format=dir).
 
1046
 
 
1047
    Root may be the top directory for tar, tgz and tbz2 formats."""
 
1048
    # TODO: list known exporters
741
1049
    takes_args = ['dest']
742
 
    takes_options = ['revision']
743
 
    def run(self, dest, revision=None):
744
 
        b = Branch('.')
 
1050
    takes_options = ['revision', 'format', 'root']
 
1051
    def run(self, dest, revision=None, format='dir', root=None):
 
1052
        b = find_branch('.')
745
1053
        if revision == None:
746
1054
            rh = b.revision_history()[-1]
747
1055
        else:
748
1056
            rh = b.lookup_revision(int(revision))
749
1057
        t = b.revision_tree(rh)
750
 
        t.export(dest)
 
1058
        t.export(dest, format, root)
751
1059
 
752
1060
 
753
1061
class cmd_cat(Command):
759
1067
    def run(self, filename, revision=None):
760
1068
        if revision == None:
761
1069
            raise BzrCommandError("bzr cat requires a revision number")
762
 
        b = Branch('.')
 
1070
        b = find_branch('.')
763
1071
        b.print_file(b.relpath(filename), int(revision))
764
1072
 
765
1073
 
774
1082
class cmd_commit(Command):
775
1083
    """Commit changes into a new revision.
776
1084
 
777
 
    TODO: Commit only selected files.
 
1085
    If selected files are specified, only changes to those files are
 
1086
    committed.  If a directory is specified then its contents are also
 
1087
    committed.
 
1088
 
 
1089
    A selected-file commit may fail in some cases where the committed
 
1090
    tree would be invalid, such as trying to commit a file in a
 
1091
    newly-added directory that is not itself committed.
778
1092
 
779
1093
    TODO: Run hooks on tree to-be-committed, and after commit.
780
1094
 
781
1095
    TODO: Strict commit that fails if there are unknown or deleted files.
782
1096
    """
 
1097
    takes_args = ['selected*']
783
1098
    takes_options = ['message', 'file', 'verbose']
784
1099
    aliases = ['ci', 'checkin']
785
1100
 
786
 
    def run(self, message=None, file=None, verbose=False):
 
1101
    def run(self, message=None, file=None, verbose=True, selected_list=None):
 
1102
        from bzrlib.commit import commit
 
1103
        from bzrlib.osutils import get_text_message
 
1104
 
787
1105
        ## Warning: shadows builtin file()
788
1106
        if not message and not file:
789
 
            raise BzrCommandError("please specify a commit message",
790
 
                                  ["use either --message or --file"])
 
1107
            import cStringIO
 
1108
            stdout = sys.stdout
 
1109
            catcher = cStringIO.StringIO()
 
1110
            sys.stdout = catcher
 
1111
            cmd_status({"file_list":selected_list}, {})
 
1112
            info = catcher.getvalue()
 
1113
            sys.stdout = stdout
 
1114
            message = get_text_message(info)
 
1115
            
 
1116
            if message is None:
 
1117
                raise BzrCommandError("please specify a commit message",
 
1118
                                      ["use either --message or --file"])
791
1119
        elif message and file:
792
1120
            raise BzrCommandError("please specify either --message or --file")
793
1121
        
795
1123
            import codecs
796
1124
            message = codecs.open(file, 'rt', bzrlib.user_encoding).read()
797
1125
 
798
 
        Branch('.').commit(message, verbose=verbose)
 
1126
        b = find_branch('.')
 
1127
        commit(b, message, verbose=verbose, specific_files=selected_list)
799
1128
 
800
1129
 
801
1130
class cmd_check(Command):
803
1132
 
804
1133
    This command checks various invariants about the branch storage to
805
1134
    detect data corruption or bzr bugs.
806
 
    """
807
 
    takes_args = ['dir?']
808
 
    def run(self, dir='.'):
809
 
        import bzrlib.check
810
 
        bzrlib.check.check(Branch(dir, find_root=False))
 
1135
 
 
1136
    If given the --update flag, it will update some optional fields
 
1137
    to help ensure data consistency.
 
1138
    """
 
1139
    takes_args = ['dir?']
 
1140
 
 
1141
    def run(self, dir='.'):
 
1142
        from bzrlib.check import check
 
1143
        check(find_branch(dir))
 
1144
 
 
1145
 
 
1146
 
 
1147
class cmd_upgrade(Command):
 
1148
    """Upgrade branch storage to current format.
 
1149
 
 
1150
    This should normally be used only after the check command tells
 
1151
    you to run it.
 
1152
    """
 
1153
    takes_args = ['dir?']
 
1154
 
 
1155
    def run(self, dir='.'):
 
1156
        from bzrlib.upgrade import upgrade
 
1157
        upgrade(find_branch(dir))
811
1158
 
812
1159
 
813
1160
 
826
1173
    """Run internal test suite"""
827
1174
    hidden = True
828
1175
    def run(self):
829
 
        failures, tests = 0, 0
830
 
 
831
 
        import doctest, bzrlib.store, bzrlib.tests
832
 
        bzrlib.trace.verbose = False
833
 
 
834
 
        for m in bzrlib.store, bzrlib.inventory, bzrlib.branch, bzrlib.osutils, \
835
 
            bzrlib.tree, bzrlib.tests, bzrlib.commands, bzrlib.add:
836
 
            mf, mt = doctest.testmod(m)
837
 
            failures += mf
838
 
            tests += mt
839
 
            print '%-40s %3d tests' % (m.__name__, mt),
840
 
            if mf:
841
 
                print '%3d FAILED!' % mf
842
 
            else:
843
 
                print
844
 
 
845
 
        print '%-40s %3d tests' % ('total', tests),
846
 
        if failures:
847
 
            print '%3d FAILED!' % failures
848
 
        else:
849
 
            print
850
 
 
 
1176
        from bzrlib.selftest import selftest
 
1177
        return int(not selftest())
851
1178
 
852
1179
 
853
1180
class cmd_version(Command):
854
 
    """Show version of bzr"""
 
1181
    """Show version of bzr."""
855
1182
    def run(self):
856
1183
        show_version()
857
1184
 
858
1185
def show_version():
859
1186
    print "bzr (bazaar-ng) %s" % bzrlib.__version__
 
1187
    # is bzrlib itself in a branch?
 
1188
    bzrrev = bzrlib.get_bzr_revision()
 
1189
    if bzrrev:
 
1190
        print "  (bzr checkout, revision %d {%s})" % bzrrev
860
1191
    print bzrlib.__copyright__
861
1192
    print "http://bazaar-ng.org/"
862
1193
    print
871
1202
    def run(self):
872
1203
        print "it sure does!"
873
1204
 
 
1205
def parse_spec(spec):
 
1206
    """
 
1207
    >>> parse_spec(None)
 
1208
    [None, None]
 
1209
    >>> parse_spec("./")
 
1210
    ['./', None]
 
1211
    >>> parse_spec("../@")
 
1212
    ['..', -1]
 
1213
    >>> parse_spec("../f/@35")
 
1214
    ['../f', 35]
 
1215
    """
 
1216
    if spec is None:
 
1217
        return [None, None]
 
1218
    if '/@' in spec:
 
1219
        parsed = spec.split('/@')
 
1220
        assert len(parsed) == 2
 
1221
        if parsed[1] == "":
 
1222
            parsed[1] = -1
 
1223
        else:
 
1224
            parsed[1] = int(parsed[1])
 
1225
            assert parsed[1] >=0
 
1226
    else:
 
1227
        parsed = [spec, None]
 
1228
    return parsed
 
1229
 
 
1230
 
 
1231
 
 
1232
class cmd_merge(Command):
 
1233
    """Perform a three-way merge of trees.
 
1234
    
 
1235
    The SPEC parameters are working tree or revision specifiers.  Working trees
 
1236
    are specified using standard paths or urls.  No component of a directory
 
1237
    path may begin with '@'.
 
1238
    
 
1239
    Working tree examples: '.', '..', 'foo@', but NOT 'foo/@bar'
 
1240
 
 
1241
    Revisions are specified using a dirname/@revno pair, where dirname is the
 
1242
    branch directory and revno is the revision within that branch.  If no revno
 
1243
    is specified, the latest revision is used.
 
1244
 
 
1245
    Revision examples: './@127', 'foo/@', '../@1'
 
1246
 
 
1247
    The OTHER_SPEC parameter is required.  If the BASE_SPEC parameter is
 
1248
    not supplied, the common ancestor of OTHER_SPEC the current branch is used
 
1249
    as the BASE.
 
1250
 
 
1251
    merge refuses to run if there are any uncommitted changes, unless
 
1252
    --force is given.
 
1253
    """
 
1254
    takes_args = ['other_spec', 'base_spec?']
 
1255
    takes_options = ['force']
 
1256
 
 
1257
    def run(self, other_spec, base_spec=None, force=False):
 
1258
        from bzrlib.merge import merge
 
1259
        merge(parse_spec(other_spec), parse_spec(base_spec),
 
1260
              check_clean=(not force))
 
1261
 
 
1262
 
 
1263
 
 
1264
class cmd_revert(Command):
 
1265
    """Restore selected files from a previous revision.
 
1266
    """
 
1267
    takes_args = ['file+']
 
1268
    def run(self, file_list):
 
1269
        from bzrlib.branch import find_branch
 
1270
        
 
1271
        if not file_list:
 
1272
            file_list = ['.']
 
1273
            
 
1274
        b = find_branch(file_list[0])
 
1275
 
 
1276
        b.revert([b.relpath(f) for f in file_list])
 
1277
 
 
1278
 
 
1279
class cmd_merge_revert(Command):
 
1280
    """Reverse all changes since the last commit.
 
1281
 
 
1282
    Only versioned files are affected.
 
1283
 
 
1284
    TODO: Store backups of any files that will be reverted, so
 
1285
          that the revert can be undone.          
 
1286
    """
 
1287
    takes_options = ['revision']
 
1288
 
 
1289
    def run(self, revision=-1):
 
1290
        from bzrlib.merge import merge
 
1291
        merge(('.', revision), parse_spec('.'),
 
1292
              check_clean=False,
 
1293
              ignore_zero=True)
 
1294
 
874
1295
 
875
1296
class cmd_assert_fail(Command):
876
1297
    """Test reporting of assertion failures"""
897
1318
    For testing only."""
898
1319
    hidden = True
899
1320
    def run(self):
900
 
        import statcache
901
 
        b = Branch('.')
902
 
        statcache.update_cache(b.base, b.read_working_inventory())
903
 
 
904
 
 
905
 
######################################################################
906
 
# main routine
 
1321
        from bzrlib.statcache import update_cache
 
1322
        b = find_branch('.')
 
1323
        update_cache(b.base, b.read_working_inventory())
 
1324
 
 
1325
 
 
1326
 
 
1327
class cmd_plugins(Command):
 
1328
    """List plugins"""
 
1329
    hidden = True
 
1330
    def run(self):
 
1331
        import bzrlib.plugin
 
1332
        from pprint import pprint
 
1333
        pprint(bzrlib.plugin.all_plugins)
 
1334
 
907
1335
 
908
1336
 
909
1337
# list of all available options; the rhs can be either None for an
911
1339
# the type.
912
1340
OPTIONS = {
913
1341
    'all':                    None,
 
1342
    'diff-options':           str,
914
1343
    'help':                   None,
915
1344
    'file':                   unicode,
 
1345
    'force':                  None,
 
1346
    'format':                 unicode,
 
1347
    'forward':                None,
916
1348
    'message':                unicode,
 
1349
    'no-recurse':             None,
917
1350
    'profile':                None,
918
 
    'revision':               int,
 
1351
    'revision':               _parse_revision_str,
919
1352
    'show-ids':               None,
920
1353
    'timezone':               str,
921
1354
    'verbose':                None,
922
1355
    'version':                None,
923
1356
    'email':                  None,
 
1357
    'update':                 None,
 
1358
    'long':                   None,
 
1359
    'root':                   str,
924
1360
    }
925
1361
 
926
1362
SHORT_OPTIONS = {
 
1363
    'F':                      'file', 
 
1364
    'h':                      'help',
927
1365
    'm':                      'message',
928
 
    'F':                      'file', 
929
1366
    'r':                      'revision',
930
1367
    'v':                      'verbose',
 
1368
    'l':                      'long',
931
1369
}
932
1370
 
933
1371
 
947
1385
    (['status'], {'all': True})
948
1386
    >>> parse_args('commit --message=biter'.split())
949
1387
    (['commit'], {'message': u'biter'})
 
1388
    >>> parse_args('log -r 500'.split())
 
1389
    (['log'], {'revision': 500})
 
1390
    >>> parse_args('log -r500:600'.split())
 
1391
    (['log'], {'revision': [500, 600]})
 
1392
    >>> parse_args('log -vr500:600'.split())
 
1393
    (['log'], {'verbose': True, 'revision': [500, 600]})
 
1394
    >>> parse_args('log -rv500:600'.split()) #the r takes an argument
 
1395
    Traceback (most recent call last):
 
1396
    ...
 
1397
    ValueError: invalid literal for int(): v500
950
1398
    """
951
1399
    args = []
952
1400
    opts = {}
966
1414
                else:
967
1415
                    optname = a[2:]
968
1416
                if optname not in OPTIONS:
969
 
                    bailout('unknown long option %r' % a)
 
1417
                    raise BzrError('unknown long option %r' % a)
970
1418
            else:
971
1419
                shortopt = a[1:]
972
 
                if shortopt not in SHORT_OPTIONS:
973
 
                    bailout('unknown short option %r' % a)
974
 
                optname = SHORT_OPTIONS[shortopt]
 
1420
                if shortopt in SHORT_OPTIONS:
 
1421
                    # Multi-character options must have a space to delimit
 
1422
                    # their value
 
1423
                    optname = SHORT_OPTIONS[shortopt]
 
1424
                else:
 
1425
                    # Single character short options, can be chained,
 
1426
                    # and have their value appended to their name
 
1427
                    shortopt = a[1:2]
 
1428
                    if shortopt not in SHORT_OPTIONS:
 
1429
                        # We didn't find the multi-character name, and we
 
1430
                        # didn't find the single char name
 
1431
                        raise BzrError('unknown short option %r' % a)
 
1432
                    optname = SHORT_OPTIONS[shortopt]
 
1433
 
 
1434
                    if a[2:]:
 
1435
                        # There are extra things on this option
 
1436
                        # see if it is the value, or if it is another
 
1437
                        # short option
 
1438
                        optargfn = OPTIONS[optname]
 
1439
                        if optargfn is None:
 
1440
                            # This option does not take an argument, so the
 
1441
                            # next entry is another short option, pack it back
 
1442
                            # into the list
 
1443
                            argv.insert(0, '-' + a[2:])
 
1444
                        else:
 
1445
                            # This option takes an argument, so pack it
 
1446
                            # into the array
 
1447
                            optarg = a[2:]
975
1448
            
976
1449
            if optname in opts:
977
1450
                # XXX: Do we ever want to support this, e.g. for -r?
978
 
                bailout('repeated option %r' % a)
 
1451
                raise BzrError('repeated option %r' % a)
979
1452
                
980
1453
            optargfn = OPTIONS[optname]
981
1454
            if optargfn:
982
1455
                if optarg == None:
983
1456
                    if not argv:
984
 
                        bailout('option %r needs an argument' % a)
 
1457
                        raise BzrError('option %r needs an argument' % a)
985
1458
                    else:
986
1459
                        optarg = argv.pop(0)
987
1460
                opts[optname] = optargfn(optarg)
988
1461
            else:
989
1462
                if optarg != None:
990
 
                    bailout('option %r takes no argument' % optname)
 
1463
                    raise BzrError('option %r takes no argument' % optname)
991
1464
                opts[optname] = True
992
1465
        else:
993
1466
            args.append(a)
1041
1514
    return argdict
1042
1515
 
1043
1516
 
 
1517
def _parse_master_args(argv):
 
1518
    """Parse the arguments that always go with the original command.
 
1519
    These are things like bzr --no-plugins, etc.
 
1520
 
 
1521
    There are now 2 types of option flags. Ones that come *before* the command,
 
1522
    and ones that come *after* the command.
 
1523
    Ones coming *before* the command are applied against all possible commands.
 
1524
    And are generally applied before plugins are loaded.
 
1525
 
 
1526
    The current list are:
 
1527
        --builtin   Allow plugins to load, but don't let them override builtin commands,
 
1528
                    they will still be allowed if they do not override a builtin.
 
1529
        --no-plugins    Don't load any plugins. This lets you get back to official source
 
1530
                        behavior.
 
1531
        --profile   Enable the hotspot profile before running the command.
 
1532
                    For backwards compatibility, this is also a non-master option.
 
1533
        --version   Spit out the version of bzr that is running and exit.
 
1534
                    This is also a non-master option.
 
1535
        --help      Run help and exit, also a non-master option (I think that should stay, though)
 
1536
 
 
1537
    >>> argv, opts = _parse_master_args(['bzr', '--test'])
 
1538
    Traceback (most recent call last):
 
1539
    ...
 
1540
    BzrCommandError: Invalid master option: 'test'
 
1541
    >>> argv, opts = _parse_master_args(['bzr', '--version', 'command'])
 
1542
    >>> print argv
 
1543
    ['command']
 
1544
    >>> print opts['version']
 
1545
    True
 
1546
    >>> argv, opts = _parse_master_args(['bzr', '--profile', 'command', '--more-options'])
 
1547
    >>> print argv
 
1548
    ['command', '--more-options']
 
1549
    >>> print opts['profile']
 
1550
    True
 
1551
    >>> argv, opts = _parse_master_args(['bzr', '--no-plugins', 'command'])
 
1552
    >>> print argv
 
1553
    ['command']
 
1554
    >>> print opts['no-plugins']
 
1555
    True
 
1556
    >>> print opts['profile']
 
1557
    False
 
1558
    >>> argv, opts = _parse_master_args(['bzr', 'command', '--profile'])
 
1559
    >>> print argv
 
1560
    ['command', '--profile']
 
1561
    >>> print opts['profile']
 
1562
    False
 
1563
    """
 
1564
    master_opts = {'builtin':False,
 
1565
        'no-plugins':False,
 
1566
        'version':False,
 
1567
        'profile':False,
 
1568
        'help':False
 
1569
    }
 
1570
 
 
1571
    # This is the point where we could hook into argv[0] to determine
 
1572
    # what front-end is supposed to be run
 
1573
    # For now, we are just ignoring it.
 
1574
    cmd_name = argv.pop(0)
 
1575
    for arg in argv[:]:
 
1576
        if arg[:2] != '--': # at the first non-option, we return the rest
 
1577
            break
 
1578
        arg = arg[2:] # Remove '--'
 
1579
        if arg not in master_opts:
 
1580
            # We could say that this is not an error, that we should
 
1581
            # just let it be handled by the main section instead
 
1582
            raise BzrCommandError('Invalid master option: %r' % arg)
 
1583
        argv.pop(0) # We are consuming this entry
 
1584
        master_opts[arg] = True
 
1585
    return argv, master_opts
 
1586
 
 
1587
 
1044
1588
 
1045
1589
def run_bzr(argv):
1046
1590
    """Execute a command.
1051
1595
    argv = [a.decode(bzrlib.user_encoding) for a in argv]
1052
1596
    
1053
1597
    try:
1054
 
        args, opts = parse_args(argv[1:])
 
1598
        # some options like --builtin and --no-plugins have special effects
 
1599
        argv, master_opts = _parse_master_args(argv)
 
1600
        if not master_opts['no-plugins']:
 
1601
            from bzrlib.plugin import load_plugins
 
1602
            load_plugins()
 
1603
 
 
1604
        args, opts = parse_args(argv)
 
1605
 
 
1606
        if master_opts['help']:
 
1607
            from bzrlib.help import help
 
1608
            if argv:
 
1609
                help(argv[0])
 
1610
            else:
 
1611
                help()
 
1612
            return 0            
 
1613
            
1055
1614
        if 'help' in opts:
1056
 
            import help
 
1615
            from bzrlib.help import help
1057
1616
            if args:
1058
 
                help.help(args[0])
 
1617
                help(args[0])
1059
1618
            else:
1060
 
                help.help()
 
1619
                help()
1061
1620
            return 0
1062
1621
        elif 'version' in opts:
1063
1622
            show_version()
1064
1623
            return 0
 
1624
        elif args and args[0] == 'builtin':
 
1625
            include_plugins=False
 
1626
            args = args[1:]
1065
1627
        cmd = str(args.pop(0))
1066
1628
    except IndexError:
1067
1629
        import help
1069
1631
        return 1
1070
1632
          
1071
1633
 
1072
 
    canonical_cmd, cmd_class = get_cmd_class(cmd)
 
1634
    plugins_override = not (master_opts['builtin'])
 
1635
    canonical_cmd, cmd_class = get_cmd_class(cmd, plugins_override=plugins_override)
1073
1636
 
1074
 
    # global option
 
1637
    profile = master_opts['profile']
 
1638
    # For backwards compatibility, I would rather stick with --profile being a
 
1639
    # master/global option
1075
1640
    if 'profile' in opts:
1076
1641
        profile = True
1077
1642
        del opts['profile']
1078
 
    else:
1079
 
        profile = False
1080
1643
 
1081
1644
    # check options are reasonable
1082
1645
    allowed = cmd_class.takes_options
1113
1676
            os.close(pffileno)
1114
1677
            os.remove(pfname)
1115
1678
    else:
1116
 
        cmdobj = cmd_class(cmdopts, cmdargs).status 
 
1679
        return cmd_class(cmdopts, cmdargs).status 
1117
1680
 
1118
1681
 
1119
1682
def _report_exception(summary, quiet=False):
1131
1694
 
1132
1695
 
1133
1696
def main(argv):
1134
 
    import errno
1135
1697
    
1136
 
    bzrlib.open_tracefile(argv)
 
1698
    bzrlib.trace.open_tracefile(argv)
1137
1699
 
1138
1700
    try:
1139
1701
        try:
1160
1722
            _report_exception('interrupted', quiet=True)
1161
1723
            return 2
1162
1724
        except Exception, e:
 
1725
            import errno
1163
1726
            quiet = False
1164
1727
            if (isinstance(e, IOError) 
1165
1728
                and hasattr(e, 'errno')