~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/commands.py

  • Committer: Martin Pool
  • Date: 2005-06-22 06:37:43 UTC
  • Revision ID: mbp@sourcefrog.net-20050622063743-e395f04c4db8977f
- move old blackbox code from testbzr into bzrlib.selftest.blackbox

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
 
24
from bzrlib.osutils import quotefn
 
25
from bzrlib import Branch, Inventory, InventoryEntry, BZRDIR, \
 
26
     format_date
26
27
 
27
28
 
28
29
plugin_cmds = {}
29
30
 
30
31
 
31
 
def register_command(cmd):
 
32
def register_plugin_command(cmd):
32
33
    "Utility function to help register a command"
33
34
    global plugin_cmds
34
35
    k = cmd.__name__
51
52
    assert cmd.startswith("cmd_")
52
53
    return cmd[4:].replace('_','-')
53
54
 
54
 
 
55
55
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']
 
56
    """This handles a revision string -> revno. 
 
57
 
 
58
    There are several possibilities:
 
59
 
 
60
        '234'       -> 234
 
61
        '234:345'   -> [234, 345]
 
62
        ':234'      -> [None, 234]
 
63
        '234:'      -> [234, None]
 
64
 
 
65
    In the future we will also support:
 
66
        'uuid:blah-blah-blah'   -> ?
 
67
        'hash:blahblahblah'     -> ?
 
68
        potentially:
 
69
        'tag:mytag'             -> ?
99
70
    """
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)
 
71
    if revstr.find(':') != -1:
 
72
        revs = revstr.split(':')
 
73
        if len(revs) > 2:
 
74
            raise ValueError('More than 2 pieces not supported for --revision: %r' % revstr)
 
75
 
 
76
        if not revs[0]:
 
77
            revs[0] = None
 
78
        else:
 
79
            revs[0] = int(revs[0])
 
80
 
 
81
        if not revs[1]:
 
82
            revs[1] = None
 
83
        else:
 
84
            revs[1] = int(revs[1])
 
85
    else:
 
86
        revs = int(revstr)
122
87
    return revs
123
88
 
124
89
 
125
 
def get_merge_type(typestring):
126
 
    """Attempt to find the merge class/factory associated with a string."""
127
 
    from merge import merge_types
128
 
    try:
129
 
        return merge_types[typestring][0]
130
 
    except KeyError:
131
 
        templ = '%s%%7s: %%s' % (' '*12)
132
 
        lines = [templ % (f[0], f[1][1]) for f in merge_types.iteritems()]
133
 
        type_list = '\n'.join(lines)
134
 
        msg = "No known merge type %s. Supported types are:\n%s" %\
135
 
            (typestring, type_list)
136
 
        raise BzrCommandError(msg)
137
 
    
138
 
 
139
90
 
140
91
def _get_cmd_dict(plugins_override=True):
141
92
    d = {}
214
165
        assert isinstance(arguments, dict)
215
166
        cmdargs = options.copy()
216
167
        cmdargs.update(arguments)
217
 
        if self.__doc__ == Command.__doc__:
218
 
            from warnings import warn
219
 
            warn("No help message set for %r" % self)
 
168
        assert self.__doc__ != Command.__doc__, \
 
169
               ("No help message set for %r" % self)
220
170
        self.status = self.run(**cmdargs)
221
 
        if self.status is None:
222
 
            self.status = 0
223
171
 
224
172
    
225
173
    def run(self):
349
297
    directory is shown.  Otherwise, only the status of the specified
350
298
    files or directories is reported.  If a directory is given, status
351
299
    is reported for everything inside that directory.
352
 
 
353
 
    If a revision is specified, the changes since that revision are shown.
354
300
    """
355
301
    takes_args = ['file*']
356
 
    takes_options = ['all', 'show-ids', 'revision']
 
302
    takes_options = ['all', 'show-ids']
357
303
    aliases = ['st', 'stat']
358
304
    
359
305
    def run(self, all=False, show_ids=False, file_list=None):
360
306
        if file_list:
361
 
            b = find_branch(file_list[0])
 
307
            b = Branch(file_list[0])
362
308
            file_list = [b.relpath(x) for x in file_list]
363
309
            # special case: only one path was given and it's the root
364
310
            # of the branch
365
311
            if file_list == ['']:
366
312
                file_list = None
367
313
        else:
368
 
            b = find_branch('.')
369
 
            
370
 
        from bzrlib.status import show_status
371
 
        show_status(b, show_unchanged=all, show_ids=show_ids,
372
 
                    specific_files=file_list)
 
314
            b = Branch('.')
 
315
        import status
 
316
        status.show_status(b, show_unchanged=all, show_ids=show_ids,
 
317
                           specific_files=file_list)
373
318
 
374
319
 
375
320
class cmd_cat_revision(Command):
379
324
    takes_args = ['revision_id']
380
325
    
381
326
    def run(self, revision_id):
382
 
        from bzrlib.xml import pack_xml
383
 
        pack_xml(find_branch('.').get_revision(revision_id), sys.stdout)
 
327
        Branch('.').get_revision(revision_id).write_xml(sys.stdout)
384
328
 
385
329
 
386
330
class cmd_revno(Command):
388
332
 
389
333
    This is equal to the number of revisions on this branch."""
390
334
    def run(self):
391
 
        print find_branch('.').revno()
392
 
 
393
 
class cmd_revision_info(Command):
394
 
    """Show revision number and revision id for a given revision identifier.
395
 
    """
396
 
    hidden = True
397
 
    takes_args = ['revision_info*']
398
 
    takes_options = ['revision']
399
 
    def run(self, revision=None, revision_info_list=None):
400
 
        from bzrlib.branch import find_branch
401
 
 
402
 
        revs = []
403
 
        if revision is not None:
404
 
            revs.extend(revision)
405
 
        if revision_info_list is not None:
406
 
            revs.extend(revision_info_list)
407
 
        if len(revs) == 0:
408
 
            raise BzrCommandError('You must supply a revision identifier')
409
 
 
410
 
        b = find_branch('.')
411
 
 
412
 
        for rev in revs:
413
 
            print '%4d %s' % b.get_revision_info(rev)
 
335
        print Branch('.').revno()
414
336
 
415
337
    
416
338
class cmd_add(Command):
426
348
    whether already versioned or not, are searched for files or
427
349
    subdirectories that are neither versioned or ignored, and these
428
350
    are added.  This search proceeds recursively into versioned
429
 
    directories.  If no names are given '.' is assumed.
 
351
    directories.
430
352
 
431
 
    Therefore simply saying 'bzr add' will version all files that
 
353
    Therefore simply saying 'bzr add .' will version all files that
432
354
    are currently unknown.
433
355
 
434
356
    TODO: Perhaps adding a file whose directly is not versioned should
435
357
    recursively add that parent, rather than giving an error?
436
358
    """
437
 
    takes_args = ['file*']
 
359
    takes_args = ['file+']
438
360
    takes_options = ['verbose', 'no-recurse']
439
361
    
440
362
    def run(self, file_list, verbose=False, no_recurse=False):
441
 
        from bzrlib.add import smart_add
442
 
        smart_add(file_list, verbose, not no_recurse)
443
 
 
444
 
 
445
 
 
446
 
class cmd_mkdir(Command):
447
 
    """Create a new versioned directory.
448
 
 
449
 
    This is equivalent to creating the directory and then adding it.
450
 
    """
451
 
    takes_args = ['dir+']
452
 
 
453
 
    def run(self, dir_list):
454
 
        b = None
455
 
        
456
 
        for d in dir_list:
457
 
            os.mkdir(d)
458
 
            if not b:
459
 
                b = find_branch(d)
460
 
            b.add([d], verbose=True)
 
363
        bzrlib.add.smart_add(file_list, verbose, not no_recurse)
461
364
 
462
365
 
463
366
class cmd_relpath(Command):
466
369
    hidden = True
467
370
    
468
371
    def run(self, filename):
469
 
        print find_branch(filename).relpath(filename)
 
372
        print Branch(filename).relpath(filename)
470
373
 
471
374
 
472
375
 
475
378
    takes_options = ['revision', 'show-ids']
476
379
    
477
380
    def run(self, revision=None, show_ids=False):
478
 
        b = find_branch('.')
 
381
        b = Branch('.')
479
382
        if revision == None:
480
383
            inv = b.read_working_inventory()
481
384
        else:
482
 
            if len(revision) > 1:
483
 
                raise BzrCommandError('bzr inventory --revision takes'
484
 
                    ' exactly one revision identifier')
485
 
            inv = b.get_revision_inventory(b.lookup_revision(revision[0]))
 
385
            inv = b.get_revision_inventory(b.lookup_revision(revision))
486
386
 
487
387
        for path, entry in inv.entries():
488
388
            if show_ids:
501
401
    """
502
402
    takes_args = ['source$', 'dest']
503
403
    def run(self, source_list, dest):
504
 
        b = find_branch('.')
 
404
        b = Branch('.')
505
405
 
506
406
        b.move([b.relpath(s) for s in source_list], b.relpath(dest))
507
407
 
523
423
    takes_args = ['from_name', 'to_name']
524
424
    
525
425
    def run(self, from_name, to_name):
526
 
        b = find_branch('.')
 
426
        b = Branch('.')
527
427
        b.rename_one(b.relpath(from_name), b.relpath(to_name))
528
428
 
529
429
 
548
448
 
549
449
    def run(self, location=None):
550
450
        from bzrlib.merge import merge
551
 
        import tempfile
552
 
        from shutil import rmtree
553
451
        import errno
554
452
        
555
 
        br_to = find_branch('.')
 
453
        br_to = Branch('.')
556
454
        stored_loc = None
557
455
        try:
558
456
            stored_loc = br_to.controlfile("x-pull", "rb").read().rstrip('\n')
559
457
        except IOError, e:
560
 
            if e.errno != errno.ENOENT:
 
458
            if errno == errno.ENOENT:
561
459
                raise
562
460
        if location is None:
563
461
            if stored_loc is None:
565
463
            else:
566
464
                print "Using last location: %s" % stored_loc
567
465
                location = stored_loc
568
 
        cache_root = tempfile.mkdtemp()
569
 
        from bzrlib.branch import DivergedBranches
 
466
        from branch import find_branch, DivergedBranches
570
467
        br_from = find_branch(location)
571
468
        location = pull_loc(br_from)
572
469
        old_revno = br_to.revno()
573
470
        try:
574
 
            from branch import find_cached_branch, DivergedBranches
575
 
            br_from = find_cached_branch(location, cache_root)
576
 
            location = pull_loc(br_from)
577
 
            old_revno = br_to.revno()
578
 
            try:
579
 
                br_to.update_revisions(br_from)
580
 
            except DivergedBranches:
581
 
                raise BzrCommandError("These branches have diverged."
582
 
                    "  Try merge.")
583
 
                
584
 
            merge(('.', -1), ('.', old_revno), check_clean=False)
585
 
            if location != stored_loc:
586
 
                br_to.controlfile("x-pull", "wb").write(location + "\n")
587
 
        finally:
588
 
            rmtree(cache_root)
 
471
            br_to.update_revisions(br_from)
 
472
        except DivergedBranches:
 
473
            raise BzrCommandError("These branches have diverged.  Try merge.")
 
474
            
 
475
        merge(('.', -1), ('.', old_revno), check_clean=False)
 
476
        if location != stored_loc:
 
477
            br_to.controlfile("x-pull", "wb").write(location + "\n")
589
478
 
590
479
 
591
480
 
604
493
    def run(self, from_location, to_location=None, revision=None):
605
494
        import errno
606
495
        from bzrlib.merge import merge
607
 
        from bzrlib.branch import DivergedBranches, NoSuchRevision, \
608
 
             find_cached_branch, Branch
 
496
        from branch import find_branch, DivergedBranches, NoSuchRevision
609
497
        from shutil import rmtree
610
 
        from meta_store import CachedStore
611
 
        import tempfile
612
 
        cache_root = tempfile.mkdtemp()
613
 
 
614
 
        if revision is None:
615
 
            revision = [None]
616
 
        elif len(revision) > 1:
617
 
            raise BzrCommandError('bzr branch --revision takes exactly 1 revision value')
618
 
 
619
 
        try:
620
 
            try:
621
 
                br_from = find_cached_branch(from_location, cache_root)
622
 
            except OSError, e:
623
 
                if e.errno == errno.ENOENT:
624
 
                    raise BzrCommandError('Source location "%s" does not'
625
 
                                          ' exist.' % to_location)
626
 
                else:
627
 
                    raise
628
 
 
629
 
            if to_location is None:
630
 
                to_location = os.path.basename(from_location.rstrip("/\\"))
631
 
 
632
 
            try:
633
 
                os.mkdir(to_location)
634
 
            except OSError, e:
635
 
                if e.errno == errno.EEXIST:
636
 
                    raise BzrCommandError('Target directory "%s" already'
637
 
                                          ' exists.' % to_location)
638
 
                if e.errno == errno.ENOENT:
639
 
                    raise BzrCommandError('Parent of "%s" does not exist.' %
640
 
                                          to_location)
641
 
                else:
642
 
                    raise
643
 
            br_to = Branch(to_location, init=True)
644
 
 
645
 
            br_to.set_root_id(br_from.get_root_id())
646
 
 
647
 
            if revision:
648
 
                if revision[0] is None:
649
 
                    revno = br_from.revno()
650
 
                else:
651
 
                    revno, rev_id = br_from.get_revision_info(revision[0])
652
 
                try:
653
 
                    br_to.update_revisions(br_from, stop_revision=revno)
654
 
                except NoSuchRevision:
655
 
                    rmtree(to_location)
656
 
                    msg = "The branch %s has no revision %d." % (from_location,
657
 
                                                                 revno)
658
 
                    raise BzrCommandError(msg)
659
 
            
660
 
            merge((to_location, -1), (to_location, 0), this_dir=to_location,
661
 
                  check_clean=False, ignore_zero=True)
662
 
            from_location = pull_loc(br_from)
663
 
            br_to.controlfile("x-pull", "wb").write(from_location + "\n")
664
 
        finally:
665
 
            rmtree(cache_root)
 
498
        try:
 
499
            br_from = find_branch(from_location)
 
500
        except OSError, e:
 
501
            if e.errno == errno.ENOENT:
 
502
                raise BzrCommandError('Source location "%s" does not exist.' %
 
503
                                      to_location)
 
504
            else:
 
505
                raise
 
506
 
 
507
        if to_location is None:
 
508
            to_location = os.path.basename(from_location.rstrip("/\\"))
 
509
 
 
510
        try:
 
511
            os.mkdir(to_location)
 
512
        except OSError, e:
 
513
            if e.errno == errno.EEXIST:
 
514
                raise BzrCommandError('Target directory "%s" already exists.' %
 
515
                                      to_location)
 
516
            if e.errno == errno.ENOENT:
 
517
                raise BzrCommandError('Parent of "%s" does not exist.' %
 
518
                                      to_location)
 
519
            else:
 
520
                raise
 
521
        br_to = Branch(to_location, init=True)
 
522
 
 
523
        try:
 
524
            br_to.update_revisions(br_from, stop_revision=revision)
 
525
        except NoSuchRevision:
 
526
            rmtree(to_location)
 
527
            msg = "The branch %s has no revision %d." % (from_location,
 
528
                                                         revision)
 
529
            raise BzrCommandError(msg)
 
530
        merge((to_location, -1), (to_location, 0), this_dir=to_location,
 
531
              check_clean=False, ignore_zero=True)
 
532
        from_location = pull_loc(br_from)
 
533
        br_to.controlfile("x-pull", "wb").write(from_location + "\n")
666
534
 
667
535
 
668
536
def pull_loc(branch):
685
553
    takes_args = ['dir?']
686
554
 
687
555
    def run(self, dir='.'):
688
 
        b = find_branch(dir)
 
556
        b = Branch(dir)
689
557
        old_inv = b.basis_tree().inventory
690
558
        new_inv = b.read_working_inventory()
691
559
 
702
570
    def run(self, branch=None):
703
571
        import info
704
572
 
 
573
        from branch import find_branch
705
574
        b = find_branch(branch)
706
575
        info.show_info(b)
707
576
 
716
585
    takes_options = ['verbose']
717
586
    
718
587
    def run(self, file_list, verbose=False):
719
 
        b = find_branch(file_list[0])
 
588
        b = Branch(file_list[0])
720
589
        b.remove([b.relpath(f) for f in file_list], verbose=verbose)
721
590
 
722
591
 
730
599
    hidden = True
731
600
    takes_args = ['filename']
732
601
    def run(self, filename):
733
 
        b = find_branch(filename)
 
602
        b = Branch(filename)
734
603
        i = b.inventory.path2id(b.relpath(filename))
735
604
        if i == None:
736
605
            raise BzrError("%r is not a versioned file" % filename)
746
615
    hidden = True
747
616
    takes_args = ['filename']
748
617
    def run(self, filename):
749
 
        b = find_branch(filename)
 
618
        b = Branch(filename)
750
619
        inv = b.inventory
751
620
        fid = inv.path2id(b.relpath(filename))
752
621
        if fid == None:
759
628
    """Display list of revision ids on this branch."""
760
629
    hidden = True
761
630
    def run(self):
762
 
        for patchid in find_branch('.').revision_history():
 
631
        for patchid in Branch('.').revision_history():
763
632
            print patchid
764
633
 
765
634
 
766
635
class cmd_directories(Command):
767
636
    """Display list of versioned directories in this branch."""
768
637
    def run(self):
769
 
        for name, ie in find_branch('.').read_working_inventory().directories():
 
638
        for name, ie in Branch('.').read_working_inventory().directories():
770
639
            if name == '':
771
640
                print '.'
772
641
            else:
787
656
        bzr commit -m 'imported project'
788
657
    """
789
658
    def run(self):
790
 
        from bzrlib.branch import Branch
791
659
        Branch('.', init=True)
792
660
 
793
661
 
821
689
 
822
690
    def run(self, revision=None, file_list=None, diff_options=None):
823
691
        from bzrlib.diff import show_diff
 
692
        from bzrlib import find_branch
824
693
 
825
694
        if file_list:
826
695
            b = find_branch(file_list[0])
829
698
                # just pointing to top-of-tree
830
699
                file_list = None
831
700
        else:
832
 
            b = find_branch('.')
833
 
 
834
 
        # TODO: Make show_diff support taking 2 arguments
835
 
        base_rev = None
836
 
        if revision is not None:
837
 
            if len(revision) != 1:
838
 
                raise BzrCommandError('bzr diff --revision takes exactly one revision identifier')
839
 
            base_rev = revision[0]
 
701
            b = Branch('.')
840
702
    
841
 
        show_diff(b, base_rev, specific_files=file_list,
 
703
        show_diff(b, revision, specific_files=file_list,
842
704
                  external_diff_options=diff_options)
843
705
 
844
706
 
851
713
    TODO: Show files deleted since a previous revision, or between two revisions.
852
714
    """
853
715
    def run(self, show_ids=False):
854
 
        b = find_branch('.')
 
716
        b = Branch('.')
855
717
        old = b.basis_tree()
856
718
        new = b.working_tree()
857
719
 
872
734
    """List files modified in working tree."""
873
735
    hidden = True
874
736
    def run(self):
875
 
        from bzrlib.diff import compare_trees
876
 
 
877
 
        b = find_branch('.')
878
 
        td = compare_trees(b.basis_tree(), b.working_tree())
879
 
 
880
 
        for path, id, kind in td.modified:
881
 
            print path
 
737
        import statcache
 
738
        b = Branch('.')
 
739
        inv = b.read_working_inventory()
 
740
        sc = statcache.update_cache(b, inv)
 
741
        basis = b.basis_tree()
 
742
        basis_inv = basis.inventory
 
743
        
 
744
        # We used to do this through iter_entries(), but that's slow
 
745
        # when most of the files are unmodified, as is usually the
 
746
        # case.  So instead we iterate by inventory entry, and only
 
747
        # calculate paths as necessary.
 
748
 
 
749
        for file_id in basis_inv:
 
750
            cacheentry = sc.get(file_id)
 
751
            if not cacheentry:                 # deleted
 
752
                continue
 
753
            ie = basis_inv[file_id]
 
754
            if cacheentry[statcache.SC_SHA1] != ie.text_sha1:
 
755
                path = inv.id2path(file_id)
 
756
                print path
882
757
 
883
758
 
884
759
 
886
761
    """List files added in working tree."""
887
762
    hidden = True
888
763
    def run(self):
889
 
        b = find_branch('.')
 
764
        b = Branch('.')
890
765
        wt = b.working_tree()
891
766
        basis_inv = b.basis_tree().inventory
892
767
        inv = wt.inventory
908
783
    takes_args = ['filename?']
909
784
    def run(self, filename=None):
910
785
        """Print the branch root."""
 
786
        from branch import find_branch
911
787
        b = find_branch(filename)
912
788
        print getattr(b, 'base', None) or getattr(b, 'baseurl')
913
789
 
919
795
    -r revision requests a specific revision, -r :end or -r begin: are
920
796
    also valid.
921
797
 
922
 
    --message allows you to give a regular expression, which will be evaluated
923
 
    so that only matching entries will be displayed.
924
 
 
925
798
    TODO: Make --revision support uuid: and hash: [future tag:] notation.
926
799
  
927
800
    """
928
801
 
929
802
    takes_args = ['filename?']
930
 
    takes_options = ['forward', 'timezone', 'verbose', 'show-ids', 'revision','long', 'message']
 
803
    takes_options = ['forward', 'timezone', 'verbose', 'show-ids', 'revision']
931
804
    
932
805
    def run(self, filename=None, timezone='original',
933
806
            verbose=False,
934
807
            show_ids=False,
935
808
            forward=False,
936
 
            revision=None,
937
 
            message=None,
938
 
            long=False):
939
 
        from bzrlib.branch import find_branch
940
 
        from bzrlib.log import log_formatter, show_log
 
809
            revision=None):
 
810
        from bzrlib import show_log, find_branch
941
811
        import codecs
942
812
 
943
813
        direction = (forward and 'forward') or 'reverse'
953
823
            b = find_branch('.')
954
824
            file_id = None
955
825
 
956
 
        if revision is None:
957
 
            rev1 = None
958
 
            rev2 = None
959
 
        elif len(revision) == 1:
960
 
            rev1 = rev2 = b.get_revision_info(revision[0])[0]
961
 
        elif len(revision) == 2:
962
 
            rev1 = b.get_revision_info(revision[0])[0]
963
 
            rev2 = b.get_revision_info(revision[1])[0]
 
826
        if revision == None:
 
827
            revision = [None, None]
 
828
        elif isinstance(revision, int):
 
829
            revision = [revision, revision]
964
830
        else:
965
 
            raise BzrCommandError('bzr log --revision takes one or two values.')
966
 
 
967
 
        if rev1 == 0:
968
 
            rev1 = None
969
 
        if rev2 == 0:
970
 
            rev2 = None
 
831
            # pair of revisions?
 
832
            pass
 
833
            
 
834
        assert len(revision) == 2
971
835
 
972
836
        mutter('encoding log as %r' % bzrlib.user_encoding)
973
837
 
975
839
        # in e.g. the default C locale.
976
840
        outf = codecs.getwriter(bzrlib.user_encoding)(sys.stdout, errors='replace')
977
841
 
978
 
        if long:
979
 
            log_format = 'long'
980
 
        else:
981
 
            log_format = 'short'
982
 
        lf = log_formatter(log_format,
983
 
                           show_ids=show_ids,
984
 
                           to_file=outf,
985
 
                           show_timezone=timezone)
986
 
 
987
 
        show_log(b,
988
 
                 lf,
989
 
                 file_id,
 
842
        show_log(b, file_id,
 
843
                 show_timezone=timezone,
990
844
                 verbose=verbose,
 
845
                 show_ids=show_ids,
 
846
                 to_file=outf,
991
847
                 direction=direction,
992
 
                 start_revision=rev1,
993
 
                 end_revision=rev2,
994
 
                 search=message)
 
848
                 start_revision=revision[0],
 
849
                 end_revision=revision[1])
995
850
 
996
851
 
997
852
 
1002
857
    hidden = True
1003
858
    takes_args = ["filename"]
1004
859
    def run(self, filename):
1005
 
        b = find_branch(filename)
 
860
        b = Branch(filename)
1006
861
        inv = b.read_working_inventory()
1007
862
        file_id = inv.path2id(b.relpath(filename))
1008
863
        for revno, revision_id, what in bzrlib.log.find_touching_revisions(b, file_id):
1016
871
    """
1017
872
    hidden = True
1018
873
    def run(self, revision=None, verbose=False):
1019
 
        b = find_branch('.')
 
874
        b = Branch('.')
1020
875
        if revision == None:
1021
876
            tree = b.working_tree()
1022
877
        else:
1040
895
class cmd_unknowns(Command):
1041
896
    """List unknown files."""
1042
897
    def run(self):
1043
 
        from bzrlib.osutils import quotefn
1044
 
        for f in find_branch('.').unknowns():
 
898
        for f in Branch('.').unknowns():
1045
899
            print quotefn(f)
1046
900
 
1047
901
 
1069
923
        from bzrlib.atomicfile import AtomicFile
1070
924
        import os.path
1071
925
 
1072
 
        b = find_branch('.')
 
926
        b = Branch('.')
1073
927
        ifn = b.abspath('.bzrignore')
1074
928
 
1075
929
        if os.path.exists(ifn):
1109
963
 
1110
964
    See also: bzr ignore"""
1111
965
    def run(self):
1112
 
        tree = find_branch('.').working_tree()
 
966
        tree = Branch('.').working_tree()
1113
967
        for path, file_class, kind, file_id in tree.list_files():
1114
968
            if file_class != 'I':
1115
969
                continue
1133
987
        except ValueError:
1134
988
            raise BzrCommandError("not a valid revision-number: %r" % revno)
1135
989
 
1136
 
        print find_branch('.').lookup_revision(revno)
 
990
        print Branch('.').lookup_revision(revno)
1137
991
 
1138
992
 
1139
993
class cmd_export(Command):
1142
996
    If no revision is specified this exports the last committed revision.
1143
997
 
1144
998
    Format may be an "exporter" name, such as tar, tgz, tbz2.  If none is
1145
 
    given, try to find the format with the extension. If no extension
1146
 
    is found exports to a directory (equivalent to --format=dir).
1147
 
 
1148
 
    Root may be the top directory for tar, tgz and tbz2 formats. If none
1149
 
    is given, the top directory will be the root name of the file."""
 
999
    given, exports to a directory (equivalent to --format=dir)."""
1150
1000
    # TODO: list known exporters
1151
1001
    takes_args = ['dest']
1152
 
    takes_options = ['revision', 'format', 'root']
1153
 
    def run(self, dest, revision=None, format=None, root=None):
1154
 
        import os.path
1155
 
        b = find_branch('.')
1156
 
        if revision is None:
1157
 
            rev_id = b.last_patch()
 
1002
    takes_options = ['revision', 'format']
 
1003
    def run(self, dest, revision=None, format='dir'):
 
1004
        b = Branch('.')
 
1005
        if revision == None:
 
1006
            rh = b.revision_history()[-1]
1158
1007
        else:
1159
 
            if len(revision) != 1:
1160
 
                raise BzrError('bzr export --revision takes exactly 1 argument')
1161
 
            revno, rev_id = b.get_revision_info(revision[0])
1162
 
        t = b.revision_tree(rev_id)
1163
 
        root, ext = os.path.splitext(dest)
1164
 
        if not format:
1165
 
            if ext in (".tar",):
1166
 
                format = "tar"
1167
 
            elif ext in (".gz", ".tgz"):
1168
 
                format = "tgz"
1169
 
            elif ext in (".bz2", ".tbz2"):
1170
 
                format = "tbz2"
1171
 
            else:
1172
 
                format = "dir"
1173
 
        t.export(dest, format, root)
 
1008
            rh = b.lookup_revision(int(revision))
 
1009
        t = b.revision_tree(rh)
 
1010
        t.export(dest, format)
1174
1011
 
1175
1012
 
1176
1013
class cmd_cat(Command):
1182
1019
    def run(self, filename, revision=None):
1183
1020
        if revision == None:
1184
1021
            raise BzrCommandError("bzr cat requires a revision number")
1185
 
        elif len(revision) != 1:
1186
 
            raise BzrCommandError("bzr cat --revision takes exactly one number")
1187
 
        b = find_branch('.')
1188
 
        b.print_file(b.relpath(filename), revision[0])
 
1022
        b = Branch('.')
 
1023
        b.print_file(b.relpath(filename), int(revision))
1189
1024
 
1190
1025
 
1191
1026
class cmd_local_time_offset(Command):
1212
1047
    TODO: Strict commit that fails if there are unknown or deleted files.
1213
1048
    """
1214
1049
    takes_args = ['selected*']
1215
 
    takes_options = ['message', 'file', 'verbose', 'unchanged']
 
1050
    takes_options = ['message', 'file', 'verbose']
1216
1051
    aliases = ['ci', 'checkin']
1217
1052
 
1218
 
    def run(self, message=None, file=None, verbose=True, selected_list=None,
1219
 
            unchanged=False):
1220
 
        from bzrlib.errors import PointlessCommit
1221
 
        from bzrlib.osutils import get_text_message
 
1053
    def run(self, message=None, file=None, verbose=True, selected_list=None):
 
1054
        from bzrlib.commit import commit
1222
1055
 
1223
1056
        ## Warning: shadows builtin file()
1224
1057
        if not message and not file:
1225
 
            import cStringIO
1226
 
            stdout = sys.stdout
1227
 
            catcher = cStringIO.StringIO()
1228
 
            sys.stdout = catcher
1229
 
            cmd_status({"file_list":selected_list}, {})
1230
 
            info = catcher.getvalue()
1231
 
            sys.stdout = stdout
1232
 
            message = get_text_message(info)
1233
 
            
1234
 
            if message is None:
1235
 
                raise BzrCommandError("please specify a commit message",
1236
 
                                      ["use either --message or --file"])
 
1058
            raise BzrCommandError("please specify a commit message",
 
1059
                                  ["use either --message or --file"])
1237
1060
        elif message and file:
1238
1061
            raise BzrCommandError("please specify either --message or --file")
1239
1062
        
1241
1064
            import codecs
1242
1065
            message = codecs.open(file, 'rt', bzrlib.user_encoding).read()
1243
1066
 
1244
 
        b = find_branch('.')
1245
 
 
1246
 
        try:
1247
 
            b.commit(message, verbose=verbose,
1248
 
                     specific_files=selected_list,
1249
 
                     allow_pointless=unchanged)
1250
 
        except PointlessCommit:
1251
 
            # FIXME: This should really happen before the file is read in;
1252
 
            # perhaps prepare the commit; get the message; then actually commit
1253
 
            raise BzrCommandError("no changes to commit",
1254
 
                                  ["use --unchanged to commit anyhow"])
 
1067
        b = Branch('.')
 
1068
        commit(b, message, verbose=verbose, specific_files=selected_list)
1255
1069
 
1256
1070
 
1257
1071
class cmd_check(Command):
1266
1080
    takes_args = ['dir?']
1267
1081
 
1268
1082
    def run(self, dir='.'):
1269
 
        from bzrlib.check import check
1270
 
        check(find_branch(dir))
1271
 
 
1272
 
 
1273
 
 
1274
 
class cmd_scan_cache(Command):
1275
 
    hidden = True
1276
 
    def run(self):
1277
 
        from bzrlib.hashcache import HashCache
1278
 
        import os
1279
 
 
1280
 
        c = HashCache('.')
1281
 
        c.read()
1282
 
        c.scan()
1283
 
            
1284
 
        print '%6d stats' % c.stat_count
1285
 
        print '%6d in hashcache' % len(c._cache)
1286
 
        print '%6d files removed from cache' % c.removed_count
1287
 
        print '%6d hashes updated' % c.update_count
1288
 
        print '%6d files changed too recently to cache' % c.danger_count
1289
 
 
1290
 
        if c.needs_write:
1291
 
            c.write()
1292
 
            
 
1083
        import bzrlib.check
 
1084
        bzrlib.check.check(Branch(dir))
 
1085
 
1293
1086
 
1294
1087
 
1295
1088
class cmd_upgrade(Command):
1302
1095
 
1303
1096
    def run(self, dir='.'):
1304
1097
        from bzrlib.upgrade import upgrade
1305
 
        upgrade(find_branch(dir))
 
1098
        upgrade(Branch(dir))
1306
1099
 
1307
1100
 
1308
1101
 
1320
1113
class cmd_selftest(Command):
1321
1114
    """Run internal test suite"""
1322
1115
    hidden = True
1323
 
    takes_options = ['verbose']
1324
 
    def run(self, verbose=False):
 
1116
    def run(self):
1325
1117
        from bzrlib.selftest import selftest
1326
 
        return int(not selftest(verbose=verbose))
 
1118
        return int(not selftest())
1327
1119
 
1328
1120
 
1329
1121
class cmd_version(Command):
1361
1153
    ['..', -1]
1362
1154
    >>> parse_spec("../f/@35")
1363
1155
    ['../f', 35]
1364
 
    >>> parse_spec('./@revid:john@arbash-meinel.com-20050711044610-3ca0327c6a222f67')
1365
 
    ['.', 'revid:john@arbash-meinel.com-20050711044610-3ca0327c6a222f67']
1366
1156
    """
1367
1157
    if spec is None:
1368
1158
        return [None, None]
1372
1162
        if parsed[1] == "":
1373
1163
            parsed[1] = -1
1374
1164
        else:
1375
 
            try:
1376
 
                parsed[1] = int(parsed[1])
1377
 
            except ValueError:
1378
 
                pass # We can allow stuff like ./@revid:blahblahblah
1379
 
            else:
1380
 
                assert parsed[1] >=0
 
1165
            parsed[1] = int(parsed[1])
 
1166
            assert parsed[1] >=0
1381
1167
    else:
1382
1168
        parsed = [spec, None]
1383
1169
    return parsed
1407
1193
    --force is given.
1408
1194
    """
1409
1195
    takes_args = ['other_spec', 'base_spec?']
1410
 
    takes_options = ['force', 'merge-type']
 
1196
    takes_options = ['force']
1411
1197
 
1412
 
    def run(self, other_spec, base_spec=None, force=False, merge_type=None):
 
1198
    def run(self, other_spec, base_spec=None, force=False):
1413
1199
        from bzrlib.merge import merge
1414
 
        from bzrlib.merge_core import ApplyMerge3
1415
 
        if merge_type is None:
1416
 
            merge_type = ApplyMerge3
1417
1200
        merge(parse_spec(other_spec), parse_spec(base_spec),
1418
 
              check_clean=(not force), merge_type=merge_type)
 
1201
              check_clean=(not force))
1419
1202
 
1420
1203
 
1421
1204
class cmd_revert(Command):
1422
1205
    """Reverse all changes since the last commit.
1423
1206
 
1424
 
    Only versioned files are affected.  Specify filenames to revert only 
1425
 
    those files.  By default, any files that are changed will be backed up
1426
 
    first.  Backup files have a '~' appended to their name.
 
1207
    Only versioned files are affected.
 
1208
 
 
1209
    TODO: Store backups of any files that will be reverted, so
 
1210
          that the revert can be undone.          
1427
1211
    """
1428
 
    takes_options = ['revision', 'no-backup']
1429
 
    takes_args = ['file*']
1430
 
    aliases = ['merge-revert']
 
1212
    takes_options = ['revision']
1431
1213
 
1432
 
    def run(self, revision=None, no_backup=False, file_list=None):
 
1214
    def run(self, revision=-1):
1433
1215
        from bzrlib.merge import merge
1434
 
        if file_list is not None:
1435
 
            if len(file_list) == 0:
1436
 
                raise BzrCommandError("No files specified")
1437
 
        if revision is None:
1438
 
            revision = [-1]
1439
 
        elif len(revision) != 1:
1440
 
            raise BzrCommandError('bzr revert --revision takes exactly 1 argument')
1441
 
        merge(('.', revision[0]), parse_spec('.'),
 
1216
        merge(('.', revision), parse_spec('.'),
1442
1217
              check_clean=False,
1443
 
              ignore_zero=True,
1444
 
              backup_files=not no_backup,
1445
 
              file_list=file_list)
 
1218
              ignore_zero=True)
1446
1219
 
1447
1220
 
1448
1221
class cmd_assert_fail(Command):
1464
1237
        help.help(topic)
1465
1238
 
1466
1239
 
1467
 
 
1468
 
 
1469
 
class cmd_plugins(Command):
1470
 
    """List plugins"""
 
1240
class cmd_update_stat_cache(Command):
 
1241
    """Update stat-cache mapping inodes to SHA-1 hashes.
 
1242
 
 
1243
    For testing only."""
1471
1244
    hidden = True
1472
1245
    def run(self):
1473
 
        import bzrlib.plugin
1474
 
        from inspect import getdoc
1475
 
        from pprint import pprint
1476
 
        for plugin in bzrlib.plugin.all_plugins:
1477
 
            print plugin.__path__[0]
1478
 
            d = getdoc(plugin)
1479
 
            if d:
1480
 
                print '\t', d.split('\n')[0]
1481
 
 
1482
 
        #pprint(bzrlib.plugin.all_plugins)
 
1246
        import statcache
 
1247
        b = Branch('.')
 
1248
        statcache.update_cache(b.base, b.read_working_inventory())
1483
1249
 
1484
1250
 
1485
1251
 
1503
1269
    'verbose':                None,
1504
1270
    'version':                None,
1505
1271
    'email':                  None,
1506
 
    'unchanged':              None,
1507
1272
    'update':                 None,
1508
 
    'long':                   None,
1509
 
    'root':                   str,
1510
 
    'no-backup':              None,
1511
 
    'merge-type':             get_merge_type,
1512
1273
    }
1513
1274
 
1514
1275
SHORT_OPTIONS = {
1517
1278
    'm':                      'message',
1518
1279
    'r':                      'revision',
1519
1280
    'v':                      'verbose',
1520
 
    'l':                      'long',
1521
1281
}
1522
1282
 
1523
1283
 
1538
1298
    >>> parse_args('commit --message=biter'.split())
1539
1299
    (['commit'], {'message': u'biter'})
1540
1300
    >>> parse_args('log -r 500'.split())
1541
 
    (['log'], {'revision': [500]})
1542
 
    >>> parse_args('log -r500..600'.split())
 
1301
    (['log'], {'revision': 500})
 
1302
    >>> parse_args('log -r500:600'.split())
1543
1303
    (['log'], {'revision': [500, 600]})
1544
 
    >>> parse_args('log -vr500..600'.split())
 
1304
    >>> parse_args('log -vr500:600'.split())
1545
1305
    (['log'], {'verbose': True, 'revision': [500, 600]})
1546
 
    >>> parse_args('log -rv500..600'.split()) #the r takes an argument
1547
 
    (['log'], {'revision': ['v500', 600]})
 
1306
    >>> parse_args('log -rv500:600'.split()) #the r takes an argument
 
1307
    Traceback (most recent call last):
 
1308
    ...
 
1309
    ValueError: invalid literal for int(): v500
1548
1310
    """
1549
1311
    args = []
1550
1312
    opts = {}
1684
1446
                    This is also a non-master option.
1685
1447
        --help      Run help and exit, also a non-master option (I think that should stay, though)
1686
1448
 
1687
 
    >>> argv, opts = _parse_master_args(['--test'])
 
1449
    >>> argv, opts = _parse_master_args(['bzr', '--test'])
1688
1450
    Traceback (most recent call last):
1689
1451
    ...
1690
1452
    BzrCommandError: Invalid master option: 'test'
1691
 
    >>> argv, opts = _parse_master_args(['--version', 'command'])
 
1453
    >>> argv, opts = _parse_master_args(['bzr', '--version', 'command'])
1692
1454
    >>> print argv
1693
1455
    ['command']
1694
1456
    >>> print opts['version']
1695
1457
    True
1696
 
    >>> argv, opts = _parse_master_args(['--profile', 'command', '--more-options'])
 
1458
    >>> argv, opts = _parse_master_args(['bzr', '--profile', 'command', '--more-options'])
1697
1459
    >>> print argv
1698
1460
    ['command', '--more-options']
1699
1461
    >>> print opts['profile']
1700
1462
    True
1701
 
    >>> argv, opts = _parse_master_args(['--no-plugins', 'command'])
 
1463
    >>> argv, opts = _parse_master_args(['bzr', '--no-plugins', 'command'])
1702
1464
    >>> print argv
1703
1465
    ['command']
1704
1466
    >>> print opts['no-plugins']
1705
1467
    True
1706
1468
    >>> print opts['profile']
1707
1469
    False
1708
 
    >>> argv, opts = _parse_master_args(['command', '--profile'])
 
1470
    >>> argv, opts = _parse_master_args(['bzr', 'command', '--profile'])
1709
1471
    >>> print argv
1710
1472
    ['command', '--profile']
1711
1473
    >>> print opts['profile']
1718
1480
        'help':False
1719
1481
    }
1720
1482
 
 
1483
    # This is the point where we could hook into argv[0] to determine
 
1484
    # what front-end is supposed to be run
 
1485
    # For now, we are just ignoring it.
 
1486
    cmd_name = argv.pop(0)
1721
1487
    for arg in argv[:]:
1722
1488
        if arg[:2] != '--': # at the first non-option, we return the rest
1723
1489
            break
1737
1503
 
1738
1504
    This is similar to main(), but without all the trappings for
1739
1505
    logging and error handling.  
1740
 
    
1741
 
    argv
1742
 
       The command-line arguments, without the program name.
1743
 
    
1744
 
    Returns a command status or raises an exception.
1745
1506
    """
1746
1507
    argv = [a.decode(bzrlib.user_encoding) for a in argv]
1747
 
 
1748
 
    # some options like --builtin and --no-plugins have special effects
1749
 
    argv, master_opts = _parse_master_args(argv)
1750
 
    if not master_opts['no-plugins']:
1751
 
        from bzrlib.plugin import load_plugins
1752
 
        load_plugins()
1753
 
 
1754
 
    args, opts = parse_args(argv)
1755
 
 
1756
 
    if master_opts.get('help') or 'help' in opts:
1757
 
        from bzrlib.help import help
1758
 
        if argv:
1759
 
            help(argv[0])
1760
 
        else:
1761
 
            help()
1762
 
        return 0            
1763
 
        
1764
 
    if 'version' in opts:
1765
 
        show_version()
1766
 
        return 0
1767
 
    
1768
 
    if args and args[0] == 'builtin':
1769
 
        include_plugins=False
1770
 
        args = args[1:]
1771
1508
    
1772
1509
    try:
 
1510
        # some options like --builtin and --no-plugins have special effects
 
1511
        argv, master_opts = _parse_master_args(argv)
 
1512
        if 'no-plugins' not in master_opts:
 
1513
            bzrlib.load_plugins()
 
1514
 
 
1515
        args, opts = parse_args(argv)
 
1516
 
 
1517
        if master_opts['help']:
 
1518
            from bzrlib.help import help
 
1519
            if argv:
 
1520
                help(argv[0])
 
1521
            else:
 
1522
                help()
 
1523
            return 0            
 
1524
            
 
1525
        if 'help' in opts:
 
1526
            from bzrlib.help import help
 
1527
            if args:
 
1528
                help(args[0])
 
1529
            else:
 
1530
                help()
 
1531
            return 0
 
1532
        elif 'version' in opts:
 
1533
            show_version()
 
1534
            return 0
 
1535
        elif args and args[0] == 'builtin':
 
1536
            include_plugins=False
 
1537
            args = args[1:]
1773
1538
        cmd = str(args.pop(0))
1774
1539
    except IndexError:
1775
 
        print >>sys.stderr, "please try 'bzr help' for help"
 
1540
        import help
 
1541
        help.help()
1776
1542
        return 1
 
1543
          
1777
1544
 
1778
1545
    plugins_override = not (master_opts['builtin'])
1779
1546
    canonical_cmd, cmd_class = get_cmd_class(cmd, plugins_override=plugins_override)
1838
1605
 
1839
1606
 
1840
1607
def main(argv):
 
1608
    import errno
1841
1609
    
1842
 
    bzrlib.trace.open_tracefile(argv)
 
1610
    bzrlib.open_tracefile(argv)
1843
1611
 
1844
1612
    try:
1845
1613
        try:
1846
1614
            try:
1847
 
                return run_bzr(argv[1:])
 
1615
                return run_bzr(argv)
1848
1616
            finally:
1849
1617
                # do this here inside the exception wrappers to catch EPIPE
1850
1618
                sys.stdout.flush()
1866
1634
            _report_exception('interrupted', quiet=True)
1867
1635
            return 2
1868
1636
        except Exception, e:
1869
 
            import errno
1870
1637
            quiet = False
1871
1638
            if (isinstance(e, IOError) 
1872
1639
                and hasattr(e, 'errno')