~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/builtins.py

Merge trunk

Show diffs side-by-side

added added

removed removed

Lines of Context:
22
22
from bzrlib.lazy_import import lazy_import
23
23
lazy_import(globals(), """
24
24
import codecs
25
 
import errno
26
 
import smtplib
27
25
import sys
28
 
import tempfile
29
26
import time
30
27
 
31
28
import bzrlib
32
29
from bzrlib import (
33
 
    branch,
34
30
    bugtracker,
35
31
    bundle,
36
32
    bzrdir,
43
39
    merge as _mod_merge,
44
40
    merge_directive,
45
41
    osutils,
46
 
    registry,
47
 
    repository,
 
42
    reconfigure,
 
43
    revision as _mod_revision,
48
44
    symbol_versioning,
49
45
    transport,
50
46
    tree as _mod_tree,
52
48
    urlutils,
53
49
    )
54
50
from bzrlib.branch import Branch
55
 
from bzrlib.bundle.apply_bundle import install_bundle, merge_bundle
56
51
from bzrlib.conflicts import ConflictList
57
 
from bzrlib.revision import common_ancestor
58
52
from bzrlib.revisionspec import RevisionSpec
 
53
from bzrlib.smtp_connection import SMTPConnection
59
54
from bzrlib.workingtree import WorkingTree
60
55
""")
61
56
 
62
57
from bzrlib.commands import Command, display_command
63
 
from bzrlib.option import ListOption, Option, RegistryOption
64
 
from bzrlib.progress import DummyProgress, ProgressPhase
65
 
from bzrlib.trace import mutter, note, log_error, warning, is_quiet, info
 
58
from bzrlib.option import ListOption, Option, RegistryOption, custom_help
 
59
from bzrlib.trace import mutter, note, warning, is_quiet, info
66
60
 
67
61
 
68
62
def tree_files(file_list, default_branch=u'.'):
152
146
    To see ignored files use 'bzr ignored'.  For details on the
153
147
    changes to file texts, use 'bzr diff'.
154
148
    
155
 
    --short gives a status flags for each item, similar to the SVN's status
156
 
    command.
157
 
 
158
 
    Column 1: versioning / renames
159
 
      + File versioned
160
 
      - File unversioned
161
 
      R File renamed
162
 
      ? File unknown
163
 
      C File has conflicts
164
 
      P Entry for a pending merge (not a file)
165
 
 
166
 
    Column 2: Contents
167
 
      N File created
168
 
      D File deleted
169
 
      K File kind changed
170
 
      M File modified
171
 
 
172
 
    Column 3: Execute
173
 
      * The execute bit was changed
 
149
    Note that --short or -S gives status flags for each item, similar
 
150
    to Subversion's status command. To get output similar to svn -q,
 
151
    use bzr -SV.
174
152
 
175
153
    If no arguments are specified, the status of the entire working
176
154
    directory is shown.  Otherwise, only the status of the specified
184
162
    # TODO: --no-recurse, --recurse options
185
163
    
186
164
    takes_args = ['file*']
187
 
    takes_options = ['show-ids', 'revision',
188
 
                     Option('short', help='Give short SVN-style status lines'),
189
 
                     Option('versioned', help='Only show versioned files')]
 
165
    takes_options = ['show-ids', 'revision', 'change',
 
166
                     Option('short', help='Use short status indicators.',
 
167
                            short_name='S'),
 
168
                     Option('versioned', help='Only show versioned files.',
 
169
                            short_name='V')
 
170
                     ]
190
171
    aliases = ['st', 'stat']
191
172
 
192
173
    encoding_type = 'replace'
193
 
    _see_also = ['diff', 'revert']
 
174
    _see_also = ['diff', 'revert', 'status-flags']
194
175
    
195
176
    @display_command
196
177
    def run(self, show_ids=False, file_list=None, revision=None, short=False,
197
178
            versioned=False):
198
179
        from bzrlib.status import show_tree_status
199
180
 
 
181
        if revision and len(revision) > 2:
 
182
            raise errors.BzrCommandError('bzr status --revision takes exactly'
 
183
                                         ' one or two revision specifiers')
 
184
 
200
185
        tree, file_list = tree_files(file_list)
201
186
            
202
187
        show_tree_status(tree, show_ids=show_ids,
219
204
    
220
205
    @display_command
221
206
    def run(self, revision_id=None, revision=None):
222
 
 
223
 
        revision_id = osutils.safe_revision_id(revision_id, warn=False)
224
207
        if revision_id is not None and revision is not None:
225
208
            raise errors.BzrCommandError('You can only supply one of'
226
209
                                         ' revision_id or --revision')
231
214
 
232
215
        # TODO: jam 20060112 should cat-revision always output utf-8?
233
216
        if revision_id is not None:
 
217
            revision_id = osutils.safe_revision_id(revision_id, warn=False)
234
218
            self.outf.write(b.repository.get_revision_xml(revision_id).decode('utf-8'))
235
219
        elif revision is not None:
236
220
            for rev in revision:
249
233
 
250
234
    To re-create the working tree, use "bzr checkout".
251
235
    """
252
 
    _see_also = ['checkout']
 
236
    _see_also = ['checkout', 'working-trees']
253
237
 
254
238
    takes_args = ['location?']
255
239
 
304
288
        if revision_info_list is not None:
305
289
            for rev in revision_info_list:
306
290
                revs.append(RevisionSpec.from_string(rev))
 
291
 
 
292
        b = Branch.open_containing(u'.')[0]
 
293
 
307
294
        if len(revs) == 0:
308
 
            raise errors.BzrCommandError('You must supply a revision identifier')
309
 
 
310
 
        b = WorkingTree.open_containing(u'.')[0].branch
 
295
            revs.append(RevisionSpec.from_string('-1'))
311
296
 
312
297
        for rev in revs:
313
298
            revinfo = rev.in_history(b)
314
299
            if revinfo.revno is None:
315
 
                print '     %s' % revinfo.rev_id
 
300
                dotted_map = b.get_revision_id_to_revno_map()
 
301
                revno = '.'.join(str(i) for i in dotted_map[revinfo.rev_id])
 
302
                print '%s %s' % (revno, revinfo.rev_id)
316
303
            else:
317
304
                print '%4d %s' % (revinfo.revno, revinfo.rev_id)
318
305
 
352
339
    into a subdirectory of this one.
353
340
    """
354
341
    takes_args = ['file*']
355
 
    takes_options = ['no-recurse', 'dry-run', 'verbose',
356
 
                     Option('file-ids-from', type=unicode,
357
 
                            help='Lookup file ids from here')]
 
342
    takes_options = [
 
343
        Option('no-recurse',
 
344
               help="Don't recursively add the contents of directories."),
 
345
        Option('dry-run',
 
346
               help="Show what would be done, but don't actually do anything."),
 
347
        'verbose',
 
348
        Option('file-ids-from',
 
349
               type=unicode,
 
350
               help='Lookup file ids from this tree.'),
 
351
        ]
358
352
    encoding_type = 'replace'
359
353
    _see_also = ['remove']
360
354
 
381
375
        if base_tree:
382
376
            base_tree.lock_read()
383
377
        try:
384
 
            added, ignored = bzrlib.add.smart_add(file_list, not no_recurse,
385
 
                action=action, save=not dry_run)
 
378
            file_list = self._maybe_expand_globs(file_list)
 
379
            if file_list:
 
380
                tree = WorkingTree.open_containing(file_list[0])[0]
 
381
            else:
 
382
                tree = WorkingTree.open_containing(u'.')[0]
 
383
            added, ignored = tree.smart_add(file_list, not
 
384
                no_recurse, action=action, save=not dry_run)
386
385
        finally:
387
386
            if base_tree is not None:
388
387
                base_tree.unlock()
445
444
 
446
445
    hidden = True
447
446
    _see_also = ['ls']
448
 
    takes_options = ['revision', 'show-ids', 'kind']
 
447
    takes_options = [
 
448
        'revision',
 
449
        'show-ids',
 
450
        Option('kind',
 
451
               help='List entries of a particular kind: file, directory, symlink.',
 
452
               type=unicode),
 
453
        ]
449
454
    takes_args = ['file*']
450
455
 
451
456
    @display_command
452
457
    def run(self, revision=None, show_ids=False, kind=None, file_list=None):
453
458
        if kind and kind not in ['file', 'directory', 'symlink']:
454
 
            raise errors.BzrCommandError('invalid kind specified')
 
459
            raise errors.BzrCommandError('invalid kind %r specified' % (kind,))
455
460
 
456
461
        work_tree, file_list = tree_files(file_list)
457
462
        work_tree.lock_read()
497
502
class cmd_mv(Command):
498
503
    """Move or rename a file.
499
504
 
500
 
    usage:
 
505
    :Usage:
501
506
        bzr mv OLDNAME NEWNAME
 
507
 
502
508
        bzr mv SOURCE... DESTINATION
503
509
 
504
510
    If the last argument is a versioned directory, all the other names
515
521
    """
516
522
 
517
523
    takes_args = ['names*']
518
 
    takes_options = [Option("after", help="move only the bzr identifier"
519
 
        " of the file (file has already been moved). Use this flag if"
520
 
        " bzr is not able to detect this itself.")]
 
524
    takes_options = [Option("after", help="Move only the bzr identifier"
 
525
        " of the file, because the file has already been moved."),
 
526
        ]
521
527
    aliases = ['move', 'rename']
522
528
    encoding_type = 'replace'
523
529
 
528
534
        if len(names_list) < 2:
529
535
            raise errors.BzrCommandError("missing file argument")
530
536
        tree, rel_names = tree_files(names_list)
531
 
        
532
 
        if os.path.isdir(names_list[-1]):
 
537
 
 
538
        dest = names_list[-1]
 
539
        isdir = os.path.isdir(dest)
 
540
        if (isdir and not tree.case_sensitive and len(rel_names) == 2
 
541
            and rel_names[0].lower() == rel_names[1].lower()):
 
542
                isdir = False
 
543
        if isdir:
533
544
            # move into existing directory
534
545
            for pair in tree.move(rel_names[:-1], rel_names[-1], after=after):
535
546
                self.outf.write("%s => %s\n" % pair)
540
551
                                             ' directory')
541
552
            tree.rename_one(rel_names[0], rel_names[1], after=after)
542
553
            self.outf.write("%s => %s\n" % (rel_names[0], rel_names[1]))
543
 
            
544
 
    
 
554
 
 
555
 
545
556
class cmd_pull(Command):
546
557
    """Turn this branch into a mirror of another branch.
547
558
 
562
573
    location can be accessed.
563
574
    """
564
575
 
565
 
    _see_also = ['push', 'update']
566
 
    takes_options = ['remember', 'overwrite', 'revision', 'verbose',
 
576
    _see_also = ['push', 'update', 'status-flags']
 
577
    takes_options = ['remember', 'overwrite', 'revision',
 
578
        custom_help('verbose',
 
579
            help='Show logs of pulled revisions.'),
567
580
        Option('directory',
568
 
            help='branch to pull into, '
569
 
                 'rather than the one containing the working directory',
 
581
            help='Branch to pull into, '
 
582
                 'rather than the one containing the working directory.',
570
583
            short_name='d',
571
584
            type=unicode,
572
585
            ),
577
590
    def run(self, location=None, remember=False, overwrite=False,
578
591
            revision=None, verbose=False,
579
592
            directory=None):
580
 
        from bzrlib.tag import _merge_tags_if_possible
581
593
        # FIXME: too much stuff is in the command class
582
594
        revision_id = None
583
595
        mergeable = None
590
602
            tree_to = None
591
603
            branch_to = Branch.open_containing(directory)[0]
592
604
 
593
 
        reader = None
 
605
        possible_transports = []
594
606
        if location is not None:
595
 
            try:
596
 
                mergeable = bundle.read_mergeable_from_url(
597
 
                    location)
598
 
            except errors.NotABundle:
599
 
                pass # Continue on considering this url a Branch
 
607
            mergeable, location_transport = _get_mergeable_helper(location)
 
608
            possible_transports.append(location_transport)
600
609
 
601
610
        stored_loc = branch_to.get_parent()
602
611
        if location is None:
606
615
            else:
607
616
                display_url = urlutils.unescape_for_display(stored_loc,
608
617
                        self.outf.encoding)
609
 
                self.outf.write("Using saved location: %s\n" % display_url)
 
618
                if not is_quiet():
 
619
                    self.outf.write("Using saved location: %s\n" % display_url)
610
620
                location = stored_loc
 
621
                location_transport = transport.get_transport(
 
622
                    location, possible_transports=possible_transports)
611
623
 
612
624
        if mergeable is not None:
613
625
            if revision is not None:
614
626
                raise errors.BzrCommandError(
615
627
                    'Cannot use -r with merge directives or bundles')
616
 
            revision_id = mergeable.install_revisions(branch_to.repository)
 
628
            mergeable.install_revisions(branch_to.repository)
 
629
            base_revision_id, revision_id, verified = \
 
630
                mergeable.get_merge_request(branch_to.repository)
617
631
            branch_from = branch_to
618
632
        else:
619
 
            branch_from = Branch.open(location)
 
633
            branch_from = Branch.open_from_transport(location_transport)
620
634
 
621
635
            if branch_to.get_parent() is None or remember:
622
636
                branch_to.set_parent(branch_from.base)
628
642
                raise errors.BzrCommandError(
629
643
                    'bzr pull --revision takes one value.')
630
644
 
631
 
        old_rh = branch_to.revision_history()
 
645
        if verbose:
 
646
            old_rh = branch_to.revision_history()
632
647
        if tree_to is not None:
 
648
            change_reporter = delta._ChangeReporter(
 
649
                unversioned_filter=tree_to.is_ignored)
633
650
            result = tree_to.pull(branch_from, overwrite, revision_id,
634
 
                delta._ChangeReporter(unversioned_filter=tree_to.is_ignored))
 
651
                                  change_reporter,
 
652
                                  possible_transports=possible_transports)
635
653
        else:
636
654
            result = branch_to.pull(branch_from, overwrite, revision_id)
637
655
 
638
656
        result.report(self.outf)
639
657
        if verbose:
640
 
            from bzrlib.log import show_changed_revisions
641
658
            new_rh = branch_to.revision_history()
642
 
            show_changed_revisions(branch_to, old_rh, new_rh,
643
 
                                   to_file=self.outf)
 
659
            log.show_changed_revisions(branch_to, old_rh, new_rh,
 
660
                                       to_file=self.outf)
644
661
 
645
662
 
646
663
class cmd_push(Command):
669
686
    location can be accessed.
670
687
    """
671
688
 
672
 
    _see_also = ['pull', 'update']
673
 
    takes_options = ['remember', 'overwrite', 'verbose',
 
689
    _see_also = ['pull', 'update', 'working-trees']
 
690
    takes_options = ['remember', 'overwrite', 'verbose', 'revision',
674
691
        Option('create-prefix',
675
692
               help='Create the path leading up to the branch '
676
 
                    'if it does not already exist'),
 
693
                    'if it does not already exist.'),
677
694
        Option('directory',
678
 
            help='branch to push from, '
679
 
                 'rather than the one containing the working directory',
 
695
            help='Branch to push from, '
 
696
                 'rather than the one containing the working directory.',
680
697
            short_name='d',
681
698
            type=unicode,
682
699
            ),
683
700
        Option('use-existing-dir',
684
701
               help='By default push will fail if the target'
685
702
                    ' directory exists, but does not already'
686
 
                    ' have a control directory. This flag will'
 
703
                    ' have a control directory.  This flag will'
687
704
                    ' allow push to proceed.'),
688
705
        ]
689
706
    takes_args = ['location?']
690
707
    encoding_type = 'replace'
691
708
 
692
709
    def run(self, location=None, remember=False, overwrite=False,
693
 
            create_prefix=False, verbose=False,
 
710
            create_prefix=False, verbose=False, revision=None,
694
711
            use_existing_dir=False,
695
712
            directory=None):
696
713
        # FIXME: Way too big!  Put this into a function called from the
709
726
                location = stored_loc
710
727
 
711
728
        to_transport = transport.get_transport(location)
712
 
        location_url = to_transport.base
713
729
 
714
730
        br_to = repository_to = dir_to = None
715
731
        try:
730
746
            else:
731
747
                # Found a branch, so we must have found a repository
732
748
                repository_to = br_to.repository
 
749
 
 
750
        if revision is not None:
 
751
            if len(revision) == 1:
 
752
                revision_id = revision[0].in_history(br_from).rev_id
 
753
            else:
 
754
                raise errors.BzrCommandError(
 
755
                    'bzr push --revision takes one value.')
 
756
        else:
 
757
            revision_id = br_from.last_revision()
 
758
 
733
759
        push_result = None
734
 
        old_rh = []
 
760
        if verbose:
 
761
            old_rh = []
735
762
        if dir_to is None:
736
763
            # The destination doesn't exist; create it.
737
764
            # XXX: Refactor the create_prefix/no_create_prefix code into a
738
765
            #      common helper function
 
766
 
 
767
            def make_directory(transport):
 
768
                transport.mkdir('.')
 
769
                return transport
 
770
 
 
771
            def redirected(redirected_transport, e, redirection_notice):
 
772
                return transport.get_transport(e.get_target_url())
 
773
 
739
774
            try:
740
 
                to_transport.mkdir('.')
 
775
                to_transport = transport.do_catching_redirections(
 
776
                    make_directory, to_transport, redirected)
741
777
            except errors.FileExists:
742
778
                if not use_existing_dir:
743
779
                    raise errors.BzrCommandError("Target directory %s"
751
787
                        "\nYou may supply --create-prefix to create all"
752
788
                        " leading parent directories."
753
789
                        % location)
754
 
 
755
 
                cur_transport = to_transport
756
 
                needed = [cur_transport]
757
 
                # Recurse upwards until we can create a directory successfully
758
 
                while True:
759
 
                    new_transport = cur_transport.clone('..')
760
 
                    if new_transport.base == cur_transport.base:
761
 
                        raise errors.BzrCommandError("Failed to create path"
762
 
                                                     " prefix for %s."
763
 
                                                     % location)
764
 
                    try:
765
 
                        new_transport.mkdir('.')
766
 
                    except errors.NoSuchFile:
767
 
                        needed.append(new_transport)
768
 
                        cur_transport = new_transport
769
 
                    else:
770
 
                        break
771
 
 
772
 
                # Now we only need to create child directories
773
 
                while needed:
774
 
                    cur_transport = needed.pop()
775
 
                    cur_transport.mkdir('.')
776
 
            
 
790
                _create_prefix(to_transport)
 
791
            except errors.TooManyRedirections:
 
792
                raise errors.BzrCommandError("Too many redirections trying "
 
793
                                             "to make %s." % location)
 
794
 
777
795
            # Now the target directory exists, but doesn't have a .bzr
778
796
            # directory. So we need to create it, along with any work to create
779
797
            # all of the dependent branches, etc.
780
 
            dir_to = br_from.bzrdir.clone(location_url,
781
 
                revision_id=br_from.last_revision())
 
798
            dir_to = br_from.bzrdir.clone_on_transport(to_transport,
 
799
                                                       revision_id=revision_id)
782
800
            br_to = dir_to.open_branch()
783
801
            # TODO: Some more useful message about what was copied
784
802
            note('Created new branch.')
796
814
        elif br_to is None:
797
815
            # We have a repository but no branch, copy the revisions, and then
798
816
            # create a branch.
799
 
            last_revision_id = br_from.last_revision()
800
 
            repository_to.fetch(br_from.repository,
801
 
                                revision_id=last_revision_id)
802
 
            br_to = br_from.clone(dir_to, revision_id=last_revision_id)
 
817
            repository_to.fetch(br_from.repository, revision_id=revision_id)
 
818
            br_to = br_from.clone(dir_to, revision_id=revision_id)
803
819
            note('Created new branch.')
804
820
            if br_from.get_push_location() is None or remember:
805
821
                br_from.set_push_location(br_to.base)
808
824
            # we don't need to successfully push because of possible divergence.
809
825
            if br_from.get_push_location() is None or remember:
810
826
                br_from.set_push_location(br_to.base)
811
 
            old_rh = br_to.revision_history()
 
827
            if verbose:
 
828
                old_rh = br_to.revision_history()
812
829
            try:
813
830
                try:
814
831
                    tree_to = dir_to.open_workingtree()
815
832
                except errors.NotLocalUrl:
816
 
                    warning('This transport does not update the working '
817
 
                            'tree of: %s' % (br_to.base,))
818
 
                    push_result = br_from.push(br_to, overwrite)
 
833
                    warning("This transport does not update the working " 
 
834
                            "tree of: %s. See 'bzr help working-trees' for "
 
835
                            "more information." % br_to.base)
 
836
                    push_result = br_from.push(br_to, overwrite,
 
837
                                               stop_revision=revision_id)
819
838
                except errors.NoWorkingTree:
820
 
                    push_result = br_from.push(br_to, overwrite)
 
839
                    push_result = br_from.push(br_to, overwrite,
 
840
                                               stop_revision=revision_id)
821
841
                else:
822
842
                    tree_to.lock_write()
823
843
                    try:
824
 
                        push_result = br_from.push(tree_to.branch, overwrite)
 
844
                        push_result = br_from.push(tree_to.branch, overwrite,
 
845
                                                   stop_revision=revision_id)
825
846
                        tree_to.update()
826
847
                    finally:
827
848
                        tree_to.unlock()
848
869
 
849
870
    If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
850
871
    be used.  In other words, "branch ../foo/bar" will attempt to create ./bar.
 
872
    If the FROM_LOCATION has no / or path separator embedded, the TO_LOCATION
 
873
    is derived from the FROM_LOCATION by stripping a leading scheme or drive
 
874
    identifier, if any. For example, "branch lp:foo-bar" will attempt to
 
875
    create ./foo-bar.
851
876
 
852
877
    To retrieve the branch as of a particular revision, supply the --revision
853
878
    parameter, as in "branch foo/bar -r 5".
855
880
 
856
881
    _see_also = ['checkout']
857
882
    takes_args = ['from_location', 'to_location?']
858
 
    takes_options = ['revision']
 
883
    takes_options = ['revision', Option('hardlink',
 
884
        help='Hard-link working tree files where possible.')]
859
885
    aliases = ['get', 'clone']
860
886
 
861
 
    def run(self, from_location, to_location=None, revision=None):
 
887
    def run(self, from_location, to_location=None, revision=None,
 
888
            hardlink=False):
862
889
        from bzrlib.tag import _merge_tags_if_possible
863
890
        if revision is None:
864
891
            revision = [None]
866
893
            raise errors.BzrCommandError(
867
894
                'bzr branch --revision takes exactly 1 revision value')
868
895
 
869
 
        br_from = Branch.open(from_location)
 
896
        accelerator_tree, br_from = bzrdir.BzrDir.open_tree_or_branch(
 
897
            from_location)
870
898
        br_from.lock_read()
871
899
        try:
872
900
            if len(revision) == 1 and revision[0] is not None:
877
905
                # RBC 20060209
878
906
                revision_id = br_from.last_revision()
879
907
            if to_location is None:
880
 
                to_location = os.path.basename(from_location.rstrip("/\\"))
 
908
                to_location = urlutils.derive_to_location(from_location)
881
909
                name = None
882
910
            else:
883
911
                name = os.path.basename(to_location) + '\n'
893
921
                                             % to_location)
894
922
            try:
895
923
                # preserve whatever source format we have.
896
 
                dir = br_from.bzrdir.sprout(to_transport.base, revision_id)
 
924
                dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
 
925
                                            possible_transports=[to_transport],
 
926
                                            accelerator_tree=accelerator_tree,
 
927
                                            hardlink=hardlink)
897
928
                branch = dir.open_branch()
898
929
            except errors.NoSuchRevision:
899
930
                to_transport.delete_tree('.')
917
948
    
918
949
    If the TO_LOCATION is omitted, the last component of the BRANCH_LOCATION will
919
950
    be used.  In other words, "checkout ../foo/bar" will attempt to create ./bar.
 
951
    If the BRANCH_LOCATION has no / or path separator embedded, the TO_LOCATION
 
952
    is derived from the BRANCH_LOCATION by stripping a leading scheme or drive
 
953
    identifier, if any. For example, "checkout lp:foo-bar" will attempt to
 
954
    create ./foo-bar.
920
955
 
921
956
    To retrieve the branch as of a particular revision, supply the --revision
922
957
    parameter, as in "checkout foo/bar -r 5". Note that this will be immediately
928
963
    takes_args = ['branch_location?', 'to_location?']
929
964
    takes_options = ['revision',
930
965
                     Option('lightweight',
931
 
                            help="perform a lightweight checkout. Lightweight "
 
966
                            help="Perform a lightweight checkout.  Lightweight "
932
967
                                 "checkouts depend on access to the branch for "
933
 
                                 "every operation. Normal checkouts can perform "
 
968
                                 "every operation.  Normal checkouts can perform "
934
969
                                 "common operations like diff and status without "
935
970
                                 "such access, and also support local commits."
936
971
                            ),
 
972
                     Option('files-from', type=str,
 
973
                            help="Get file contents from this tree."),
 
974
                     Option('hardlink',
 
975
                            help='Hard-link working tree files where possible.'
 
976
                            ),
937
977
                     ]
938
978
    aliases = ['co']
939
979
 
940
980
    def run(self, branch_location=None, to_location=None, revision=None,
941
 
            lightweight=False):
 
981
            lightweight=False, files_from=None, hardlink=False):
942
982
        if revision is None:
943
983
            revision = [None]
944
984
        elif len(revision) > 1:
947
987
        if branch_location is None:
948
988
            branch_location = osutils.getcwd()
949
989
            to_location = branch_location
950
 
        source = Branch.open(branch_location)
 
990
        accelerator_tree, source = bzrdir.BzrDir.open_tree_or_branch(
 
991
            branch_location)
 
992
        if files_from is not None:
 
993
            accelerator_tree = WorkingTree.open(files_from)
951
994
        if len(revision) == 1 and revision[0] is not None:
952
 
            revision_id = revision[0].in_history(source)[1]
 
995
            revision_id = _mod_revision.ensure_null(
 
996
                revision[0].in_history(source)[1])
953
997
        else:
954
998
            revision_id = None
955
999
        if to_location is None:
956
 
            to_location = os.path.basename(branch_location.rstrip("/\\"))
 
1000
            to_location = urlutils.derive_to_location(branch_location)
957
1001
        # if the source and to_location are the same, 
958
1002
        # and there is no working tree,
959
1003
        # then reconstitute a branch
962
1006
            try:
963
1007
                source.bzrdir.open_workingtree()
964
1008
            except errors.NoWorkingTree:
965
 
                source.bzrdir.create_workingtree()
 
1009
                source.bzrdir.create_workingtree(revision_id)
966
1010
                return
967
 
        try:
968
 
            os.mkdir(to_location)
969
 
        except OSError, e:
970
 
            if e.errno == errno.EEXIST:
971
 
                raise errors.BzrCommandError('Target directory "%s" already'
972
 
                                             ' exists.' % to_location)
973
 
            if e.errno == errno.ENOENT:
974
 
                raise errors.BzrCommandError('Parent of "%s" does not exist.'
975
 
                                             % to_location)
976
 
            else:
977
 
                raise
978
 
        source.create_checkout(to_location, revision_id, lightweight)
 
1011
        source.create_checkout(to_location, revision_id, lightweight,
 
1012
                               accelerator_tree, hardlink)
979
1013
 
980
1014
 
981
1015
class cmd_renames(Command):
1018
1052
    'bzr revert' instead of 'bzr commit' after the update.
1019
1053
    """
1020
1054
 
1021
 
    _see_also = ['pull']
 
1055
    _see_also = ['pull', 'working-trees', 'status-flags']
1022
1056
    takes_args = ['dir?']
1023
1057
    aliases = ['up']
1024
1058
 
1025
1059
    def run(self, dir='.'):
1026
1060
        tree = WorkingTree.open_containing(dir)[0]
1027
 
        master = tree.branch.get_master_branch()
 
1061
        possible_transports = []
 
1062
        master = tree.branch.get_master_branch(
 
1063
            possible_transports=possible_transports)
1028
1064
        if master is not None:
1029
1065
            tree.lock_write()
1030
1066
        else:
1031
1067
            tree.lock_tree_write()
1032
1068
        try:
1033
1069
            existing_pending_merges = tree.get_parent_ids()[1:]
1034
 
            last_rev = tree.last_revision()
1035
 
            if last_rev == tree.branch.last_revision():
 
1070
            last_rev = _mod_revision.ensure_null(tree.last_revision())
 
1071
            if last_rev == _mod_revision.ensure_null(
 
1072
                tree.branch.last_revision()):
1036
1073
                # may be up to date, check master too.
1037
 
                master = tree.branch.get_master_branch()
1038
 
                if master is None or last_rev == master.last_revision():
 
1074
                if master is None or last_rev == _mod_revision.ensure_null(
 
1075
                    master.last_revision()):
1039
1076
                    revno = tree.branch.revision_id_to_revno(last_rev)
1040
1077
                    note("Tree is up to date at revision %d." % (revno,))
1041
1078
                    return 0
1042
 
            conflicts = tree.update()
1043
 
            revno = tree.branch.revision_id_to_revno(tree.last_revision())
 
1079
            conflicts = tree.update(
 
1080
                delta._ChangeReporter(unversioned_filter=tree.is_ignored),
 
1081
                possible_transports=possible_transports)
 
1082
            revno = tree.branch.revision_id_to_revno(
 
1083
                _mod_revision.ensure_null(tree.last_revision()))
1044
1084
            note('Updated to revision %d.' % (revno,))
1045
1085
            if tree.get_parent_ids()[1:] != existing_pending_merges:
1046
1086
                note('Your local commits will now show as pending merges with '
1062
1102
 
1063
1103
    Branches and working trees will also report any missing revisions.
1064
1104
    """
1065
 
    _see_also = ['revno']
 
1105
    _see_also = ['revno', 'working-trees', 'repositories']
1066
1106
    takes_args = ['location?']
1067
1107
    takes_options = ['verbose']
 
1108
    encoding_type = 'replace'
1068
1109
 
1069
1110
    @display_command
1070
1111
    def run(self, location=None, verbose=False):
 
1112
        if verbose:
 
1113
            noise_level = 2
 
1114
        else:
 
1115
            noise_level = 0
1071
1116
        from bzrlib.info import show_bzrdir_info
1072
1117
        show_bzrdir_info(bzrdir.BzrDir.open_containing(location)[0],
1073
 
                         verbose=verbose)
 
1118
                         verbose=noise_level, outfile=self.outf)
1074
1119
 
1075
1120
 
1076
1121
class cmd_remove(Command):
1086
1131
    """
1087
1132
    takes_args = ['file*']
1088
1133
    takes_options = ['verbose',
1089
 
        Option('new', help='remove newly-added files'),
 
1134
        Option('new', help='Remove newly-added files.'),
1090
1135
        RegistryOption.from_kwargs('file-deletion-strategy',
1091
 
            'The file deletion mode to be used',
 
1136
            'The file deletion mode to be used.',
1092
1137
            title='Deletion Strategy', value_switches=True, enum_switch=False,
1093
1138
            safe='Only delete files if they can be'
1094
1139
                 ' safely recovered (default).',
1103
1148
        tree, file_list = tree_files(file_list)
1104
1149
 
1105
1150
        if file_list is not None:
1106
 
            file_list = [f for f in file_list if f != '']
 
1151
            file_list = [f for f in file_list]
1107
1152
        elif not new:
1108
1153
            raise errors.BzrCommandError('Specify one or more files to'
1109
1154
            ' remove, or use --new.')
1247
1292
    If there is already a branch at the location but it has no working tree,
1248
1293
    the tree can be populated with 'bzr checkout'.
1249
1294
 
1250
 
    Recipe for importing a tree of files:
 
1295
    Recipe for importing a tree of files::
 
1296
 
1251
1297
        cd ~/project
1252
1298
        bzr init
1253
1299
        bzr add .
1254
1300
        bzr status
1255
 
        bzr commit -m 'imported project'
 
1301
        bzr commit -m "imported project"
1256
1302
    """
1257
1303
 
1258
 
    _see_also = ['init-repo', 'branch', 'checkout']
 
1304
    _see_also = ['init-repository', 'branch', 'checkout']
1259
1305
    takes_args = ['location?']
1260
1306
    takes_options = [
 
1307
        Option('create-prefix',
 
1308
               help='Create the path leading up to the branch '
 
1309
                    'if it does not already exist.'),
1261
1310
         RegistryOption('format',
1262
1311
                help='Specify a format for this branch. '
1263
1312
                'See "help formats".',
1270
1319
                help='Never change revnos or the existing log.'
1271
1320
                '  Append revisions to it only.')
1272
1321
         ]
1273
 
    def run(self, location=None, format=None, append_revisions_only=False):
 
1322
    def run(self, location=None, format=None, append_revisions_only=False,
 
1323
            create_prefix=False):
1274
1324
        if format is None:
1275
1325
            format = bzrdir.format_registry.make_bzrdir('default')
1276
1326
        if location is None:
1283
1333
        # Just using os.mkdir, since I don't
1284
1334
        # believe that we want to create a bunch of
1285
1335
        # locations if the user supplies an extended path
1286
 
        # TODO: create-prefix
1287
 
        try:
1288
 
            to_transport.mkdir('.')
1289
 
        except errors.FileExists:
1290
 
            pass
1291
 
                    
1292
 
        try:
1293
 
            existing_bzrdir = bzrdir.BzrDir.open(location)
 
1336
        try:
 
1337
            to_transport.ensure_base()
 
1338
        except errors.NoSuchFile:
 
1339
            if not create_prefix:
 
1340
                raise errors.BzrCommandError("Parent directory of %s"
 
1341
                    " does not exist."
 
1342
                    "\nYou may supply --create-prefix to create all"
 
1343
                    " leading parent directories."
 
1344
                    % location)
 
1345
            _create_prefix(to_transport)
 
1346
 
 
1347
        try:
 
1348
            existing_bzrdir = bzrdir.BzrDir.open_from_transport(to_transport)
1294
1349
        except errors.NotBranchError:
1295
1350
            # really a NotBzrDir error...
1296
 
            branch = bzrdir.BzrDir.create_branch_convenience(to_transport.base,
1297
 
                                                             format=format)
 
1351
            create_branch = bzrdir.BzrDir.create_branch_convenience
 
1352
            branch = create_branch(to_transport.base, format=format,
 
1353
                                   possible_transports=[to_transport])
1298
1354
        else:
1299
1355
            from bzrlib.transport.local import LocalTransport
1300
1356
            if existing_bzrdir.has_branch():
1316
1372
class cmd_init_repository(Command):
1317
1373
    """Create a shared repository to hold branches.
1318
1374
 
1319
 
    New branches created under the repository directory will store their revisions
1320
 
    in the repository, not in the branch directory.
1321
 
 
1322
 
    example:
1323
 
        bzr init-repo --no-trees repo
1324
 
        bzr init repo/trunk
1325
 
        bzr checkout --lightweight repo/trunk trunk-checkout
1326
 
        cd trunk-checkout
1327
 
        (add files here)
 
1375
    New branches created under the repository directory will store their
 
1376
    revisions in the repository, not in the branch directory.
 
1377
 
 
1378
    If the --no-trees option is used then the branches in the repository
 
1379
    will not have working trees by default.
 
1380
 
 
1381
    :Examples:
 
1382
        Create a shared repositories holding just branches::
 
1383
 
 
1384
            bzr init-repo --no-trees repo
 
1385
            bzr init repo/trunk
 
1386
 
 
1387
        Make a lightweight checkout elsewhere::
 
1388
 
 
1389
            bzr checkout --lightweight repo/trunk trunk-checkout
 
1390
            cd trunk-checkout
 
1391
            (add files here)
1328
1392
    """
1329
1393
 
1330
 
    _see_also = ['init', 'branch', 'checkout']
 
1394
    _see_also = ['init', 'branch', 'checkout', 'repositories']
1331
1395
    takes_args = ["location"]
1332
1396
    takes_options = [RegistryOption('format',
1333
1397
                            help='Specify a format for this repository. See'
1334
 
                                 ' "bzr help formats" for details',
 
1398
                                 ' "bzr help formats" for details.',
1335
1399
                            registry=bzrdir.format_registry,
1336
1400
                            converter=bzrdir.format_registry.make_bzrdir,
1337
1401
                            value_switches=True, title='Repository format'),
1338
1402
                     Option('no-trees',
1339
1403
                             help='Branches in the repository will default to'
1340
 
                                  ' not having a working tree'),
 
1404
                                  ' not having a working tree.'),
1341
1405
                    ]
1342
1406
    aliases = ["init-repo"]
1343
1407
 
1349
1413
            location = '.'
1350
1414
 
1351
1415
        to_transport = transport.get_transport(location)
1352
 
        try:
1353
 
            to_transport.mkdir('.')
1354
 
        except errors.FileExists:
1355
 
            pass
 
1416
        to_transport.ensure_base()
1356
1417
 
1357
1418
        newdir = format.initialize_on_transport(to_transport)
1358
1419
        repo = newdir.create_repository(shared=True)
1360
1421
 
1361
1422
 
1362
1423
class cmd_diff(Command):
1363
 
    """Show differences in the working tree or between revisions.
 
1424
    """Show differences in the working tree, between revisions or branches.
1364
1425
    
1365
 
    If files are listed, only the changes in those files are listed.
1366
 
    Otherwise, all changes for the tree are listed.
 
1426
    If no arguments are given, all changes for the current tree are listed.
 
1427
    If files are given, only the changes in those files are listed.
 
1428
    Remote and multiple branches can be compared by using the --old and
 
1429
    --new options. If not provided, the default for both is derived from
 
1430
    the first argument, if any, or the current tree if no arguments are
 
1431
    given.
1367
1432
 
1368
1433
    "bzr diff -p1" is equivalent to "bzr diff --prefix old/:new/", and
1369
1434
    produces patches suitable for "patch -p1".
1370
1435
 
1371
 
    examples:
1372
 
        bzr diff
1373
 
            Shows the difference in the working tree versus the last commit
1374
 
        bzr diff -r1
1375
 
            Difference between the working tree and revision 1
1376
 
        bzr diff -r1..2
1377
 
            Difference between revision 2 and revision 1
1378
 
        bzr diff --prefix old/:new/
1379
 
            Same as 'bzr diff' but prefix paths with old/ and new/
1380
 
        bzr diff bzr.mine bzr.dev
1381
 
            Show the differences between the two working trees
1382
 
        bzr diff foo.c
1383
 
            Show just the differences for 'foo.c'
 
1436
    :Exit values:
 
1437
        1 - changed
 
1438
        2 - unrepresentable changes
 
1439
        3 - error
 
1440
        0 - no change
 
1441
 
 
1442
    :Examples:
 
1443
        Shows the difference in the working tree versus the last commit::
 
1444
 
 
1445
            bzr diff
 
1446
 
 
1447
        Difference between the working tree and revision 1::
 
1448
 
 
1449
            bzr diff -r1
 
1450
 
 
1451
        Difference between revision 2 and revision 1::
 
1452
 
 
1453
            bzr diff -r1..2
 
1454
 
 
1455
        Difference between revision 2 and revision 1 for branch xxx::
 
1456
 
 
1457
            bzr diff -r1..2 xxx
 
1458
 
 
1459
        Show just the differences for file NEWS::
 
1460
 
 
1461
            bzr diff NEWS
 
1462
 
 
1463
        Show the differences in working tree xxx for file NEWS::
 
1464
 
 
1465
            bzr diff xxx/NEWS
 
1466
 
 
1467
        Show the differences from branch xxx to this working tree:
 
1468
 
 
1469
            bzr diff --old xxx
 
1470
 
 
1471
        Show the differences between two branches for file NEWS::
 
1472
 
 
1473
            bzr diff --old xxx --new yyy NEWS
 
1474
 
 
1475
        Same as 'bzr diff' but prefix paths with old/ and new/::
 
1476
 
 
1477
            bzr diff --prefix old/:new/
1384
1478
    """
1385
 
    # TODO: Option to use external diff command; could be GNU diff, wdiff,
1386
 
    #       or a graphical diff.
1387
 
 
1388
 
    # TODO: Python difflib is not exactly the same as unidiff; should
1389
 
    #       either fix it up or prefer to use an external diff.
1390
 
 
1391
 
    # TODO: Selected-file diff is inefficient and doesn't show you
1392
 
    #       deleted files.
1393
 
 
1394
 
    # TODO: This probably handles non-Unix newlines poorly.
1395
 
 
1396
1479
    _see_also = ['status']
1397
1480
    takes_args = ['file*']
1398
 
    takes_options = ['revision', 'diff-options',
 
1481
    takes_options = [
 
1482
        Option('diff-options', type=str,
 
1483
               help='Pass these options to the external diff program.'),
1399
1484
        Option('prefix', type=str,
1400
1485
               short_name='p',
1401
 
               help='Set prefixes to added to old and new filenames, as '
1402
 
                    'two values separated by a colon. (eg "old/:new/")'),
 
1486
               help='Set prefixes added to old and new filenames, as '
 
1487
                    'two values separated by a colon. (eg "old/:new/").'),
 
1488
        Option('old',
 
1489
            help='Branch/tree to compare from.',
 
1490
            type=unicode,
 
1491
            ),
 
1492
        Option('new',
 
1493
            help='Branch/tree to compare to.',
 
1494
            type=unicode,
 
1495
            ),
 
1496
        'revision',
 
1497
        'change',
 
1498
        Option('using',
 
1499
            help='Use this command to compare files.',
 
1500
            type=unicode,
 
1501
            ),
1403
1502
        ]
1404
1503
    aliases = ['di', 'dif']
1405
1504
    encoding_type = 'exact'
1406
1505
 
1407
1506
    @display_command
1408
1507
    def run(self, revision=None, file_list=None, diff_options=None,
1409
 
            prefix=None):
1410
 
        from bzrlib.diff import diff_cmd_helper, show_diff_trees
 
1508
            prefix=None, old=None, new=None, using=None):
 
1509
        from bzrlib.diff import _get_trees_to_diff, show_diff_trees
1411
1510
 
1412
1511
        if (prefix is None) or (prefix == '0'):
1413
1512
            # diff -p0 format
1427
1526
            raise errors.BzrCommandError('bzr diff --revision takes exactly'
1428
1527
                                         ' one or two revision specifiers')
1429
1528
 
1430
 
        try:
1431
 
            tree1, file_list = internal_tree_files(file_list)
1432
 
            tree2 = None
1433
 
            b = None
1434
 
            b2 = None
1435
 
        except errors.FileInWrongBranch:
1436
 
            if len(file_list) != 2:
1437
 
                raise errors.BzrCommandError("Files are in different branches")
1438
 
 
1439
 
            tree1, file1 = WorkingTree.open_containing(file_list[0])
1440
 
            tree2, file2 = WorkingTree.open_containing(file_list[1])
1441
 
            if file1 != "" or file2 != "":
1442
 
                # FIXME diff those two files. rbc 20051123
1443
 
                raise errors.BzrCommandError("Files are in different branches")
1444
 
            file_list = None
1445
 
        except errors.NotBranchError:
1446
 
            if (revision is not None and len(revision) == 2
1447
 
                and not revision[0].needs_branch()
1448
 
                and not revision[1].needs_branch()):
1449
 
                # If both revision specs include a branch, we can
1450
 
                # diff them without needing a local working tree
1451
 
                tree1, tree2 = None, None
1452
 
            else:
1453
 
                raise
1454
 
 
1455
 
        if tree2 is not None:
1456
 
            if revision is not None:
1457
 
                # FIXME: but there should be a clean way to diff between
1458
 
                # non-default versions of two trees, it's not hard to do
1459
 
                # internally...
1460
 
                raise errors.BzrCommandError(
1461
 
                        "Sorry, diffing arbitrary revisions across branches "
1462
 
                        "is not implemented yet")
1463
 
            return show_diff_trees(tree1, tree2, sys.stdout, 
1464
 
                                   specific_files=file_list,
1465
 
                                   external_diff_options=diff_options,
1466
 
                                   old_label=old_label, new_label=new_label)
1467
 
 
1468
 
        return diff_cmd_helper(tree1, file_list, diff_options,
1469
 
                               revision_specs=revision,
1470
 
                               old_label=old_label, new_label=new_label)
 
1529
        old_tree, new_tree, specific_files, extra_trees = \
 
1530
                _get_trees_to_diff(file_list, revision, old, new)
 
1531
        return show_diff_trees(old_tree, new_tree, sys.stdout, 
 
1532
                               specific_files=specific_files,
 
1533
                               external_diff_options=diff_options,
 
1534
                               old_label=old_label, new_label=new_label,
 
1535
                               extra_trees=extra_trees, using=using)
1471
1536
 
1472
1537
 
1473
1538
class cmd_deleted(Command):
1564
1629
        self.outf.write(tree.basedir + '\n')
1565
1630
 
1566
1631
 
 
1632
def _parse_limit(limitstring):
 
1633
    try:
 
1634
        return int(limitstring)
 
1635
    except ValueError:
 
1636
        msg = "The limit argument must be an integer."
 
1637
        raise errors.BzrCommandError(msg)
 
1638
 
 
1639
 
1567
1640
class cmd_log(Command):
1568
1641
    """Show log of a branch, file, or directory.
1569
1642
 
1573
1646
    -r revision requests a specific revision, -r ..end or -r begin.. are
1574
1647
    also valid.
1575
1648
 
1576
 
    examples:
1577
 
        bzr log
1578
 
        bzr log foo.c
1579
 
        bzr log -r -10.. http://server/branch
 
1649
    :Examples:
 
1650
        Log the current branch::
 
1651
 
 
1652
            bzr log
 
1653
 
 
1654
        Log a file::
 
1655
 
 
1656
            bzr log foo.c
 
1657
 
 
1658
        Log the last 10 revisions of a branch::
 
1659
 
 
1660
            bzr log -r -10.. http://server/branch
1580
1661
    """
1581
1662
 
1582
1663
    # TODO: Make --revision support uuid: and hash: [future tag:] notation.
1583
1664
 
1584
1665
    takes_args = ['location?']
1585
 
    takes_options = [Option('forward', 
1586
 
                            help='show from oldest to newest'),
1587
 
                     'timezone', 
1588
 
                     Option('verbose', 
1589
 
                             short_name='v',
1590
 
                             help='show files changed in each revision'),
1591
 
                     'show-ids', 'revision',
1592
 
                     'log-format',
1593
 
                     Option('message',
1594
 
                            short_name='m',
1595
 
                            help='show revisions whose message matches this regexp',
1596
 
                            type=str),
1597
 
                     ]
 
1666
    takes_options = [
 
1667
            Option('forward',
 
1668
                   help='Show from oldest to newest.'),
 
1669
            Option('timezone',
 
1670
                   type=str,
 
1671
                   help='Display timezone as local, original, or utc.'),
 
1672
            custom_help('verbose',
 
1673
                   help='Show files changed in each revision.'),
 
1674
            'show-ids',
 
1675
            'revision',
 
1676
            'log-format',
 
1677
            Option('message',
 
1678
                   short_name='m',
 
1679
                   help='Show revisions whose message matches this '
 
1680
                        'regular expression.',
 
1681
                   type=str),
 
1682
            Option('limit',
 
1683
                   short_name='l',
 
1684
                   help='Limit the output to the first N revisions.',
 
1685
                   argname='N',
 
1686
                   type=_parse_limit),
 
1687
            ]
1598
1688
    encoding_type = 'replace'
1599
1689
 
1600
1690
    @display_command
1604
1694
            forward=False,
1605
1695
            revision=None,
1606
1696
            log_format=None,
1607
 
            message=None):
 
1697
            message=None,
 
1698
            limit=None):
1608
1699
        from bzrlib.log import show_log
1609
1700
        assert message is None or isinstance(message, basestring), \
1610
1701
            "invalid message argument %r" % message
1642
1733
                rev1 = None
1643
1734
                rev2 = None
1644
1735
            elif len(revision) == 1:
1645
 
                rev1 = rev2 = revision[0].in_history(b).revno
 
1736
                rev1 = rev2 = revision[0].in_history(b)
1646
1737
            elif len(revision) == 2:
1647
1738
                if revision[1].get_branch() != revision[0].get_branch():
1648
1739
                    # b is taken from revision[0].get_branch(), and
1651
1742
                    raise errors.BzrCommandError(
1652
1743
                        "Log doesn't accept two revisions in different"
1653
1744
                        " branches.")
1654
 
                if revision[0].spec is None:
1655
 
                    # missing begin-range means first revision
1656
 
                    rev1 = 1
1657
 
                else:
1658
 
                    rev1 = revision[0].in_history(b).revno
1659
 
 
1660
 
                if revision[1].spec is None:
1661
 
                    # missing end-range means last known revision
1662
 
                    rev2 = b.revno()
1663
 
                else:
1664
 
                    rev2 = revision[1].in_history(b).revno
 
1745
                rev1 = revision[0].in_history(b)
 
1746
                rev2 = revision[1].in_history(b)
1665
1747
            else:
1666
1748
                raise errors.BzrCommandError(
1667
1749
                    'bzr log --revision takes one or two values.')
1668
1750
 
1669
 
            # By this point, the revision numbers are converted to the +ve
1670
 
            # form if they were supplied in the -ve form, so we can do
1671
 
            # this comparison in relative safety
1672
 
            if rev1 > rev2:
1673
 
                (rev2, rev1) = (rev1, rev2)
1674
 
 
1675
1751
            if log_format is None:
1676
1752
                log_format = log.log_formatter_registry.get_default(b)
1677
1753
 
1685
1761
                     direction=direction,
1686
1762
                     start_revision=rev1,
1687
1763
                     end_revision=rev2,
1688
 
                     search=message)
 
1764
                     search=message,
 
1765
                     limit=limit)
1689
1766
        finally:
1690
1767
            b.unlock()
1691
1768
 
1726
1803
    _see_also = ['status', 'cat']
1727
1804
    takes_args = ['path?']
1728
1805
    # TODO: Take a revision or remote path and list that tree instead.
1729
 
    takes_options = ['verbose', 'revision',
1730
 
                     Option('non-recursive',
1731
 
                            help='don\'t recurse into sub-directories'),
1732
 
                     Option('from-root',
1733
 
                            help='Print all paths from the root of the branch.'),
1734
 
                     Option('unknown', help='Print unknown files'),
1735
 
                     Option('versioned', help='Print versioned files'),
1736
 
                     Option('ignored', help='Print ignored files'),
1737
 
 
1738
 
                     Option('null', help='Null separate the files'),
1739
 
                     'kind', 'show-ids'
1740
 
                    ]
 
1806
    takes_options = [
 
1807
            'verbose',
 
1808
            'revision',
 
1809
            Option('non-recursive',
 
1810
                   help='Don\'t recurse into subdirectories.'),
 
1811
            Option('from-root',
 
1812
                   help='Print paths relative to the root of the branch.'),
 
1813
            Option('unknown', help='Print unknown files.'),
 
1814
            Option('versioned', help='Print versioned files.'),
 
1815
            Option('ignored', help='Print ignored files.'),
 
1816
            Option('null',
 
1817
                   help='Write an ascii NUL (\\0) separator '
 
1818
                   'between files rather than a newline.'),
 
1819
            Option('kind',
 
1820
                   help='List entries of a particular kind: file, directory, symlink.',
 
1821
                   type=unicode),
 
1822
            'show-ids',
 
1823
            ]
1741
1824
    @display_command
1742
 
    def run(self, revision=None, verbose=False, 
 
1825
    def run(self, revision=None, verbose=False,
1743
1826
            non_recursive=False, from_root=False,
1744
1827
            unknown=False, versioned=False, ignored=False,
1745
1828
            null=False, kind=None, show_ids=False, path=None):
1837
1920
 
1838
1921
    Ignore patterns specifying absolute paths are not allowed.
1839
1922
 
1840
 
    Ignore patterns may include globbing wildcards such as:
 
1923
    Ignore patterns may include globbing wildcards such as::
 
1924
 
1841
1925
      ? - Matches any single character except '/'
1842
1926
      * - Matches 0 or more characters except '/'
1843
1927
      /**/ - Matches 0 or more directories in a path
1851
1935
    Note: ignore patterns containing shell wildcards must be quoted from 
1852
1936
    the shell on Unix.
1853
1937
 
1854
 
    examples:
1855
 
        bzr ignore ./Makefile
1856
 
        bzr ignore '*.class'
1857
 
        bzr ignore 'lib/**/*.o'
1858
 
        bzr ignore 'RE:lib/.*\.o'
 
1938
    :Examples:
 
1939
        Ignore the top level Makefile::
 
1940
 
 
1941
            bzr ignore ./Makefile
 
1942
 
 
1943
        Ignore class files in all directories::
 
1944
 
 
1945
            bzr ignore "*.class"
 
1946
 
 
1947
        Ignore .o files under the lib directory::
 
1948
 
 
1949
            bzr ignore "lib/**/*.o"
 
1950
 
 
1951
        Ignore .o files under the lib directory::
 
1952
 
 
1953
            bzr ignore "RE:lib/.*\.o"
 
1954
 
 
1955
        Ignore everything but the "debian" toplevel directory::
 
1956
 
 
1957
            bzr ignore "RE:(?!debian/).*"
1859
1958
    """
1860
1959
 
1861
1960
    _see_also = ['status', 'ignored']
1862
1961
    takes_args = ['name_pattern*']
1863
1962
    takes_options = [
1864
 
                     Option('old-default-rules',
1865
 
                            help='Out the ignore rules bzr < 0.9 always used.')
1866
 
                     ]
 
1963
        Option('old-default-rules',
 
1964
               help='Write out the ignore rules bzr < 0.9 always used.')
 
1965
        ]
1867
1966
    
1868
1967
    def run(self, name_pattern_list=None, old_default_rules=None):
1869
1968
        from bzrlib.atomicfile import AtomicFile
1911
2010
        if not tree.path2id('.bzrignore'):
1912
2011
            tree.add(['.bzrignore'])
1913
2012
 
 
2013
        ignored = globbing.Globster(name_pattern_list)
 
2014
        matches = []
 
2015
        tree.lock_read()
 
2016
        for entry in tree.list_files():
 
2017
            id = entry[3]
 
2018
            if id is not None:
 
2019
                filename = entry[0]
 
2020
                if ignored.match(filename):
 
2021
                    matches.append(filename.encode('utf-8'))
 
2022
        tree.unlock()
 
2023
        if len(matches) > 0:
 
2024
            print "Warning: the following files are version controlled and" \
 
2025
                  " match your ignore pattern:\n%s" % ("\n".join(matches),)
1914
2026
 
1915
2027
class cmd_ignored(Command):
1916
2028
    """List ignored files and the patterns that matched them.
1917
2029
    """
1918
2030
 
 
2031
    encoding_type = 'replace'
1919
2032
    _see_also = ['ignore']
 
2033
 
1920
2034
    @display_command
1921
2035
    def run(self):
1922
2036
        tree = WorkingTree.open_containing(u'.')[0]
1927
2041
                    continue
1928
2042
                ## XXX: Slightly inefficient since this was already calculated
1929
2043
                pat = tree.is_ignored(path)
1930
 
                print '%-50s %s' % (path, pat)
 
2044
                self.outf.write('%-50s %s\n' % (path, pat))
1931
2045
        finally:
1932
2046
            tree.unlock()
1933
2047
 
1935
2049
class cmd_lookup_revision(Command):
1936
2050
    """Lookup the revision-id from a revision-number
1937
2051
 
1938
 
    example:
 
2052
    :Examples:
1939
2053
        bzr lookup-revision 33
1940
2054
    """
1941
2055
    hidden = True
1969
2083
 
1970
2084
    Note: Export of tree with non-ASCII filenames to zip is not supported.
1971
2085
 
1972
 
     Supported formats       Autodetected by extension
1973
 
     -----------------       -------------------------
1974
 
         dir                            -
 
2086
      =================       =========================
 
2087
      Supported formats       Autodetected by extension
 
2088
      =================       =========================
 
2089
         dir                         (none)
1975
2090
         tar                          .tar
1976
2091
         tbz2                    .tar.bz2, .tbz2
1977
2092
         tgz                      .tar.gz, .tgz
1978
2093
         zip                          .zip
 
2094
      =================       =========================
1979
2095
    """
1980
2096
    takes_args = ['dest', 'branch?']
1981
 
    takes_options = ['revision', 'format', 'root']
 
2097
    takes_options = [
 
2098
        Option('format',
 
2099
               help="Type of file to export to.",
 
2100
               type=unicode),
 
2101
        'revision',
 
2102
        Option('root',
 
2103
               type=str,
 
2104
               help="Name of the root directory inside the exported file."),
 
2105
        ]
1982
2106
    def run(self, dest, branch=None, revision=None, format=None, root=None):
1983
2107
        from bzrlib.export import export
1984
2108
 
2012
2136
    """
2013
2137
 
2014
2138
    _see_also = ['ls']
2015
 
    takes_options = ['revision', 'name-from-revision']
 
2139
    takes_options = [
 
2140
        Option('name-from-revision', help='The path name in the old tree.'),
 
2141
        'revision',
 
2142
        ]
2016
2143
    takes_args = ['filename']
2017
2144
    encoding_type = 'exact'
2018
2145
 
2020
2147
    def run(self, filename, revision=None, name_from_revision=False):
2021
2148
        if revision is not None and len(revision) != 1:
2022
2149
            raise errors.BzrCommandError("bzr cat --revision takes exactly"
2023
 
                                        " one number")
2024
 
 
2025
 
        tree = None
 
2150
                                         " one revision specifier")
 
2151
        tree, branch, relpath = \
 
2152
            bzrdir.BzrDir.open_containing_tree_or_branch(filename)
 
2153
        branch.lock_read()
2026
2154
        try:
2027
 
            tree, b, relpath = \
2028
 
                    bzrdir.BzrDir.open_containing_tree_or_branch(filename)
2029
 
        except errors.NotBranchError:
2030
 
            pass
 
2155
            return self._run(tree, branch, relpath, filename, revision,
 
2156
                             name_from_revision)
 
2157
        finally:
 
2158
            branch.unlock()
2031
2159
 
2032
 
        if revision is not None and revision[0].get_branch() is not None:
2033
 
            b = Branch.open(revision[0].get_branch())
 
2160
    def _run(self, tree, b, relpath, filename, revision, name_from_revision):
2034
2161
        if tree is None:
2035
2162
            tree = b.basis_tree()
2036
2163
        if revision is None:
2075
2202
    committed.  If a directory is specified then the directory and everything 
2076
2203
    within it is committed.
2077
2204
 
 
2205
    If author of the change is not the same person as the committer, you can
 
2206
    specify the author's name using the --author option. The name should be
 
2207
    in the same format as a committer-id, e.g. "John Doe <jdoe@example.com>".
 
2208
 
2078
2209
    A selected-file commit may fail in some cases where the committed
2079
2210
    tree would be invalid. Consider::
2080
2211
 
2105
2236
 
2106
2237
    _see_also = ['bugs', 'uncommit']
2107
2238
    takes_args = ['selected*']
2108
 
    takes_options = ['message', 'verbose', 
2109
 
                     Option('unchanged',
2110
 
                            help='commit even if nothing has changed'),
2111
 
                     Option('file', type=str, 
2112
 
                            short_name='F',
2113
 
                            argname='msgfile',
2114
 
                            help='file containing commit message'),
2115
 
                     Option('strict',
2116
 
                            help="refuse to commit if there are unknown "
2117
 
                            "files in the working tree."),
2118
 
                     ListOption('fixes', type=str,
2119
 
                                help="mark a bug as being fixed by this "
2120
 
                                     "revision."),
2121
 
                     Option('local',
2122
 
                            help="perform a local only commit in a bound "
2123
 
                                 "branch. Such commits are not pushed to "
2124
 
                                 "the master branch until a normal commit "
2125
 
                                 "is performed."
2126
 
                            ),
2127
 
                     ]
 
2239
    takes_options = [
 
2240
            Option('message', type=unicode,
 
2241
                   short_name='m',
 
2242
                   help="Description of the new revision."),
 
2243
            'verbose',
 
2244
             Option('unchanged',
 
2245
                    help='Commit even if nothing has changed.'),
 
2246
             Option('file', type=str,
 
2247
                    short_name='F',
 
2248
                    argname='msgfile',
 
2249
                    help='Take commit message from this file.'),
 
2250
             Option('strict',
 
2251
                    help="Refuse to commit if there are unknown "
 
2252
                    "files in the working tree."),
 
2253
             ListOption('fixes', type=str,
 
2254
                    help="Mark a bug as being fixed by this revision."),
 
2255
             Option('author', type=unicode,
 
2256
                    help="Set the author's name, if it's different "
 
2257
                         "from the committer."),
 
2258
             Option('local',
 
2259
                    help="Perform a local commit in a bound "
 
2260
                         "branch.  Local commits are not pushed to "
 
2261
                         "the master branch until a normal commit "
 
2262
                         "is performed."
 
2263
                    ),
 
2264
              Option('show-diff',
 
2265
                     help='When no message is supplied, show the diff along'
 
2266
                     ' with the status summary in the message editor.'),
 
2267
             ]
2128
2268
    aliases = ['ci', 'checkin']
2129
2269
 
2130
2270
    def _get_bug_fix_properties(self, fixes, branch):
2149
2289
            properties.append('%s fixed' % bug_url)
2150
2290
        return '\n'.join(properties)
2151
2291
 
2152
 
    def run(self, message=None, file=None, verbose=True, selected_list=None,
2153
 
            unchanged=False, strict=False, local=False, fixes=None):
2154
 
        from bzrlib.commit import (NullCommitReporter, ReportCommitToLog)
2155
 
        from bzrlib.errors import (PointlessCommit, ConflictsInTree,
2156
 
                StrictCommitFailed)
2157
 
        from bzrlib.msgeditor import edit_commit_message, \
2158
 
                make_commit_message_template
 
2292
    def run(self, message=None, file=None, verbose=False, selected_list=None,
 
2293
            unchanged=False, strict=False, local=False, fixes=None,
 
2294
            author=None, show_diff=False):
 
2295
        from bzrlib.errors import (
 
2296
            PointlessCommit,
 
2297
            ConflictsInTree,
 
2298
            StrictCommitFailed
 
2299
        )
 
2300
        from bzrlib.msgeditor import (
 
2301
            edit_commit_message_encoded,
 
2302
            make_commit_message_template_encoded
 
2303
        )
2159
2304
 
2160
2305
        # TODO: Need a blackbox test for invoking the external editor; may be
2161
2306
        # slightly problematic to run this cross-platform.
2172
2317
            # selected-file merge commit is not done yet
2173
2318
            selected_list = []
2174
2319
 
 
2320
        if fixes is None:
 
2321
            fixes = []
2175
2322
        bug_property = self._get_bug_fix_properties(fixes, tree.branch)
2176
2323
        if bug_property:
2177
2324
            properties['bugs'] = bug_property
2183
2330
            """Callback to get commit message"""
2184
2331
            my_message = message
2185
2332
            if my_message is None and not file:
2186
 
                template = make_commit_message_template(tree, selected_list)
2187
 
                my_message = edit_commit_message(template)
 
2333
                t = make_commit_message_template_encoded(tree,
 
2334
                        selected_list, diff=show_diff,
 
2335
                        output_encoding=bzrlib.user_encoding)
 
2336
                my_message = edit_commit_message_encoded(t)
2188
2337
                if my_message is None:
2189
2338
                    raise errors.BzrCommandError("please specify a commit"
2190
2339
                        " message with either --message or --file")
2198
2347
                raise errors.BzrCommandError("empty commit message specified")
2199
2348
            return my_message
2200
2349
 
2201
 
        if verbose:
2202
 
            reporter = ReportCommitToLog()
2203
 
        else:
2204
 
            reporter = NullCommitReporter()
2205
 
 
2206
2350
        try:
2207
2351
            tree.commit(message_callback=get_message,
2208
2352
                        specific_files=selected_list,
2209
2353
                        allow_pointless=unchanged, strict=strict, local=local,
2210
 
                        reporter=reporter, revprops=properties)
 
2354
                        reporter=None, verbose=verbose, revprops=properties,
 
2355
                        author=author)
2211
2356
        except PointlessCommit:
2212
2357
            # FIXME: This should really happen before the file is read in;
2213
2358
            # perhaps prepare the commit; get the message; then actually commit
2232
2377
 
2233
2378
    This command checks various invariants about the branch storage to
2234
2379
    detect data corruption or bzr bugs.
 
2380
 
 
2381
    Output fields:
 
2382
 
 
2383
        revisions: This is just the number of revisions checked.  It doesn't
 
2384
            indicate a problem.
 
2385
        versionedfiles: This is just the number of versionedfiles checked.  It
 
2386
            doesn't indicate a problem.
 
2387
        unreferenced ancestors: Texts that are ancestors of other texts, but
 
2388
            are not properly referenced by the revision ancestry.  This is a
 
2389
            subtle problem that Bazaar can work around.
 
2390
        unique file texts: This is the total number of unique file contents
 
2391
            seen in the checked revisions.  It does not indicate a problem.
 
2392
        repeated file texts: This is the total number of repeated texts seen
 
2393
            in the checked revisions.  Texts can be repeated when their file
 
2394
            entries are modified, but the file contents are not.  It does not
 
2395
            indicate a problem.
2235
2396
    """
2236
2397
 
2237
2398
    _see_also = ['reconcile']
2241
2402
    def run(self, branch=None, verbose=False):
2242
2403
        from bzrlib.check import check
2243
2404
        if branch is None:
2244
 
            tree = WorkingTree.open_containing()[0]
2245
 
            branch = tree.branch
2246
 
        else:
2247
 
            branch = Branch.open(branch)
2248
 
        check(branch, verbose)
 
2405
            branch_obj = Branch.open_containing('.')[0]
 
2406
        else:
 
2407
            branch_obj = Branch.open(branch)
 
2408
        check(branch_obj, verbose)
 
2409
        # bit hacky, check the tree parent is accurate
 
2410
        try:
 
2411
            if branch is None:
 
2412
                tree = WorkingTree.open_containing('.')[0]
 
2413
            else:
 
2414
                tree = WorkingTree.open(branch)
 
2415
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
2416
            pass
 
2417
        else:
 
2418
            # This is a primitive 'check' for tree state. Currently this is not
 
2419
            # integrated into the main check logic as yet.
 
2420
            tree.lock_read()
 
2421
            try:
 
2422
                tree_basis = tree.basis_tree()
 
2423
                tree_basis.lock_read()
 
2424
                try:
 
2425
                    repo_basis = tree.branch.repository.revision_tree(
 
2426
                        tree.last_revision())
 
2427
                    if len(list(repo_basis.iter_changes(tree_basis))):
 
2428
                        raise errors.BzrCheckError(
 
2429
                            "Mismatched basis inventory content.")
 
2430
                    tree._validate()
 
2431
                finally:
 
2432
                    tree_basis.unlock()
 
2433
            finally:
 
2434
                tree.unlock()
2249
2435
 
2250
2436
 
2251
2437
class cmd_upgrade(Command):
2261
2447
    takes_options = [
2262
2448
                    RegistryOption('format',
2263
2449
                        help='Upgrade to a specific format.  See "bzr help'
2264
 
                             ' formats" for details',
 
2450
                             ' formats" for details.',
2265
2451
                        registry=bzrdir.format_registry,
2266
2452
                        converter=bzrdir.format_registry.make_bzrdir,
2267
2453
                        value_switches=True, title='Branch format'),
2277
2463
class cmd_whoami(Command):
2278
2464
    """Show or set bzr user id.
2279
2465
    
2280
 
    examples:
2281
 
        bzr whoami --email
2282
 
        bzr whoami 'Frank Chu <fchu@example.com>'
 
2466
    :Examples:
 
2467
        Show the email of the current user::
 
2468
 
 
2469
            bzr whoami --email
 
2470
 
 
2471
        Set the current user::
 
2472
 
 
2473
            bzr whoami "Frank Chu <fchu@example.com>"
2283
2474
    """
2284
2475
    takes_options = [ Option('email',
2285
 
                             help='display email address only'),
 
2476
                             help='Display email address only.'),
2286
2477
                      Option('branch',
2287
 
                             help='set identity for the current branch instead of '
2288
 
                                  'globally'),
 
2478
                             help='Set identity for the current branch instead of '
 
2479
                                  'globally.'),
2289
2480
                    ]
2290
2481
    takes_args = ['name?']
2291
2482
    encoding_type = 'replace'
2343
2534
class cmd_selftest(Command):
2344
2535
    """Run internal test suite.
2345
2536
    
2346
 
    This creates temporary test directories in the working directory, but no
2347
 
    existing data is affected.  These directories are deleted if the tests
2348
 
    pass, or left behind to help in debugging if they fail and --keep-output
2349
 
    is specified.
2350
 
    
2351
2537
    If arguments are given, they are regular expressions that say which tests
2352
2538
    should run.  Tests matching any expression are run, and other tests are
2353
2539
    not run.
2376
2562
    modified by plugins will not be tested, and tests provided by plugins will
2377
2563
    not be run.
2378
2564
 
2379
 
    examples::
2380
 
        bzr selftest ignore
2381
 
            run only tests relating to 'ignore'
2382
 
        bzr --no-plugins selftest -v
2383
 
            disable plugins and list tests as they're run
2384
 
 
2385
 
    For each test, that needs actual disk access, bzr create their own
2386
 
    subdirectory in the temporary testing directory (testXXXX.tmp).
2387
 
    By default the name of such subdirectory is based on the name of the test.
2388
 
    If option '--numbered-dirs' is given, bzr will use sequent numbers
2389
 
    of running tests to create such subdirectories. This is default behavior
2390
 
    on Windows because of path length limitation.
 
2565
    Tests that need working space on disk use a common temporary directory, 
 
2566
    typically inside $TMPDIR or /tmp.
 
2567
 
 
2568
    :Examples:
 
2569
        Run only tests relating to 'ignore'::
 
2570
 
 
2571
            bzr selftest ignore
 
2572
 
 
2573
        Disable plugins and list tests as they're run::
 
2574
 
 
2575
            bzr --no-plugins selftest -v
2391
2576
    """
2392
2577
    # NB: this is used from the class without creating an instance, which is
2393
2578
    # why it does not have a self parameter.
2410
2595
    takes_args = ['testspecs*']
2411
2596
    takes_options = ['verbose',
2412
2597
                     Option('one',
2413
 
                             help='stop when one test fails',
 
2598
                             help='Stop when one test fails.',
2414
2599
                             short_name='1',
2415
2600
                             ),
2416
 
                     Option('keep-output',
2417
 
                            help='keep output directories when tests fail'),
2418
2601
                     Option('transport',
2419
2602
                            help='Use a different transport by default '
2420
2603
                                 'throughout the test suite.',
2421
2604
                            type=get_transport_type),
2422
 
                     Option('benchmark', help='run the bzr benchmarks.'),
 
2605
                     Option('benchmark',
 
2606
                            help='Run the benchmarks rather than selftests.'),
2423
2607
                     Option('lsprof-timed',
2424
 
                            help='generate lsprof output for benchmarked'
 
2608
                            help='Generate lsprof output for benchmarked'
2425
2609
                                 ' sections of code.'),
2426
2610
                     Option('cache-dir', type=str,
2427
 
                            help='a directory to cache intermediate'
2428
 
                                 ' benchmark steps'),
2429
 
                     Option('clean-output',
2430
 
                            help='clean temporary tests directories'
2431
 
                                 ' without running tests'),
 
2611
                            help='Cache intermediate benchmark output in this '
 
2612
                                 'directory.'),
2432
2613
                     Option('first',
2433
 
                            help='run all tests, but run specified tests first',
 
2614
                            help='Run all tests, but run specified tests first.',
2434
2615
                            short_name='f',
2435
2616
                            ),
2436
 
                     Option('numbered-dirs',
2437
 
                            help='use numbered dirs for TestCaseInTempDir'),
2438
2617
                     Option('list-only',
2439
 
                            help='list the tests instead of running them'),
 
2618
                            help='List the tests instead of running them.'),
2440
2619
                     Option('randomize', type=str, argname="SEED",
2441
 
                            help='randomize the order of tests using the given'
2442
 
                                 ' seed or "now" for the current time'),
 
2620
                            help='Randomize the order of tests using the given'
 
2621
                                 ' seed or "now" for the current time.'),
2443
2622
                     Option('exclude', type=str, argname="PATTERN",
2444
2623
                            short_name='x',
2445
 
                            help='exclude tests that match this regular'
2446
 
                                 ' expression'),
 
2624
                            help='Exclude tests that match this regular'
 
2625
                                 ' expression.'),
 
2626
                     Option('strict', help='Fail on missing dependencies or '
 
2627
                            'known failures.'),
 
2628
                     Option('load-list', type=str, argname='TESTLISTFILE',
 
2629
                            help='Load a test id list from a text file.'),
2447
2630
                     ]
2448
2631
    encoding_type = 'replace'
2449
2632
 
2450
 
    def run(self, testspecs_list=None, verbose=None, one=False,
2451
 
            keep_output=False, transport=None, benchmark=None,
2452
 
            lsprof_timed=None, cache_dir=None, clean_output=False,
2453
 
            first=False, numbered_dirs=None, list_only=False,
2454
 
            randomize=None, exclude=None):
 
2633
    def run(self, testspecs_list=None, verbose=False, one=False,
 
2634
            transport=None, benchmark=None,
 
2635
            lsprof_timed=None, cache_dir=None,
 
2636
            first=False, list_only=False,
 
2637
            randomize=None, exclude=None, strict=False,
 
2638
            load_list=None):
2455
2639
        import bzrlib.ui
2456
2640
        from bzrlib.tests import selftest
2457
2641
        import bzrlib.benchmarks as benchmarks
2458
2642
        from bzrlib.benchmarks import tree_creator
2459
2643
 
2460
 
        if clean_output:
2461
 
            from bzrlib.tests import clean_selftest_output
2462
 
            clean_selftest_output()
2463
 
            return 0
2464
 
 
2465
 
        if numbered_dirs is None and sys.platform == 'win32':
2466
 
            numbered_dirs = True
2467
 
 
2468
2644
        if cache_dir is not None:
2469
2645
            tree_creator.TreeCreator.CACHE_ROOT = osutils.abspath(cache_dir)
2470
 
        print '%10s: %s' % ('bzr', osutils.realpath(sys.argv[0]))
2471
 
        print '%10s: %s' % ('bzrlib', bzrlib.__path__[0])
 
2646
        if not list_only:
 
2647
            print 'testing: %s' % (osutils.realpath(sys.argv[0]),)
 
2648
            print '   %s (%s python%s)' % (
 
2649
                    bzrlib.__path__[0],
 
2650
                    bzrlib.version_string,
 
2651
                    '.'.join(map(str, sys.version_info)),
 
2652
                    )
2472
2653
        print
2473
2654
        if testspecs_list is not None:
2474
2655
            pattern = '|'.join(testspecs_list)
2476
2657
            pattern = ".*"
2477
2658
        if benchmark:
2478
2659
            test_suite_factory = benchmarks.test_suite
2479
 
            if verbose is None:
2480
 
                verbose = True
 
2660
            # Unless user explicitly asks for quiet, be verbose in benchmarks
 
2661
            verbose = not is_quiet()
2481
2662
            # TODO: should possibly lock the history file...
2482
2663
            benchfile = open(".perf_history", "at", buffering=1)
2483
2664
        else:
2484
2665
            test_suite_factory = None
2485
 
            if verbose is None:
2486
 
                verbose = False
2487
2666
            benchfile = None
2488
2667
        try:
2489
 
            result = selftest(verbose=verbose, 
 
2668
            result = selftest(verbose=verbose,
2490
2669
                              pattern=pattern,
2491
 
                              stop_on_failure=one, 
2492
 
                              keep_output=keep_output,
 
2670
                              stop_on_failure=one,
2493
2671
                              transport=transport,
2494
2672
                              test_suite_factory=test_suite_factory,
2495
2673
                              lsprof_timed=lsprof_timed,
2496
2674
                              bench_history=benchfile,
2497
2675
                              matching_tests_first=first,
2498
 
                              numbered_dirs=numbered_dirs,
2499
2676
                              list_only=list_only,
2500
2677
                              random_seed=randomize,
2501
 
                              exclude_pattern=exclude
 
2678
                              exclude_pattern=exclude,
 
2679
                              strict=strict,
 
2680
                              load_list=load_list,
2502
2681
                              )
2503
2682
        finally:
2504
2683
            if benchfile is not None:
2505
2684
                benchfile.close()
2506
2685
        if result:
2507
 
            info('tests passed')
 
2686
            note('tests passed')
2508
2687
        else:
2509
 
            info('tests failed')
 
2688
            note('tests failed')
2510
2689
        return int(not result)
2511
2690
 
2512
2691
 
2513
2692
class cmd_version(Command):
2514
2693
    """Show version of bzr."""
2515
2694
 
 
2695
    encoding_type = 'replace'
 
2696
 
2516
2697
    @display_command
2517
2698
    def run(self):
2518
2699
        from bzrlib.version import show_version
2519
 
        show_version()
 
2700
        show_version(to_file=self.outf)
2520
2701
 
2521
2702
 
2522
2703
class cmd_rocks(Command):
2538
2719
    
2539
2720
    @display_command
2540
2721
    def run(self, branch, other):
2541
 
        from bzrlib.revision import MultipleRevisionSources
 
2722
        from bzrlib.revision import ensure_null
2542
2723
        
2543
2724
        branch1 = Branch.open_containing(branch)[0]
2544
2725
        branch2 = Branch.open_containing(other)[0]
2545
 
 
2546
 
        last1 = branch1.last_revision()
2547
 
        last2 = branch2.last_revision()
2548
 
 
2549
 
        source = MultipleRevisionSources(branch1.repository, 
2550
 
                                         branch2.repository)
2551
 
        
2552
 
        base_rev_id = common_ancestor(last1, last2, source)
2553
 
 
2554
 
        print 'merge base is revision %s' % base_rev_id
 
2726
        branch1.lock_read()
 
2727
        try:
 
2728
            branch2.lock_read()
 
2729
            try:
 
2730
                last1 = ensure_null(branch1.last_revision())
 
2731
                last2 = ensure_null(branch2.last_revision())
 
2732
 
 
2733
                graph = branch1.repository.get_graph(branch2.repository)
 
2734
                base_rev_id = graph.find_unique_lca(last1, last2)
 
2735
 
 
2736
                print 'merge base is revision %s' % base_rev_id
 
2737
            finally:
 
2738
                branch2.unlock()
 
2739
        finally:
 
2740
            branch1.unlock()
2555
2741
 
2556
2742
 
2557
2743
class cmd_merge(Command):
2582
2768
    The results of the merge are placed into the destination working
2583
2769
    directory, where they can be reviewed (with bzr diff), tested, and then
2584
2770
    committed to record the result of the merge.
2585
 
 
2586
 
    Examples:
2587
 
 
2588
 
    To merge the latest revision from bzr.dev:
2589
 
        bzr merge ../bzr.dev
2590
 
 
2591
 
    To merge changes up to and including revision 82 from bzr.dev:
2592
 
        bzr merge -r 82 ../bzr.dev
2593
 
 
2594
 
    To merge the changes introduced by 82, without previous changes:
2595
 
        bzr merge -r 81..82 ../bzr.dev
2596
2771
    
2597
2772
    merge refuses to run if there are any uncommitted changes, unless
2598
2773
    --force is given.
 
2774
 
 
2775
    :Examples:
 
2776
        To merge the latest revision from bzr.dev::
 
2777
 
 
2778
            bzr merge ../bzr.dev
 
2779
 
 
2780
        To merge changes up to and including revision 82 from bzr.dev::
 
2781
 
 
2782
            bzr merge -r 82 ../bzr.dev
 
2783
 
 
2784
        To merge the changes introduced by 82, without previous changes::
 
2785
 
 
2786
            bzr merge -r 81..82 ../bzr.dev
2599
2787
    """
2600
2788
 
2601
 
    _see_also = ['update', 'remerge']
 
2789
    encoding_type = 'exact'
 
2790
    _see_also = ['update', 'remerge', 'status-flags']
2602
2791
    takes_args = ['branch?']
2603
 
    takes_options = ['revision', 'force', 'merge-type', 'reprocess', 'remember',
 
2792
    takes_options = [
 
2793
        'change',
 
2794
        'revision',
 
2795
        Option('force',
 
2796
               help='Merge even if the destination tree has uncommitted changes.'),
 
2797
        'merge-type',
 
2798
        'reprocess',
 
2799
        'remember',
2604
2800
        Option('show-base', help="Show base revision text in "
2605
 
               "conflicts"),
 
2801
               "conflicts."),
2606
2802
        Option('uncommitted', help='Apply uncommitted changes'
2607
 
               ' from a working copy, instead of branch changes'),
 
2803
               ' from a working copy, instead of branch changes.'),
2608
2804
        Option('pull', help='If the destination is already'
2609
2805
                ' completely merged into the source, pull from the'
2610
 
                ' source rather than merging. When this happens,'
 
2806
                ' source rather than merging.  When this happens,'
2611
2807
                ' you do not need to commit the result.'),
2612
2808
        Option('directory',
2613
 
            help='Branch to merge into, '
2614
 
                 'rather than the one containing the working directory',
2615
 
            short_name='d',
2616
 
            type=unicode,
2617
 
            ),
 
2809
               help='Branch to merge into, '
 
2810
                    'rather than the one containing the working directory.',
 
2811
               short_name='d',
 
2812
               type=unicode,
 
2813
               ),
 
2814
        Option('preview', help='Instead of merging, show a diff of the merge.')
2618
2815
    ]
2619
2816
 
2620
2817
    def run(self, branch=None, revision=None, force=False, merge_type=None,
2621
2818
            show_base=False, reprocess=False, remember=False,
2622
2819
            uncommitted=False, pull=False,
2623
2820
            directory=None,
 
2821
            preview=False,
2624
2822
            ):
2625
 
        from bzrlib.tag import _merge_tags_if_possible
2626
 
        other_revision_id = None
 
2823
        # This is actually a branch (or merge-directive) *location*.
 
2824
        location = branch
 
2825
        del branch
 
2826
 
2627
2827
        if merge_type is None:
2628
2828
            merge_type = _mod_merge.Merge3Merger
2629
2829
 
2630
2830
        if directory is None: directory = u'.'
2631
 
        # XXX: jam 20070225 WorkingTree should be locked before you extract its
2632
 
        #      inventory. Because merge is a mutating operation, it really
2633
 
        #      should be a lock_write() for the whole cmd_merge operation.
2634
 
        #      However, cmd_merge open's its own tree in _merge_helper, which
2635
 
        #      means if we lock here, the later lock_write() will always block.
2636
 
        #      Either the merge helper code should be updated to take a tree,
2637
 
        #      (What about tree.merge_from_branch?)
 
2831
        possible_transports = []
 
2832
        merger = None
 
2833
        allow_pending = True
 
2834
        verified = 'inapplicable'
2638
2835
        tree = WorkingTree.open_containing(directory)[0]
2639
2836
        change_reporter = delta._ChangeReporter(
2640
2837
            unversioned_filter=tree.is_ignored)
2641
 
 
2642
 
        if branch is not None:
2643
 
            try:
2644
 
                mergeable = bundle.read_mergeable_from_url(
2645
 
                    branch)
2646
 
            except errors.NotABundle:
2647
 
                pass # Continue on considering this url a Branch
2648
 
            else:
2649
 
                if revision is not None:
2650
 
                    raise errors.BzrCommandError(
2651
 
                        'Cannot use -r with merge directives or bundles')
2652
 
                other_revision_id = mergeable.install_revisions(
2653
 
                    tree.branch.repository)
2654
 
                revision = [RevisionSpec.from_string(
2655
 
                    'revid:' + other_revision_id)]
2656
 
 
2657
 
        if revision is None \
2658
 
                or len(revision) < 1 or revision[0].needs_branch():
2659
 
            branch = self._get_remembered_parent(tree, branch, 'Merging from')
2660
 
 
2661
 
        if revision is None or len(revision) < 1:
2662
 
            if uncommitted:
2663
 
                base = [branch, -1]
2664
 
                other = [branch, None]
2665
 
            else:
2666
 
                base = [None, None]
2667
 
                other = [branch, -1]
2668
 
            other_branch, path = Branch.open_containing(branch)
2669
 
        else:
2670
 
            if uncommitted:
2671
 
                raise errors.BzrCommandError('Cannot use --uncommitted and'
2672
 
                                             ' --revision at the same time.')
2673
 
            branch = revision[0].get_branch() or branch
2674
 
            if len(revision) == 1:
2675
 
                base = [None, None]
2676
 
                if other_revision_id is not None:
2677
 
                    other_branch = None
2678
 
                    path = ""
2679
 
                    other = None
2680
 
                else:
2681
 
                    other_branch, path = Branch.open_containing(branch)
2682
 
                    revno = revision[0].in_history(other_branch).revno
2683
 
                    other = [branch, revno]
2684
 
            else:
2685
 
                assert len(revision) == 2
2686
 
                if None in revision:
2687
 
                    raise errors.BzrCommandError(
2688
 
                        "Merge doesn't permit empty revision specifier.")
2689
 
                base_branch, path = Branch.open_containing(branch)
2690
 
                branch1 = revision[1].get_branch() or branch
2691
 
                other_branch, path1 = Branch.open_containing(branch1)
2692
 
                if revision[0].get_branch() is not None:
2693
 
                    # then path was obtained from it, and is None.
2694
 
                    path = path1
2695
 
 
2696
 
                base = [branch, revision[0].in_history(base_branch).revno]
2697
 
                other = [branch1, revision[1].in_history(other_branch).revno]
2698
 
 
2699
 
        if ((tree.branch.get_parent() is None or remember) and
2700
 
            other_branch is not None):
2701
 
            tree.branch.set_parent(other_branch.base)
2702
 
 
2703
 
        # pull tags now... it's a bit inconsistent to do it ahead of copying
2704
 
        # the history but that's done inside the merge code
2705
 
        if other_branch is not None:
2706
 
            _merge_tags_if_possible(other_branch, tree.branch)
2707
 
 
2708
 
        if path != "":
2709
 
            interesting_files = [path]
2710
 
        else:
2711
 
            interesting_files = None
2712
 
        pb = ui.ui_factory.nested_progress_bar()
 
2838
        cleanups = []
2713
2839
        try:
2714
 
            try:
2715
 
                conflict_count = _merge_helper(
2716
 
                    other, base, other_rev_id=other_revision_id,
2717
 
                    check_clean=(not force),
2718
 
                    merge_type=merge_type,
2719
 
                    reprocess=reprocess,
2720
 
                    show_base=show_base,
2721
 
                    pull=pull,
2722
 
                    this_dir=directory,
2723
 
                    pb=pb, file_list=interesting_files,
2724
 
                    change_reporter=change_reporter)
2725
 
            finally:
2726
 
                pb.finished()
2727
 
            if conflict_count != 0:
2728
 
                return 1
2729
 
            else:
 
2840
            pb = ui.ui_factory.nested_progress_bar()
 
2841
            cleanups.append(pb.finished)
 
2842
            tree.lock_write()
 
2843
            cleanups.append(tree.unlock)
 
2844
            if location is not None:
 
2845
                mergeable, other_transport = _get_mergeable_helper(location)
 
2846
                if mergeable:
 
2847
                    if uncommitted:
 
2848
                        raise errors.BzrCommandError('Cannot use --uncommitted'
 
2849
                            ' with bundles or merge directives.')
 
2850
 
 
2851
                    if revision is not None:
 
2852
                        raise errors.BzrCommandError(
 
2853
                            'Cannot use -r with merge directives or bundles')
 
2854
                    merger, verified = _mod_merge.Merger.from_mergeable(tree,
 
2855
                       mergeable, pb)
 
2856
                possible_transports.append(other_transport)
 
2857
 
 
2858
            if merger is None and uncommitted:
 
2859
                if revision is not None and len(revision) > 0:
 
2860
                    raise errors.BzrCommandError('Cannot use --uncommitted and'
 
2861
                        ' --revision at the same time.')
 
2862
                location = self._select_branch_location(tree, location)[0]
 
2863
                other_tree, other_path = WorkingTree.open_containing(location)
 
2864
                merger = _mod_merge.Merger.from_uncommitted(tree, other_tree,
 
2865
                    pb)
 
2866
                allow_pending = False
 
2867
                if other_path != '':
 
2868
                    merger.interesting_files = [other_path]
 
2869
 
 
2870
            if merger is None:
 
2871
                merger, allow_pending = self._get_merger_from_branch(tree,
 
2872
                    location, revision, remember, possible_transports, pb)
 
2873
 
 
2874
            merger.merge_type = merge_type
 
2875
            merger.reprocess = reprocess
 
2876
            merger.show_base = show_base
 
2877
            self.sanity_check_merger(merger)
 
2878
            if (merger.base_rev_id == merger.other_rev_id and
 
2879
                merger.other_rev_id != None):
 
2880
                note('Nothing to do.')
2730
2881
                return 0
2731
 
        except errors.AmbiguousBase, e:
2732
 
            m = ("sorry, bzr can't determine the right merge base yet\n"
2733
 
                 "candidates are:\n  "
2734
 
                 + "\n  ".join(e.bases)
2735
 
                 + "\n"
2736
 
                 "please specify an explicit base with -r,\n"
2737
 
                 "and (if you want) report this to the bzr developers\n")
2738
 
            log_error(m)
2739
 
 
2740
 
    # TODO: move up to common parent; this isn't merge-specific anymore. 
2741
 
    def _get_remembered_parent(self, tree, supplied_location, verb_string):
 
2882
            if pull:
 
2883
                if merger.interesting_files is not None:
 
2884
                    raise errors.BzrCommandError('Cannot pull individual files')
 
2885
                if (merger.base_rev_id == tree.last_revision()):
 
2886
                    result = tree.pull(merger.other_branch, False,
 
2887
                                       merger.other_rev_id)
 
2888
                    result.report(self.outf)
 
2889
                    return 0
 
2890
            merger.check_basis(not force)
 
2891
            if preview:
 
2892
                return self._do_preview(merger)
 
2893
            else:
 
2894
                return self._do_merge(merger, change_reporter, allow_pending,
 
2895
                                      verified)
 
2896
        finally:
 
2897
            for cleanup in reversed(cleanups):
 
2898
                cleanup()
 
2899
 
 
2900
    def _do_preview(self, merger):
 
2901
        from bzrlib.diff import show_diff_trees
 
2902
        tree_merger = merger.make_merger()
 
2903
        tt = tree_merger.make_preview_transform()
 
2904
        try:
 
2905
            result_tree = tt.get_preview_tree()
 
2906
            show_diff_trees(merger.this_tree, result_tree, self.outf,
 
2907
                            old_label='', new_label='')
 
2908
        finally:
 
2909
            tt.finalize()
 
2910
 
 
2911
    def _do_merge(self, merger, change_reporter, allow_pending, verified):
 
2912
        merger.change_reporter = change_reporter
 
2913
        conflict_count = merger.do_merge()
 
2914
        if allow_pending:
 
2915
            merger.set_pending()
 
2916
        if verified == 'failed':
 
2917
            warning('Preview patch does not match changes')
 
2918
        if conflict_count != 0:
 
2919
            return 1
 
2920
        else:
 
2921
            return 0
 
2922
 
 
2923
    def sanity_check_merger(self, merger):
 
2924
        if (merger.show_base and
 
2925
            not merger.merge_type is _mod_merge.Merge3Merger):
 
2926
            raise errors.BzrCommandError("Show-base is not supported for this"
 
2927
                                         " merge type. %s" % merger.merge_type)
 
2928
        if merger.reprocess and not merger.merge_type.supports_reprocess:
 
2929
            raise errors.BzrCommandError("Conflict reduction is not supported"
 
2930
                                         " for merge type %s." %
 
2931
                                         merger.merge_type)
 
2932
        if merger.reprocess and merger.show_base:
 
2933
            raise errors.BzrCommandError("Cannot do conflict reduction and"
 
2934
                                         " show base.")
 
2935
 
 
2936
    def _get_merger_from_branch(self, tree, location, revision, remember,
 
2937
                                possible_transports, pb):
 
2938
        """Produce a merger from a location, assuming it refers to a branch."""
 
2939
        from bzrlib.tag import _merge_tags_if_possible
 
2940
        assert revision is None or len(revision) < 3
 
2941
        # find the branch locations
 
2942
        other_loc, user_location = self._select_branch_location(tree, location,
 
2943
            revision, -1)
 
2944
        if revision is not None and len(revision) == 2:
 
2945
            base_loc, _unused = self._select_branch_location(tree,
 
2946
                location, revision, 0)
 
2947
        else:
 
2948
            base_loc = other_loc
 
2949
        # Open the branches
 
2950
        other_branch, other_path = Branch.open_containing(other_loc,
 
2951
            possible_transports)
 
2952
        if base_loc == other_loc:
 
2953
            base_branch = other_branch
 
2954
        else:
 
2955
            base_branch, base_path = Branch.open_containing(base_loc,
 
2956
                possible_transports)
 
2957
        # Find the revision ids
 
2958
        if revision is None or len(revision) < 1 or revision[-1] is None:
 
2959
            other_revision_id = _mod_revision.ensure_null(
 
2960
                other_branch.last_revision())
 
2961
        else:
 
2962
            other_revision_id = \
 
2963
                _mod_revision.ensure_null(
 
2964
                    revision[-1].in_history(other_branch).rev_id)
 
2965
        if (revision is not None and len(revision) == 2
 
2966
            and revision[0] is not None):
 
2967
            base_revision_id = \
 
2968
                _mod_revision.ensure_null(
 
2969
                    revision[0].in_history(base_branch).rev_id)
 
2970
        else:
 
2971
            base_revision_id = None
 
2972
        # Remember where we merge from
 
2973
        if ((remember or tree.branch.get_submit_branch() is None) and
 
2974
             user_location is not None):
 
2975
            tree.branch.set_submit_branch(other_branch.base)
 
2976
        _merge_tags_if_possible(other_branch, tree.branch)
 
2977
        merger = _mod_merge.Merger.from_revision_ids(pb, tree,
 
2978
            other_revision_id, base_revision_id, other_branch, base_branch)
 
2979
        if other_path != '':
 
2980
            allow_pending = False
 
2981
            merger.interesting_files = [other_path]
 
2982
        else:
 
2983
            allow_pending = True
 
2984
        return merger, allow_pending
 
2985
 
 
2986
    def _select_branch_location(self, tree, user_location, revision=None,
 
2987
                                index=None):
 
2988
        """Select a branch location, according to possible inputs.
 
2989
 
 
2990
        If provided, branches from ``revision`` are preferred.  (Both
 
2991
        ``revision`` and ``index`` must be supplied.)
 
2992
 
 
2993
        Otherwise, the ``location`` parameter is used.  If it is None, then the
 
2994
        ``submit`` or ``parent`` location is used, and a note is printed.
 
2995
 
 
2996
        :param tree: The working tree to select a branch for merging into
 
2997
        :param location: The location entered by the user
 
2998
        :param revision: The revision parameter to the command
 
2999
        :param index: The index to use for the revision parameter.  Negative
 
3000
            indices are permitted.
 
3001
        :return: (selected_location, user_location).  The default location
 
3002
            will be the user-entered location.
 
3003
        """
 
3004
        if (revision is not None and index is not None
 
3005
            and revision[index] is not None):
 
3006
            branch = revision[index].get_branch()
 
3007
            if branch is not None:
 
3008
                return branch, branch
 
3009
        if user_location is None:
 
3010
            location = self._get_remembered(tree, 'Merging from')
 
3011
        else:
 
3012
            location = user_location
 
3013
        return location, user_location
 
3014
 
 
3015
    def _get_remembered(self, tree, verb_string):
2742
3016
        """Use tree.branch's parent if none was supplied.
2743
3017
 
2744
3018
        Report if the remembered location was used.
2745
3019
        """
2746
 
        if supplied_location is not None:
2747
 
            return supplied_location
2748
 
        stored_location = tree.branch.get_parent()
 
3020
        stored_location = tree.branch.get_submit_branch()
 
3021
        if stored_location is None:
 
3022
            stored_location = tree.branch.get_parent()
2749
3023
        mutter("%s", stored_location)
2750
3024
        if stored_location is None:
2751
3025
            raise errors.BzrCommandError("No location specified or remembered")
2752
 
        display_url = urlutils.unescape_for_display(stored_location, self.outf.encoding)
2753
 
        self.outf.write("%s remembered location %s\n" % (verb_string, display_url))
 
3026
        display_url = urlutils.unescape_for_display(stored_location, 'utf-8')
 
3027
        note(u"%s remembered location %s", verb_string, display_url)
2754
3028
        return stored_location
2755
3029
 
2756
3030
 
2765
3039
    merge.  The difference is that remerge can (only) be run when there is a
2766
3040
    pending merge, and it lets you specify particular files.
2767
3041
 
2768
 
    Examples:
2769
 
 
2770
 
    $ bzr remerge --show-base
 
3042
    :Examples:
2771
3043
        Re-do the merge of all conflicted files, and show the base text in
2772
 
        conflict regions, in addition to the usual THIS and OTHER texts.
 
3044
        conflict regions, in addition to the usual THIS and OTHER texts::
 
3045
      
 
3046
            bzr remerge --show-base
2773
3047
 
2774
 
    $ bzr remerge --merge-type weave --reprocess foobar
2775
3048
        Re-do the merge of "foobar", using the weave merge algorithm, with
2776
 
        additional processing to reduce the size of conflict regions.
 
3049
        additional processing to reduce the size of conflict regions::
 
3050
      
 
3051
            bzr remerge --merge-type weave --reprocess foobar
2777
3052
    """
2778
3053
    takes_args = ['file*']
2779
 
    takes_options = ['merge-type', 'reprocess',
2780
 
                     Option('show-base', help="Show base revision text in "
2781
 
                            "conflicts")]
 
3054
    takes_options = [
 
3055
            'merge-type',
 
3056
            'reprocess',
 
3057
            Option('show-base',
 
3058
                   help="Show base revision text in conflicts."),
 
3059
            ]
2782
3060
 
2783
3061
    def run(self, file_list=None, merge_type=None, show_base=False,
2784
3062
            reprocess=False):
2793
3071
                                             " merges.  Not cherrypicking or"
2794
3072
                                             " multi-merges.")
2795
3073
            repository = tree.branch.repository
2796
 
            base_revision = common_ancestor(parents[0],
2797
 
                                            parents[1], repository)
2798
 
            base_tree = repository.revision_tree(base_revision)
2799
 
            other_tree = repository.revision_tree(parents[1])
2800
3074
            interesting_ids = None
2801
3075
            new_conflicts = []
2802
3076
            conflicts = tree.conflicts()
2827
3101
                    restore(tree.abspath(filename))
2828
3102
                except errors.NotConflicted:
2829
3103
                    pass
2830
 
            conflicts = _mod_merge.merge_inner(
2831
 
                                      tree.branch, other_tree, base_tree,
2832
 
                                      this_tree=tree,
2833
 
                                      interesting_ids=interesting_ids,
2834
 
                                      other_rev_id=parents[1],
2835
 
                                      merge_type=merge_type,
2836
 
                                      show_base=show_base,
2837
 
                                      reprocess=reprocess)
 
3104
            # Disable pending merges, because the file texts we are remerging
 
3105
            # have not had those merges performed.  If we use the wrong parents
 
3106
            # list, we imply that the working tree text has seen and rejected
 
3107
            # all the changes from the other tree, when in fact those changes
 
3108
            # have not yet been seen.
 
3109
            pb = ui.ui_factory.nested_progress_bar()
 
3110
            tree.set_parent_ids(parents[:1])
 
3111
            try:
 
3112
                merger = _mod_merge.Merger.from_revision_ids(pb,
 
3113
                                                             tree, parents[1])
 
3114
                merger.interesting_ids = interesting_ids
 
3115
                merger.merge_type = merge_type
 
3116
                merger.show_base = show_base
 
3117
                merger.reprocess = reprocess
 
3118
                conflicts = merger.do_merge()
 
3119
            finally:
 
3120
                tree.set_parent_ids(parents)
 
3121
                pb.finished()
2838
3122
        finally:
2839
3123
            tree.unlock()
2840
3124
        if conflicts > 0:
2851
3135
    last committed revision is used.
2852
3136
 
2853
3137
    To remove only some changes, without reverting to a prior version, use
2854
 
    merge instead.  For example, "merge . --r-2..-3" will remove the changes
2855
 
    introduced by -2, without affecting the changes introduced by -1.  Or
2856
 
    to remove certain changes on a hunk-by-hunk basis, see the Shelf plugin.
 
3138
    merge instead.  For example, "merge . --revision -2..-3" will remove the
 
3139
    changes introduced by -2, without affecting the changes introduced by -1.
 
3140
    Or to remove certain changes on a hunk-by-hunk basis, see the Shelf plugin.
2857
3141
    
2858
3142
    By default, any files that have been manually changed will be backed up
2859
3143
    first.  (Files changed only by merge are not backed up.)  Backup files have
2863
3147
    from the target revision.  So you can use revert to "undelete" a file by
2864
3148
    name.  If you name a directory, all the contents of that directory will be
2865
3149
    reverted.
 
3150
 
 
3151
    Any files that have been newly added since that revision will be deleted,
 
3152
    with a backup kept if appropriate.  Directories containing unknown files
 
3153
    will not be deleted.
 
3154
 
 
3155
    The working tree contains a list of pending merged revisions, which will
 
3156
    be included as parents in the next commit.  Normally, revert clears that
 
3157
    list as well as reverting the files.  If any files are specified, revert
 
3158
    leaves the pending merge list alone and reverts only the files.  Use "bzr
 
3159
    revert ." in the tree root to revert all files but keep the merge record,
 
3160
    and "bzr revert --forget-merges" to clear the pending merge list without
 
3161
    reverting any files.
2866
3162
    """
2867
3163
 
2868
3164
    _see_also = ['cat', 'export']
2869
 
    takes_options = ['revision', 'no-backup']
 
3165
    takes_options = [
 
3166
        'revision',
 
3167
        Option('no-backup', "Do not save backups of reverted files."),
 
3168
        Option('forget-merges',
 
3169
               'Remove pending merge marker, without changing any files.'),
 
3170
        ]
2870
3171
    takes_args = ['file*']
2871
3172
 
2872
 
    def run(self, revision=None, no_backup=False, file_list=None):
2873
 
        if file_list is not None:
2874
 
            if len(file_list) == 0:
2875
 
                raise errors.BzrCommandError("No files specified")
 
3173
    def run(self, revision=None, no_backup=False, file_list=None,
 
3174
            forget_merges=None):
 
3175
        tree, file_list = tree_files(file_list)
 
3176
        if forget_merges:
 
3177
            tree.set_parent_ids(tree.get_parent_ids()[:1])
2876
3178
        else:
2877
 
            file_list = []
2878
 
        
2879
 
        tree, file_list = tree_files(file_list)
 
3179
            self._revert_tree_to_revision(tree, revision, file_list, no_backup)
 
3180
 
 
3181
    @staticmethod
 
3182
    def _revert_tree_to_revision(tree, revision, file_list, no_backup):
2880
3183
        if revision is None:
2881
 
            # FIXME should be tree.last_revision
2882
3184
            rev_id = tree.last_revision()
2883
3185
        elif len(revision) != 1:
2884
3186
            raise errors.BzrCommandError('bzr revert --revision takes exactly 1 argument')
2886
3188
            rev_id = revision[0].in_history(tree.branch).rev_id
2887
3189
        pb = ui.ui_factory.nested_progress_bar()
2888
3190
        try:
2889
 
            tree.revert(file_list, 
 
3191
            tree.revert(file_list,
2890
3192
                        tree.branch.repository.revision_tree(rev_id),
2891
3193
                        not no_backup, pb, report_changes=True)
2892
3194
        finally:
2908
3210
    """
2909
3211
 
2910
3212
    _see_also = ['topics']
2911
 
    takes_options = [Option('long', 'show help on all commands')]
 
3213
    takes_options = [
 
3214
            Option('long', 'Show help on all commands.'),
 
3215
            ]
2912
3216
    takes_args = ['topic?']
2913
3217
    aliases = ['?', '--help', '-?', '-h']
2914
3218
    
2951
3255
 
2952
3256
class cmd_missing(Command):
2953
3257
    """Show unmerged/unpulled revisions between two branches.
2954
 
 
 
3258
    
2955
3259
    OTHER_BRANCH may be local or remote.
2956
3260
    """
2957
3261
 
2958
3262
    _see_also = ['merge', 'pull']
2959
3263
    takes_args = ['other_branch?']
2960
 
    takes_options = [Option('reverse', 'Reverse the order of revisions'),
2961
 
                     Option('mine-only', 
2962
 
                            'Display changes in the local branch only'),
2963
 
                     Option('theirs-only', 
2964
 
                            'Display changes in the remote branch only'), 
2965
 
                     'log-format',
2966
 
                     'show-ids',
2967
 
                     'verbose'
2968
 
                     ]
 
3264
    takes_options = [
 
3265
            Option('reverse', 'Reverse the order of revisions.'),
 
3266
            Option('mine-only',
 
3267
                   'Display changes in the local branch only.'),
 
3268
            Option('this' , 'Same as --mine-only.'),
 
3269
            Option('theirs-only',
 
3270
                   'Display changes in the remote branch only.'),
 
3271
            Option('other', 'Same as --theirs-only.'),
 
3272
            'log-format',
 
3273
            'show-ids',
 
3274
            'verbose'
 
3275
            ]
2969
3276
    encoding_type = 'replace'
2970
3277
 
2971
3278
    @display_command
2972
3279
    def run(self, other_branch=None, reverse=False, mine_only=False,
2973
3280
            theirs_only=False, log_format=None, long=False, short=False, line=False, 
2974
 
            show_ids=False, verbose=False):
2975
 
        from bzrlib.missing import find_unmerged, iter_log_data
2976
 
        from bzrlib.log import log_formatter
 
3281
            show_ids=False, verbose=False, this=False, other=False):
 
3282
        from bzrlib.missing import find_unmerged, iter_log_revisions
 
3283
 
 
3284
        if this:
 
3285
          mine_only = this
 
3286
        if other:
 
3287
          theirs_only = other
 
3288
 
2977
3289
        local_branch = Branch.open_containing(u".")[0]
2978
3290
        parent = local_branch.get_parent()
2979
3291
        if other_branch is None:
2980
3292
            other_branch = parent
2981
3293
            if other_branch is None:
2982
 
                raise errors.BzrCommandError("No peer location known or specified.")
 
3294
                raise errors.BzrCommandError("No peer location known"
 
3295
                                             " or specified.")
2983
3296
            display_url = urlutils.unescape_for_display(parent,
2984
3297
                                                        self.outf.encoding)
2985
 
            print "Using last location: " + display_url
 
3298
            self.outf.write("Using last location: " + display_url + "\n")
2986
3299
 
2987
3300
        remote_branch = Branch.open(other_branch)
2988
3301
        if remote_branch.base == local_branch.base:
2991
3304
        try:
2992
3305
            remote_branch.lock_read()
2993
3306
            try:
2994
 
                local_extra, remote_extra = find_unmerged(local_branch, remote_branch)
2995
 
                if (log_format is None):
2996
 
                    log_format = log.log_formatter_registry.get_default(
2997
 
                        local_branch)
 
3307
                local_extra, remote_extra = find_unmerged(local_branch,
 
3308
                                                          remote_branch)
 
3309
                if log_format is None:
 
3310
                    registry = log.log_formatter_registry
 
3311
                    log_format = registry.get_default(local_branch)
2998
3312
                lf = log_format(to_file=self.outf,
2999
3313
                                show_ids=show_ids,
3000
3314
                                show_timezone='original')
3002
3316
                    local_extra.reverse()
3003
3317
                    remote_extra.reverse()
3004
3318
                if local_extra and not theirs_only:
3005
 
                    print "You have %d extra revision(s):" % len(local_extra)
3006
 
                    for data in iter_log_data(local_extra, local_branch.repository,
3007
 
                                              verbose):
3008
 
                        lf.show(*data)
 
3319
                    self.outf.write("You have %d extra revision(s):\n" %
 
3320
                                    len(local_extra))
 
3321
                    for revision in iter_log_revisions(local_extra,
 
3322
                                        local_branch.repository,
 
3323
                                        verbose):
 
3324
                        lf.log_revision(revision)
3009
3325
                    printed_local = True
3010
3326
                else:
3011
3327
                    printed_local = False
3012
3328
                if remote_extra and not mine_only:
3013
3329
                    if printed_local is True:
3014
 
                        print "\n\n"
3015
 
                    print "You are missing %d revision(s):" % len(remote_extra)
3016
 
                    for data in iter_log_data(remote_extra, remote_branch.repository, 
3017
 
                                              verbose):
3018
 
                        lf.show(*data)
 
3330
                        self.outf.write("\n\n\n")
 
3331
                    self.outf.write("You are missing %d revision(s):\n" %
 
3332
                                    len(remote_extra))
 
3333
                    for revision in iter_log_revisions(remote_extra,
 
3334
                                        remote_branch.repository,
 
3335
                                        verbose):
 
3336
                        lf.log_revision(revision)
3019
3337
                if not remote_extra and not local_extra:
3020
3338
                    status_code = 0
3021
 
                    print "Branches are up to date."
 
3339
                    self.outf.write("Branches are up to date.\n")
3022
3340
                else:
3023
3341
                    status_code = 1
3024
3342
            finally:
3036
3354
        return status_code
3037
3355
 
3038
3356
 
 
3357
class cmd_pack(Command):
 
3358
    """Compress the data within a repository."""
 
3359
 
 
3360
    _see_also = ['repositories']
 
3361
    takes_args = ['branch_or_repo?']
 
3362
 
 
3363
    def run(self, branch_or_repo='.'):
 
3364
        dir = bzrdir.BzrDir.open_containing(branch_or_repo)[0]
 
3365
        try:
 
3366
            branch = dir.open_branch()
 
3367
            repository = branch.repository
 
3368
        except errors.NotBranchError:
 
3369
            repository = dir.open_repository()
 
3370
        repository.pack()
 
3371
 
 
3372
 
3039
3373
class cmd_plugins(Command):
3040
 
    """List plugins"""
3041
 
    hidden = True
 
3374
    """List the installed plugins.
 
3375
    
 
3376
    This command displays the list of installed plugins including
 
3377
    version of plugin and a short description of each.
 
3378
 
 
3379
    --verbose shows the path where each plugin is located.
 
3380
 
 
3381
    A plugin is an external component for Bazaar that extends the
 
3382
    revision control system, by adding or replacing code in Bazaar.
 
3383
    Plugins can do a variety of things, including overriding commands,
 
3384
    adding new commands, providing additional network transports and
 
3385
    customizing log output.
 
3386
 
 
3387
    See the Bazaar web site, http://bazaar-vcs.org, for further
 
3388
    information on plugins including where to find them and how to
 
3389
    install them. Instructions are also provided there on how to
 
3390
    write new plugins using the Python programming language.
 
3391
    """
 
3392
    takes_options = ['verbose']
 
3393
 
3042
3394
    @display_command
3043
 
    def run(self):
 
3395
    def run(self, verbose=False):
3044
3396
        import bzrlib.plugin
3045
3397
        from inspect import getdoc
3046
 
        for name, plugin in bzrlib.plugin.all_plugins().items():
3047
 
            if getattr(plugin, '__path__', None) is not None:
3048
 
                print plugin.__path__[0]
3049
 
            elif getattr(plugin, '__file__', None) is not None:
3050
 
                print plugin.__file__
3051
 
            else:
3052
 
                print repr(plugin)
3053
 
                
3054
 
            d = getdoc(plugin)
 
3398
        result = []
 
3399
        for name, plugin in bzrlib.plugin.plugins().items():
 
3400
            version = plugin.__version__
 
3401
            if version == 'unknown':
 
3402
                version = ''
 
3403
            name_ver = '%s %s' % (name, version)
 
3404
            d = getdoc(plugin.module)
3055
3405
            if d:
3056
 
                print '\t', d.split('\n')[0]
 
3406
                doc = d.split('\n')[0]
 
3407
            else:
 
3408
                doc = '(no description)'
 
3409
            result.append((name_ver, doc, plugin.path()))
 
3410
        for name_ver, doc, path in sorted(result):
 
3411
            print name_ver
 
3412
            print '   ', doc
 
3413
            if verbose:
 
3414
                print '   ', path
 
3415
            print
3057
3416
 
3058
3417
 
3059
3418
class cmd_testament(Command):
3060
3419
    """Show testament (signing-form) of a revision."""
3061
 
    takes_options = ['revision',
3062
 
                     Option('long', help='Produce long-format testament'), 
3063
 
                     Option('strict', help='Produce a strict-format'
3064
 
                            ' testament')]
 
3420
    takes_options = [
 
3421
            'revision',
 
3422
            Option('long', help='Produce long-format testament.'),
 
3423
            Option('strict',
 
3424
                   help='Produce a strict-format testament.')]
3065
3425
    takes_args = ['branch?']
3066
3426
    @display_command
3067
3427
    def run(self, branch=u'.', revision=None, long=False, strict=False):
3100
3460
    #       with new uncommitted lines marked
3101
3461
    aliases = ['ann', 'blame', 'praise']
3102
3462
    takes_args = ['filename']
3103
 
    takes_options = [Option('all', help='show annotations on all lines'),
3104
 
                     Option('long', help='show date in annotations'),
 
3463
    takes_options = [Option('all', help='Show annotations on all lines.'),
 
3464
                     Option('long', help='Show commit date in annotations.'),
3105
3465
                     'revision',
3106
3466
                     'show-ids',
3107
3467
                     ]
 
3468
    encoding_type = 'exact'
3108
3469
 
3109
3470
    @display_command
3110
3471
    def run(self, filename, all=False, long=False, revision=None,
3111
3472
            show_ids=False):
3112
3473
        from bzrlib.annotate import annotate_file
3113
 
        tree, relpath = WorkingTree.open_containing(filename)
3114
 
        branch = tree.branch
3115
 
        branch.lock_read()
 
3474
        wt, branch, relpath = \
 
3475
            bzrdir.BzrDir.open_containing_tree_or_branch(filename)
 
3476
        if wt is not None:
 
3477
            wt.lock_read()
 
3478
        else:
 
3479
            branch.lock_read()
3116
3480
        try:
3117
3481
            if revision is None:
3118
3482
                revision_id = branch.last_revision()
3120
3484
                raise errors.BzrCommandError('bzr annotate --revision takes exactly 1 argument')
3121
3485
            else:
3122
3486
                revision_id = revision[0].in_history(branch).rev_id
3123
 
            file_id = tree.path2id(relpath)
3124
3487
            tree = branch.repository.revision_tree(revision_id)
 
3488
            if wt is not None:
 
3489
                file_id = wt.path2id(relpath)
 
3490
            else:
 
3491
                file_id = tree.path2id(relpath)
 
3492
            if file_id is None:
 
3493
                raise errors.NotVersionedError(filename)
3125
3494
            file_version = tree.inventory[file_id].revision
3126
 
            annotate_file(branch, file_version, file_id, long, all, sys.stdout,
 
3495
            annotate_file(branch, file_version, file_id, long, all, self.outf,
3127
3496
                          show_ids=show_ids)
3128
3497
        finally:
3129
 
            branch.unlock()
 
3498
            if wt is not None:
 
3499
                wt.unlock()
 
3500
            else:
 
3501
                branch.unlock()
3130
3502
 
3131
3503
 
3132
3504
class cmd_re_sign(Command):
3138
3510
    takes_options = ['revision']
3139
3511
    
3140
3512
    def run(self, revision_id_list=None, revision=None):
3141
 
        import bzrlib.gpg as gpg
3142
3513
        if revision_id_list is not None and revision is not None:
3143
3514
            raise errors.BzrCommandError('You can only supply one of revision_id or --revision')
3144
3515
        if revision_id_list is None and revision is None:
3145
3516
            raise errors.BzrCommandError('You must supply either --revision or a revision_id')
3146
3517
        b = WorkingTree.open_containing(u'.')[0].branch
 
3518
        b.lock_write()
 
3519
        try:
 
3520
            return self._run(b, revision_id_list, revision)
 
3521
        finally:
 
3522
            b.unlock()
 
3523
 
 
3524
    def _run(self, b, revision_id_list, revision):
 
3525
        import bzrlib.gpg as gpg
3147
3526
        gpg_strategy = gpg.GPGStrategy(b.get_config())
3148
3527
        if revision_id_list is not None:
3149
 
            for revision_id in revision_id_list:
3150
 
                b.repository.sign_revision(revision_id, gpg_strategy)
 
3528
            b.repository.start_write_group()
 
3529
            try:
 
3530
                for revision_id in revision_id_list:
 
3531
                    b.repository.sign_revision(revision_id, gpg_strategy)
 
3532
            except:
 
3533
                b.repository.abort_write_group()
 
3534
                raise
 
3535
            else:
 
3536
                b.repository.commit_write_group()
3151
3537
        elif revision is not None:
3152
3538
            if len(revision) == 1:
3153
3539
                revno, rev_id = revision[0].in_history(b)
3154
 
                b.repository.sign_revision(rev_id, gpg_strategy)
 
3540
                b.repository.start_write_group()
 
3541
                try:
 
3542
                    b.repository.sign_revision(rev_id, gpg_strategy)
 
3543
                except:
 
3544
                    b.repository.abort_write_group()
 
3545
                    raise
 
3546
                else:
 
3547
                    b.repository.commit_write_group()
3155
3548
            elif len(revision) == 2:
3156
3549
                # are they both on rh- if so we can walk between them
3157
3550
                # might be nice to have a range helper for arbitrary
3162
3555
                    to_revno = b.revno()
3163
3556
                if from_revno is None or to_revno is None:
3164
3557
                    raise errors.BzrCommandError('Cannot sign a range of non-revision-history revisions')
3165
 
                for revno in range(from_revno, to_revno + 1):
3166
 
                    b.repository.sign_revision(b.get_rev_id(revno), 
3167
 
                                               gpg_strategy)
 
3558
                b.repository.start_write_group()
 
3559
                try:
 
3560
                    for revno in range(from_revno, to_revno + 1):
 
3561
                        b.repository.sign_revision(b.get_rev_id(revno),
 
3562
                                                   gpg_strategy)
 
3563
                except:
 
3564
                    b.repository.abort_write_group()
 
3565
                    raise
 
3566
                else:
 
3567
                    b.repository.commit_write_group()
3168
3568
            else:
3169
3569
                raise errors.BzrCommandError('Please supply either one revision, or a range.')
3170
3570
 
3223
3623
    --verbose will print out what is being removed.
3224
3624
    --dry-run will go through all the motions, but not actually
3225
3625
    remove anything.
3226
 
    
 
3626
 
 
3627
    If --revision is specified, uncommit revisions to leave the branch at the
 
3628
    specified revision.  For example, "bzr uncommit -r 15" will leave the
 
3629
    branch at revision 15.
 
3630
 
3227
3631
    In the future, uncommit will create a revision bundle, which can then
3228
3632
    be re-applied.
3229
3633
    """
3234
3638
    # information in shared branches as well.
3235
3639
    _see_also = ['commit']
3236
3640
    takes_options = ['verbose', 'revision',
3237
 
                    Option('dry-run', help='Don\'t actually make changes'),
 
3641
                    Option('dry-run', help='Don\'t actually make changes.'),
3238
3642
                    Option('force', help='Say yes to all questions.')]
3239
3643
    takes_args = ['location?']
3240
3644
    aliases = []
 
3645
    encoding_type = 'replace'
3241
3646
 
3242
3647
    def run(self, location=None,
3243
3648
            dry_run=False, verbose=False,
3244
3649
            revision=None, force=False):
3245
 
        from bzrlib.log import log_formatter, show_log
3246
 
        import sys
3247
 
        from bzrlib.uncommit import uncommit
3248
 
 
3249
3650
        if location is None:
3250
3651
            location = u'.'
3251
3652
        control, relpath = bzrdir.BzrDir.open_containing(location)
3256
3657
            tree = None
3257
3658
            b = control.open_branch()
3258
3659
 
 
3660
        if tree is not None:
 
3661
            tree.lock_write()
 
3662
        else:
 
3663
            b.lock_write()
 
3664
        try:
 
3665
            return self._run(b, tree, dry_run, verbose, revision, force)
 
3666
        finally:
 
3667
            if tree is not None:
 
3668
                tree.unlock()
 
3669
            else:
 
3670
                b.unlock()
 
3671
 
 
3672
    def _run(self, b, tree, dry_run, verbose, revision, force):
 
3673
        from bzrlib.log import log_formatter, show_log
 
3674
        from bzrlib.uncommit import uncommit
 
3675
 
 
3676
        last_revno, last_rev_id = b.last_revision_info()
 
3677
 
3259
3678
        rev_id = None
3260
3679
        if revision is None:
3261
 
            revno = b.revno()
 
3680
            revno = last_revno
 
3681
            rev_id = last_rev_id
3262
3682
        else:
3263
3683
            # 'bzr uncommit -r 10' actually means uncommit
3264
3684
            # so that the final tree is at revno 10.
3265
3685
            # but bzrlib.uncommit.uncommit() actually uncommits
3266
3686
            # the revisions that are supplied.
3267
3687
            # So we need to offset it by one
3268
 
            revno = revision[0].in_history(b).revno+1
 
3688
            revno = revision[0].in_history(b).revno + 1
 
3689
            if revno <= last_revno:
 
3690
                rev_id = b.get_rev_id(revno)
3269
3691
 
3270
 
        if revno <= b.revno():
3271
 
            rev_id = b.get_rev_id(revno)
3272
 
        if rev_id is None:
 
3692
        if rev_id is None or _mod_revision.is_null(rev_id):
3273
3693
            self.outf.write('No revisions to uncommit.\n')
3274
3694
            return 1
3275
3695
 
3282
3702
                 verbose=False,
3283
3703
                 direction='forward',
3284
3704
                 start_revision=revno,
3285
 
                 end_revision=b.revno())
 
3705
                 end_revision=last_revno)
3286
3706
 
3287
3707
        if dry_run:
3288
3708
            print 'Dry-run, pretending to remove the above revisions.'
3297
3717
                    return 0
3298
3718
 
3299
3719
        uncommit(b, tree=tree, dry_run=dry_run, verbose=verbose,
3300
 
                revno=revno)
 
3720
                 revno=revno)
3301
3721
 
3302
3722
 
3303
3723
class cmd_break_lock(Command):
3308
3728
 
3309
3729
    You can get information on what locks are open via the 'bzr info' command.
3310
3730
    
3311
 
    example:
 
3731
    :Examples:
3312
3732
        bzr break-lock
3313
3733
    """
3314
3734
    takes_args = ['location?']
3344
3764
 
3345
3765
    takes_options = [
3346
3766
        Option('inet',
3347
 
               help='serve on stdin/out for use from inetd or sshd'),
 
3767
               help='Serve on stdin/out for use from inetd or sshd.'),
3348
3768
        Option('port',
3349
 
               help='listen for connections on nominated port of the form '
3350
 
                    '[hostname:]portnumber. Passing 0 as the port number will '
3351
 
                    'result in a dynamically allocated port. Default port is '
 
3769
               help='Listen for connections on nominated port of the form '
 
3770
                    '[hostname:]portnumber.  Passing 0 as the port number will '
 
3771
                    'result in a dynamically allocated port.  The default port is '
3352
3772
                    '4155.',
3353
3773
               type=str),
3354
3774
        Option('directory',
3355
 
               help='serve contents of directory',
 
3775
               help='Serve contents of this directory.',
3356
3776
               type=unicode),
3357
3777
        Option('allow-writes',
3358
 
               help='By default the server is a readonly server. Supplying '
 
3778
               help='By default the server is a readonly server.  Supplying '
3359
3779
                    '--allow-writes enables write access to the contents of '
3360
 
                    'the served directory and below. '
 
3780
                    'the served directory and below.'
3361
3781
                ),
3362
3782
        ]
3363
3783
 
3364
3784
    def run(self, port=None, inet=False, directory=None, allow_writes=False):
 
3785
        from bzrlib import lockdir
3365
3786
        from bzrlib.smart import medium, server
3366
3787
        from bzrlib.transport import get_transport
3367
3788
        from bzrlib.transport.chroot import ChrootServer
3368
 
        from bzrlib.transport.remote import BZR_DEFAULT_PORT, BZR_DEFAULT_INTERFACE
3369
3789
        if directory is None:
3370
3790
            directory = os.getcwd()
3371
3791
        url = urlutils.local_path_to_url(directory)
3378
3798
            smart_server = medium.SmartServerPipeStreamMedium(
3379
3799
                sys.stdin, sys.stdout, t)
3380
3800
        else:
3381
 
            host = BZR_DEFAULT_INTERFACE
 
3801
            host = medium.BZR_DEFAULT_INTERFACE
3382
3802
            if port is None:
3383
 
                port = BZR_DEFAULT_PORT
 
3803
                port = medium.BZR_DEFAULT_PORT
3384
3804
            else:
3385
3805
                if ':' in port:
3386
3806
                    host, port = port.split(':')
3393
3813
        # be changed with care though, as we dont want to use bandwidth sending
3394
3814
        # progress over stderr to smart server clients!
3395
3815
        old_factory = ui.ui_factory
 
3816
        old_lockdir_timeout = lockdir._DEFAULT_TIMEOUT_SECONDS
3396
3817
        try:
3397
3818
            ui.ui_factory = ui.SilentUIFactory()
 
3819
            lockdir._DEFAULT_TIMEOUT_SECONDS = 0
3398
3820
            smart_server.serve()
3399
3821
        finally:
3400
3822
            ui.ui_factory = old_factory
 
3823
            lockdir._DEFAULT_TIMEOUT_SECONDS = old_lockdir_timeout
3401
3824
 
3402
3825
 
3403
3826
class cmd_join(Command):
3423
3846
 
3424
3847
    _see_also = ['split']
3425
3848
    takes_args = ['tree']
3426
 
    takes_options = [Option('reference', 'join by reference')]
 
3849
    takes_options = [
 
3850
            Option('reference', help='Join by reference.'),
 
3851
            ]
3427
3852
    hidden = True
3428
3853
 
3429
3854
    def run(self, tree, reference=False):
3453
3878
 
3454
3879
 
3455
3880
class cmd_split(Command):
3456
 
    """Split a tree into two trees.
 
3881
    """Split a subdirectory of a tree into a separate tree.
3457
3882
 
3458
 
    This command is for experimental use only.  It requires the target tree
3459
 
    to be in dirstate-with-subtree format, which cannot be converted into
3460
 
    earlier formats.
 
3883
    This command will produce a target tree in a format that supports
 
3884
    rich roots, like 'rich-root' or 'rich-root-pack'.  These formats cannot be
 
3885
    converted into earlier formats like 'dirstate-tags'.
3461
3886
 
3462
3887
    The TREE argument should be a subdirectory of a working tree.  That
3463
3888
    subdirectory will be converted into an independent tree, with its own
3464
3889
    branch.  Commits in the top-level tree will not apply to the new subtree.
3465
 
    If you want that behavior, do "bzr join --reference TREE".
3466
3890
    """
3467
3891
 
3468
 
    _see_also = ['join']
 
3892
    # join is not un-hidden yet
 
3893
    #_see_also = ['join']
3469
3894
    takes_args = ['tree']
3470
3895
 
3471
 
    hidden = True
3472
 
 
3473
3896
    def run(self, tree):
3474
3897
        containing_tree, subdir = WorkingTree.open_containing(tree)
3475
3898
        sub_id = containing_tree.path2id(subdir)
3481
3904
            raise errors.UpgradeRequired(containing_tree.branch.base)
3482
3905
 
3483
3906
 
3484
 
 
3485
3907
class cmd_merge_directive(Command):
3486
3908
    """Generate a merge directive for auto-merge tools.
3487
3909
 
3501
3923
 
3502
3924
    takes_args = ['submit_branch?', 'public_branch?']
3503
3925
 
 
3926
    hidden = True
 
3927
 
 
3928
    _see_also = ['send']
 
3929
 
3504
3930
    takes_options = [
3505
3931
        RegistryOption.from_kwargs('patch-type',
3506
 
            'The type of patch to include in the directive',
3507
 
            title='Patch type', value_switches=True, enum_switch=False,
3508
 
            bundle='Bazaar revision bundle (default)',
3509
 
            diff='Normal unified diff',
3510
 
            plain='No patch, just directive'),
3511
 
        Option('sign', help='GPG-sign the directive'), 'revision',
 
3932
            'The type of patch to include in the directive.',
 
3933
            title='Patch type',
 
3934
            value_switches=True,
 
3935
            enum_switch=False,
 
3936
            bundle='Bazaar revision bundle (default).',
 
3937
            diff='Normal unified diff.',
 
3938
            plain='No patch, just directive.'),
 
3939
        Option('sign', help='GPG-sign the directive.'), 'revision',
3512
3940
        Option('mail-to', type=str,
3513
 
            help='Instead of printing the directive, email to this address'),
 
3941
            help='Instead of printing the directive, email to this address.'),
3514
3942
        Option('message', type=str, short_name='m',
3515
 
            help='Message to use when committing this merge')
 
3943
            help='Message to use when committing this merge.')
3516
3944
        ]
3517
3945
 
 
3946
    encoding_type = 'exact'
 
3947
 
3518
3948
    def run(self, submit_branch=None, public_branch=None, patch_type='bundle',
3519
3949
            sign=False, revision=None, mail_to=None, message=None):
3520
 
        if patch_type == 'plain':
3521
 
            patch_type = None
 
3950
        from bzrlib.revision import ensure_null, NULL_REVISION
 
3951
        include_patch, include_bundle = {
 
3952
            'plain': (False, False),
 
3953
            'diff': (True, False),
 
3954
            'bundle': (True, True),
 
3955
            }[patch_type]
3522
3956
        branch = Branch.open('.')
3523
3957
        stored_submit_branch = branch.get_submit_branch()
3524
3958
        if submit_branch is None:
3536
3970
            public_branch = stored_public_branch
3537
3971
        elif stored_public_branch is None:
3538
3972
            branch.set_public_branch(public_branch)
3539
 
        if patch_type != "bundle" and public_branch is None:
 
3973
        if not include_bundle and public_branch is None:
3540
3974
            raise errors.BzrCommandError('No public branch specified or'
3541
3975
                                         ' known')
 
3976
        base_revision_id = None
3542
3977
        if revision is not None:
3543
 
            if len(revision) != 1:
 
3978
            if len(revision) > 2:
3544
3979
                raise errors.BzrCommandError('bzr merge-directive takes '
3545
 
                    'exactly one revision identifier')
3546
 
            else:
3547
 
                revision_id = revision[0].in_history(branch).rev_id
 
3980
                    'at most two one revision identifiers')
 
3981
            revision_id = revision[-1].in_history(branch).rev_id
 
3982
            if len(revision) == 2:
 
3983
                base_revision_id = revision[0].in_history(branch).rev_id
 
3984
                base_revision_id = ensure_null(base_revision_id)
3548
3985
        else:
3549
3986
            revision_id = branch.last_revision()
3550
 
        directive = merge_directive.MergeDirective.from_objects(
 
3987
        revision_id = ensure_null(revision_id)
 
3988
        if revision_id == NULL_REVISION:
 
3989
            raise errors.BzrCommandError('No revisions to bundle.')
 
3990
        directive = merge_directive.MergeDirective2.from_objects(
3551
3991
            branch.repository, revision_id, time.time(),
3552
3992
            osutils.local_time_offset(), submit_branch,
3553
 
            public_branch=public_branch, patch_type=patch_type,
3554
 
            message=message)
 
3993
            public_branch=public_branch, include_patch=include_patch,
 
3994
            include_bundle=include_bundle, message=message,
 
3995
            base_revision_id=base_revision_id)
3555
3996
        if mail_to is None:
3556
3997
            if sign:
3557
3998
                self.outf.write(directive.to_signed(branch))
3559
4000
                self.outf.writelines(directive.to_lines())
3560
4001
        else:
3561
4002
            message = directive.to_email(mail_to, branch, sign)
3562
 
            s = smtplib.SMTP()
3563
 
            server = branch.get_config().get_user_option('smtp_server')
3564
 
            if not server:
3565
 
                server = 'localhost'
3566
 
            s.connect(server)
3567
 
            s.sendmail(message['From'], message['To'], message.as_string())
 
4003
            s = SMTPConnection(branch.get_config())
 
4004
            s.send_email(message)
 
4005
 
 
4006
 
 
4007
class cmd_send(Command):
 
4008
    """Mail or create a merge-directive for submiting changes.
 
4009
 
 
4010
    A merge directive provides many things needed for requesting merges:
 
4011
 
 
4012
    * A machine-readable description of the merge to perform
 
4013
 
 
4014
    * An optional patch that is a preview of the changes requested
 
4015
 
 
4016
    * An optional bundle of revision data, so that the changes can be applied
 
4017
      directly from the merge directive, without retrieving data from a
 
4018
      branch.
 
4019
 
 
4020
    If --no-bundle is specified, then public_branch is needed (and must be
 
4021
    up-to-date), so that the receiver can perform the merge using the
 
4022
    public_branch.  The public_branch is always included if known, so that
 
4023
    people can check it later.
 
4024
 
 
4025
    The submit branch defaults to the parent, but can be overridden.  Both
 
4026
    submit branch and public branch will be remembered if supplied.
 
4027
 
 
4028
    If a public_branch is known for the submit_branch, that public submit
 
4029
    branch is used in the merge instructions.  This means that a local mirror
 
4030
    can be used as your actual submit branch, once you have set public_branch
 
4031
    for that mirror.
 
4032
 
 
4033
    Mail is sent using your preferred mail program.  This should be transparent
 
4034
    on Windows (it uses MAPI).  On Linux, it requires the xdg-email utility.
 
4035
    If the preferred client can't be found (or used), your editor will be used.
 
4036
    
 
4037
    To use a specific mail program, set the mail_client configuration option.
 
4038
    (For Thunderbird 1.5, this works around some bugs.)  Supported values for
 
4039
    specific clients are "evolution", "kmail", "mutt", and "thunderbird";
 
4040
    generic options are "default", "editor", "mapi", and "xdg-email".
 
4041
 
 
4042
    If mail is being sent, a to address is required.  This can be supplied
 
4043
    either on the commandline, by setting the submit_to configuration
 
4044
    option in the branch itself or the child_submit_to configuration option 
 
4045
    in the submit branch.
 
4046
 
 
4047
    Two formats are currently supported: "4" uses revision bundle format 4 and
 
4048
    merge directive format 2.  It is significantly faster and smaller than
 
4049
    older formats.  It is compatible with Bazaar 0.19 and later.  It is the
 
4050
    default.  "0.9" uses revision bundle format 0.9 and merge directive
 
4051
    format 1.  It is compatible with Bazaar 0.12 - 0.18.
 
4052
    """
 
4053
 
 
4054
    encoding_type = 'exact'
 
4055
 
 
4056
    _see_also = ['merge']
 
4057
 
 
4058
    takes_args = ['submit_branch?', 'public_branch?']
 
4059
 
 
4060
    takes_options = [
 
4061
        Option('no-bundle',
 
4062
               help='Do not include a bundle in the merge directive.'),
 
4063
        Option('no-patch', help='Do not include a preview patch in the merge'
 
4064
               ' directive.'),
 
4065
        Option('remember',
 
4066
               help='Remember submit and public branch.'),
 
4067
        Option('from',
 
4068
               help='Branch to generate the submission from, '
 
4069
               'rather than the one containing the working directory.',
 
4070
               short_name='f',
 
4071
               type=unicode),
 
4072
        Option('output', short_name='o', help='Write directive to this file.',
 
4073
               type=unicode),
 
4074
        Option('mail-to', help='Mail the request to this address.',
 
4075
               type=unicode),
 
4076
        'revision',
 
4077
        'message',
 
4078
        RegistryOption.from_kwargs('format',
 
4079
        'Use the specified output format.',
 
4080
        **{'4': 'Bundle format 4, Merge Directive 2 (default)',
 
4081
           '0.9': 'Bundle format 0.9, Merge Directive 1',})
 
4082
        ]
 
4083
 
 
4084
    def run(self, submit_branch=None, public_branch=None, no_bundle=False,
 
4085
            no_patch=False, revision=None, remember=False, output=None,
 
4086
            format='4', mail_to=None, message=None, **kwargs):
 
4087
        return self._run(submit_branch, revision, public_branch, remember,
 
4088
                         format, no_bundle, no_patch, output,
 
4089
                         kwargs.get('from', '.'), mail_to, message)
 
4090
 
 
4091
    def _run(self, submit_branch, revision, public_branch, remember, format,
 
4092
             no_bundle, no_patch, output, from_, mail_to, message):
 
4093
        from bzrlib.revision import NULL_REVISION
 
4094
        branch = Branch.open_containing(from_)[0]
 
4095
        if output is None:
 
4096
            outfile = StringIO()
 
4097
        elif output == '-':
 
4098
            outfile = self.outf
 
4099
        else:
 
4100
            outfile = open(output, 'wb')
 
4101
        # we may need to write data into branch's repository to calculate
 
4102
        # the data to send.
 
4103
        branch.lock_write()
 
4104
        try:
 
4105
            if output is None:
 
4106
                config = branch.get_config()
 
4107
                if mail_to is None:
 
4108
                    mail_to = config.get_user_option('submit_to')
 
4109
                mail_client = config.get_mail_client()
 
4110
            if remember and submit_branch is None:
 
4111
                raise errors.BzrCommandError(
 
4112
                    '--remember requires a branch to be specified.')
 
4113
            stored_submit_branch = branch.get_submit_branch()
 
4114
            remembered_submit_branch = False
 
4115
            if submit_branch is None:
 
4116
                submit_branch = stored_submit_branch
 
4117
                remembered_submit_branch = True
 
4118
            else:
 
4119
                if stored_submit_branch is None or remember:
 
4120
                    branch.set_submit_branch(submit_branch)
 
4121
            if submit_branch is None:
 
4122
                submit_branch = branch.get_parent()
 
4123
                remembered_submit_branch = True
 
4124
            if submit_branch is None:
 
4125
                raise errors.BzrCommandError('No submit branch known or'
 
4126
                                             ' specified')
 
4127
            if remembered_submit_branch:
 
4128
                note('Using saved location: %s', submit_branch)
 
4129
 
 
4130
            if mail_to is None:
 
4131
                submit_config = Branch.open(submit_branch).get_config()
 
4132
                mail_to = submit_config.get_user_option("child_submit_to")
 
4133
 
 
4134
            stored_public_branch = branch.get_public_branch()
 
4135
            if public_branch is None:
 
4136
                public_branch = stored_public_branch
 
4137
            elif stored_public_branch is None or remember:
 
4138
                branch.set_public_branch(public_branch)
 
4139
            if no_bundle and public_branch is None:
 
4140
                raise errors.BzrCommandError('No public branch specified or'
 
4141
                                             ' known')
 
4142
            base_revision_id = None
 
4143
            revision_id = None
 
4144
            if revision is not None:
 
4145
                if len(revision) > 2:
 
4146
                    raise errors.BzrCommandError('bzr send takes '
 
4147
                        'at most two one revision identifiers')
 
4148
                revision_id = revision[-1].in_history(branch).rev_id
 
4149
                if len(revision) == 2:
 
4150
                    base_revision_id = revision[0].in_history(branch).rev_id
 
4151
            if revision_id is None:
 
4152
                revision_id = branch.last_revision()
 
4153
            if revision_id == NULL_REVISION:
 
4154
                raise errors.BzrCommandError('No revisions to submit.')
 
4155
            if format == '4':
 
4156
                directive = merge_directive.MergeDirective2.from_objects(
 
4157
                    branch.repository, revision_id, time.time(),
 
4158
                    osutils.local_time_offset(), submit_branch,
 
4159
                    public_branch=public_branch, include_patch=not no_patch,
 
4160
                    include_bundle=not no_bundle, message=message,
 
4161
                    base_revision_id=base_revision_id)
 
4162
            elif format == '0.9':
 
4163
                if not no_bundle:
 
4164
                    if not no_patch:
 
4165
                        patch_type = 'bundle'
 
4166
                    else:
 
4167
                        raise errors.BzrCommandError('Format 0.9 does not'
 
4168
                            ' permit bundle with no patch')
 
4169
                else:
 
4170
                    if not no_patch:
 
4171
                        patch_type = 'diff'
 
4172
                    else:
 
4173
                        patch_type = None
 
4174
                directive = merge_directive.MergeDirective.from_objects(
 
4175
                    branch.repository, revision_id, time.time(),
 
4176
                    osutils.local_time_offset(), submit_branch,
 
4177
                    public_branch=public_branch, patch_type=patch_type,
 
4178
                    message=message)
 
4179
 
 
4180
            outfile.writelines(directive.to_lines())
 
4181
            if output is None:
 
4182
                subject = '[MERGE] '
 
4183
                if message is not None:
 
4184
                    subject += message
 
4185
                else:
 
4186
                    revision = branch.repository.get_revision(revision_id)
 
4187
                    subject += revision.get_summary()
 
4188
                basename = directive.get_disk_name(branch)
 
4189
                mail_client.compose_merge_request(mail_to, subject,
 
4190
                                                  outfile.getvalue(), basename)
 
4191
        finally:
 
4192
            if output != '-':
 
4193
                outfile.close()
 
4194
            branch.unlock()
 
4195
 
 
4196
 
 
4197
class cmd_bundle_revisions(cmd_send):
 
4198
 
 
4199
    """Create a merge-directive for submiting changes.
 
4200
 
 
4201
    A merge directive provides many things needed for requesting merges:
 
4202
 
 
4203
    * A machine-readable description of the merge to perform
 
4204
 
 
4205
    * An optional patch that is a preview of the changes requested
 
4206
 
 
4207
    * An optional bundle of revision data, so that the changes can be applied
 
4208
      directly from the merge directive, without retrieving data from a
 
4209
      branch.
 
4210
 
 
4211
    If --no-bundle is specified, then public_branch is needed (and must be
 
4212
    up-to-date), so that the receiver can perform the merge using the
 
4213
    public_branch.  The public_branch is always included if known, so that
 
4214
    people can check it later.
 
4215
 
 
4216
    The submit branch defaults to the parent, but can be overridden.  Both
 
4217
    submit branch and public branch will be remembered if supplied.
 
4218
 
 
4219
    If a public_branch is known for the submit_branch, that public submit
 
4220
    branch is used in the merge instructions.  This means that a local mirror
 
4221
    can be used as your actual submit branch, once you have set public_branch
 
4222
    for that mirror.
 
4223
 
 
4224
    Two formats are currently supported: "4" uses revision bundle format 4 and
 
4225
    merge directive format 2.  It is significantly faster and smaller than
 
4226
    older formats.  It is compatible with Bazaar 0.19 and later.  It is the
 
4227
    default.  "0.9" uses revision bundle format 0.9 and merge directive
 
4228
    format 1.  It is compatible with Bazaar 0.12 - 0.18.
 
4229
    """
 
4230
 
 
4231
    takes_options = [
 
4232
        Option('no-bundle',
 
4233
               help='Do not include a bundle in the merge directive.'),
 
4234
        Option('no-patch', help='Do not include a preview patch in the merge'
 
4235
               ' directive.'),
 
4236
        Option('remember',
 
4237
               help='Remember submit and public branch.'),
 
4238
        Option('from',
 
4239
               help='Branch to generate the submission from, '
 
4240
               'rather than the one containing the working directory.',
 
4241
               short_name='f',
 
4242
               type=unicode),
 
4243
        Option('output', short_name='o', help='Write directive to this file.',
 
4244
               type=unicode),
 
4245
        'revision',
 
4246
        RegistryOption.from_kwargs('format',
 
4247
        'Use the specified output format.',
 
4248
        **{'4': 'Bundle format 4, Merge Directive 2 (default)',
 
4249
           '0.9': 'Bundle format 0.9, Merge Directive 1',})
 
4250
        ]
 
4251
    aliases = ['bundle']
 
4252
 
 
4253
    _see_also = ['send', 'merge']
 
4254
 
 
4255
    hidden = True
 
4256
 
 
4257
    def run(self, submit_branch=None, public_branch=None, no_bundle=False,
 
4258
            no_patch=False, revision=None, remember=False, output=None,
 
4259
            format='4', **kwargs):
 
4260
        if output is None:
 
4261
            output = '-'
 
4262
        return self._run(submit_branch, revision, public_branch, remember,
 
4263
                         format, no_bundle, no_patch, output,
 
4264
                         kwargs.get('from', '.'), None, None)
3568
4265
 
3569
4266
 
3570
4267
class cmd_tag(Command):
3571
 
    """Create a tag naming a revision.
 
4268
    """Create, remove or modify a tag naming a revision.
3572
4269
    
3573
4270
    Tags give human-meaningful names to revisions.  Commands that take a -r
3574
4271
    (--revision) option can be given -rtag:X, where X is any previously
3593
4290
            type=unicode,
3594
4291
            ),
3595
4292
        Option('force',
3596
 
            help='Replace existing tags',
 
4293
            help='Replace existing tags.',
3597
4294
            ),
3598
4295
        'revision',
3599
4296
        ]
3630
4327
class cmd_tags(Command):
3631
4328
    """List tags.
3632
4329
 
3633
 
    This tag shows a table of tag names and the revisions they reference.
 
4330
    This command shows a table of tag names and the revisions they reference.
3634
4331
    """
3635
4332
 
3636
4333
    _see_also = ['tag']
3637
4334
    takes_options = [
3638
4335
        Option('directory',
3639
 
            help='Branch whose tags should be displayed',
 
4336
            help='Branch whose tags should be displayed.',
3640
4337
            short_name='d',
3641
4338
            type=unicode,
3642
4339
            ),
 
4340
        RegistryOption.from_kwargs('sort',
 
4341
            'Sort tags by different criteria.', title='Sorting',
 
4342
            alpha='Sort tags lexicographically (default).',
 
4343
            time='Sort tags chronologically.',
 
4344
            ),
 
4345
        'show-ids',
3643
4346
    ]
3644
4347
 
3645
4348
    @display_command
3646
4349
    def run(self,
3647
4350
            directory='.',
 
4351
            sort='alpha',
 
4352
            show_ids=False,
3648
4353
            ):
3649
4354
        branch, relpath = Branch.open_containing(directory)
3650
 
        for tag_name, target in sorted(branch.tags.get_tag_dict().items()):
3651
 
            self.outf.write('%-20s %s\n' % (tag_name, target))
3652
 
 
3653
 
 
3654
 
# command-line interpretation helper for merge-related commands
3655
 
def _merge_helper(other_revision, base_revision,
3656
 
                  check_clean=True, ignore_zero=False,
3657
 
                  this_dir=None, backup_files=False,
3658
 
                  merge_type=None,
3659
 
                  file_list=None, show_base=False, reprocess=False,
3660
 
                  pull=False,
3661
 
                  pb=DummyProgress(),
3662
 
                  change_reporter=None,
3663
 
                  other_rev_id=None):
3664
 
    """Merge changes into a tree.
3665
 
 
3666
 
    base_revision
3667
 
        list(path, revno) Base for three-way merge.  
3668
 
        If [None, None] then a base will be automatically determined.
3669
 
    other_revision
3670
 
        list(path, revno) Other revision for three-way merge.
3671
 
    this_dir
3672
 
        Directory to merge changes into; '.' by default.
3673
 
    check_clean
3674
 
        If true, this_dir must have no uncommitted changes before the
3675
 
        merge begins.
3676
 
    ignore_zero - If true, suppress the "zero conflicts" message when 
3677
 
        there are no conflicts; should be set when doing something we expect
3678
 
        to complete perfectly.
3679
 
    file_list - If supplied, merge only changes to selected files.
3680
 
 
3681
 
    All available ancestors of other_revision and base_revision are
3682
 
    automatically pulled into the branch.
3683
 
 
3684
 
    The revno may be -1 to indicate the last revision on the branch, which is
3685
 
    the typical case.
3686
 
 
3687
 
    This function is intended for use from the command line; programmatic
3688
 
    clients might prefer to call merge.merge_inner(), which has less magic 
3689
 
    behavior.
3690
 
    """
3691
 
    # Loading it late, so that we don't always have to import bzrlib.merge
3692
 
    if merge_type is None:
3693
 
        merge_type = _mod_merge.Merge3Merger
3694
 
    if this_dir is None:
3695
 
        this_dir = u'.'
3696
 
    this_tree = WorkingTree.open_containing(this_dir)[0]
3697
 
    if show_base and not merge_type is _mod_merge.Merge3Merger:
3698
 
        raise errors.BzrCommandError("Show-base is not supported for this merge"
3699
 
                                     " type. %s" % merge_type)
3700
 
    if reprocess and not merge_type.supports_reprocess:
3701
 
        raise errors.BzrCommandError("Conflict reduction is not supported for merge"
3702
 
                                     " type %s." % merge_type)
3703
 
    if reprocess and show_base:
3704
 
        raise errors.BzrCommandError("Cannot do conflict reduction and show base.")
3705
 
    # TODO: jam 20070226 We should really lock these trees earlier. However, we
3706
 
    #       only want to take out a lock_tree_write() if we don't have to pull
3707
 
    #       any ancestry. But merge might fetch ancestry in the middle, in
3708
 
    #       which case we would need a lock_write().
3709
 
    #       Because we cannot upgrade locks, for now we live with the fact that
3710
 
    #       the tree will be locked multiple times during a merge. (Maybe
3711
 
    #       read-only some of the time, but it means things will get read
3712
 
    #       multiple times.)
3713
 
    try:
3714
 
        merger = _mod_merge.Merger(this_tree.branch, this_tree=this_tree,
3715
 
                                   pb=pb, change_reporter=change_reporter)
3716
 
        merger.pp = ProgressPhase("Merge phase", 5, pb)
3717
 
        merger.pp.next_phase()
3718
 
        merger.check_basis(check_clean)
3719
 
        if other_rev_id is not None:
3720
 
            merger.set_other_revision(other_rev_id, this_tree.branch)
 
4355
        tags = branch.tags.get_tag_dict().items()
 
4356
        if sort == 'alpha':
 
4357
            tags.sort()
 
4358
        elif sort == 'time':
 
4359
            timestamps = {}
 
4360
            for tag, revid in tags:
 
4361
                try:
 
4362
                    revobj = branch.repository.get_revision(revid)
 
4363
                except errors.NoSuchRevision:
 
4364
                    timestamp = sys.maxint # place them at the end
 
4365
                else:
 
4366
                    timestamp = revobj.timestamp
 
4367
                timestamps[revid] = timestamp
 
4368
            tags.sort(key=lambda x: timestamps[x[1]])
 
4369
        if not show_ids:
 
4370
            # [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
 
4371
            revno_map = branch.get_revision_id_to_revno_map()
 
4372
            tags = [ (tag, '.'.join(map(str, revno_map.get(revid, ('?',)))))
 
4373
                        for tag, revid in tags ]
 
4374
        for tag, revspec in tags:
 
4375
            self.outf.write('%-20s %s\n' % (tag, revspec))
 
4376
 
 
4377
 
 
4378
class cmd_reconfigure(Command):
 
4379
    """Reconfigure the type of a bzr directory.
 
4380
 
 
4381
    A target configuration must be specified.
 
4382
 
 
4383
    For checkouts, the bind-to location will be auto-detected if not specified.
 
4384
    The order of preference is
 
4385
    1. For a lightweight checkout, the current bound location.
 
4386
    2. For branches that used to be checkouts, the previously-bound location.
 
4387
    3. The push location.
 
4388
    4. The parent location.
 
4389
    If none of these is available, --bind-to must be specified.
 
4390
    """
 
4391
 
 
4392
    takes_args = ['location?']
 
4393
    takes_options = [RegistryOption.from_kwargs('target_type',
 
4394
                     title='Target type',
 
4395
                     help='The type to reconfigure the directory to.',
 
4396
                     value_switches=True, enum_switch=False,
 
4397
                     branch='Reconfigure to a branch.',
 
4398
                     tree='Reconfigure to a tree.',
 
4399
                     checkout='Reconfigure to a checkout.',
 
4400
                     lightweight_checkout='Reconfigure to a lightweight'
 
4401
                     ' checkout.'),
 
4402
                     Option('bind-to', help='Branch to bind checkout to.',
 
4403
                            type=str),
 
4404
                     Option('force',
 
4405
                        help='Perform reconfiguration even if local changes'
 
4406
                        ' will be lost.')
 
4407
                     ]
 
4408
 
 
4409
    def run(self, location=None, target_type=None, bind_to=None, force=False):
 
4410
        directory = bzrdir.BzrDir.open(location)
 
4411
        if target_type is None:
 
4412
            raise errors.BzrCommandError('No target configuration specified')
 
4413
        elif target_type == 'branch':
 
4414
            reconfiguration = reconfigure.Reconfigure.to_branch(directory)
 
4415
        elif target_type == 'tree':
 
4416
            reconfiguration = reconfigure.Reconfigure.to_tree(directory)
 
4417
        elif target_type == 'checkout':
 
4418
            reconfiguration = reconfigure.Reconfigure.to_checkout(directory,
 
4419
                                                                  bind_to)
 
4420
        elif target_type == 'lightweight-checkout':
 
4421
            reconfiguration = reconfigure.Reconfigure.to_lightweight_checkout(
 
4422
                directory, bind_to)
 
4423
        reconfiguration.apply(force)
 
4424
 
 
4425
 
 
4426
class cmd_switch(Command):
 
4427
    """Set the branch of a checkout and update.
 
4428
    
 
4429
    For lightweight checkouts, this changes the branch being referenced.
 
4430
    For heavyweight checkouts, this checks that there are no local commits
 
4431
    versus the current bound branch, then it makes the local branch a mirror
 
4432
    of the new location and binds to it.
 
4433
    
 
4434
    In both cases, the working tree is updated and uncommitted changes
 
4435
    are merged. The user can commit or revert these as they desire.
 
4436
 
 
4437
    Pending merges need to be committed or reverted before using switch.
 
4438
    """
 
4439
 
 
4440
    takes_args = ['to_location']
 
4441
    takes_options = [Option('force',
 
4442
                        help='Switch even if local commits will be lost.')
 
4443
                     ]
 
4444
 
 
4445
    def run(self, to_location, force=False):
 
4446
        from bzrlib import switch
 
4447
        to_branch = Branch.open(to_location)
 
4448
        tree_location = '.'
 
4449
        control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
 
4450
        switch.switch(control_dir, to_branch, force)
 
4451
        note('Switched to branch: %s',
 
4452
            urlutils.unescape_for_display(to_branch.base, 'utf-8'))
 
4453
 
 
4454
 
 
4455
class cmd_hooks(Command):
 
4456
    """Show a branch's currently registered hooks.
 
4457
    """
 
4458
 
 
4459
    hidden = True
 
4460
    takes_args = ['path?']
 
4461
 
 
4462
    def run(self, path=None):
 
4463
        if path is None:
 
4464
            path = '.'
 
4465
        branch_hooks = Branch.open(path).hooks
 
4466
        for hook_type in branch_hooks:
 
4467
            hooks = branch_hooks[hook_type]
 
4468
            self.outf.write("%s:\n" % (hook_type,))
 
4469
            if hooks:
 
4470
                for hook in hooks:
 
4471
                    self.outf.write("  %s\n" %
 
4472
                                    (branch_hooks.get_hook_name(hook),))
 
4473
            else:
 
4474
                self.outf.write("  <no hooks installed>\n")
 
4475
 
 
4476
 
 
4477
def _create_prefix(cur_transport):
 
4478
    needed = [cur_transport]
 
4479
    # Recurse upwards until we can create a directory successfully
 
4480
    while True:
 
4481
        new_transport = cur_transport.clone('..')
 
4482
        if new_transport.base == cur_transport.base:
 
4483
            raise errors.BzrCommandError(
 
4484
                "Failed to create path prefix for %s."
 
4485
                % cur_transport.base)
 
4486
        try:
 
4487
            new_transport.mkdir('.')
 
4488
        except errors.NoSuchFile:
 
4489
            needed.append(new_transport)
 
4490
            cur_transport = new_transport
3721
4491
        else:
3722
 
            merger.set_other(other_revision)
3723
 
        merger.pp.next_phase()
3724
 
        merger.set_base(base_revision)
3725
 
        if merger.base_rev_id == merger.other_rev_id:
3726
 
            note('Nothing to do.')
3727
 
            return 0
3728
 
        if file_list is None:
3729
 
            if pull and merger.base_rev_id == merger.this_rev_id:
3730
 
                # FIXME: deduplicate with pull
3731
 
                result = merger.this_tree.pull(merger.this_branch,
3732
 
                        False, merger.other_rev_id)
3733
 
                if result.old_revid == result.new_revid:
3734
 
                    note('No revisions to pull.')
3735
 
                else:
3736
 
                    note('Now on revision %d.' % result.new_revno)
3737
 
                return 0
3738
 
        merger.backup_files = backup_files
3739
 
        merger.merge_type = merge_type 
3740
 
        merger.set_interesting_files(file_list)
3741
 
        merger.show_base = show_base 
3742
 
        merger.reprocess = reprocess
3743
 
        conflicts = merger.do_merge()
3744
 
        if file_list is None:
3745
 
            merger.set_pending()
3746
 
    finally:
3747
 
        pb.clear()
3748
 
    return conflicts
3749
 
 
3750
 
 
3751
 
# Compatibility
3752
 
merge = _merge_helper
 
4492
            break
 
4493
    # Now we only need to create child directories
 
4494
    while needed:
 
4495
        cur_transport = needed.pop()
 
4496
        cur_transport.ensure_base()
 
4497
 
 
4498
 
 
4499
def _get_mergeable_helper(location):
 
4500
    """Get a merge directive or bundle if 'location' points to one.
 
4501
 
 
4502
    Try try to identify a bundle and returns its mergeable form. If it's not,
 
4503
    we return the tried transport anyway so that it can reused to access the
 
4504
    branch
 
4505
 
 
4506
    :param location: can point to a bundle or a branch.
 
4507
 
 
4508
    :return: mergeable, transport
 
4509
    """
 
4510
    mergeable = None
 
4511
    url = urlutils.normalize_url(location)
 
4512
    url, filename = urlutils.split(url, exclude_trailing_slash=False)
 
4513
    location_transport = transport.get_transport(url)
 
4514
    if filename:
 
4515
        try:
 
4516
            # There may be redirections but we ignore the intermediate
 
4517
            # and final transports used
 
4518
            read = bundle.read_mergeable_from_transport
 
4519
            mergeable, t = read(location_transport, filename)
 
4520
        except errors.NotABundle:
 
4521
            # Continue on considering this url a Branch but adjust the
 
4522
            # location_transport
 
4523
            location_transport = location_transport.clone(filename)
 
4524
    return mergeable, location_transport
3753
4525
 
3754
4526
 
3755
4527
# these get imported and then picked up by the scan for cmd_*
3759
4531
# details were needed.
3760
4532
from bzrlib.cmd_version_info import cmd_version_info
3761
4533
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore
3762
 
from bzrlib.bundle.commands import cmd_bundle_revisions
 
4534
from bzrlib.bundle.commands import (
 
4535
    cmd_bundle_info,
 
4536
    )
3763
4537
from bzrlib.sign_my_commits import cmd_sign_my_commits
3764
 
from bzrlib.weave_commands import cmd_weave_list, cmd_weave_join, \
 
4538
from bzrlib.weave_commands import cmd_versionedfile_list, cmd_weave_join, \
3765
4539
        cmd_weave_plan_merge, cmd_weave_merge_text