~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/commands.py

  • Committer: Martin Pool
  • Date: 2005-06-20 04:24:35 UTC
  • Revision ID: mbp@sourcefrog.net-20050620042435-7c315b5a93001b89
- add jk's patchwork client

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, warning
 
22
from bzrlib.trace import mutter, note, log_error
23
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__])
 
24
from bzrlib.osutils import quotefn
 
25
from bzrlib import Branch, Inventory, InventoryEntry, BZRDIR, \
 
26
     format_date
44
27
 
45
28
 
46
29
def _squish_command_name(cmd):
51
34
    assert cmd.startswith("cmd_")
52
35
    return cmd[4:].replace('_','-')
53
36
 
54
 
 
55
37
def _parse_revision_str(revstr):
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']
 
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'             -> ?
99
52
    """
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)
 
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)
122
69
    return revs
123
70
 
124
 
 
125
 
 
126
 
def _get_cmd_dict(plugins_override=True):
 
71
def _find_plugins():
 
72
    """Find all python files which are plugins, and load their commands
 
73
    to add to the list of "all commands"
 
74
 
 
75
    The environment variable BZRPATH is considered a delimited set of
 
76
    paths to look through. Each entry is searched for *.py files.
 
77
    If a directory is found, it is also searched, but they are 
 
78
    not searched recursively. This allows you to revctl the plugins.
 
79
    
 
80
    Inside the plugin should be a series of cmd_* function, which inherit from
 
81
    the bzrlib.commands.Command class.
 
82
    """
 
83
    bzrpath = os.environ.get('BZRPLUGINPATH', '')
 
84
 
 
85
    plugin_cmds = {} 
 
86
    if not bzrpath:
 
87
        return plugin_cmds
 
88
    _platform_extensions = {
 
89
        'win32':'.pyd',
 
90
        'cygwin':'.dll',
 
91
        'darwin':'.dylib',
 
92
        'linux2':'.so'
 
93
        }
 
94
    if _platform_extensions.has_key(sys.platform):
 
95
        platform_extension = _platform_extensions[sys.platform]
 
96
    else:
 
97
        platform_extension = None
 
98
    for d in bzrpath.split(os.pathsep):
 
99
        plugin_names = {} # This should really be a set rather than a dict
 
100
        for f in os.listdir(d):
 
101
            if f.endswith('.py'):
 
102
                f = f[:-3]
 
103
            elif f.endswith('.pyc') or f.endswith('.pyo'):
 
104
                f = f[:-4]
 
105
            elif platform_extension and f.endswith(platform_extension):
 
106
                f = f[:-len(platform_extension)]
 
107
                if f.endswidth('module'):
 
108
                    f = f[:-len('module')]
 
109
            else:
 
110
                continue
 
111
            if not plugin_names.has_key(f):
 
112
                plugin_names[f] = True
 
113
 
 
114
        plugin_names = plugin_names.keys()
 
115
        plugin_names.sort()
 
116
        try:
 
117
            sys.path.insert(0, d)
 
118
            for name in plugin_names:
 
119
                try:
 
120
                    old_module = None
 
121
                    try:
 
122
                        if sys.modules.has_key(name):
 
123
                            old_module = sys.modules[name]
 
124
                            del sys.modules[name]
 
125
                        plugin = __import__(name, locals())
 
126
                        for k in dir(plugin):
 
127
                            if k.startswith('cmd_'):
 
128
                                k_unsquished = _unsquish_command_name(k)
 
129
                                if not plugin_cmds.has_key(k_unsquished):
 
130
                                    plugin_cmds[k_unsquished] = getattr(plugin, k)
 
131
                                else:
 
132
                                    log_error('Two plugins defined the same command: %r' % k)
 
133
                                    log_error('Not loading the one in %r in dir %r' % (name, d))
 
134
                    finally:
 
135
                        if old_module:
 
136
                            sys.modules[name] = old_module
 
137
                except ImportError, e:
 
138
                    log_error('Unable to load plugin: %r from %r\n%s' % (name, d, e))
 
139
        finally:
 
140
            sys.path.pop(0)
 
141
    return plugin_cmds
 
142
 
 
143
def _get_cmd_dict(include_plugins=True):
127
144
    d = {}
128
145
    for k, v in globals().iteritems():
129
146
        if k.startswith("cmd_"):
130
147
            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
 
148
    if include_plugins:
 
149
        d.update(_find_plugins())
138
150
    return d
139
 
 
140
151
    
141
 
def get_all_cmds(plugins_override=True):
 
152
def get_all_cmds(include_plugins=True):
142
153
    """Return canonical name and class for all registered commands."""
143
 
    for k, v in _get_cmd_dict(plugins_override=plugins_override).iteritems():
 
154
    for k, v in _get_cmd_dict(include_plugins=include_plugins).iteritems():
144
155
        yield k,v
145
156
 
146
157
 
147
 
def get_cmd_class(cmd, plugins_override=True):
 
158
def get_cmd_class(cmd,include_plugins=True):
148
159
    """Return the canonical name and command class for a command.
149
160
    """
150
161
    cmd = str(cmd)                      # not unicode
151
162
 
152
163
    # first look up this command under the specified name
153
 
    cmds = _get_cmd_dict(plugins_override=plugins_override)
 
164
    cmds = _get_cmd_dict(include_plugins=include_plugins)
154
165
    try:
155
166
        return cmd, cmds[cmd]
156
167
    except KeyError:
332
343
    directory is shown.  Otherwise, only the status of the specified
333
344
    files or directories is reported.  If a directory is given, status
334
345
    is reported for everything inside that directory.
335
 
 
336
 
    If a revision is specified, the changes since that revision are shown.
337
346
    """
338
347
    takes_args = ['file*']
339
 
    takes_options = ['all', 'show-ids', 'revision']
 
348
    takes_options = ['all', 'show-ids']
340
349
    aliases = ['st', 'stat']
341
350
    
342
351
    def run(self, all=False, show_ids=False, file_list=None):
343
352
        if file_list:
344
 
            b = find_branch(file_list[0])
 
353
            b = Branch(file_list[0])
345
354
            file_list = [b.relpath(x) for x in file_list]
346
355
            # special case: only one path was given and it's the root
347
356
            # of the branch
348
357
            if file_list == ['']:
349
358
                file_list = None
350
359
        else:
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)
 
360
            b = Branch('.')
 
361
        import status
 
362
        status.show_status(b, show_unchanged=all, show_ids=show_ids,
 
363
                           specific_files=file_list)
356
364
 
357
365
 
358
366
class cmd_cat_revision(Command):
362
370
    takes_args = ['revision_id']
363
371
    
364
372
    def run(self, revision_id):
365
 
        from bzrlib.xml import pack_xml
366
 
        pack_xml(find_branch('.').get_revision(revision_id), sys.stdout)
 
373
        Branch('.').get_revision(revision_id).write_xml(sys.stdout)
367
374
 
368
375
 
369
376
class cmd_revno(Command):
371
378
 
372
379
    This is equal to the number of revisions on this branch."""
373
380
    def run(self):
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)
 
381
        print Branch('.').revno()
397
382
 
398
383
    
399
384
class cmd_add(Command):
421
406
    takes_options = ['verbose', 'no-recurse']
422
407
    
423
408
    def run(self, file_list, verbose=False, no_recurse=False):
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)
 
409
        bzrlib.add.smart_add(file_list, verbose, not no_recurse)
444
410
 
445
411
 
446
412
class cmd_relpath(Command):
449
415
    hidden = True
450
416
    
451
417
    def run(self, filename):
452
 
        print find_branch(filename).relpath(filename)
 
418
        print Branch(filename).relpath(filename)
453
419
 
454
420
 
455
421
 
458
424
    takes_options = ['revision', 'show-ids']
459
425
    
460
426
    def run(self, revision=None, show_ids=False):
461
 
        b = find_branch('.')
 
427
        b = Branch('.')
462
428
        if revision == None:
463
429
            inv = b.read_working_inventory()
464
430
        else:
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]))
 
431
            inv = b.get_revision_inventory(b.lookup_revision(revision))
469
432
 
470
433
        for path, entry in inv.entries():
471
434
            if show_ids:
484
447
    """
485
448
    takes_args = ['source$', 'dest']
486
449
    def run(self, source_list, dest):
487
 
        b = find_branch('.')
 
450
        b = Branch('.')
488
451
 
489
452
        b.move([b.relpath(s) for s in source_list], b.relpath(dest))
490
453
 
506
469
    takes_args = ['from_name', 'to_name']
507
470
    
508
471
    def run(self, from_name, to_name):
509
 
        b = find_branch('.')
 
472
        b = Branch('.')
510
473
        b.rename_one(b.relpath(from_name), b.relpath(to_name))
511
474
 
512
475
 
531
494
 
532
495
    def run(self, location=None):
533
496
        from bzrlib.merge import merge
534
 
        import tempfile
535
 
        from shutil import rmtree
536
497
        import errno
537
498
        
538
 
        br_to = find_branch('.')
 
499
        br_to = Branch('.')
539
500
        stored_loc = None
540
501
        try:
541
502
            stored_loc = br_to.controlfile("x-pull", "rb").read().rstrip('\n')
542
503
        except IOError, e:
543
 
            if e.errno != errno.ENOENT:
 
504
            if errno == errno.ENOENT:
544
505
                raise
545
506
        if location is None:
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
 
507
            location = stored_loc
 
508
        if location is None:
 
509
            raise BzrCommandError("No pull location known or specified.")
 
510
        from branch import find_branch, DivergedBranches
553
511
        br_from = find_branch(location)
554
512
        location = pull_loc(br_from)
555
513
        old_revno = br_to.revno()
556
514
        try:
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)
 
515
            br_to.update_revisions(br_from)
 
516
        except DivergedBranches:
 
517
            raise BzrCommandError("These branches have diverged.  Try merge.")
 
518
            
 
519
        merge(('.', -1), ('.', old_revno), check_clean=False)
 
520
        if location != stored_loc:
 
521
            br_to.controlfile("x-pull", "wb").write(location + "\n")
572
522
 
573
523
 
574
524
 
587
537
    def run(self, from_location, to_location=None, revision=None):
588
538
        import errno
589
539
        from bzrlib.merge import merge
590
 
        from bzrlib.branch import DivergedBranches, NoSuchRevision, \
591
 
             find_cached_branch, Branch
 
540
        from branch import find_branch, DivergedBranches, NoSuchRevision
592
541
        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)
 
542
        try:
 
543
            br_from = find_branch(from_location)
 
544
        except OSError, e:
 
545
            if e.errno == errno.ENOENT:
 
546
                raise BzrCommandError('Source location "%s" does not exist.' %
 
547
                                      to_location)
 
548
            else:
 
549
                raise
 
550
 
 
551
        if to_location is None:
 
552
            to_location = os.path.basename(from_location.rstrip("/\\"))
 
553
 
 
554
        try:
 
555
            os.mkdir(to_location)
 
556
        except OSError, e:
 
557
            if e.errno == errno.EEXIST:
 
558
                raise BzrCommandError('Target directory "%s" already exists.' %
 
559
                                      to_location)
 
560
            if e.errno == errno.ENOENT:
 
561
                raise BzrCommandError('Parent of "%s" does not exist.' %
 
562
                                      to_location)
 
563
            else:
 
564
                raise
 
565
        br_to = Branch(to_location, init=True)
 
566
 
 
567
        try:
 
568
            br_to.update_revisions(br_from, stop_revision=revision)
 
569
        except NoSuchRevision:
 
570
            rmtree(to_location)
 
571
            msg = "The branch %s has no revision %d." % (from_location,
 
572
                                                         revision)
 
573
            raise BzrCommandError(msg)
 
574
        merge((to_location, -1), (to_location, 0), this_dir=to_location,
 
575
              check_clean=False, ignore_zero=True)
 
576
        from_location = pull_loc(br_from)
 
577
        br_to.controlfile("x-pull", "wb").write(from_location + "\n")
649
578
 
650
579
 
651
580
def pull_loc(branch):
668
597
    takes_args = ['dir?']
669
598
 
670
599
    def run(self, dir='.'):
671
 
        b = find_branch(dir)
 
600
        b = Branch(dir)
672
601
        old_inv = b.basis_tree().inventory
673
602
        new_inv = b.read_working_inventory()
674
603
 
685
614
    def run(self, branch=None):
686
615
        import info
687
616
 
 
617
        from branch import find_branch
688
618
        b = find_branch(branch)
689
619
        info.show_info(b)
690
620
 
699
629
    takes_options = ['verbose']
700
630
    
701
631
    def run(self, file_list, verbose=False):
702
 
        b = find_branch(file_list[0])
 
632
        b = Branch(file_list[0])
703
633
        b.remove([b.relpath(f) for f in file_list], verbose=verbose)
704
634
 
705
635
 
713
643
    hidden = True
714
644
    takes_args = ['filename']
715
645
    def run(self, filename):
716
 
        b = find_branch(filename)
 
646
        b = Branch(filename)
717
647
        i = b.inventory.path2id(b.relpath(filename))
718
648
        if i == None:
719
649
            raise BzrError("%r is not a versioned file" % filename)
729
659
    hidden = True
730
660
    takes_args = ['filename']
731
661
    def run(self, filename):
732
 
        b = find_branch(filename)
 
662
        b = Branch(filename)
733
663
        inv = b.inventory
734
664
        fid = inv.path2id(b.relpath(filename))
735
665
        if fid == None:
742
672
    """Display list of revision ids on this branch."""
743
673
    hidden = True
744
674
    def run(self):
745
 
        for patchid in find_branch('.').revision_history():
 
675
        for patchid in Branch('.').revision_history():
746
676
            print patchid
747
677
 
748
678
 
749
679
class cmd_directories(Command):
750
680
    """Display list of versioned directories in this branch."""
751
681
    def run(self):
752
 
        for name, ie in find_branch('.').read_working_inventory().directories():
 
682
        for name, ie in Branch('.').read_working_inventory().directories():
753
683
            if name == '':
754
684
                print '.'
755
685
            else:
770
700
        bzr commit -m 'imported project'
771
701
    """
772
702
    def run(self):
773
 
        from bzrlib.branch import Branch
774
703
        Branch('.', init=True)
775
704
 
776
705
 
804
733
 
805
734
    def run(self, revision=None, file_list=None, diff_options=None):
806
735
        from bzrlib.diff import show_diff
 
736
        from bzrlib import find_branch
807
737
 
808
738
        if file_list:
809
739
            b = find_branch(file_list[0])
812
742
                # just pointing to top-of-tree
813
743
                file_list = None
814
744
        else:
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]
 
745
            b = Branch('.')
823
746
    
824
 
        show_diff(b, base_rev, specific_files=file_list,
 
747
        show_diff(b, revision, specific_files=file_list,
825
748
                  external_diff_options=diff_options)
826
749
 
827
750
 
834
757
    TODO: Show files deleted since a previous revision, or between two revisions.
835
758
    """
836
759
    def run(self, show_ids=False):
837
 
        b = find_branch('.')
 
760
        b = Branch('.')
838
761
        old = b.basis_tree()
839
762
        new = b.working_tree()
840
763
 
855
778
    """List files modified in working tree."""
856
779
    hidden = True
857
780
    def run(self):
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
 
781
        import statcache
 
782
        b = Branch('.')
 
783
        inv = b.read_working_inventory()
 
784
        sc = statcache.update_cache(b, inv)
 
785
        basis = b.basis_tree()
 
786
        basis_inv = basis.inventory
 
787
        
 
788
        # We used to do this through iter_entries(), but that's slow
 
789
        # when most of the files are unmodified, as is usually the
 
790
        # case.  So instead we iterate by inventory entry, and only
 
791
        # calculate paths as necessary.
 
792
 
 
793
        for file_id in basis_inv:
 
794
            cacheentry = sc.get(file_id)
 
795
            if not cacheentry:                 # deleted
 
796
                continue
 
797
            ie = basis_inv[file_id]
 
798
            if cacheentry[statcache.SC_SHA1] != ie.text_sha1:
 
799
                path = inv.id2path(file_id)
 
800
                print path
865
801
 
866
802
 
867
803
 
869
805
    """List files added in working tree."""
870
806
    hidden = True
871
807
    def run(self):
872
 
        b = find_branch('.')
 
808
        b = Branch('.')
873
809
        wt = b.working_tree()
874
810
        basis_inv = b.basis_tree().inventory
875
811
        inv = wt.inventory
891
827
    takes_args = ['filename?']
892
828
    def run(self, filename=None):
893
829
        """Print the branch root."""
 
830
        from branch import find_branch
894
831
        b = find_branch(filename)
895
832
        print getattr(b, 'base', None) or getattr(b, 'baseurl')
896
833
 
902
839
    -r revision requests a specific revision, -r :end or -r begin: are
903
840
    also valid.
904
841
 
905
 
    --message allows you to give a regular expression, which will be evaluated
906
 
    so that only matching entries will be displayed.
907
 
 
908
842
    TODO: Make --revision support uuid: and hash: [future tag:] notation.
909
843
  
910
844
    """
911
845
 
912
846
    takes_args = ['filename?']
913
 
    takes_options = ['forward', 'timezone', 'verbose', 'show-ids', 'revision','long', 'message']
 
847
    takes_options = ['forward', 'timezone', 'verbose', 'show-ids', 'revision']
914
848
    
915
849
    def run(self, filename=None, timezone='original',
916
850
            verbose=False,
917
851
            show_ids=False,
918
852
            forward=False,
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
 
853
            revision=None):
 
854
        from bzrlib import show_log, find_branch
924
855
        import codecs
925
856
 
926
857
        direction = (forward and 'forward') or 'reverse'
936
867
            b = find_branch('.')
937
868
            file_id = None
938
869
 
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]
 
870
        if revision == None:
 
871
            revision = [None, None]
 
872
        elif isinstance(revision, int):
 
873
            revision = [revision, revision]
947
874
        else:
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
 
875
            # pair of revisions?
 
876
            pass
 
877
            
 
878
        assert len(revision) == 2
954
879
 
955
880
        mutter('encoding log as %r' % bzrlib.user_encoding)
956
881
 
958
883
        # in e.g. the default C locale.
959
884
        outf = codecs.getwriter(bzrlib.user_encoding)(sys.stdout, errors='replace')
960
885
 
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,
 
886
        show_log(b, file_id,
 
887
                 show_timezone=timezone,
973
888
                 verbose=verbose,
 
889
                 show_ids=show_ids,
 
890
                 to_file=outf,
974
891
                 direction=direction,
975
 
                 start_revision=rev1,
976
 
                 end_revision=rev2,
977
 
                 search=message)
 
892
                 start_revision=revision[0],
 
893
                 end_revision=revision[1])
978
894
 
979
895
 
980
896
 
985
901
    hidden = True
986
902
    takes_args = ["filename"]
987
903
    def run(self, filename):
988
 
        b = find_branch(filename)
 
904
        b = Branch(filename)
989
905
        inv = b.read_working_inventory()
990
906
        file_id = inv.path2id(b.relpath(filename))
991
907
        for revno, revision_id, what in bzrlib.log.find_touching_revisions(b, file_id):
999
915
    """
1000
916
    hidden = True
1001
917
    def run(self, revision=None, verbose=False):
1002
 
        b = find_branch('.')
 
918
        b = Branch('.')
1003
919
        if revision == None:
1004
920
            tree = b.working_tree()
1005
921
        else:
1023
939
class cmd_unknowns(Command):
1024
940
    """List unknown files."""
1025
941
    def run(self):
1026
 
        from bzrlib.osutils import quotefn
1027
 
        for f in find_branch('.').unknowns():
 
942
        for f in Branch('.').unknowns():
1028
943
            print quotefn(f)
1029
944
 
1030
945
 
1052
967
        from bzrlib.atomicfile import AtomicFile
1053
968
        import os.path
1054
969
 
1055
 
        b = find_branch('.')
 
970
        b = Branch('.')
1056
971
        ifn = b.abspath('.bzrignore')
1057
972
 
1058
973
        if os.path.exists(ifn):
1092
1007
 
1093
1008
    See also: bzr ignore"""
1094
1009
    def run(self):
1095
 
        tree = find_branch('.').working_tree()
 
1010
        tree = Branch('.').working_tree()
1096
1011
        for path, file_class, kind, file_id in tree.list_files():
1097
1012
            if file_class != 'I':
1098
1013
                continue
1116
1031
        except ValueError:
1117
1032
            raise BzrCommandError("not a valid revision-number: %r" % revno)
1118
1033
 
1119
 
        print find_branch('.').lookup_revision(revno)
 
1034
        print Branch('.').lookup_revision(revno)
1120
1035
 
1121
1036
 
1122
1037
class cmd_export(Command):
1125
1040
    If no revision is specified this exports the last committed revision.
1126
1041
 
1127
1042
    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."""
 
1043
    given, exports to a directory (equivalent to --format=dir)."""
1133
1044
    # TODO: list known exporters
1134
1045
    takes_args = ['dest']
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()
 
1046
    takes_options = ['revision', 'format']
 
1047
    def run(self, dest, revision=None, format='dir'):
 
1048
        b = Branch('.')
 
1049
        if revision == None:
 
1050
            rh = b.revision_history()[-1]
1141
1051
        else:
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)
 
1052
            rh = b.lookup_revision(int(revision))
 
1053
        t = b.revision_tree(rh)
 
1054
        t.export(dest, format)
1157
1055
 
1158
1056
 
1159
1057
class cmd_cat(Command):
1165
1063
    def run(self, filename, revision=None):
1166
1064
        if revision == None:
1167
1065
            raise BzrCommandError("bzr cat requires a revision number")
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])
 
1066
        b = Branch('.')
 
1067
        b.print_file(b.relpath(filename), int(revision))
1172
1068
 
1173
1069
 
1174
1070
class cmd_local_time_offset(Command):
1195
1091
    TODO: Strict commit that fails if there are unknown or deleted files.
1196
1092
    """
1197
1093
    takes_args = ['selected*']
1198
 
    takes_options = ['message', 'file', 'verbose', 'unchanged']
 
1094
    takes_options = ['message', 'file', 'verbose']
1199
1095
    aliases = ['ci', 'checkin']
1200
1096
 
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
 
1097
    def run(self, message=None, file=None, verbose=True, selected_list=None):
 
1098
        from bzrlib.commit import commit
1205
1099
 
1206
1100
        ## Warning: shadows builtin file()
1207
1101
        if not message and not 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"])
 
1102
            raise BzrCommandError("please specify a commit message",
 
1103
                                  ["use either --message or --file"])
1220
1104
        elif message and file:
1221
1105
            raise BzrCommandError("please specify either --message or --file")
1222
1106
        
1224
1108
            import codecs
1225
1109
            message = codecs.open(file, 'rt', bzrlib.user_encoding).read()
1226
1110
 
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"])
 
1111
        b = Branch('.')
 
1112
        commit(b, message, verbose=verbose, specific_files=selected_list)
1238
1113
 
1239
1114
 
1240
1115
class cmd_check(Command):
1249
1124
    takes_args = ['dir?']
1250
1125
 
1251
1126
    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
 
            
 
1127
        import bzrlib.check
 
1128
        bzrlib.check.check(Branch(dir))
 
1129
 
1276
1130
 
1277
1131
 
1278
1132
class cmd_upgrade(Command):
1285
1139
 
1286
1140
    def run(self, dir='.'):
1287
1141
        from bzrlib.upgrade import upgrade
1288
 
        upgrade(find_branch(dir))
 
1142
        upgrade(Branch(dir))
1289
1143
 
1290
1144
 
1291
1145
 
1305
1159
    hidden = True
1306
1160
    def run(self):
1307
1161
        from bzrlib.selftest import selftest
1308
 
        return int(not selftest())
 
1162
        if selftest():
 
1163
            return 0
 
1164
        else:
 
1165
            return 1
 
1166
 
1309
1167
 
1310
1168
 
1311
1169
class cmd_version(Command):
1343
1201
    ['..', -1]
1344
1202
    >>> parse_spec("../f/@35")
1345
1203
    ['../f', 35]
1346
 
    >>> parse_spec('./@revid:john@arbash-meinel.com-20050711044610-3ca0327c6a222f67')
1347
 
    ['.', 'revid:john@arbash-meinel.com-20050711044610-3ca0327c6a222f67']
1348
1204
    """
1349
1205
    if spec is None:
1350
1206
        return [None, None]
1354
1210
        if parsed[1] == "":
1355
1211
            parsed[1] = -1
1356
1212
        else:
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
 
1213
            parsed[1] = int(parsed[1])
 
1214
            assert parsed[1] >=0
1363
1215
    else:
1364
1216
        parsed = [spec, None]
1365
1217
    return parsed
1397
1249
              check_clean=(not force))
1398
1250
 
1399
1251
 
1400
 
 
1401
1252
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):
1417
1253
    """Reverse all changes since the last commit.
1418
1254
 
1419
1255
    Only versioned files are affected.
1423
1259
    """
1424
1260
    takes_options = ['revision']
1425
1261
 
1426
 
    def run(self, revision=None):
 
1262
    def run(self, revision=-1):
1427
1263
        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('.'),
 
1264
        merge(('.', revision), parse_spec('.'),
1433
1265
              check_clean=False,
1434
1266
              ignore_zero=True)
1435
1267
 
1453
1285
        help.help(topic)
1454
1286
 
1455
1287
 
1456
 
 
1457
 
 
1458
 
class cmd_plugins(Command):
1459
 
    """List plugins"""
 
1288
class cmd_update_stat_cache(Command):
 
1289
    """Update stat-cache mapping inodes to SHA-1 hashes.
 
1290
 
 
1291
    For testing only."""
1460
1292
    hidden = True
1461
1293
    def run(self):
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)
 
1294
        import statcache
 
1295
        b = Branch('.')
 
1296
        statcache.update_cache(b.base, b.read_working_inventory())
1472
1297
 
1473
1298
 
1474
1299
 
1492
1317
    'verbose':                None,
1493
1318
    'version':                None,
1494
1319
    'email':                  None,
1495
 
    'unchanged':              None,
1496
1320
    'update':                 None,
1497
 
    'long':                   None,
1498
 
    'root':                   str,
1499
1321
    }
1500
1322
 
1501
1323
SHORT_OPTIONS = {
1504
1326
    'm':                      'message',
1505
1327
    'r':                      'revision',
1506
1328
    'v':                      'verbose',
1507
 
    'l':                      'long',
1508
1329
}
1509
1330
 
1510
1331
 
1525
1346
    >>> parse_args('commit --message=biter'.split())
1526
1347
    (['commit'], {'message': u'biter'})
1527
1348
    >>> parse_args('log -r 500'.split())
1528
 
    (['log'], {'revision': [500]})
1529
 
    >>> parse_args('log -r500..600'.split())
 
1349
    (['log'], {'revision': 500})
 
1350
    >>> parse_args('log -r500:600'.split())
1530
1351
    (['log'], {'revision': [500, 600]})
1531
 
    >>> parse_args('log -vr500..600'.split())
 
1352
    >>> parse_args('log -vr500:600'.split())
1532
1353
    (['log'], {'verbose': True, 'revision': [500, 600]})
1533
 
    >>> parse_args('log -rv500..600'.split()) #the r takes an argument
1534
 
    (['log'], {'revision': ['v500', 600]})
 
1354
    >>> parse_args('log -rv500:600'.split()) #the r takes an argument
 
1355
    Traceback (most recent call last):
 
1356
    ...
 
1357
    ValueError: invalid literal for int(): v500
1535
1358
    """
1536
1359
    args = []
1537
1360
    opts = {}
1651
1474
    return argdict
1652
1475
 
1653
1476
 
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
 
 
1725
1477
 
1726
1478
def run_bzr(argv):
1727
1479
    """Execute a command.
1731
1483
    """
1732
1484
    argv = [a.decode(bzrlib.user_encoding) for a in argv]
1733
1485
    
 
1486
    include_plugins=True
1734
1487
    try:
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
 
            
 
1488
        args, opts = parse_args(argv[1:])
1751
1489
        if 'help' in opts:
1752
 
            from bzrlib.help import help
 
1490
            import help
1753
1491
            if args:
1754
 
                help(args[0])
 
1492
                help.help(args[0])
1755
1493
            else:
1756
 
                help()
 
1494
                help.help()
1757
1495
            return 0
1758
1496
        elif 'version' in opts:
1759
1497
            show_version()
1768
1506
        return 1
1769
1507
          
1770
1508
 
1771
 
    plugins_override = not (master_opts['builtin'])
1772
 
    canonical_cmd, cmd_class = get_cmd_class(cmd, plugins_override=plugins_override)
 
1509
    canonical_cmd, cmd_class = get_cmd_class(cmd,include_plugins=include_plugins)
1773
1510
 
1774
 
    profile = master_opts['profile']
1775
 
    # For backwards compatibility, I would rather stick with --profile being a
1776
 
    # master/global option
 
1511
    # global option
1777
1512
    if 'profile' in opts:
1778
1513
        profile = True
1779
1514
        del opts['profile']
 
1515
    else:
 
1516
        profile = False
1780
1517
 
1781
1518
    # check options are reasonable
1782
1519
    allowed = cmd_class.takes_options
1831
1568
 
1832
1569
 
1833
1570
def main(argv):
 
1571
    import errno
1834
1572
    
1835
 
    bzrlib.trace.open_tracefile(argv)
 
1573
    bzrlib.open_tracefile(argv)
1836
1574
 
1837
1575
    try:
1838
1576
        try:
1859
1597
            _report_exception('interrupted', quiet=True)
1860
1598
            return 2
1861
1599
        except Exception, e:
1862
 
            import errno
1863
1600
            quiet = False
1864
1601
            if (isinstance(e, IOError) 
1865
1602
                and hasattr(e, 'errno')