~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/builtins.py

  • Committer: John Arbash Meinel
  • Author(s): Mark Hammond
  • Date: 2008-09-09 17:02:21 UTC
  • mto: This revision was merged to the branch mainline in revision 3697.
  • Revision ID: john@arbash-meinel.com-20080909170221-svim3jw2mrz0amp3
An updated transparent icon for bzr.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2004, 2005, 2006, 2007 Canonical Ltd
 
1
# Copyright (C) 2004, 2005, 2006, 2007, 2008 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
87
87
    if file_list is None or len(file_list) == 0:
88
88
        return WorkingTree.open_containing(default_branch)[0], file_list
89
89
    tree = WorkingTree.open_containing(osutils.realpath(file_list[0]))[0]
 
90
    return tree, safe_relpath_files(tree, file_list)
 
91
 
 
92
 
 
93
def safe_relpath_files(tree, file_list):
 
94
    """Convert file_list into a list of relpaths in tree.
 
95
 
 
96
    :param tree: A tree to operate on.
 
97
    :param file_list: A list of user provided paths or None.
 
98
    :return: A list of relative paths.
 
99
    :raises errors.PathNotChild: When a provided path is in a different tree
 
100
        than tree.
 
101
    """
 
102
    if file_list is None:
 
103
        return None
90
104
    new_list = []
91
105
    for filename in file_list:
92
106
        try:
93
107
            new_list.append(tree.relpath(osutils.dereference_path(filename)))
94
108
        except errors.PathNotChild:
95
109
            raise errors.FileInWrongBranch(tree.branch, filename)
96
 
    return tree, new_list
97
 
 
98
 
 
99
 
@symbol_versioning.deprecated_function(symbol_versioning.zero_fifteen)
100
 
def get_format_type(typestring):
101
 
    """Parse and return a format specifier."""
102
 
    # Have to use BzrDirMetaFormat1 directly, so that
103
 
    # RepositoryFormat.set_default_format works
104
 
    if typestring == "default":
105
 
        return bzrdir.BzrDirMetaFormat1()
106
 
    try:
107
 
        return bzrdir.format_registry.make_bzrdir(typestring)
108
 
    except KeyError:
109
 
        msg = 'Unknown bzr format "%s". See "bzr help formats".' % typestring
110
 
        raise errors.BzrCommandError(msg)
 
110
    return new_list
111
111
 
112
112
 
113
113
# TODO: Make sure no commands unconditionally use the working directory as a
148
148
    
149
149
    Note that --short or -S gives status flags for each item, similar
150
150
    to Subversion's status command. To get output similar to svn -q,
151
 
    use bzr -SV.
 
151
    use bzr status -SV.
152
152
 
153
153
    If no arguments are specified, the status of the entire working
154
154
    directory is shown.  Otherwise, only the status of the specified
166
166
                     Option('short', help='Use short status indicators.',
167
167
                            short_name='S'),
168
168
                     Option('versioned', help='Only show versioned files.',
169
 
                            short_name='V')
 
169
                            short_name='V'),
 
170
                     Option('no-pending', help='Don\'t show pending merges.',
 
171
                           ),
170
172
                     ]
171
173
    aliases = ['st', 'stat']
172
174
 
175
177
    
176
178
    @display_command
177
179
    def run(self, show_ids=False, file_list=None, revision=None, short=False,
178
 
            versioned=False):
 
180
            versioned=False, no_pending=False):
179
181
        from bzrlib.status import show_tree_status
180
182
 
181
183
        if revision and len(revision) > 2:
182
184
            raise errors.BzrCommandError('bzr status --revision takes exactly'
183
185
                                         ' one or two revision specifiers')
184
186
 
185
 
        tree, file_list = tree_files(file_list)
186
 
            
 
187
        tree, relfile_list = tree_files(file_list)
 
188
        # Avoid asking for specific files when that is not needed.
 
189
        if relfile_list == ['']:
 
190
            relfile_list = None
 
191
            # Don't disable pending merges for full trees other than '.'.
 
192
            if file_list == ['.']:
 
193
                no_pending = True
 
194
        # A specific path within a tree was given.
 
195
        elif relfile_list is not None:
 
196
            no_pending = True
187
197
        show_tree_status(tree, show_ids=show_ids,
188
 
                         specific_files=file_list, revision=revision,
189
 
                         to_file=self.outf, short=short, versioned=versioned)
 
198
                         specific_files=relfile_list, revision=revision,
 
199
                         to_file=self.outf, short=short, versioned=versioned,
 
200
                         show_pending=(not no_pending))
190
201
 
191
202
 
192
203
class cmd_cat_revision(Command):
215
226
        # TODO: jam 20060112 should cat-revision always output utf-8?
216
227
        if revision_id is not None:
217
228
            revision_id = osutils.safe_revision_id(revision_id, warn=False)
218
 
            self.outf.write(b.repository.get_revision_xml(revision_id).decode('utf-8'))
 
229
            try:
 
230
                self.outf.write(b.repository.get_revision_xml(revision_id).decode('utf-8'))
 
231
            except errors.NoSuchRevision:
 
232
                msg = "The repository %s contains no revision %s." % (b.repository.base,
 
233
                    revision_id)
 
234
                raise errors.BzrCommandError(msg)
219
235
        elif revision is not None:
220
236
            for rev in revision:
221
237
                if rev is None:
222
238
                    raise errors.BzrCommandError('You cannot specify a NULL'
223
239
                                                 ' revision.')
224
 
                revno, rev_id = rev.in_history(b)
 
240
                rev_id = rev.as_revision_id(b)
225
241
                self.outf.write(b.repository.get_revision_xml(rev_id).decode('utf-8'))
226
242
    
227
243
 
295
311
            revs.append(RevisionSpec.from_string('-1'))
296
312
 
297
313
        for rev in revs:
298
 
            revinfo = rev.in_history(b)
299
 
            if revinfo.revno is None:
 
314
            revision_id = rev.as_revision_id(b)
 
315
            try:
 
316
                revno = '%4d' % (b.revision_id_to_revno(revision_id))
 
317
            except errors.NoSuchRevision:
300
318
                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)
303
 
            else:
304
 
                print '%4d %s' % (revinfo.revno, revinfo.rev_id)
 
319
                revno = '.'.join(str(i) for i in dotted_map[revision_id])
 
320
            print '%s %s' % (revno, revision_id)
305
321
 
306
322
    
307
323
class cmd_add(Command):
466
482
                    raise errors.BzrCommandError(
467
483
                        'bzr inventory --revision takes exactly one revision'
468
484
                        ' identifier')
469
 
                revision_id = revision[0].in_history(work_tree.branch).rev_id
 
485
                revision_id = revision[0].as_revision_id(work_tree.branch)
470
486
                tree = work_tree.branch.repository.revision_tree(revision_id)
471
487
 
472
488
                extra_trees = [work_tree]
534
550
        if len(names_list) < 2:
535
551
            raise errors.BzrCommandError("missing file argument")
536
552
        tree, rel_names = tree_files(names_list)
537
 
        
538
 
        if os.path.isdir(names_list[-1]):
 
553
        tree.lock_write()
 
554
        try:
 
555
            self._run(tree, names_list, rel_names, after)
 
556
        finally:
 
557
            tree.unlock()
 
558
 
 
559
    def _run(self, tree, names_list, rel_names, after):
 
560
        into_existing = osutils.isdir(names_list[-1])
 
561
        if into_existing and len(names_list) == 2:
 
562
            # special cases:
 
563
            # a. case-insensitive filesystem and change case of dir
 
564
            # b. move directory after the fact (if the source used to be
 
565
            #    a directory, but now doesn't exist in the working tree
 
566
            #    and the target is an existing directory, just rename it)
 
567
            if (not tree.case_sensitive
 
568
                and rel_names[0].lower() == rel_names[1].lower()):
 
569
                into_existing = False
 
570
            else:
 
571
                inv = tree.inventory
 
572
                from_id = tree.path2id(rel_names[0])
 
573
                if (not osutils.lexists(names_list[0]) and
 
574
                    from_id and inv.get_file_kind(from_id) == "directory"):
 
575
                    into_existing = False
 
576
        # move/rename
 
577
        if into_existing:
539
578
            # move into existing directory
540
579
            for pair in tree.move(rel_names[:-1], rel_names[-1], after=after):
541
580
                self.outf.write("%s => %s\n" % pair)
546
585
                                             ' directory')
547
586
            tree.rename_one(rel_names[0], rel_names[1], after=after)
548
587
            self.outf.write("%s => %s\n" % (rel_names[0], rel_names[1]))
549
 
            
550
 
    
 
588
 
 
589
 
551
590
class cmd_pull(Command):
552
591
    """Turn this branch into a mirror of another branch.
553
592
 
566
605
    that, you can omit the location to use the default.  To change the
567
606
    default, use --remember. The value will only be saved if the remote
568
607
    location can be accessed.
 
608
 
 
609
    Note: The location can be specified either in the form of a branch,
 
610
    or in the form of a path to a file containing a merge directive generated
 
611
    with bzr send.
569
612
    """
570
613
 
571
614
    _see_also = ['push', 'update', 'status-flags']
599
642
 
600
643
        possible_transports = []
601
644
        if location is not None:
602
 
            mergeable, location_transport = _get_mergeable_helper(location)
603
 
            possible_transports.append(location_transport)
 
645
            try:
 
646
                mergeable = bundle.read_mergeable_from_url(location,
 
647
                    possible_transports=possible_transports)
 
648
            except errors.NotABundle:
 
649
                mergeable = None
604
650
 
605
651
        stored_loc = branch_to.get_parent()
606
652
        if location is None:
610
656
            else:
611
657
                display_url = urlutils.unescape_for_display(stored_loc,
612
658
                        self.outf.encoding)
613
 
                self.outf.write("Using saved location: %s\n" % display_url)
 
659
                if not is_quiet():
 
660
                    self.outf.write("Using saved parent location: %s\n" % display_url)
614
661
                location = stored_loc
615
 
                location_transport = transport.get_transport(
616
 
                    location, possible_transports=possible_transports)
617
662
 
618
663
        if mergeable is not None:
619
664
            if revision is not None:
624
669
                mergeable.get_merge_request(branch_to.repository)
625
670
            branch_from = branch_to
626
671
        else:
627
 
            branch_from = Branch.open_from_transport(location_transport)
 
672
            branch_from = Branch.open(location,
 
673
                possible_transports=possible_transports)
628
674
 
629
675
            if branch_to.get_parent() is None or remember:
630
676
                branch_to.set_parent(branch_from.base)
631
677
 
632
678
        if revision is not None:
633
679
            if len(revision) == 1:
634
 
                revision_id = revision[0].in_history(branch_from).rev_id
 
680
                revision_id = revision[0].as_revision_id(branch_from)
635
681
            else:
636
682
                raise errors.BzrCommandError(
637
683
                    'bzr pull --revision takes one value.')
638
684
 
639
 
        if verbose:
640
 
            old_rh = branch_to.revision_history()
641
 
        if tree_to is not None:
642
 
            change_reporter = delta._ChangeReporter(
643
 
                unversioned_filter=tree_to.is_ignored)
644
 
            result = tree_to.pull(branch_from, overwrite, revision_id,
645
 
                                  change_reporter,
646
 
                                  possible_transports=possible_transports)
647
 
        else:
648
 
            result = branch_to.pull(branch_from, overwrite, revision_id)
 
685
        branch_to.lock_write()
 
686
        try:
 
687
            if tree_to is not None:
 
688
                change_reporter = delta._ChangeReporter(
 
689
                    unversioned_filter=tree_to.is_ignored)
 
690
                result = tree_to.pull(branch_from, overwrite, revision_id,
 
691
                                      change_reporter,
 
692
                                      possible_transports=possible_transports)
 
693
            else:
 
694
                result = branch_to.pull(branch_from, overwrite, revision_id)
649
695
 
650
 
        result.report(self.outf)
651
 
        if verbose:
652
 
            new_rh = branch_to.revision_history()
653
 
            log.show_changed_revisions(branch_to, old_rh, new_rh,
654
 
                                       to_file=self.outf)
 
696
            result.report(self.outf)
 
697
            if verbose and result.old_revid != result.new_revid:
 
698
                old_rh = list(
 
699
                    branch_to.repository.iter_reverse_revision_history(
 
700
                    result.old_revid))
 
701
                old_rh.reverse()
 
702
                new_rh = branch_to.revision_history()
 
703
                log.show_changed_revisions(branch_to, old_rh, new_rh,
 
704
                                           to_file=self.outf)
 
705
        finally:
 
706
            branch_to.unlock()
655
707
 
656
708
 
657
709
class cmd_push(Command):
681
733
    """
682
734
 
683
735
    _see_also = ['pull', 'update', 'working-trees']
684
 
    takes_options = ['remember', 'overwrite', 'verbose',
 
736
    takes_options = ['remember', 'overwrite', 'verbose', 'revision',
685
737
        Option('create-prefix',
686
738
               help='Create the path leading up to the branch '
687
739
                    'if it does not already exist.'),
696
748
                    ' directory exists, but does not already'
697
749
                    ' have a control directory.  This flag will'
698
750
                    ' allow push to proceed.'),
 
751
        Option('stacked',
 
752
            help='Create a stacked branch that references the public location '
 
753
                'of the parent branch.'),
 
754
        Option('stacked-on',
 
755
            help='Create a stacked branch that refers to another branch '
 
756
                'for the commit history. Only the work not present in the '
 
757
                'referenced branch is included in the branch created.',
 
758
            type=unicode),
699
759
        ]
700
760
    takes_args = ['location?']
701
761
    encoding_type = 'replace'
702
762
 
703
763
    def run(self, location=None, remember=False, overwrite=False,
704
 
            create_prefix=False, verbose=False,
705
 
            use_existing_dir=False,
706
 
            directory=None):
707
 
        # FIXME: Way too big!  Put this into a function called from the
708
 
        # command.
 
764
        create_prefix=False, verbose=False, revision=None,
 
765
        use_existing_dir=False, directory=None, stacked_on=None,
 
766
        stacked=False):
 
767
        from bzrlib.push import _show_push_branch
 
768
 
 
769
        # Get the source branch and revision_id
709
770
        if directory is None:
710
771
            directory = '.'
711
772
        br_from = Branch.open_containing(directory)[0]
712
 
        stored_loc = br_from.get_push_location()
 
773
        if revision is not None:
 
774
            if len(revision) == 1:
 
775
                revision_id = revision[0].in_history(br_from).rev_id
 
776
            else:
 
777
                raise errors.BzrCommandError(
 
778
                    'bzr push --revision takes one value.')
 
779
        else:
 
780
            revision_id = br_from.last_revision()
 
781
 
 
782
        # Get the stacked_on branch, if any
 
783
        if stacked_on is not None:
 
784
            stacked_on = urlutils.normalize_url(stacked_on)
 
785
        elif stacked:
 
786
            parent_url = br_from.get_parent()
 
787
            if parent_url:
 
788
                parent = Branch.open(parent_url)
 
789
                stacked_on = parent.get_public_branch()
 
790
                if not stacked_on:
 
791
                    # I considered excluding non-http url's here, thus forcing
 
792
                    # 'public' branches only, but that only works for some
 
793
                    # users, so it's best to just depend on the user spotting an
 
794
                    # error by the feedback given to them. RBC 20080227.
 
795
                    stacked_on = parent_url
 
796
            if not stacked_on:
 
797
                raise errors.BzrCommandError(
 
798
                    "Could not determine branch to refer to.")
 
799
 
 
800
        # Get the destination location
713
801
        if location is None:
 
802
            stored_loc = br_from.get_push_location()
714
803
            if stored_loc is None:
715
 
                raise errors.BzrCommandError("No push location known or specified.")
 
804
                raise errors.BzrCommandError(
 
805
                    "No push location known or specified.")
716
806
            else:
717
807
                display_url = urlutils.unescape_for_display(stored_loc,
718
808
                        self.outf.encoding)
719
 
                self.outf.write("Using saved location: %s\n" % display_url)
 
809
                self.outf.write("Using saved push location: %s\n" % display_url)
720
810
                location = stored_loc
721
811
 
722
 
        to_transport = transport.get_transport(location)
723
 
 
724
 
        br_to = repository_to = dir_to = None
725
 
        try:
726
 
            dir_to = bzrdir.BzrDir.open_from_transport(to_transport)
727
 
        except errors.NotBranchError:
728
 
            pass # Didn't find anything
729
 
        else:
730
 
            # If we can open a branch, use its direct repository, otherwise see
731
 
            # if there is a repository without a branch.
732
 
            try:
733
 
                br_to = dir_to.open_branch()
734
 
            except errors.NotBranchError:
735
 
                # Didn't find a branch, can we find a repository?
736
 
                try:
737
 
                    repository_to = dir_to.find_repository()
738
 
                except errors.NoRepositoryPresent:
739
 
                    pass
740
 
            else:
741
 
                # Found a branch, so we must have found a repository
742
 
                repository_to = br_to.repository
743
 
        push_result = None
744
 
        if verbose:
745
 
            old_rh = []
746
 
        if dir_to is None:
747
 
            # The destination doesn't exist; create it.
748
 
            # XXX: Refactor the create_prefix/no_create_prefix code into a
749
 
            #      common helper function
750
 
            try:
751
 
                to_transport.mkdir('.')
752
 
            except errors.FileExists:
753
 
                if not use_existing_dir:
754
 
                    raise errors.BzrCommandError("Target directory %s"
755
 
                         " already exists, but does not have a valid .bzr"
756
 
                         " directory. Supply --use-existing-dir to push"
757
 
                         " there anyway." % location)
758
 
            except errors.NoSuchFile:
759
 
                if not create_prefix:
760
 
                    raise errors.BzrCommandError("Parent directory of %s"
761
 
                        " does not exist."
762
 
                        "\nYou may supply --create-prefix to create all"
763
 
                        " leading parent directories."
764
 
                        % location)
765
 
                _create_prefix(to_transport)
766
 
 
767
 
            # Now the target directory exists, but doesn't have a .bzr
768
 
            # directory. So we need to create it, along with any work to create
769
 
            # all of the dependent branches, etc.
770
 
            dir_to = br_from.bzrdir.clone_on_transport(to_transport,
771
 
                revision_id=br_from.last_revision())
772
 
            br_to = dir_to.open_branch()
773
 
            # TODO: Some more useful message about what was copied
774
 
            note('Created new branch.')
775
 
            # We successfully created the target, remember it
776
 
            if br_from.get_push_location() is None or remember:
777
 
                br_from.set_push_location(br_to.base)
778
 
        elif repository_to is None:
779
 
            # we have a bzrdir but no branch or repository
780
 
            # XXX: Figure out what to do other than complain.
781
 
            raise errors.BzrCommandError("At %s you have a valid .bzr control"
782
 
                " directory, but not a branch or repository. This is an"
783
 
                " unsupported configuration. Please move the target directory"
784
 
                " out of the way and try again."
785
 
                % location)
786
 
        elif br_to is None:
787
 
            # We have a repository but no branch, copy the revisions, and then
788
 
            # create a branch.
789
 
            last_revision_id = br_from.last_revision()
790
 
            repository_to.fetch(br_from.repository,
791
 
                                revision_id=last_revision_id)
792
 
            br_to = br_from.clone(dir_to, revision_id=last_revision_id)
793
 
            note('Created new branch.')
794
 
            if br_from.get_push_location() is None or remember:
795
 
                br_from.set_push_location(br_to.base)
796
 
        else: # We have a valid to branch
797
 
            # We were able to connect to the remote location, so remember it
798
 
            # we don't need to successfully push because of possible divergence.
799
 
            if br_from.get_push_location() is None or remember:
800
 
                br_from.set_push_location(br_to.base)
801
 
            if verbose:
802
 
                old_rh = br_to.revision_history()
803
 
            try:
804
 
                try:
805
 
                    tree_to = dir_to.open_workingtree()
806
 
                except errors.NotLocalUrl:
807
 
                    warning("This transport does not update the working " 
808
 
                            "tree of: %s. See 'bzr help working-trees' for "
809
 
                            "more information." % br_to.base)
810
 
                    push_result = br_from.push(br_to, overwrite)
811
 
                except errors.NoWorkingTree:
812
 
                    push_result = br_from.push(br_to, overwrite)
813
 
                else:
814
 
                    tree_to.lock_write()
815
 
                    try:
816
 
                        push_result = br_from.push(tree_to.branch, overwrite)
817
 
                        tree_to.update()
818
 
                    finally:
819
 
                        tree_to.unlock()
820
 
            except errors.DivergedBranches:
821
 
                raise errors.BzrCommandError('These branches have diverged.'
822
 
                                        '  Try using "merge" and then "push".')
823
 
        if push_result is not None:
824
 
            push_result.report(self.outf)
825
 
        elif verbose:
826
 
            new_rh = br_to.revision_history()
827
 
            if old_rh != new_rh:
828
 
                # Something changed
829
 
                from bzrlib.log import show_changed_revisions
830
 
                show_changed_revisions(br_to, old_rh, new_rh,
831
 
                                       to_file=self.outf)
832
 
        else:
833
 
            # we probably did a clone rather than a push, so a message was
834
 
            # emitted above
835
 
            pass
 
812
        _show_push_branch(br_from, revision_id, location, self.outf,
 
813
            verbose=verbose, overwrite=overwrite, remember=remember,
 
814
            stacked_on=stacked_on, create_prefix=create_prefix,
 
815
            use_existing_dir=use_existing_dir)
836
816
 
837
817
 
838
818
class cmd_branch(Command):
851
831
 
852
832
    _see_also = ['checkout']
853
833
    takes_args = ['from_location', 'to_location?']
854
 
    takes_options = ['revision']
 
834
    takes_options = ['revision', Option('hardlink',
 
835
        help='Hard-link working tree files where possible.'),
 
836
        Option('stacked',
 
837
            help='Create a stacked branch referring to the source branch. '
 
838
                'The new branch will depend on the availability of the source '
 
839
                'branch for all operations.'),
 
840
        ]
855
841
    aliases = ['get', 'clone']
856
842
 
857
 
    def run(self, from_location, to_location=None, revision=None):
 
843
    def run(self, from_location, to_location=None, revision=None,
 
844
            hardlink=False, stacked=False):
858
845
        from bzrlib.tag import _merge_tags_if_possible
859
846
        if revision is None:
860
847
            revision = [None]
862
849
            raise errors.BzrCommandError(
863
850
                'bzr branch --revision takes exactly 1 revision value')
864
851
 
865
 
        br_from = Branch.open(from_location)
 
852
        accelerator_tree, br_from = bzrdir.BzrDir.open_tree_or_branch(
 
853
            from_location)
866
854
        br_from.lock_read()
867
855
        try:
868
856
            if len(revision) == 1 and revision[0] is not None:
869
 
                revision_id = revision[0].in_history(br_from)[1]
 
857
                revision_id = revision[0].as_revision_id(br_from)
870
858
            else:
871
859
                # FIXME - wt.last_revision, fallback to branch, fall back to
872
860
                # None or perhaps NULL_REVISION to mean copy nothing
874
862
                revision_id = br_from.last_revision()
875
863
            if to_location is None:
876
864
                to_location = urlutils.derive_to_location(from_location)
877
 
                name = None
878
 
            else:
879
 
                name = os.path.basename(to_location) + '\n'
880
 
 
881
865
            to_transport = transport.get_transport(to_location)
882
866
            try:
883
867
                to_transport.mkdir('.')
890
874
            try:
891
875
                # preserve whatever source format we have.
892
876
                dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
893
 
                                            possible_transports=[to_transport])
 
877
                                            possible_transports=[to_transport],
 
878
                                            accelerator_tree=accelerator_tree,
 
879
                                            hardlink=hardlink, stacked=stacked)
894
880
                branch = dir.open_branch()
895
881
            except errors.NoSuchRevision:
896
882
                to_transport.delete_tree('.')
897
 
                msg = "The branch %s has no revision %s." % (from_location, revision[0])
 
883
                msg = "The branch %s has no revision %s." % (from_location,
 
884
                    revision[0])
898
885
                raise errors.BzrCommandError(msg)
899
 
            if name:
900
 
                branch.control_files.put_utf8('branch-name', name)
901
886
            _merge_tags_if_possible(br_from, branch)
902
 
            note('Branched %d revision(s).' % branch.revno())
 
887
            # If the source branch is stacked, the new branch may
 
888
            # be stacked whether we asked for that explicitly or not.
 
889
            # We therefore need a try/except here and not just 'if stacked:'
 
890
            try:
 
891
                note('Created new stacked branch referring to %s.' %
 
892
                    branch.get_stacked_on_url())
 
893
            except (errors.NotStacked, errors.UnstackableBranchFormat,
 
894
                errors.UnstackableRepositoryFormat), e:
 
895
                note('Branched %d revision(s).' % branch.revno())
903
896
        finally:
904
897
            br_from.unlock()
905
898
 
935
928
                                 "common operations like diff and status without "
936
929
                                 "such access, and also support local commits."
937
930
                            ),
 
931
                     Option('files-from', type=str,
 
932
                            help="Get file contents from this tree."),
 
933
                     Option('hardlink',
 
934
                            help='Hard-link working tree files where possible.'
 
935
                            ),
938
936
                     ]
939
937
    aliases = ['co']
940
938
 
941
939
    def run(self, branch_location=None, to_location=None, revision=None,
942
 
            lightweight=False):
 
940
            lightweight=False, files_from=None, hardlink=False):
943
941
        if revision is None:
944
942
            revision = [None]
945
943
        elif len(revision) > 1:
948
946
        if branch_location is None:
949
947
            branch_location = osutils.getcwd()
950
948
            to_location = branch_location
951
 
        source = Branch.open(branch_location)
 
949
        accelerator_tree, source = bzrdir.BzrDir.open_tree_or_branch(
 
950
            branch_location)
 
951
        if files_from is not None:
 
952
            accelerator_tree = WorkingTree.open(files_from)
952
953
        if len(revision) == 1 and revision[0] is not None:
953
 
            revision_id = _mod_revision.ensure_null(
954
 
                revision[0].in_history(source)[1])
 
954
            revision_id = revision[0].as_revision_id(source)
955
955
        else:
956
956
            revision_id = None
957
957
        if to_location is None:
966
966
            except errors.NoWorkingTree:
967
967
                source.bzrdir.create_workingtree(revision_id)
968
968
                return
969
 
        source.create_checkout(to_location, revision_id, lightweight)
 
969
        source.create_checkout(to_location, revision_id, lightweight,
 
970
                               accelerator_tree, hardlink)
970
971
 
971
972
 
972
973
class cmd_renames(Command):
1062
1063
    _see_also = ['revno', 'working-trees', 'repositories']
1063
1064
    takes_args = ['location?']
1064
1065
    takes_options = ['verbose']
 
1066
    encoding_type = 'replace'
1065
1067
 
1066
1068
    @display_command
1067
1069
    def run(self, location=None, verbose=False):
1071
1073
            noise_level = 0
1072
1074
        from bzrlib.info import show_bzrdir_info
1073
1075
        show_bzrdir_info(bzrdir.BzrDir.open_containing(location)[0],
1074
 
                         verbose=noise_level)
 
1076
                         verbose=noise_level, outfile=self.outf)
1075
1077
 
1076
1078
 
1077
1079
class cmd_remove(Command):
1078
1080
    """Remove files or directories.
1079
1081
 
1080
 
    This makes bzr stop tracking changes to the specified files and
1081
 
    delete them if they can easily be recovered using revert.
1082
 
 
1083
 
    You can specify one or more files, and/or --new.  If you specify --new,
1084
 
    only 'added' files will be removed.  If you specify both, then new files
1085
 
    in the specified directories will be removed.  If the directories are
1086
 
    also new, they will also be removed.
 
1082
    This makes bzr stop tracking changes to the specified files. bzr will delete
 
1083
    them if they can easily be recovered using revert. If no options or
 
1084
    parameters are given bzr will scan for files that are being tracked by bzr
 
1085
    but missing in your tree and stop tracking them for you.
1087
1086
    """
1088
1087
    takes_args = ['file*']
1089
1088
    takes_options = ['verbose',
1090
 
        Option('new', help='Remove newly-added files.'),
 
1089
        Option('new', help='Only remove files that have never been committed.'),
1091
1090
        RegistryOption.from_kwargs('file-deletion-strategy',
1092
1091
            'The file deletion mode to be used.',
1093
1092
            title='Deletion Strategy', value_switches=True, enum_switch=False,
1096
1095
            keep="Don't delete any files.",
1097
1096
            force='Delete all the specified files, even if they can not be '
1098
1097
                'recovered and even if they are non-empty directories.')]
1099
 
    aliases = ['rm']
 
1098
    aliases = ['rm', 'del']
1100
1099
    encoding_type = 'replace'
1101
1100
 
1102
1101
    def run(self, file_list, verbose=False, new=False,
1105
1104
 
1106
1105
        if file_list is not None:
1107
1106
            file_list = [f for f in file_list]
1108
 
        elif not new:
1109
 
            raise errors.BzrCommandError('Specify one or more files to'
1110
 
            ' remove, or use --new.')
1111
1107
 
1112
 
        if new:
1113
 
            added = tree.changes_from(tree.basis_tree(),
1114
 
                specific_files=file_list).added
1115
 
            file_list = sorted([f[0] for f in added], reverse=True)
1116
 
            if len(file_list) == 0:
1117
 
                raise errors.BzrCommandError('No matching files.')
1118
 
        tree.remove(file_list, verbose=verbose, to_file=self.outf,
1119
 
            keep_files=file_deletion_strategy=='keep',
1120
 
            force=file_deletion_strategy=='force')
 
1108
        tree.lock_write()
 
1109
        try:
 
1110
            # Heuristics should probably all move into tree.remove_smart or
 
1111
            # some such?
 
1112
            if new:
 
1113
                added = tree.changes_from(tree.basis_tree(),
 
1114
                    specific_files=file_list).added
 
1115
                file_list = sorted([f[0] for f in added], reverse=True)
 
1116
                if len(file_list) == 0:
 
1117
                    raise errors.BzrCommandError('No matching files.')
 
1118
            elif file_list is None:
 
1119
                # missing files show up in iter_changes(basis) as
 
1120
                # versioned-with-no-kind.
 
1121
                missing = []
 
1122
                for change in tree.iter_changes(tree.basis_tree()):
 
1123
                    # Find paths in the working tree that have no kind:
 
1124
                    if change[1][1] is not None and change[6][1] is None:
 
1125
                        missing.append(change[1][1])
 
1126
                file_list = sorted(missing, reverse=True)
 
1127
                file_deletion_strategy = 'keep'
 
1128
            tree.remove(file_list, verbose=verbose, to_file=self.outf,
 
1129
                keep_files=file_deletion_strategy=='keep',
 
1130
                force=file_deletion_strategy=='force')
 
1131
        finally:
 
1132
            tree.unlock()
1121
1133
 
1122
1134
 
1123
1135
class cmd_file_id(Command):
1228
1240
            last_revision = wt.last_revision()
1229
1241
 
1230
1242
        revision_ids = b.repository.get_ancestry(last_revision)
1231
 
        assert revision_ids[0] is None
1232
1243
        revision_ids.pop(0)
1233
1244
        for revision_id in revision_ids:
1234
1245
            self.outf.write(revision_id + '\n')
1254
1265
        bzr init
1255
1266
        bzr add .
1256
1267
        bzr status
1257
 
        bzr commit -m 'imported project'
 
1268
        bzr commit -m "imported project"
1258
1269
    """
1259
1270
 
1260
1271
    _see_also = ['init-repository', 'branch', 'checkout']
1323
1334
            except errors.UpgradeRequired:
1324
1335
                raise errors.BzrCommandError('This branch format cannot be set'
1325
1336
                    ' to append-revisions-only.  Try --experimental-branch6')
 
1337
        if not is_quiet():
 
1338
            from bzrlib.info import show_bzrdir_info
 
1339
            show_bzrdir_info(bzrdir.BzrDir.open_containing_from_transport(
 
1340
                to_transport)[0], verbose=0, outfile=self.outf)
1326
1341
 
1327
1342
 
1328
1343
class cmd_init_repository(Command):
1374
1389
        newdir = format.initialize_on_transport(to_transport)
1375
1390
        repo = newdir.create_repository(shared=True)
1376
1391
        repo.set_make_working_trees(not no_trees)
 
1392
        if not is_quiet():
 
1393
            from bzrlib.info import show_bzrdir_info
 
1394
            show_bzrdir_info(bzrdir.BzrDir.open_containing_from_transport(
 
1395
                to_transport)[0], verbose=0, outfile=self.outf)
1377
1396
 
1378
1397
 
1379
1398
class cmd_diff(Command):
1380
 
    """Show differences in the working tree or between revisions.
 
1399
    """Show differences in the working tree, between revisions or branches.
1381
1400
    
1382
 
    If files are listed, only the changes in those files are listed.
1383
 
    Otherwise, all changes for the tree are listed.
 
1401
    If no arguments are given, all changes for the current tree are listed.
 
1402
    If files are given, only the changes in those files are listed.
 
1403
    Remote and multiple branches can be compared by using the --old and
 
1404
    --new options. If not provided, the default for both is derived from
 
1405
    the first argument, if any, or the current tree if no arguments are
 
1406
    given.
1384
1407
 
1385
1408
    "bzr diff -p1" is equivalent to "bzr diff --prefix old/:new/", and
1386
1409
    produces patches suitable for "patch -p1".
1387
1410
 
 
1411
    :Exit values:
 
1412
        1 - changed
 
1413
        2 - unrepresentable changes
 
1414
        3 - error
 
1415
        0 - no change
 
1416
 
1388
1417
    :Examples:
1389
1418
        Shows the difference in the working tree versus the last commit::
1390
1419
 
1398
1427
 
1399
1428
            bzr diff -r1..2
1400
1429
 
 
1430
        Difference between revision 2 and revision 1 for branch xxx::
 
1431
 
 
1432
            bzr diff -r1..2 xxx
 
1433
 
 
1434
        Show just the differences for file NEWS::
 
1435
 
 
1436
            bzr diff NEWS
 
1437
 
 
1438
        Show the differences in working tree xxx for file NEWS::
 
1439
 
 
1440
            bzr diff xxx/NEWS
 
1441
 
 
1442
        Show the differences from branch xxx to this working tree:
 
1443
 
 
1444
            bzr diff --old xxx
 
1445
 
 
1446
        Show the differences between two branches for file NEWS::
 
1447
 
 
1448
            bzr diff --old xxx --new yyy NEWS
 
1449
 
1401
1450
        Same as 'bzr diff' but prefix paths with old/ and new/::
1402
1451
 
1403
1452
            bzr diff --prefix old/:new/
1404
 
 
1405
 
        Show the differences between the two working trees::
1406
 
 
1407
 
            bzr diff bzr.mine bzr.dev
1408
 
 
1409
 
        Show just the differences for 'foo.c'::
1410
 
 
1411
 
            bzr diff foo.c
1412
1453
    """
1413
 
    # TODO: Option to use external diff command; could be GNU diff, wdiff,
1414
 
    #       or a graphical diff.
1415
 
 
1416
 
    # TODO: Python difflib is not exactly the same as unidiff; should
1417
 
    #       either fix it up or prefer to use an external diff.
1418
 
 
1419
 
    # TODO: Selected-file diff is inefficient and doesn't show you
1420
 
    #       deleted files.
1421
 
 
1422
 
    # TODO: This probably handles non-Unix newlines poorly.
1423
 
 
1424
1454
    _see_also = ['status']
1425
1455
    takes_args = ['file*']
1426
1456
    takes_options = [
1430
1460
               short_name='p',
1431
1461
               help='Set prefixes added to old and new filenames, as '
1432
1462
                    'two values separated by a colon. (eg "old/:new/").'),
 
1463
        Option('old',
 
1464
            help='Branch/tree to compare from.',
 
1465
            type=unicode,
 
1466
            ),
 
1467
        Option('new',
 
1468
            help='Branch/tree to compare to.',
 
1469
            type=unicode,
 
1470
            ),
1433
1471
        'revision',
1434
1472
        'change',
 
1473
        Option('using',
 
1474
            help='Use this command to compare files.',
 
1475
            type=unicode,
 
1476
            ),
1435
1477
        ]
1436
1478
    aliases = ['di', 'dif']
1437
1479
    encoding_type = 'exact'
1438
1480
 
1439
1481
    @display_command
1440
1482
    def run(self, revision=None, file_list=None, diff_options=None,
1441
 
            prefix=None):
1442
 
        from bzrlib.diff import diff_cmd_helper, show_diff_trees
 
1483
            prefix=None, old=None, new=None, using=None):
 
1484
        from bzrlib.diff import _get_trees_to_diff, show_diff_trees
1443
1485
 
1444
1486
        if (prefix is None) or (prefix == '0'):
1445
1487
            # diff -p0 format
1459
1501
            raise errors.BzrCommandError('bzr diff --revision takes exactly'
1460
1502
                                         ' one or two revision specifiers')
1461
1503
 
1462
 
        try:
1463
 
            tree1, file_list = internal_tree_files(file_list)
1464
 
            tree2 = None
1465
 
            b = None
1466
 
            b2 = None
1467
 
        except errors.FileInWrongBranch:
1468
 
            if len(file_list) != 2:
1469
 
                raise errors.BzrCommandError("Files are in different branches")
1470
 
 
1471
 
            tree1, file1 = WorkingTree.open_containing(file_list[0])
1472
 
            tree2, file2 = WorkingTree.open_containing(file_list[1])
1473
 
            if file1 != "" or file2 != "":
1474
 
                # FIXME diff those two files. rbc 20051123
1475
 
                raise errors.BzrCommandError("Files are in different branches")
1476
 
            file_list = None
1477
 
        except errors.NotBranchError:
1478
 
            if (revision is not None and len(revision) == 2
1479
 
                and not revision[0].needs_branch()
1480
 
                and not revision[1].needs_branch()):
1481
 
                # If both revision specs include a branch, we can
1482
 
                # diff them without needing a local working tree
1483
 
                tree1, tree2 = None, None
1484
 
            else:
1485
 
                raise
1486
 
 
1487
 
        if tree2 is not None:
1488
 
            if revision is not None:
1489
 
                # FIXME: but there should be a clean way to diff between
1490
 
                # non-default versions of two trees, it's not hard to do
1491
 
                # internally...
1492
 
                raise errors.BzrCommandError(
1493
 
                        "Sorry, diffing arbitrary revisions across branches "
1494
 
                        "is not implemented yet")
1495
 
            return show_diff_trees(tree1, tree2, sys.stdout, 
1496
 
                                   specific_files=file_list,
1497
 
                                   external_diff_options=diff_options,
1498
 
                                   old_label=old_label, new_label=new_label)
1499
 
 
1500
 
        return diff_cmd_helper(tree1, file_list, diff_options,
1501
 
                               revision_specs=revision,
1502
 
                               old_label=old_label, new_label=new_label)
 
1504
        old_tree, new_tree, specific_files, extra_trees = \
 
1505
                _get_trees_to_diff(file_list, revision, old, new)
 
1506
        return show_diff_trees(old_tree, new_tree, sys.stdout, 
 
1507
                               specific_files=specific_files,
 
1508
                               external_diff_options=diff_options,
 
1509
                               old_label=old_label, new_label=new_label,
 
1510
                               extra_trees=extra_trees, using=using)
1503
1511
 
1504
1512
 
1505
1513
class cmd_deleted(Command):
1541
1549
 
1542
1550
    hidden = True
1543
1551
    _see_also = ['status', 'ls']
 
1552
    takes_options = [
 
1553
            Option('null',
 
1554
                   help='Write an ascii NUL (\\0) separator '
 
1555
                   'between files rather than a newline.')
 
1556
            ]
1544
1557
 
1545
1558
    @display_command
1546
 
    def run(self):
 
1559
    def run(self, null=False):
1547
1560
        tree = WorkingTree.open_containing(u'.')[0]
1548
1561
        td = tree.changes_from(tree.basis_tree())
1549
1562
        for path, id, kind, text_modified, meta_modified in td.modified:
1550
 
            self.outf.write(path + '\n')
 
1563
            if null:
 
1564
                self.outf.write(path + '\0')
 
1565
            else:
 
1566
                self.outf.write(osutils.quotefn(path) + '\n')
1551
1567
 
1552
1568
 
1553
1569
class cmd_added(Command):
1556
1572
 
1557
1573
    hidden = True
1558
1574
    _see_also = ['status', 'ls']
 
1575
    takes_options = [
 
1576
            Option('null',
 
1577
                   help='Write an ascii NUL (\\0) separator '
 
1578
                   'between files rather than a newline.')
 
1579
            ]
1559
1580
 
1560
1581
    @display_command
1561
 
    def run(self):
 
1582
    def run(self, null=False):
1562
1583
        wt = WorkingTree.open_containing(u'.')[0]
1563
1584
        wt.lock_read()
1564
1585
        try:
1575
1596
                    path = inv.id2path(file_id)
1576
1597
                    if not os.access(osutils.abspath(path), os.F_OK):
1577
1598
                        continue
1578
 
                    self.outf.write(path + '\n')
 
1599
                    if null:
 
1600
                        self.outf.write(path + '\0')
 
1601
                    else:
 
1602
                        self.outf.write(osutils.quotefn(path) + '\n')
1579
1603
            finally:
1580
1604
                basis.unlock()
1581
1605
        finally:
1647
1671
                        'regular expression.',
1648
1672
                   type=str),
1649
1673
            Option('limit',
 
1674
                   short_name='l',
1650
1675
                   help='Limit the output to the first N revisions.',
1651
1676
                   argname='N',
1652
1677
                   type=_parse_limit),
1663
1688
            message=None,
1664
1689
            limit=None):
1665
1690
        from bzrlib.log import show_log
1666
 
        assert message is None or isinstance(message, basestring), \
1667
 
            "invalid message argument %r" % message
1668
1691
        direction = (forward and 'forward') or 'reverse'
1669
1692
        
1670
1693
        # log everything
1777
1800
            Option('from-root',
1778
1801
                   help='Print paths relative to the root of the branch.'),
1779
1802
            Option('unknown', help='Print unknown files.'),
1780
 
            Option('versioned', help='Print versioned files.'),
 
1803
            Option('versioned', help='Print versioned files.',
 
1804
                   short_name='V'),
1781
1805
            Option('ignored', help='Print ignored files.'),
1782
1806
            Option('null',
1783
1807
                   help='Write an ascii NUL (\\0) separator '
1819
1843
            relpath += '/'
1820
1844
        if revision is not None:
1821
1845
            tree = branch.repository.revision_tree(
1822
 
                revision[0].in_history(branch).rev_id)
 
1846
                revision[0].as_revision_id(branch))
1823
1847
        elif tree is None:
1824
1848
            tree = branch.basis_tree()
1825
1849
 
1876
1900
class cmd_ignore(Command):
1877
1901
    """Ignore specified files or patterns.
1878
1902
 
 
1903
    See ``bzr help patterns`` for details on the syntax of patterns.
 
1904
 
1879
1905
    To remove patterns from the ignore list, edit the .bzrignore file.
1880
 
 
1881
 
    Trailing slashes on patterns are ignored. 
1882
 
    If the pattern contains a slash or is a regular expression, it is compared 
1883
 
    to the whole path from the branch root.  Otherwise, it is compared to only
1884
 
    the last component of the path.  To match a file only in the root 
1885
 
    directory, prepend './'.
1886
 
 
1887
 
    Ignore patterns specifying absolute paths are not allowed.
1888
 
 
1889
 
    Ignore patterns may include globbing wildcards such as::
1890
 
 
1891
 
      ? - Matches any single character except '/'
1892
 
      * - Matches 0 or more characters except '/'
1893
 
      /**/ - Matches 0 or more directories in a path
1894
 
      [a-z] - Matches a single character from within a group of characters
1895
 
 
1896
 
    Ignore patterns may also be Python regular expressions.  
1897
 
    Regular expression ignore patterns are identified by a 'RE:' prefix 
1898
 
    followed by the regular expression.  Regular expression ignore patterns
1899
 
    may not include named or numbered groups.
 
1906
    After adding, editing or deleting that file either indirectly by
 
1907
    using this command or directly by using an editor, be sure to commit
 
1908
    it.
1900
1909
 
1901
1910
    Note: ignore patterns containing shell wildcards must be quoted from 
1902
1911
    the shell on Unix.
1908
1917
 
1909
1918
        Ignore class files in all directories::
1910
1919
 
1911
 
            bzr ignore '*.class'
1912
 
 
1913
 
        Ignore .o files under the lib directory::
1914
 
 
1915
 
            bzr ignore 'lib/**/*.o'
1916
 
 
1917
 
        Ignore .o files under the lib directory::
1918
 
 
1919
 
            bzr ignore 'RE:lib/.*\.o'
 
1920
            bzr ignore "*.class"
 
1921
 
 
1922
        Ignore .o files under the lib directory::
 
1923
 
 
1924
            bzr ignore "lib/**/*.o"
 
1925
 
 
1926
        Ignore .o files under the lib directory::
 
1927
 
 
1928
            bzr ignore "RE:lib/.*\.o"
 
1929
 
 
1930
        Ignore everything but the "debian" toplevel directory::
 
1931
 
 
1932
            bzr ignore "RE:(?!debian/).*"
1920
1933
    """
1921
1934
 
1922
 
    _see_also = ['status', 'ignored']
 
1935
    _see_also = ['status', 'ignored', 'patterns']
1923
1936
    takes_args = ['name_pattern*']
1924
1937
    takes_options = [
1925
1938
        Option('old-default-rules',
1927
1940
        ]
1928
1941
    
1929
1942
    def run(self, name_pattern_list=None, old_default_rules=None):
1930
 
        from bzrlib.atomicfile import AtomicFile
 
1943
        from bzrlib import ignores
1931
1944
        if old_default_rules is not None:
1932
1945
            # dump the rules and exit
1933
1946
            for pattern in ignores.OLD_DEFAULTS:
1944
1957
                raise errors.BzrCommandError(
1945
1958
                    "NAME_PATTERN should not be an absolute path")
1946
1959
        tree, relpath = WorkingTree.open_containing(u'.')
1947
 
        ifn = tree.abspath('.bzrignore')
1948
 
        if os.path.exists(ifn):
1949
 
            f = open(ifn, 'rt')
1950
 
            try:
1951
 
                igns = f.read().decode('utf-8')
1952
 
            finally:
1953
 
                f.close()
1954
 
        else:
1955
 
            igns = ''
1956
 
 
1957
 
        # TODO: If the file already uses crlf-style termination, maybe
1958
 
        # we should use that for the newly added lines?
1959
 
 
1960
 
        if igns and igns[-1] != '\n':
1961
 
            igns += '\n'
1962
 
        for name_pattern in name_pattern_list:
1963
 
            igns += name_pattern + '\n'
1964
 
 
1965
 
        f = AtomicFile(ifn, 'wb')
1966
 
        try:
1967
 
            f.write(igns.encode('utf-8'))
1968
 
            f.commit()
1969
 
        finally:
1970
 
            f.close()
1971
 
 
1972
 
        if not tree.path2id('.bzrignore'):
1973
 
            tree.add(['.bzrignore'])
1974
 
 
 
1960
        ignores.tree_ignores_add_patterns(tree, name_pattern_list)
1975
1961
        ignored = globbing.Globster(name_pattern_list)
1976
1962
        matches = []
1977
1963
        tree.lock_read()
1986
1972
            print "Warning: the following files are version controlled and" \
1987
1973
                  " match your ignore pattern:\n%s" % ("\n".join(matches),)
1988
1974
 
 
1975
 
1989
1976
class cmd_ignored(Command):
1990
1977
    """List ignored files and the patterns that matched them.
 
1978
 
 
1979
    List all the ignored files and the ignore pattern that caused the file to
 
1980
    be ignored.
 
1981
 
 
1982
    Alternatively, to list just the files::
 
1983
 
 
1984
        bzr ls --ignored
1991
1985
    """
1992
1986
 
1993
 
    _see_also = ['ignore']
 
1987
    encoding_type = 'replace'
 
1988
    _see_also = ['ignore', 'ls']
 
1989
 
1994
1990
    @display_command
1995
1991
    def run(self):
1996
1992
        tree = WorkingTree.open_containing(u'.')[0]
2001
1997
                    continue
2002
1998
                ## XXX: Slightly inefficient since this was already calculated
2003
1999
                pat = tree.is_ignored(path)
2004
 
                print '%-50s %s' % (path, pat)
 
2000
                self.outf.write('%-50s %s\n' % (path, pat))
2005
2001
        finally:
2006
2002
            tree.unlock()
2007
2003
 
2053
2049
         zip                          .zip
2054
2050
      =================       =========================
2055
2051
    """
2056
 
    takes_args = ['dest', 'branch?']
 
2052
    takes_args = ['dest', 'branch_or_subdir?']
2057
2053
    takes_options = [
2058
2054
        Option('format',
2059
2055
               help="Type of file to export to.",
2063
2059
               type=str,
2064
2060
               help="Name of the root directory inside the exported file."),
2065
2061
        ]
2066
 
    def run(self, dest, branch=None, revision=None, format=None, root=None):
 
2062
    def run(self, dest, branch_or_subdir=None, revision=None, format=None,
 
2063
        root=None):
2067
2064
        from bzrlib.export import export
2068
2065
 
2069
 
        if branch is None:
 
2066
        if branch_or_subdir is None:
2070
2067
            tree = WorkingTree.open_containing(u'.')[0]
2071
2068
            b = tree.branch
 
2069
            subdir = None
2072
2070
        else:
2073
 
            b = Branch.open(branch)
 
2071
            b, subdir = Branch.open_containing(branch_or_subdir)
2074
2072
            
2075
2073
        if revision is None:
2076
2074
            # should be tree.last_revision  FIXME
2078
2076
        else:
2079
2077
            if len(revision) != 1:
2080
2078
                raise errors.BzrCommandError('bzr export --revision takes exactly 1 argument')
2081
 
            rev_id = revision[0].in_history(b).rev_id
 
2079
            rev_id = revision[0].as_revision_id(b)
2082
2080
        t = b.repository.revision_tree(rev_id)
2083
2081
        try:
2084
 
            export(t, dest, format, root)
 
2082
            export(t, dest, format, root, subdir)
2085
2083
        except errors.NoSuchExportFormat, e:
2086
2084
            raise errors.BzrCommandError('Unsupported export format: %s' % e.format)
2087
2085
 
2107
2105
    def run(self, filename, revision=None, name_from_revision=False):
2108
2106
        if revision is not None and len(revision) != 1:
2109
2107
            raise errors.BzrCommandError("bzr cat --revision takes exactly"
2110
 
                                        " one number")
2111
 
 
2112
 
        tree = None
 
2108
                                         " one revision specifier")
 
2109
        tree, branch, relpath = \
 
2110
            bzrdir.BzrDir.open_containing_tree_or_branch(filename)
 
2111
        branch.lock_read()
2113
2112
        try:
2114
 
            tree, b, relpath = \
2115
 
                    bzrdir.BzrDir.open_containing_tree_or_branch(filename)
2116
 
        except errors.NotBranchError:
2117
 
            pass
 
2113
            return self._run(tree, branch, relpath, filename, revision,
 
2114
                             name_from_revision)
 
2115
        finally:
 
2116
            branch.unlock()
2118
2117
 
2119
 
        if revision is not None and revision[0].get_branch() is not None:
2120
 
            b = Branch.open(revision[0].get_branch())
 
2118
    def _run(self, tree, b, relpath, filename, revision, name_from_revision):
2121
2119
        if tree is None:
2122
2120
            tree = b.basis_tree()
2123
2121
        if revision is None:
2124
2122
            revision_id = b.last_revision()
2125
2123
        else:
2126
 
            revision_id = revision[0].in_history(b).rev_id
 
2124
            revision_id = revision[0].as_revision_id(b)
2127
2125
 
2128
2126
        cur_file_id = tree.path2id(relpath)
2129
2127
        rev_tree = b.repository.revision_tree(revision_id)
2134
2132
                raise errors.BzrCommandError("%r is not present in revision %s"
2135
2133
                                                % (filename, revision_id))
2136
2134
            else:
2137
 
                rev_tree.print_file(old_file_id)
 
2135
                content = rev_tree.get_file_text(old_file_id)
2138
2136
        elif cur_file_id is not None:
2139
 
            rev_tree.print_file(cur_file_id)
 
2137
            content = rev_tree.get_file_text(cur_file_id)
2140
2138
        elif old_file_id is not None:
2141
 
            rev_tree.print_file(old_file_id)
 
2139
            content = rev_tree.get_file_text(old_file_id)
2142
2140
        else:
2143
2141
            raise errors.BzrCommandError("%r is not present in revision %s" %
2144
2142
                                         (filename, revision_id))
 
2143
        self.outf.write(content)
2145
2144
 
2146
2145
 
2147
2146
class cmd_local_time_offset(Command):
2162
2161
    committed.  If a directory is specified then the directory and everything 
2163
2162
    within it is committed.
2164
2163
 
 
2164
    When excludes are given, they take precedence over selected files.
 
2165
    For example, too commit only changes within foo, but not changes within
 
2166
    foo/bar::
 
2167
 
 
2168
      bzr commit foo -x foo/bar
 
2169
 
2165
2170
    If author of the change is not the same person as the committer, you can
2166
2171
    specify the author's name using the --author option. The name should be
2167
2172
    in the same format as a committer-id, e.g. "John Doe <jdoe@example.com>".
2197
2202
    _see_also = ['bugs', 'uncommit']
2198
2203
    takes_args = ['selected*']
2199
2204
    takes_options = [
 
2205
            ListOption('exclude', type=str, short_name='x',
 
2206
                help="Do not consider changes made to a given path."),
2200
2207
            Option('message', type=unicode,
2201
2208
                   short_name='m',
2202
2209
                   help="Description of the new revision."),
2212
2219
                    "files in the working tree."),
2213
2220
             ListOption('fixes', type=str,
2214
2221
                    help="Mark a bug as being fixed by this revision."),
2215
 
             Option('author', type=str,
 
2222
             Option('author', type=unicode,
2216
2223
                    help="Set the author's name, if it's different "
2217
2224
                         "from the committer."),
2218
2225
             Option('local',
2251
2258
 
2252
2259
    def run(self, message=None, file=None, verbose=False, selected_list=None,
2253
2260
            unchanged=False, strict=False, local=False, fixes=None,
2254
 
            author=None, show_diff=False):
 
2261
            author=None, show_diff=False, exclude=None):
2255
2262
        from bzrlib.errors import (
2256
2263
            PointlessCommit,
2257
2264
            ConflictsInTree,
2301
2308
                raise errors.BzrCommandError(
2302
2309
                    "please specify either --message or --file")
2303
2310
            if file:
2304
 
                my_message = codecs.open(file, 'rt', 
 
2311
                my_message = codecs.open(file, 'rt',
2305
2312
                                         bzrlib.user_encoding).read()
2306
2313
            if my_message == "":
2307
2314
                raise errors.BzrCommandError("empty commit message specified")
2312
2319
                        specific_files=selected_list,
2313
2320
                        allow_pointless=unchanged, strict=strict, local=local,
2314
2321
                        reporter=None, verbose=verbose, revprops=properties,
2315
 
                        author=author)
 
2322
                        author=author,
 
2323
                        exclude=safe_relpath_files(tree, exclude))
2316
2324
        except PointlessCommit:
2317
2325
            # FIXME: This should really happen before the file is read in;
2318
2326
            # perhaps prepare the commit; get the message; then actually commit
2333
2341
 
2334
2342
 
2335
2343
class cmd_check(Command):
2336
 
    """Validate consistency of branch history.
2337
 
 
2338
 
    This command checks various invariants about the branch storage to
2339
 
    detect data corruption or bzr bugs.
2340
 
 
2341
 
    Output fields:
 
2344
    """Validate working tree structure, branch consistency and repository history.
 
2345
 
 
2346
    This command checks various invariants about branch and repository storage
 
2347
    to detect data corruption or bzr bugs.
 
2348
 
 
2349
    The working tree and branch checks will only give output if a problem is
 
2350
    detected. The output fields of the repository check are:
2342
2351
 
2343
2352
        revisions: This is just the number of revisions checked.  It doesn't
2344
2353
            indicate a problem.
2353
2362
            in the checked revisions.  Texts can be repeated when their file
2354
2363
            entries are modified, but the file contents are not.  It does not
2355
2364
            indicate a problem.
 
2365
 
 
2366
    If no restrictions are specified, all Bazaar data that is found at the given
 
2367
    location will be checked.
 
2368
 
 
2369
    :Examples:
 
2370
 
 
2371
        Check the tree and branch at 'foo'::
 
2372
 
 
2373
            bzr check --tree --branch foo
 
2374
 
 
2375
        Check only the repository at 'bar'::
 
2376
 
 
2377
            bzr check --repo bar
 
2378
 
 
2379
        Check everything at 'baz'::
 
2380
 
 
2381
            bzr check baz
2356
2382
    """
2357
2383
 
2358
2384
    _see_also = ['reconcile']
2359
 
    takes_args = ['branch?']
2360
 
    takes_options = ['verbose']
 
2385
    takes_args = ['path?']
 
2386
    takes_options = ['verbose',
 
2387
                     Option('branch', help="Check the branch related to the"
 
2388
                                           " current directory."),
 
2389
                     Option('repo', help="Check the repository related to the"
 
2390
                                         " current directory."),
 
2391
                     Option('tree', help="Check the working tree related to"
 
2392
                                         " the current directory.")]
2361
2393
 
2362
 
    def run(self, branch=None, verbose=False):
2363
 
        from bzrlib.check import check
2364
 
        if branch is None:
2365
 
            branch = Branch.open_containing('.')[0]
2366
 
        else:
2367
 
            branch = Branch.open(branch)
2368
 
        check(branch, verbose)
 
2394
    def run(self, path=None, verbose=False, branch=False, repo=False,
 
2395
            tree=False):
 
2396
        from bzrlib.check import check_dwim
 
2397
        if path is None:
 
2398
            path = '.'
 
2399
        if not branch and not repo and not tree:
 
2400
            branch = repo = tree = True
 
2401
        check_dwim(path, verbose, do_branch=branch, do_repo=repo, do_tree=tree)
2369
2402
 
2370
2403
 
2371
2404
class cmd_upgrade(Command):
2404
2437
 
2405
2438
        Set the current user::
2406
2439
 
2407
 
            bzr whoami 'Frank Chu <fchu@example.com>'
 
2440
            bzr whoami "Frank Chu <fchu@example.com>"
2408
2441
    """
2409
2442
    takes_options = [ Option('email',
2410
2443
                             help='Display email address only.'),
2465
2498
        print branch.nick
2466
2499
 
2467
2500
 
 
2501
class cmd_alias(Command):
 
2502
    """Set/unset and display aliases.
 
2503
 
 
2504
    :Examples:
 
2505
        Show the current aliases::
 
2506
 
 
2507
            bzr alias
 
2508
 
 
2509
        Show the alias specified for 'll'::
 
2510
 
 
2511
            bzr alias ll
 
2512
 
 
2513
        Set an alias for 'll'::
 
2514
 
 
2515
            bzr alias ll="log --line -r-10..-1"
 
2516
 
 
2517
        To remove an alias for 'll'::
 
2518
 
 
2519
            bzr alias --remove ll
 
2520
 
 
2521
    """
 
2522
    takes_args = ['name?']
 
2523
    takes_options = [
 
2524
        Option('remove', help='Remove the alias.'),
 
2525
        ]
 
2526
 
 
2527
    def run(self, name=None, remove=False):
 
2528
        if remove:
 
2529
            self.remove_alias(name)
 
2530
        elif name is None:
 
2531
            self.print_aliases()
 
2532
        else:
 
2533
            equal_pos = name.find('=')
 
2534
            if equal_pos == -1:
 
2535
                self.print_alias(name)
 
2536
            else:
 
2537
                self.set_alias(name[:equal_pos], name[equal_pos+1:])
 
2538
 
 
2539
    def remove_alias(self, alias_name):
 
2540
        if alias_name is None:
 
2541
            raise errors.BzrCommandError(
 
2542
                'bzr alias --remove expects an alias to remove.')
 
2543
        # If alias is not found, print something like:
 
2544
        # unalias: foo: not found
 
2545
        c = config.GlobalConfig()
 
2546
        c.unset_alias(alias_name)
 
2547
 
 
2548
    @display_command
 
2549
    def print_aliases(self):
 
2550
        """Print out the defined aliases in a similar format to bash."""
 
2551
        aliases = config.GlobalConfig().get_aliases()
 
2552
        for key, value in sorted(aliases.iteritems()):
 
2553
            self.outf.write('bzr alias %s="%s"\n' % (key, value))
 
2554
 
 
2555
    @display_command
 
2556
    def print_alias(self, alias_name):
 
2557
        from bzrlib.commands import get_alias
 
2558
        alias = get_alias(alias_name)
 
2559
        if alias is None:
 
2560
            self.outf.write("bzr alias: %s: not found\n" % alias_name)
 
2561
        else:
 
2562
            self.outf.write(
 
2563
                'bzr alias %s="%s"\n' % (alias_name, ' '.join(alias)))
 
2564
 
 
2565
    def set_alias(self, alias_name, alias_command):
 
2566
        """Save the alias in the global config."""
 
2567
        c = config.GlobalConfig()
 
2568
        c.set_alias(alias_name, alias_command)
 
2569
 
 
2570
 
2468
2571
class cmd_selftest(Command):
2469
2572
    """Run internal test suite.
2470
2573
    
2559
2662
                                 ' expression.'),
2560
2663
                     Option('strict', help='Fail on missing dependencies or '
2561
2664
                            'known failures.'),
 
2665
                     Option('load-list', type=str, argname='TESTLISTFILE',
 
2666
                            help='Load a test id list from a text file.'),
 
2667
                     ListOption('debugflag', type=str, short_name='E',
 
2668
                                help='Turn on a selftest debug flag.'),
 
2669
                     ListOption('starting-with', type=str, argname='TESTID',
 
2670
                                param_name='starting_with', short_name='s',
 
2671
                                help=
 
2672
                                'Load only the tests starting with TESTID.'),
2562
2673
                     ]
2563
2674
    encoding_type = 'replace'
2564
2675
 
2566
2677
            transport=None, benchmark=None,
2567
2678
            lsprof_timed=None, cache_dir=None,
2568
2679
            first=False, list_only=False,
2569
 
            randomize=None, exclude=None, strict=False):
 
2680
            randomize=None, exclude=None, strict=False,
 
2681
            load_list=None, debugflag=None, starting_with=None):
2570
2682
        import bzrlib.ui
2571
2683
        from bzrlib.tests import selftest
2572
2684
        import bzrlib.benchmarks as benchmarks
2573
2685
        from bzrlib.benchmarks import tree_creator
2574
2686
 
 
2687
        # Make deprecation warnings visible, unless -Werror is set
 
2688
        symbol_versioning.activate_deprecation_warnings(override=False)
 
2689
 
2575
2690
        if cache_dir is not None:
2576
2691
            tree_creator.TreeCreator.CACHE_ROOT = osutils.abspath(cache_dir)
2577
2692
        if not list_only:
2579
2694
            print '   %s (%s python%s)' % (
2580
2695
                    bzrlib.__path__[0],
2581
2696
                    bzrlib.version_string,
2582
 
                    '.'.join(map(str, sys.version_info)),
 
2697
                    bzrlib._format_version_tuple(sys.version_info),
2583
2698
                    )
2584
2699
        print
2585
2700
        if testspecs_list is not None:
2608
2723
                              random_seed=randomize,
2609
2724
                              exclude_pattern=exclude,
2610
2725
                              strict=strict,
 
2726
                              load_list=load_list,
 
2727
                              debug_flags=debugflag,
 
2728
                              starting_with=starting_with,
2611
2729
                              )
2612
2730
        finally:
2613
2731
            if benchfile is not None:
2614
2732
                benchfile.close()
2615
2733
        if result:
2616
 
            info('tests passed')
 
2734
            note('tests passed')
2617
2735
        else:
2618
 
            info('tests failed')
 
2736
            note('tests failed')
2619
2737
        return int(not result)
2620
2738
 
2621
2739
 
2623
2741
    """Show version of bzr."""
2624
2742
 
2625
2743
    encoding_type = 'replace'
 
2744
    takes_options = [
 
2745
        Option("short", help="Print just the version number."),
 
2746
        ]
2626
2747
 
2627
2748
    @display_command
2628
 
    def run(self):
 
2749
    def run(self, short=False):
2629
2750
        from bzrlib.version import show_version
2630
 
        show_version(to_file=self.outf)
 
2751
        if short:
 
2752
            self.outf.write(bzrlib.version_string + '\n')
 
2753
        else:
 
2754
            show_version(to_file=self.outf)
2631
2755
 
2632
2756
 
2633
2757
class cmd_rocks(Command):
2653
2777
        
2654
2778
        branch1 = Branch.open_containing(branch)[0]
2655
2779
        branch2 = Branch.open_containing(other)[0]
2656
 
 
2657
 
        last1 = ensure_null(branch1.last_revision())
2658
 
        last2 = ensure_null(branch2.last_revision())
2659
 
 
2660
 
        graph = branch1.repository.get_graph(branch2.repository)
2661
 
        base_rev_id = graph.find_unique_lca(last1, last2)
2662
 
 
2663
 
        print 'merge base is revision %s' % base_rev_id
 
2780
        branch1.lock_read()
 
2781
        try:
 
2782
            branch2.lock_read()
 
2783
            try:
 
2784
                last1 = ensure_null(branch1.last_revision())
 
2785
                last2 = ensure_null(branch2.last_revision())
 
2786
 
 
2787
                graph = branch1.repository.get_graph(branch2.repository)
 
2788
                base_rev_id = graph.find_unique_lca(last1, last2)
 
2789
 
 
2790
                print 'merge base is revision %s' % base_rev_id
 
2791
            finally:
 
2792
                branch2.unlock()
 
2793
        finally:
 
2794
            branch1.unlock()
2664
2795
 
2665
2796
 
2666
2797
class cmd_merge(Command):
2667
2798
    """Perform a three-way merge.
2668
2799
    
2669
 
    The branch is the branch you will merge from.  By default, it will merge
2670
 
    the latest revision.  If you specify a revision, that revision will be
2671
 
    merged.  If you specify two revisions, the first will be used as a BASE,
2672
 
    and the second one as OTHER.  Revision numbers are always relative to the
2673
 
    specified branch.
 
2800
    The source of the merge can be specified either in the form of a branch,
 
2801
    or in the form of a path to a file containing a merge directive generated
 
2802
    with bzr send. If neither is specified, the default is the upstream branch
 
2803
    or the branch most recently merged using --remember.
 
2804
 
 
2805
    When merging a branch, by default the tip will be merged. To pick a different
 
2806
    revision, pass --revision. If you specify two values, the first will be used as
 
2807
    BASE and the second one as OTHER. Merging individual revisions, or a subset of
 
2808
    available revisions, like this is commonly referred to as "cherrypicking".
 
2809
 
 
2810
    Revision numbers are always relative to the branch being merged.
2674
2811
 
2675
2812
    By default, bzr will try to merge in all new work from the other
2676
2813
    branch, automatically determining an appropriate base.  If this
2707
2844
        To merge the changes introduced by 82, without previous changes::
2708
2845
 
2709
2846
            bzr merge -r 81..82 ../bzr.dev
 
2847
 
 
2848
        To apply a merge directive contained in in /tmp/merge:
 
2849
 
 
2850
            bzr merge /tmp/merge
2710
2851
    """
2711
2852
 
 
2853
    encoding_type = 'exact'
2712
2854
    _see_also = ['update', 'remerge', 'status-flags']
2713
 
    takes_args = ['branch?']
 
2855
    takes_args = ['location?']
2714
2856
    takes_options = [
2715
2857
        'change',
2716
2858
        'revision',
2733
2875
               short_name='d',
2734
2876
               type=unicode,
2735
2877
               ),
 
2878
        Option('preview', help='Instead of merging, show a diff of the merge.')
2736
2879
    ]
2737
2880
 
2738
 
    def run(self, branch=None, revision=None, force=False, merge_type=None,
2739
 
            show_base=False, reprocess=False, remember=False,
 
2881
    def run(self, location=None, revision=None, force=False,
 
2882
            merge_type=None, show_base=False, reprocess=False, remember=False,
2740
2883
            uncommitted=False, pull=False,
2741
2884
            directory=None,
 
2885
            preview=False,
2742
2886
            ):
2743
 
        # This is actually a branch (or merge-directive) *location*.
2744
 
        location = branch
2745
 
        del branch
2746
 
 
2747
2887
        if merge_type is None:
2748
2888
            merge_type = _mod_merge.Merge3Merger
2749
2889
 
2762
2902
            tree.lock_write()
2763
2903
            cleanups.append(tree.unlock)
2764
2904
            if location is not None:
2765
 
                mergeable, other_transport = _get_mergeable_helper(location)
2766
 
                if mergeable:
 
2905
                try:
 
2906
                    mergeable = bundle.read_mergeable_from_url(location,
 
2907
                        possible_transports=possible_transports)
 
2908
                except errors.NotABundle:
 
2909
                    mergeable = None
 
2910
                else:
2767
2911
                    if uncommitted:
2768
2912
                        raise errors.BzrCommandError('Cannot use --uncommitted'
2769
2913
                            ' with bundles or merge directives.')
2773
2917
                            'Cannot use -r with merge directives or bundles')
2774
2918
                    merger, verified = _mod_merge.Merger.from_mergeable(tree,
2775
2919
                       mergeable, pb)
2776
 
                possible_transports.append(other_transport)
2777
2920
 
2778
2921
            if merger is None and uncommitted:
2779
2922
                if revision is not None and len(revision) > 0:
2784
2927
                merger = _mod_merge.Merger.from_uncommitted(tree, other_tree,
2785
2928
                    pb)
2786
2929
                allow_pending = False
 
2930
                if other_path != '':
 
2931
                    merger.interesting_files = [other_path]
2787
2932
 
2788
2933
            if merger is None:
2789
2934
                merger, allow_pending = self._get_merger_from_branch(tree,
2792
2937
            merger.merge_type = merge_type
2793
2938
            merger.reprocess = reprocess
2794
2939
            merger.show_base = show_base
2795
 
            merger.change_reporter = change_reporter
2796
2940
            self.sanity_check_merger(merger)
2797
2941
            if (merger.base_rev_id == merger.other_rev_id and
2798
 
                merger.other_rev_id != None):
 
2942
                merger.other_rev_id is not None):
2799
2943
                note('Nothing to do.')
2800
2944
                return 0
2801
2945
            if pull:
2807
2951
                    result.report(self.outf)
2808
2952
                    return 0
2809
2953
            merger.check_basis(not force)
2810
 
            conflict_count = merger.do_merge()
2811
 
            if allow_pending:
2812
 
                merger.set_pending()
2813
 
            if verified == 'failed':
2814
 
                warning('Preview patch does not match changes')
2815
 
            if conflict_count != 0:
2816
 
                return 1
 
2954
            if preview:
 
2955
                return self._do_preview(merger)
2817
2956
            else:
2818
 
                return 0
 
2957
                return self._do_merge(merger, change_reporter, allow_pending,
 
2958
                                      verified)
2819
2959
        finally:
2820
2960
            for cleanup in reversed(cleanups):
2821
2961
                cleanup()
2822
2962
 
 
2963
    def _do_preview(self, merger):
 
2964
        from bzrlib.diff import show_diff_trees
 
2965
        tree_merger = merger.make_merger()
 
2966
        tt = tree_merger.make_preview_transform()
 
2967
        try:
 
2968
            result_tree = tt.get_preview_tree()
 
2969
            show_diff_trees(merger.this_tree, result_tree, self.outf,
 
2970
                            old_label='', new_label='')
 
2971
        finally:
 
2972
            tt.finalize()
 
2973
 
 
2974
    def _do_merge(self, merger, change_reporter, allow_pending, verified):
 
2975
        merger.change_reporter = change_reporter
 
2976
        conflict_count = merger.do_merge()
 
2977
        if allow_pending:
 
2978
            merger.set_pending()
 
2979
        if verified == 'failed':
 
2980
            warning('Preview patch does not match changes')
 
2981
        if conflict_count != 0:
 
2982
            return 1
 
2983
        else:
 
2984
            return 0
 
2985
 
2823
2986
    def sanity_check_merger(self, merger):
2824
2987
        if (merger.show_base and
2825
2988
            not merger.merge_type is _mod_merge.Merge3Merger):
2837
3000
                                possible_transports, pb):
2838
3001
        """Produce a merger from a location, assuming it refers to a branch."""
2839
3002
        from bzrlib.tag import _merge_tags_if_possible
2840
 
        assert revision is None or len(revision) < 3
2841
3003
        # find the branch locations
2842
 
        other_loc, location = self._select_branch_location(tree, location,
 
3004
        other_loc, user_location = self._select_branch_location(tree, location,
2843
3005
            revision, -1)
2844
3006
        if revision is not None and len(revision) == 2:
2845
 
            base_loc, location = self._select_branch_location(tree, location,
2846
 
                                                              revision, 0)
 
3007
            base_loc, _unused = self._select_branch_location(tree,
 
3008
                location, revision, 0)
2847
3009
        else:
2848
3010
            base_loc = other_loc
2849
3011
        # Open the branches
2859
3021
            other_revision_id = _mod_revision.ensure_null(
2860
3022
                other_branch.last_revision())
2861
3023
        else:
2862
 
            other_revision_id = \
2863
 
                _mod_revision.ensure_null(
2864
 
                    revision[-1].in_history(other_branch).rev_id)
 
3024
            other_revision_id = revision[-1].as_revision_id(other_branch)
2865
3025
        if (revision is not None and len(revision) == 2
2866
3026
            and revision[0] is not None):
2867
 
            base_revision_id = \
2868
 
                _mod_revision.ensure_null(
2869
 
                    revision[0].in_history(base_branch).rev_id)
 
3027
            base_revision_id = revision[0].as_revision_id(base_branch)
2870
3028
        else:
2871
3029
            base_revision_id = None
2872
3030
        # Remember where we merge from
2873
 
        if ((tree.branch.get_parent() is None or remember) and
2874
 
            other_branch is not None):
2875
 
            tree.branch.set_parent(other_branch.base)
 
3031
        if ((remember or tree.branch.get_submit_branch() is None) and
 
3032
             user_location is not None):
 
3033
            tree.branch.set_submit_branch(other_branch.base)
2876
3034
        _merge_tags_if_possible(other_branch, tree.branch)
2877
3035
        merger = _mod_merge.Merger.from_revision_ids(pb, tree,
2878
3036
            other_revision_id, base_revision_id, other_branch, base_branch)
2883
3041
            allow_pending = True
2884
3042
        return merger, allow_pending
2885
3043
 
2886
 
    def _select_branch_location(self, tree, location, revision=None,
 
3044
    def _select_branch_location(self, tree, user_location, revision=None,
2887
3045
                                index=None):
2888
3046
        """Select a branch location, according to possible inputs.
2889
3047
 
2891
3049
        ``revision`` and ``index`` must be supplied.)
2892
3050
 
2893
3051
        Otherwise, the ``location`` parameter is used.  If it is None, then the
2894
 
        ``parent`` location is used, and a note is printed.
 
3052
        ``submit`` or ``parent`` location is used, and a note is printed.
2895
3053
 
2896
3054
        :param tree: The working tree to select a branch for merging into
2897
3055
        :param location: The location entered by the user
2898
3056
        :param revision: The revision parameter to the command
2899
3057
        :param index: The index to use for the revision parameter.  Negative
2900
3058
            indices are permitted.
2901
 
        :return: (selected_location, default_location).  The default location
2902
 
            will be the user-entered location, if any, or else the remembered
2903
 
            location.
 
3059
        :return: (selected_location, user_location).  The default location
 
3060
            will be the user-entered location.
2904
3061
        """
2905
3062
        if (revision is not None and index is not None
2906
3063
            and revision[index] is not None):
2907
3064
            branch = revision[index].get_branch()
2908
3065
            if branch is not None:
2909
 
                return branch, location
2910
 
        location = self._get_remembered_parent(tree, location, 'Merging from')
2911
 
        return location, location
 
3066
                return branch, branch
 
3067
        if user_location is None:
 
3068
            location = self._get_remembered(tree, 'Merging from')
 
3069
        else:
 
3070
            location = user_location
 
3071
        return location, user_location
2912
3072
 
2913
 
    # TODO: move up to common parent; this isn't merge-specific anymore. 
2914
 
    def _get_remembered_parent(self, tree, supplied_location, verb_string):
 
3073
    def _get_remembered(self, tree, verb_string):
2915
3074
        """Use tree.branch's parent if none was supplied.
2916
3075
 
2917
3076
        Report if the remembered location was used.
2918
3077
        """
2919
 
        if supplied_location is not None:
2920
 
            return supplied_location
2921
 
        stored_location = tree.branch.get_parent()
 
3078
        stored_location = tree.branch.get_submit_branch()
 
3079
        stored_location_type = "submit"
 
3080
        if stored_location is None:
 
3081
            stored_location = tree.branch.get_parent()
 
3082
            stored_location_type = "parent"
2922
3083
        mutter("%s", stored_location)
2923
3084
        if stored_location is None:
2924
3085
            raise errors.BzrCommandError("No location specified or remembered")
2925
 
        display_url = urlutils.unescape_for_display(stored_location,
2926
 
            self.outf.encoding)
2927
 
        self.outf.write("%s remembered location %s\n" % (verb_string,
2928
 
            display_url))
 
3086
        display_url = urlutils.unescape_for_display(stored_location, 'utf-8')
 
3087
        note(u"%s remembered %s location %s", verb_string,
 
3088
                stored_location_type, display_url)
2929
3089
        return stored_location
2930
3090
 
2931
3091
 
2972
3132
                                             " merges.  Not cherrypicking or"
2973
3133
                                             " multi-merges.")
2974
3134
            repository = tree.branch.repository
2975
 
            graph = repository.get_graph()
2976
 
            base_revision = graph.find_unique_lca(parents[0], parents[1])
2977
 
            base_tree = repository.revision_tree(base_revision)
2978
 
            other_tree = repository.revision_tree(parents[1])
2979
3135
            interesting_ids = None
2980
3136
            new_conflicts = []
2981
3137
            conflicts = tree.conflicts()
3011
3167
            # list, we imply that the working tree text has seen and rejected
3012
3168
            # all the changes from the other tree, when in fact those changes
3013
3169
            # have not yet been seen.
 
3170
            pb = ui.ui_factory.nested_progress_bar()
3014
3171
            tree.set_parent_ids(parents[:1])
3015
3172
            try:
3016
 
                conflicts = _mod_merge.merge_inner(
3017
 
                                          tree.branch, other_tree, base_tree,
3018
 
                                          this_tree=tree,
3019
 
                                          interesting_ids=interesting_ids,
3020
 
                                          other_rev_id=parents[1],
3021
 
                                          merge_type=merge_type,
3022
 
                                          show_base=show_base,
3023
 
                                          reprocess=reprocess)
 
3173
                merger = _mod_merge.Merger.from_revision_ids(pb,
 
3174
                                                             tree, parents[1])
 
3175
                merger.interesting_ids = interesting_ids
 
3176
                merger.merge_type = merge_type
 
3177
                merger.show_base = show_base
 
3178
                merger.reprocess = reprocess
 
3179
                conflicts = merger.do_merge()
3024
3180
            finally:
3025
3181
                tree.set_parent_ids(parents)
 
3182
                pb.finished()
3026
3183
        finally:
3027
3184
            tree.unlock()
3028
3185
        if conflicts > 0:
3039
3196
    last committed revision is used.
3040
3197
 
3041
3198
    To remove only some changes, without reverting to a prior version, use
3042
 
    merge instead.  For example, "merge . --r-2..-3" will remove the changes
3043
 
    introduced by -2, without affecting the changes introduced by -1.  Or
3044
 
    to remove certain changes on a hunk-by-hunk basis, see the Shelf plugin.
 
3199
    merge instead.  For example, "merge . --revision -2..-3" will remove the
 
3200
    changes introduced by -2, without affecting the changes introduced by -1.
 
3201
    Or to remove certain changes on a hunk-by-hunk basis, see the Shelf plugin.
3045
3202
    
3046
3203
    By default, any files that have been manually changed will be backed up
3047
3204
    first.  (Files changed only by merge are not backed up.)  Backup files have
3058
3215
 
3059
3216
    The working tree contains a list of pending merged revisions, which will
3060
3217
    be included as parents in the next commit.  Normally, revert clears that
3061
 
    list as well as reverting the files.  If any files, are specified, revert
3062
 
    leaves the pending merge list alnone and reverts only the files.  Use "bzr
 
3218
    list as well as reverting the files.  If any files are specified, revert
 
3219
    leaves the pending merge list alone and reverts only the files.  Use "bzr
3063
3220
    revert ." in the tree root to revert all files but keep the merge record,
3064
3221
    and "bzr revert --forget-merges" to clear the pending merge list without
3065
3222
    reverting any files.
3089
3246
        elif len(revision) != 1:
3090
3247
            raise errors.BzrCommandError('bzr revert --revision takes exactly 1 argument')
3091
3248
        else:
3092
 
            rev_id = revision[0].in_history(tree.branch).rev_id
 
3249
            rev_id = revision[0].as_revision_id(tree.branch)
3093
3250
        pb = ui.ui_factory.nested_progress_bar()
3094
3251
        try:
3095
3252
            tree.revert(file_list,
3143
3300
        shellcomplete.shellcomplete(context)
3144
3301
 
3145
3302
 
3146
 
class cmd_fetch(Command):
3147
 
    """Copy in history from another branch but don't merge it.
3148
 
 
3149
 
    This is an internal method used for pull and merge.
3150
 
    """
3151
 
    hidden = True
3152
 
    takes_args = ['from_branch', 'to_branch']
3153
 
    def run(self, from_branch, to_branch):
3154
 
        from bzrlib.fetch import Fetcher
3155
 
        from_b = Branch.open(from_branch)
3156
 
        to_b = Branch.open(to_branch)
3157
 
        Fetcher(to_b, from_b)
3158
 
 
3159
 
 
3160
3303
class cmd_missing(Command):
3161
3304
    """Show unmerged/unpulled revisions between two branches.
3162
3305
    
3186
3329
        from bzrlib.missing import find_unmerged, iter_log_revisions
3187
3330
 
3188
3331
        if this:
3189
 
          mine_only = this
 
3332
            mine_only = this
3190
3333
        if other:
3191
 
          theirs_only = other
 
3334
            theirs_only = other
 
3335
        # TODO: We should probably check that we don't have mine-only and
 
3336
        #       theirs-only set, but it gets complicated because we also have
 
3337
        #       this and other which could be used.
 
3338
        restrict = 'all'
 
3339
        if mine_only:
 
3340
            restrict = 'local'
 
3341
        elif theirs_only:
 
3342
            restrict = 'remote'
3192
3343
 
3193
3344
        local_branch = Branch.open_containing(u".")[0]
3194
3345
        parent = local_branch.get_parent()
3199
3350
                                             " or specified.")
3200
3351
            display_url = urlutils.unescape_for_display(parent,
3201
3352
                                                        self.outf.encoding)
3202
 
            self.outf.write("Using last location: " + display_url + "\n")
 
3353
            self.outf.write("Using saved parent location: "
 
3354
                    + display_url + "\n")
3203
3355
 
3204
3356
        remote_branch = Branch.open(other_branch)
3205
3357
        if remote_branch.base == local_branch.base:
3208
3360
        try:
3209
3361
            remote_branch.lock_read()
3210
3362
            try:
3211
 
                local_extra, remote_extra = find_unmerged(local_branch,
3212
 
                                                          remote_branch)
 
3363
                local_extra, remote_extra = find_unmerged(
 
3364
                    local_branch, remote_branch, restrict)
 
3365
 
3213
3366
                if log_format is None:
3214
3367
                    registry = log.log_formatter_registry
3215
3368
                    log_format = registry.get_default(local_branch)
3217
3370
                                show_ids=show_ids,
3218
3371
                                show_timezone='original')
3219
3372
                if reverse is False:
3220
 
                    local_extra.reverse()
3221
 
                    remote_extra.reverse()
 
3373
                    if local_extra is not None:
 
3374
                        local_extra.reverse()
 
3375
                    if remote_extra is not None:
 
3376
                        remote_extra.reverse()
 
3377
 
 
3378
                status_code = 0
3222
3379
                if local_extra and not theirs_only:
3223
3380
                    self.outf.write("You have %d extra revision(s):\n" %
3224
3381
                                    len(local_extra))
3227
3384
                                        verbose):
3228
3385
                        lf.log_revision(revision)
3229
3386
                    printed_local = True
 
3387
                    status_code = 1
3230
3388
                else:
3231
3389
                    printed_local = False
 
3390
 
3232
3391
                if remote_extra and not mine_only:
3233
3392
                    if printed_local is True:
3234
3393
                        self.outf.write("\n\n\n")
3238
3397
                                        remote_branch.repository,
3239
3398
                                        verbose):
3240
3399
                        lf.log_revision(revision)
3241
 
                if not remote_extra and not local_extra:
3242
 
                    status_code = 0
 
3400
                    status_code = 1
 
3401
 
 
3402
                if mine_only and not local_extra:
 
3403
                    # We checked local, and found nothing extra
 
3404
                    self.outf.write('This branch is up to date.\n')
 
3405
                elif theirs_only and not remote_extra:
 
3406
                    # We checked remote, and found nothing extra
 
3407
                    self.outf.write('Other branch is up to date.\n')
 
3408
                elif not (mine_only or theirs_only or local_extra or
 
3409
                          remote_extra):
 
3410
                    # We checked both branches, and neither one had extra
 
3411
                    # revisions
3243
3412
                    self.outf.write("Branches are up to date.\n")
3244
 
                else:
3245
 
                    status_code = 1
3246
3413
            finally:
3247
3414
                remote_branch.unlock()
3248
3415
        finally:
3277
3444
class cmd_plugins(Command):
3278
3445
    """List the installed plugins.
3279
3446
    
3280
 
    This command displays the list of installed plugins including the
3281
 
    path where each one is located and a short description of each.
 
3447
    This command displays the list of installed plugins including
 
3448
    version of plugin and a short description of each.
 
3449
 
 
3450
    --verbose shows the path where each plugin is located.
3282
3451
 
3283
3452
    A plugin is an external component for Bazaar that extends the
3284
3453
    revision control system, by adding or replacing code in Bazaar.
3291
3460
    install them. Instructions are also provided there on how to
3292
3461
    write new plugins using the Python programming language.
3293
3462
    """
 
3463
    takes_options = ['verbose']
3294
3464
 
3295
3465
    @display_command
3296
 
    def run(self):
 
3466
    def run(self, verbose=False):
3297
3467
        import bzrlib.plugin
3298
3468
        from inspect import getdoc
 
3469
        result = []
3299
3470
        for name, plugin in bzrlib.plugin.plugins().items():
3300
 
            print plugin.path(), "[%s]" % plugin.__version__
 
3471
            version = plugin.__version__
 
3472
            if version == 'unknown':
 
3473
                version = ''
 
3474
            name_ver = '%s %s' % (name, version)
3301
3475
            d = getdoc(plugin.module)
3302
3476
            if d:
3303
 
                print '\t', d.split('\n')[0]
 
3477
                doc = d.split('\n')[0]
 
3478
            else:
 
3479
                doc = '(no description)'
 
3480
            result.append((name_ver, doc, plugin.path()))
 
3481
        for name_ver, doc, path in sorted(result):
 
3482
            print name_ver
 
3483
            print '   ', doc
 
3484
            if verbose:
 
3485
                print '   ', path
 
3486
            print
3304
3487
 
3305
3488
 
3306
3489
class cmd_testament(Command):
3318
3501
            testament_class = StrictTestament
3319
3502
        else:
3320
3503
            testament_class = Testament
3321
 
        b = WorkingTree.open_containing(branch)[0].branch
 
3504
        if branch == '.':
 
3505
            b = Branch.open_containing(branch)[0]
 
3506
        else:
 
3507
            b = Branch.open(branch)
3322
3508
        b.lock_read()
3323
3509
        try:
3324
3510
            if revision is None:
3325
3511
                rev_id = b.last_revision()
3326
3512
            else:
3327
 
                rev_id = revision[0].in_history(b).rev_id
 
3513
                rev_id = revision[0].as_revision_id(b)
3328
3514
            t = testament_class.from_revision(b.repository, rev_id)
3329
3515
            if long:
3330
3516
                sys.stdout.writelines(t.as_text_lines())
3359
3545
    def run(self, filename, all=False, long=False, revision=None,
3360
3546
            show_ids=False):
3361
3547
        from bzrlib.annotate import annotate_file
3362
 
        tree, relpath = WorkingTree.open_containing(filename)
3363
 
        branch = tree.branch
3364
 
        branch.lock_read()
 
3548
        wt, branch, relpath = \
 
3549
            bzrdir.BzrDir.open_containing_tree_or_branch(filename)
 
3550
        if wt is not None:
 
3551
            wt.lock_read()
 
3552
        else:
 
3553
            branch.lock_read()
3365
3554
        try:
3366
3555
            if revision is None:
3367
3556
                revision_id = branch.last_revision()
3368
3557
            elif len(revision) != 1:
3369
3558
                raise errors.BzrCommandError('bzr annotate --revision takes exactly 1 argument')
3370
3559
            else:
3371
 
                revision_id = revision[0].in_history(branch).rev_id
3372
 
            file_id = tree.path2id(relpath)
 
3560
                revision_id = revision[0].as_revision_id(branch)
 
3561
            tree = branch.repository.revision_tree(revision_id)
 
3562
            if wt is not None:
 
3563
                file_id = wt.path2id(relpath)
 
3564
            else:
 
3565
                file_id = tree.path2id(relpath)
3373
3566
            if file_id is None:
3374
3567
                raise errors.NotVersionedError(filename)
3375
 
            tree = branch.repository.revision_tree(revision_id)
3376
3568
            file_version = tree.inventory[file_id].revision
3377
3569
            annotate_file(branch, file_version, file_id, long, all, self.outf,
3378
3570
                          show_ids=show_ids)
3379
3571
        finally:
3380
 
            branch.unlock()
 
3572
            if wt is not None:
 
3573
                wt.unlock()
 
3574
            else:
 
3575
                branch.unlock()
3381
3576
 
3382
3577
 
3383
3578
class cmd_re_sign(Command):
3389
3584
    takes_options = ['revision']
3390
3585
    
3391
3586
    def run(self, revision_id_list=None, revision=None):
3392
 
        import bzrlib.gpg as gpg
3393
3587
        if revision_id_list is not None and revision is not None:
3394
3588
            raise errors.BzrCommandError('You can only supply one of revision_id or --revision')
3395
3589
        if revision_id_list is None and revision is None:
3396
3590
            raise errors.BzrCommandError('You must supply either --revision or a revision_id')
3397
3591
        b = WorkingTree.open_containing(u'.')[0].branch
 
3592
        b.lock_write()
 
3593
        try:
 
3594
            return self._run(b, revision_id_list, revision)
 
3595
        finally:
 
3596
            b.unlock()
 
3597
 
 
3598
    def _run(self, b, revision_id_list, revision):
 
3599
        import bzrlib.gpg as gpg
3398
3600
        gpg_strategy = gpg.GPGStrategy(b.get_config())
3399
3601
        if revision_id_list is not None:
3400
 
            for revision_id in revision_id_list:
3401
 
                b.repository.sign_revision(revision_id, gpg_strategy)
 
3602
            b.repository.start_write_group()
 
3603
            try:
 
3604
                for revision_id in revision_id_list:
 
3605
                    b.repository.sign_revision(revision_id, gpg_strategy)
 
3606
            except:
 
3607
                b.repository.abort_write_group()
 
3608
                raise
 
3609
            else:
 
3610
                b.repository.commit_write_group()
3402
3611
        elif revision is not None:
3403
3612
            if len(revision) == 1:
3404
3613
                revno, rev_id = revision[0].in_history(b)
3405
 
                b.repository.sign_revision(rev_id, gpg_strategy)
 
3614
                b.repository.start_write_group()
 
3615
                try:
 
3616
                    b.repository.sign_revision(rev_id, gpg_strategy)
 
3617
                except:
 
3618
                    b.repository.abort_write_group()
 
3619
                    raise
 
3620
                else:
 
3621
                    b.repository.commit_write_group()
3406
3622
            elif len(revision) == 2:
3407
3623
                # are they both on rh- if so we can walk between them
3408
3624
                # might be nice to have a range helper for arbitrary
3413
3629
                    to_revno = b.revno()
3414
3630
                if from_revno is None or to_revno is None:
3415
3631
                    raise errors.BzrCommandError('Cannot sign a range of non-revision-history revisions')
3416
 
                for revno in range(from_revno, to_revno + 1):
3417
 
                    b.repository.sign_revision(b.get_rev_id(revno), 
3418
 
                                               gpg_strategy)
 
3632
                b.repository.start_write_group()
 
3633
                try:
 
3634
                    for revno in range(from_revno, to_revno + 1):
 
3635
                        b.repository.sign_revision(b.get_rev_id(revno),
 
3636
                                                   gpg_strategy)
 
3637
                except:
 
3638
                    b.repository.abort_write_group()
 
3639
                    raise
 
3640
                else:
 
3641
                    b.repository.commit_write_group()
3419
3642
            else:
3420
3643
                raise errors.BzrCommandError('Please supply either one revision, or a range.')
3421
3644
 
3479
3702
    specified revision.  For example, "bzr uncommit -r 15" will leave the
3480
3703
    branch at revision 15.
3481
3704
 
3482
 
    In the future, uncommit will create a revision bundle, which can then
3483
 
    be re-applied.
 
3705
    Uncommit leaves the working tree ready for a new commit.  The only change
 
3706
    it may make is to restore any pending merges that were present before
 
3707
    the commit.
3484
3708
    """
3485
3709
 
3486
3710
    # TODO: jam 20060108 Add an option to allow uncommit to remove
3490
3714
    _see_also = ['commit']
3491
3715
    takes_options = ['verbose', 'revision',
3492
3716
                    Option('dry-run', help='Don\'t actually make changes.'),
3493
 
                    Option('force', help='Say yes to all questions.')]
 
3717
                    Option('force', help='Say yes to all questions.'),
 
3718
                    Option('local',
 
3719
                           help="Only remove the commits from the local branch"
 
3720
                                " when in a checkout."
 
3721
                           ),
 
3722
                    ]
3494
3723
    takes_args = ['location?']
3495
3724
    aliases = []
 
3725
    encoding_type = 'replace'
3496
3726
 
3497
3727
    def run(self, location=None,
3498
3728
            dry_run=False, verbose=False,
3499
 
            revision=None, force=False):
3500
 
        from bzrlib.log import log_formatter, show_log
3501
 
        from bzrlib.uncommit import uncommit
3502
 
 
 
3729
            revision=None, force=False, local=False):
3503
3730
        if location is None:
3504
3731
            location = u'.'
3505
3732
        control, relpath = bzrdir.BzrDir.open_containing(location)
3510
3737
            tree = None
3511
3738
            b = control.open_branch()
3512
3739
 
 
3740
        if tree is not None:
 
3741
            tree.lock_write()
 
3742
        else:
 
3743
            b.lock_write()
 
3744
        try:
 
3745
            return self._run(b, tree, dry_run, verbose, revision, force,
 
3746
                             local=local)
 
3747
        finally:
 
3748
            if tree is not None:
 
3749
                tree.unlock()
 
3750
            else:
 
3751
                b.unlock()
 
3752
 
 
3753
    def _run(self, b, tree, dry_run, verbose, revision, force, local=False):
 
3754
        from bzrlib.log import log_formatter, show_log
 
3755
        from bzrlib.uncommit import uncommit
 
3756
 
 
3757
        last_revno, last_rev_id = b.last_revision_info()
 
3758
 
3513
3759
        rev_id = None
3514
3760
        if revision is None:
3515
 
            revno = b.revno()
 
3761
            revno = last_revno
 
3762
            rev_id = last_rev_id
3516
3763
        else:
3517
3764
            # 'bzr uncommit -r 10' actually means uncommit
3518
3765
            # so that the final tree is at revno 10.
3519
3766
            # but bzrlib.uncommit.uncommit() actually uncommits
3520
3767
            # the revisions that are supplied.
3521
3768
            # So we need to offset it by one
3522
 
            revno = revision[0].in_history(b).revno+1
 
3769
            revno = revision[0].in_history(b).revno + 1
 
3770
            if revno <= last_revno:
 
3771
                rev_id = b.get_rev_id(revno)
3523
3772
 
3524
 
        if revno <= b.revno():
3525
 
            rev_id = b.get_rev_id(revno)
3526
 
        if rev_id is None:
 
3773
        if rev_id is None or _mod_revision.is_null(rev_id):
3527
3774
            self.outf.write('No revisions to uncommit.\n')
3528
3775
            return 1
3529
3776
 
3536
3783
                 verbose=False,
3537
3784
                 direction='forward',
3538
3785
                 start_revision=revno,
3539
 
                 end_revision=b.revno())
 
3786
                 end_revision=last_revno)
3540
3787
 
3541
3788
        if dry_run:
3542
3789
            print 'Dry-run, pretending to remove the above revisions.'
3550
3797
                    print 'Canceled'
3551
3798
                    return 0
3552
3799
 
 
3800
        mutter('Uncommitting from {%s} to {%s}',
 
3801
               last_rev_id, rev_id)
3553
3802
        uncommit(b, tree=tree, dry_run=dry_run, verbose=verbose,
3554
 
                revno=revno)
 
3803
                 revno=revno, local=local)
 
3804
        note('You can restore the old tip by running:\n'
 
3805
             '  bzr pull . -r revid:%s', last_rev_id)
3555
3806
 
3556
3807
 
3557
3808
class cmd_break_lock(Command):
3616
3867
        ]
3617
3868
 
3618
3869
    def run(self, port=None, inet=False, directory=None, allow_writes=False):
 
3870
        from bzrlib import lockdir
3619
3871
        from bzrlib.smart import medium, server
3620
3872
        from bzrlib.transport import get_transport
3621
3873
        from bzrlib.transport.chroot import ChrootServer
3622
 
        from bzrlib.transport.remote import BZR_DEFAULT_PORT, BZR_DEFAULT_INTERFACE
3623
3874
        if directory is None:
3624
3875
            directory = os.getcwd()
3625
3876
        url = urlutils.local_path_to_url(directory)
3632
3883
            smart_server = medium.SmartServerPipeStreamMedium(
3633
3884
                sys.stdin, sys.stdout, t)
3634
3885
        else:
3635
 
            host = BZR_DEFAULT_INTERFACE
 
3886
            host = medium.BZR_DEFAULT_INTERFACE
3636
3887
            if port is None:
3637
 
                port = BZR_DEFAULT_PORT
 
3888
                port = medium.BZR_DEFAULT_PORT
3638
3889
            else:
3639
3890
                if ':' in port:
3640
3891
                    host, port = port.split(':')
3647
3898
        # be changed with care though, as we dont want to use bandwidth sending
3648
3899
        # progress over stderr to smart server clients!
3649
3900
        old_factory = ui.ui_factory
 
3901
        old_lockdir_timeout = lockdir._DEFAULT_TIMEOUT_SECONDS
3650
3902
        try:
3651
3903
            ui.ui_factory = ui.SilentUIFactory()
 
3904
            lockdir._DEFAULT_TIMEOUT_SECONDS = 0
3652
3905
            smart_server.serve()
3653
3906
        finally:
3654
3907
            ui.ui_factory = old_factory
 
3908
            lockdir._DEFAULT_TIMEOUT_SECONDS = old_lockdir_timeout
3655
3909
 
3656
3910
 
3657
3911
class cmd_join(Command):
3709
3963
 
3710
3964
 
3711
3965
class cmd_split(Command):
3712
 
    """Split a tree into two trees.
 
3966
    """Split a subdirectory of a tree into a separate tree.
3713
3967
 
3714
 
    This command is for experimental use only.  It requires the target tree
3715
 
    to be in dirstate-with-subtree format, which cannot be converted into
3716
 
    earlier formats.
 
3968
    This command will produce a target tree in a format that supports
 
3969
    rich roots, like 'rich-root' or 'rich-root-pack'.  These formats cannot be
 
3970
    converted into earlier formats like 'dirstate-tags'.
3717
3971
 
3718
3972
    The TREE argument should be a subdirectory of a working tree.  That
3719
3973
    subdirectory will be converted into an independent tree, with its own
3720
3974
    branch.  Commits in the top-level tree will not apply to the new subtree.
3721
 
    If you want that behavior, do "bzr join --reference TREE".
3722
3975
    """
3723
3976
 
3724
 
    _see_also = ['join']
 
3977
    # join is not un-hidden yet
 
3978
    #_see_also = ['join']
3725
3979
    takes_args = ['tree']
3726
3980
 
3727
 
    hidden = True
3728
 
 
3729
3981
    def run(self, tree):
3730
3982
        containing_tree, subdir = WorkingTree.open_containing(tree)
3731
3983
        sub_id = containing_tree.path2id(subdir)
3737
3989
            raise errors.UpgradeRequired(containing_tree.branch.base)
3738
3990
 
3739
3991
 
3740
 
 
3741
3992
class cmd_merge_directive(Command):
3742
3993
    """Generate a merge directive for auto-merge tools.
3743
3994
 
3812
4063
            if len(revision) > 2:
3813
4064
                raise errors.BzrCommandError('bzr merge-directive takes '
3814
4065
                    'at most two one revision identifiers')
3815
 
            revision_id = revision[-1].in_history(branch).rev_id
 
4066
            revision_id = revision[-1].as_revision_id(branch)
3816
4067
            if len(revision) == 2:
3817
 
                base_revision_id = revision[0].in_history(branch).rev_id
3818
 
                base_revision_id = ensure_null(base_revision_id)
 
4068
                base_revision_id = revision[0].as_revision_id(branch)
3819
4069
        else:
3820
4070
            revision_id = branch.last_revision()
3821
4071
        revision_id = ensure_null(revision_id)
3865
4115
    for that mirror.
3866
4116
 
3867
4117
    Mail is sent using your preferred mail program.  This should be transparent
3868
 
    on Windows (it uses MAPI).  On *nix, it requires the xdg-email utility.  If
3869
 
    the preferred client can't be found (or used), your editor will be used.
 
4118
    on Windows (it uses MAPI).  On Linux, it requires the xdg-email utility.
 
4119
    If the preferred client can't be found (or used), your editor will be used.
3870
4120
    
3871
4121
    To use a specific mail program, set the mail_client configuration option.
3872
4122
    (For Thunderbird 1.5, this works around some bugs.)  Supported values for
3873
4123
    specific clients are "evolution", "kmail", "mutt", and "thunderbird";
3874
 
    generic options are "default", "editor", "mapi", and "xdg-email".
 
4124
    generic options are "default", "editor", "emacsclient", "mapi", and
 
4125
    "xdg-email".  Plugins may also add supported clients.
3875
4126
 
3876
4127
    If mail is being sent, a to address is required.  This can be supplied
3877
 
    either on the commandline, or by setting the submit_to configuration
3878
 
    option.
 
4128
    either on the commandline, by setting the submit_to configuration
 
4129
    option in the branch itself or the child_submit_to configuration option 
 
4130
    in the submit branch.
3879
4131
 
3880
4132
    Two formats are currently supported: "4" uses revision bundle format 4 and
3881
4133
    merge directive format 2.  It is significantly faster and smaller than
3882
4134
    older formats.  It is compatible with Bazaar 0.19 and later.  It is the
3883
4135
    default.  "0.9" uses revision bundle format 0.9 and merge directive
3884
4136
    format 1.  It is compatible with Bazaar 0.12 - 0.18.
 
4137
    
 
4138
    Merge directives are applied using the merge command or the pull command.
3885
4139
    """
3886
4140
 
3887
4141
    encoding_type = 'exact'
3888
4142
 
3889
 
    _see_also = ['merge']
 
4143
    _see_also = ['merge', 'pull']
3890
4144
 
3891
4145
    takes_args = ['submit_branch?', 'public_branch?']
3892
4146
 
3902
4156
               'rather than the one containing the working directory.',
3903
4157
               short_name='f',
3904
4158
               type=unicode),
3905
 
        Option('output', short_name='o', help='Write directive to this file.',
 
4159
        Option('output', short_name='o',
 
4160
               help='Write merge directive to this file; '
 
4161
                    'use - for stdout.',
3906
4162
               type=unicode),
3907
4163
        Option('mail-to', help='Mail the request to this address.',
3908
4164
               type=unicode),
3924
4180
    def _run(self, submit_branch, revision, public_branch, remember, format,
3925
4181
             no_bundle, no_patch, output, from_, mail_to, message):
3926
4182
        from bzrlib.revision import NULL_REVISION
 
4183
        branch = Branch.open_containing(from_)[0]
3927
4184
        if output is None:
3928
4185
            outfile = StringIO()
3929
4186
        elif output == '-':
3930
4187
            outfile = self.outf
3931
4188
        else:
3932
4189
            outfile = open(output, 'wb')
 
4190
        # we may need to write data into branch's repository to calculate
 
4191
        # the data to send.
 
4192
        branch.lock_write()
3933
4193
        try:
3934
 
            branch = Branch.open_containing(from_)[0]
3935
4194
            if output is None:
3936
4195
                config = branch.get_config()
3937
4196
                if mail_to is None:
3938
4197
                    mail_to = config.get_user_option('submit_to')
3939
 
                if mail_to is None:
3940
 
                    raise errors.BzrCommandError('No mail-to address'
3941
 
                                                 ' specified')
3942
4198
                mail_client = config.get_mail_client()
3943
4199
            if remember and submit_branch is None:
3944
4200
                raise errors.BzrCommandError(
3945
4201
                    '--remember requires a branch to be specified.')
3946
4202
            stored_submit_branch = branch.get_submit_branch()
3947
 
            remembered_submit_branch = False
 
4203
            remembered_submit_branch = None
3948
4204
            if submit_branch is None:
3949
4205
                submit_branch = stored_submit_branch
3950
 
                remembered_submit_branch = True
 
4206
                remembered_submit_branch = "submit"
3951
4207
            else:
3952
4208
                if stored_submit_branch is None or remember:
3953
4209
                    branch.set_submit_branch(submit_branch)
3954
4210
            if submit_branch is None:
3955
4211
                submit_branch = branch.get_parent()
3956
 
                remembered_submit_branch = True
 
4212
                remembered_submit_branch = "parent"
3957
4213
            if submit_branch is None:
3958
4214
                raise errors.BzrCommandError('No submit branch known or'
3959
4215
                                             ' specified')
3960
 
            if remembered_submit_branch:
3961
 
                note('Using saved location: %s', submit_branch)
 
4216
            if remembered_submit_branch is not None:
 
4217
                note('Using saved %s location "%s" to determine what '
 
4218
                        'changes to submit.', remembered_submit_branch,
 
4219
                        submit_branch)
 
4220
 
 
4221
            if mail_to is None:
 
4222
                submit_config = Branch.open(submit_branch).get_config()
 
4223
                mail_to = submit_config.get_user_option("child_submit_to")
3962
4224
 
3963
4225
            stored_public_branch = branch.get_public_branch()
3964
4226
            if public_branch is None:
3974
4236
                if len(revision) > 2:
3975
4237
                    raise errors.BzrCommandError('bzr send takes '
3976
4238
                        'at most two one revision identifiers')
3977
 
                revision_id = revision[-1].in_history(branch).rev_id
 
4239
                revision_id = revision[-1].as_revision_id(branch)
3978
4240
                if len(revision) == 2:
3979
 
                    base_revision_id = revision[0].in_history(branch).rev_id
 
4241
                    base_revision_id = revision[0].as_revision_id(branch)
3980
4242
            if revision_id is None:
3981
4243
                revision_id = branch.last_revision()
3982
4244
            if revision_id == NULL_REVISION:
4014
4276
                else:
4015
4277
                    revision = branch.repository.get_revision(revision_id)
4016
4278
                    subject += revision.get_summary()
 
4279
                basename = directive.get_disk_name(branch)
4017
4280
                mail_client.compose_merge_request(mail_to, subject,
4018
 
                                                  outfile.getvalue())
 
4281
                                                  outfile.getvalue(), basename)
4019
4282
        finally:
4020
4283
            if output != '-':
4021
4284
                outfile.close()
 
4285
            branch.unlock()
4022
4286
 
4023
4287
 
4024
4288
class cmd_bundle_revisions(cmd_send):
4103
4367
 
4104
4368
    It is an error to give a tag name that already exists unless you pass 
4105
4369
    --force, in which case the tag is moved to point to the new revision.
 
4370
 
 
4371
    To rename a tag (change the name but keep it on the same revsion), run ``bzr
 
4372
    tag new-name -r tag:old-name`` and then ``bzr tag --delete oldname``.
4106
4373
    """
4107
4374
 
4108
4375
    _see_also = ['commit', 'tags']
4140
4407
                        raise errors.BzrCommandError(
4141
4408
                            "Tags can only be placed on a single revision, "
4142
4409
                            "not on a range")
4143
 
                    revision_id = revision[0].in_history(branch).rev_id
 
4410
                    revision_id = revision[0].as_revision_id(branch)
4144
4411
                else:
4145
4412
                    revision_id = branch.last_revision()
4146
4413
                if (not force) and branch.tags.has_tag(tag_name):
4154
4421
class cmd_tags(Command):
4155
4422
    """List tags.
4156
4423
 
4157
 
    This tag shows a table of tag names and the revisions they reference.
 
4424
    This command shows a table of tag names and the revisions they reference.
4158
4425
    """
4159
4426
 
4160
4427
    _see_also = ['tag']
4164
4431
            short_name='d',
4165
4432
            type=unicode,
4166
4433
            ),
 
4434
        RegistryOption.from_kwargs('sort',
 
4435
            'Sort tags by different criteria.', title='Sorting',
 
4436
            alpha='Sort tags lexicographically (default).',
 
4437
            time='Sort tags chronologically.',
 
4438
            ),
 
4439
        'show-ids',
4167
4440
    ]
4168
4441
 
4169
4442
    @display_command
4170
4443
    def run(self,
4171
4444
            directory='.',
 
4445
            sort='alpha',
 
4446
            show_ids=False,
4172
4447
            ):
4173
4448
        branch, relpath = Branch.open_containing(directory)
4174
 
        for tag_name, target in sorted(branch.tags.get_tag_dict().items()):
4175
 
            self.outf.write('%-20s %s\n' % (tag_name, target))
 
4449
        tags = branch.tags.get_tag_dict().items()
 
4450
        if not tags:
 
4451
            return
 
4452
        if sort == 'alpha':
 
4453
            tags.sort()
 
4454
        elif sort == 'time':
 
4455
            timestamps = {}
 
4456
            for tag, revid in tags:
 
4457
                try:
 
4458
                    revobj = branch.repository.get_revision(revid)
 
4459
                except errors.NoSuchRevision:
 
4460
                    timestamp = sys.maxint # place them at the end
 
4461
                else:
 
4462
                    timestamp = revobj.timestamp
 
4463
                timestamps[revid] = timestamp
 
4464
            tags.sort(key=lambda x: timestamps[x[1]])
 
4465
        if not show_ids:
 
4466
            # [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
 
4467
            revno_map = branch.get_revision_id_to_revno_map()
 
4468
            tags = [ (tag, '.'.join(map(str, revno_map.get(revid, ('?',)))))
 
4469
                        for tag, revid in tags ]
 
4470
        for tag, revspec in tags:
 
4471
            self.outf.write('%-20s %s\n' % (tag, revspec))
4176
4472
 
4177
4473
 
4178
4474
class cmd_reconfigure(Command):
4189
4485
    If none of these is available, --bind-to must be specified.
4190
4486
    """
4191
4487
 
 
4488
    _see_also = ['branches', 'checkouts', 'standalone-trees', 'working-trees']
4192
4489
    takes_args = ['location?']
4193
4490
    takes_options = [RegistryOption.from_kwargs('target_type',
4194
4491
                     title='Target type',
4195
4492
                     help='The type to reconfigure the directory to.',
4196
4493
                     value_switches=True, enum_switch=False,
4197
 
                     branch='Reconfigure to a branch.',
4198
 
                     tree='Reconfigure to a tree.',
4199
 
                     checkout='Reconfigure to a checkout.'),
 
4494
                     branch='Reconfigure to be an unbound branch '
 
4495
                        'with no working tree.',
 
4496
                     tree='Reconfigure to be an unbound branch '
 
4497
                        'with a working tree.',
 
4498
                     checkout='Reconfigure to be a bound branch '
 
4499
                        'with a working tree.',
 
4500
                     lightweight_checkout='Reconfigure to be a lightweight'
 
4501
                     ' checkout (with no local history).',
 
4502
                     standalone='Reconfigure to be a standalone branch '
 
4503
                        '(i.e. stop using shared repository).',
 
4504
                     use_shared='Reconfigure to use a shared repository.'),
4200
4505
                     Option('bind-to', help='Branch to bind checkout to.',
4201
4506
                            type=str),
4202
4507
                     Option('force',
4215
4520
        elif target_type == 'checkout':
4216
4521
            reconfiguration = reconfigure.Reconfigure.to_checkout(directory,
4217
4522
                                                                  bind_to)
 
4523
        elif target_type == 'lightweight-checkout':
 
4524
            reconfiguration = reconfigure.Reconfigure.to_lightweight_checkout(
 
4525
                directory, bind_to)
 
4526
        elif target_type == 'use-shared':
 
4527
            reconfiguration = reconfigure.Reconfigure.to_use_shared(directory)
 
4528
        elif target_type == 'standalone':
 
4529
            reconfiguration = reconfigure.Reconfigure.to_standalone(directory)
4218
4530
        reconfiguration.apply(force)
4219
4531
 
4220
4532
 
 
4533
class cmd_switch(Command):
 
4534
    """Set the branch of a checkout and update.
 
4535
    
 
4536
    For lightweight checkouts, this changes the branch being referenced.
 
4537
    For heavyweight checkouts, this checks that there are no local commits
 
4538
    versus the current bound branch, then it makes the local branch a mirror
 
4539
    of the new location and binds to it.
 
4540
    
 
4541
    In both cases, the working tree is updated and uncommitted changes
 
4542
    are merged. The user can commit or revert these as they desire.
 
4543
 
 
4544
    Pending merges need to be committed or reverted before using switch.
 
4545
 
 
4546
    The path to the branch to switch to can be specified relative to the parent
 
4547
    directory of the current branch. For example, if you are currently in a
 
4548
    checkout of /path/to/branch, specifying 'newbranch' will find a branch at
 
4549
    /path/to/newbranch.
 
4550
    """
 
4551
 
 
4552
    takes_args = ['to_location']
 
4553
    takes_options = [Option('force',
 
4554
                        help='Switch even if local commits will be lost.')
 
4555
                     ]
 
4556
 
 
4557
    def run(self, to_location, force=False):
 
4558
        from bzrlib import switch
 
4559
        tree_location = '.'
 
4560
        control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
 
4561
        try:
 
4562
            to_branch = Branch.open(to_location)
 
4563
        except errors.NotBranchError:
 
4564
            to_branch = Branch.open(
 
4565
                control_dir.open_branch().base + '../' + to_location)
 
4566
        switch.switch(control_dir, to_branch, force)
 
4567
        note('Switched to branch: %s',
 
4568
            urlutils.unescape_for_display(to_branch.base, 'utf-8'))
 
4569
 
 
4570
 
 
4571
class cmd_hooks(Command):
 
4572
    """Show a branch's currently registered hooks.
 
4573
    """
 
4574
 
 
4575
    hidden = True
 
4576
    takes_args = ['path?']
 
4577
 
 
4578
    def run(self, path=None):
 
4579
        if path is None:
 
4580
            path = '.'
 
4581
        branch_hooks = Branch.open(path).hooks
 
4582
        for hook_type in branch_hooks:
 
4583
            hooks = branch_hooks[hook_type]
 
4584
            self.outf.write("%s:\n" % (hook_type,))
 
4585
            if hooks:
 
4586
                for hook in hooks:
 
4587
                    self.outf.write("  %s\n" %
 
4588
                                    (branch_hooks.get_hook_name(hook),))
 
4589
            else:
 
4590
                self.outf.write("  <no hooks installed>\n")
 
4591
 
 
4592
 
4221
4593
def _create_prefix(cur_transport):
4222
4594
    needed = [cur_transport]
4223
4595
    # Recurse upwards until we can create a directory successfully
4240
4612
        cur_transport.ensure_base()
4241
4613
 
4242
4614
 
4243
 
def _get_mergeable_helper(location):
4244
 
    """Get a merge directive or bundle if 'location' points to one.
4245
 
 
4246
 
    Try try to identify a bundle and returns its mergeable form. If it's not,
4247
 
    we return the tried transport anyway so that it can reused to access the
4248
 
    branch
4249
 
 
4250
 
    :param location: can point to a bundle or a branch.
4251
 
 
4252
 
    :return: mergeable, transport
4253
 
    """
4254
 
    mergeable = None
4255
 
    url = urlutils.normalize_url(location)
4256
 
    url, filename = urlutils.split(url, exclude_trailing_slash=False)
4257
 
    location_transport = transport.get_transport(url)
4258
 
    if filename:
4259
 
        try:
4260
 
            # There may be redirections but we ignore the intermediate
4261
 
            # and final transports used
4262
 
            read = bundle.read_mergeable_from_transport
4263
 
            mergeable, t = read(location_transport, filename)
4264
 
        except errors.NotABundle:
4265
 
            # Continue on considering this url a Branch but adjust the
4266
 
            # location_transport
4267
 
            location_transport = location_transport.clone(filename)
4268
 
    return mergeable, location_transport
4269
 
 
4270
 
 
4271
4615
# these get imported and then picked up by the scan for cmd_*
4272
4616
# TODO: Some more consistent way to split command definitions across files;
4273
4617
# we do need to load at least some information about them to know of 
4279
4623
    cmd_bundle_info,
4280
4624
    )
4281
4625
from bzrlib.sign_my_commits import cmd_sign_my_commits
4282
 
from bzrlib.weave_commands import cmd_versionedfile_list, cmd_weave_join, \
 
4626
from bzrlib.weave_commands import cmd_versionedfile_list, \
4283
4627
        cmd_weave_plan_merge, cmd_weave_merge_text