~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/builtins.py

  • Committer: Martin Pool
  • Date: 2008-04-30 08:04:11 UTC
  • mto: This revision was merged to the branch mainline in revision 3396.
  • Revision ID: mbp@sourcefrog.net-20080430080411-imrex2wtwpb9eivj
_format_version_tuple can take a 3-tuple

Show diffs side-by-side

added added

removed removed

Lines of Context:
17
17
"""builtin bzr commands"""
18
18
 
19
19
import os
 
20
from StringIO import StringIO
20
21
 
21
22
from bzrlib.lazy_import import lazy_import
22
23
lazy_import(globals(), """
23
24
import codecs
24
 
import errno
25
25
import sys
26
 
import tempfile
 
26
import time
27
27
 
28
28
import bzrlib
29
29
from bzrlib import (
30
 
    branch,
 
30
    bugtracker,
31
31
    bundle,
32
32
    bzrdir,
33
33
    delta,
34
34
    config,
35
35
    errors,
 
36
    globbing,
36
37
    ignores,
37
38
    log,
38
39
    merge as _mod_merge,
 
40
    merge_directive,
39
41
    osutils,
40
 
    repository,
 
42
    reconfigure,
 
43
    revision as _mod_revision,
41
44
    symbol_versioning,
42
45
    transport,
43
46
    tree as _mod_tree,
45
48
    urlutils,
46
49
    )
47
50
from bzrlib.branch import Branch
48
 
from bzrlib.bundle.apply_bundle import install_bundle, merge_bundle
49
51
from bzrlib.conflicts import ConflictList
50
 
from bzrlib.revision import common_ancestor
51
52
from bzrlib.revisionspec import RevisionSpec
 
53
from bzrlib.smtp_connection import SMTPConnection
52
54
from bzrlib.workingtree import WorkingTree
53
55
""")
54
56
 
55
57
from bzrlib.commands import Command, display_command
56
 
from bzrlib.option import Option, RegistryOption
57
 
from bzrlib.progress import DummyProgress, ProgressPhase
58
 
from bzrlib.trace import mutter, note, log_error, warning, is_quiet, info
 
58
from bzrlib.option import ListOption, Option, RegistryOption, custom_help
 
59
from bzrlib.trace import mutter, note, warning, is_quiet, info
59
60
 
60
61
 
61
62
def tree_files(file_list, default_branch=u'.'):
142
143
    unknown
143
144
        Not versioned and not matching an ignore pattern.
144
145
 
145
 
    To see ignored files use 'bzr ignored'.  For details in the
 
146
    To see ignored files use 'bzr ignored'.  For details on the
146
147
    changes to file texts, use 'bzr diff'.
147
148
    
148
 
    --short gives a status flags for each item, similar to the SVN's status
149
 
    command.
150
 
 
151
 
    Column 1: versioning / renames
152
 
      + File versioned
153
 
      - File unversioned
154
 
      R File renamed
155
 
      ? File unknown
156
 
      C File has conflicts
157
 
      P Entry for a pending merge (not a file)
158
 
 
159
 
    Column 2: Contents
160
 
      N File created
161
 
      D File deleted
162
 
      K File kind changed
163
 
      M File modified
164
 
 
165
 
    Column 3: Execute
166
 
      * The execute bit was changed
 
149
    Note that --short or -S gives status flags for each item, similar
 
150
    to Subversion's status command. To get output similar to svn -q,
 
151
    use bzr -SV.
167
152
 
168
153
    If no arguments are specified, the status of the entire working
169
154
    directory is shown.  Otherwise, only the status of the specified
177
162
    # TODO: --no-recurse, --recurse options
178
163
    
179
164
    takes_args = ['file*']
180
 
    takes_options = ['show-ids', 'revision', 'short']
 
165
    takes_options = ['show-ids', 'revision', 'change',
 
166
                     Option('short', help='Use short status indicators.',
 
167
                            short_name='S'),
 
168
                     Option('versioned', help='Only show versioned files.',
 
169
                            short_name='V'),
 
170
                     Option('no-pending', help='Don\'t show pending merges.',
 
171
                           ),
 
172
                     ]
181
173
    aliases = ['st', 'stat']
182
174
 
183
175
    encoding_type = 'replace'
 
176
    _see_also = ['diff', 'revert', 'status-flags']
184
177
    
185
178
    @display_command
186
 
    def run(self, show_ids=False, file_list=None, revision=None, short=False):
 
179
    def run(self, show_ids=False, file_list=None, revision=None, short=False,
 
180
            versioned=False, no_pending=False):
187
181
        from bzrlib.status import show_tree_status
188
182
 
 
183
        if revision and len(revision) > 2:
 
184
            raise errors.BzrCommandError('bzr status --revision takes exactly'
 
185
                                         ' one or two revision specifiers')
 
186
 
189
187
        tree, file_list = tree_files(file_list)
190
188
            
191
189
        show_tree_status(tree, show_ids=show_ids,
192
190
                         specific_files=file_list, revision=revision,
193
 
                         to_file=self.outf,
194
 
                         short=short)
 
191
                         to_file=self.outf, short=short, versioned=versioned,
 
192
                         show_pending=not no_pending)
195
193
 
196
194
 
197
195
class cmd_cat_revision(Command):
209
207
    
210
208
    @display_command
211
209
    def run(self, revision_id=None, revision=None):
212
 
 
213
210
        if revision_id is not None and revision is not None:
214
211
            raise errors.BzrCommandError('You can only supply one of'
215
212
                                         ' revision_id or --revision')
220
217
 
221
218
        # TODO: jam 20060112 should cat-revision always output utf-8?
222
219
        if revision_id is not None:
 
220
            revision_id = osutils.safe_revision_id(revision_id, warn=False)
223
221
            self.outf.write(b.repository.get_revision_xml(revision_id).decode('utf-8'))
224
222
        elif revision is not None:
225
223
            for rev in revision:
226
224
                if rev is None:
227
225
                    raise errors.BzrCommandError('You cannot specify a NULL'
228
226
                                                 ' revision.')
229
 
                revno, rev_id = rev.in_history(b)
 
227
                rev_id = rev.as_revision_id(b)
230
228
                self.outf.write(b.repository.get_revision_xml(rev_id).decode('utf-8'))
231
229
    
232
230
 
235
233
 
236
234
    Since a lightweight checkout is little more than a working tree
237
235
    this will refuse to run against one.
 
236
 
 
237
    To re-create the working tree, use "bzr checkout".
238
238
    """
 
239
    _see_also = ['checkout', 'working-trees']
239
240
 
240
241
    takes_args = ['location?']
241
242
 
265
266
    This is equal to the number of revisions on this branch.
266
267
    """
267
268
 
 
269
    _see_also = ['info']
268
270
    takes_args = ['location?']
269
271
 
270
272
    @display_command
289
291
        if revision_info_list is not None:
290
292
            for rev in revision_info_list:
291
293
                revs.append(RevisionSpec.from_string(rev))
 
294
 
 
295
        b = Branch.open_containing(u'.')[0]
 
296
 
292
297
        if len(revs) == 0:
293
 
            raise errors.BzrCommandError('You must supply a revision identifier')
294
 
 
295
 
        b = WorkingTree.open_containing(u'.')[0].branch
 
298
            revs.append(RevisionSpec.from_string('-1'))
296
299
 
297
300
        for rev in revs:
298
 
            revinfo = rev.in_history(b)
299
 
            if revinfo.revno is None:
300
 
                print '     %s' % revinfo.rev_id
301
 
            else:
302
 
                print '%4d %s' % (revinfo.revno, revinfo.rev_id)
 
301
            revision_id = rev.as_revision_id(b)
 
302
            try:
 
303
                revno = '%4d' % (b.revision_id_to_revno(revision_id))
 
304
            except errors.NoSuchRevision:
 
305
                dotted_map = b.get_revision_id_to_revno_map()
 
306
                revno = '.'.join(str(i) for i in dotted_map[revision_id])
 
307
            print '%s %s' % (revno, revision_id)
303
308
 
304
309
    
305
310
class cmd_add(Command):
330
335
 
331
336
    --file-ids-from will try to use the file ids from the supplied path.
332
337
    It looks up ids trying to find a matching parent directory with the
333
 
    same filename, and then by pure path.
 
338
    same filename, and then by pure path. This option is rarely needed
 
339
    but can be useful when adding the same logical file into two
 
340
    branches that will be merged later (without showing the two different
 
341
    adds as a conflict). It is also useful when merging another project
 
342
    into a subdirectory of this one.
334
343
    """
335
344
    takes_args = ['file*']
336
 
    takes_options = ['no-recurse', 'dry-run', 'verbose',
337
 
                     Option('file-ids-from', type=unicode,
338
 
                            help='Lookup file ids from here')]
 
345
    takes_options = [
 
346
        Option('no-recurse',
 
347
               help="Don't recursively add the contents of directories."),
 
348
        Option('dry-run',
 
349
               help="Show what would be done, but don't actually do anything."),
 
350
        'verbose',
 
351
        Option('file-ids-from',
 
352
               type=unicode,
 
353
               help='Lookup file ids from this tree.'),
 
354
        ]
339
355
    encoding_type = 'replace'
 
356
    _see_also = ['remove']
340
357
 
341
358
    def run(self, file_list, no_recurse=False, dry_run=False, verbose=False,
342
359
            file_ids_from=None):
343
360
        import bzrlib.add
344
361
 
 
362
        base_tree = None
345
363
        if file_ids_from is not None:
346
364
            try:
347
365
                base_tree, base_path = WorkingTree.open_containing(
357
375
            action = bzrlib.add.AddAction(to_file=self.outf,
358
376
                should_print=(not is_quiet()))
359
377
 
360
 
        added, ignored = bzrlib.add.smart_add(file_list, not no_recurse,
361
 
                                              action=action, save=not dry_run)
 
378
        if base_tree:
 
379
            base_tree.lock_read()
 
380
        try:
 
381
            file_list = self._maybe_expand_globs(file_list)
 
382
            if file_list:
 
383
                tree = WorkingTree.open_containing(file_list[0])[0]
 
384
            else:
 
385
                tree = WorkingTree.open_containing(u'.')[0]
 
386
            added, ignored = tree.smart_add(file_list, not
 
387
                no_recurse, action=action, save=not dry_run)
 
388
        finally:
 
389
            if base_tree is not None:
 
390
                base_tree.unlock()
362
391
        if len(ignored) > 0:
363
392
            if verbose:
364
393
                for glob in sorted(ignored.keys()):
414
443
 
415
444
    It is also possible to restrict the list of files to a specific
416
445
    set. For example: bzr inventory --show-ids this/file
417
 
 
418
 
    See also: bzr ls
419
446
    """
420
447
 
421
448
    hidden = True
422
 
 
423
 
    takes_options = ['revision', 'show-ids', 'kind']
424
 
 
 
449
    _see_also = ['ls']
 
450
    takes_options = [
 
451
        'revision',
 
452
        'show-ids',
 
453
        Option('kind',
 
454
               help='List entries of a particular kind: file, directory, symlink.',
 
455
               type=unicode),
 
456
        ]
425
457
    takes_args = ['file*']
426
458
 
427
459
    @display_command
428
460
    def run(self, revision=None, show_ids=False, kind=None, file_list=None):
429
461
        if kind and kind not in ['file', 'directory', 'symlink']:
430
 
            raise errors.BzrCommandError('invalid kind specified')
 
462
            raise errors.BzrCommandError('invalid kind %r specified' % (kind,))
431
463
 
432
464
        work_tree, file_list = tree_files(file_list)
433
 
 
434
 
        if revision is not None:
435
 
            if len(revision) > 1:
436
 
                raise errors.BzrCommandError('bzr inventory --revision takes'
437
 
                                             ' exactly one revision identifier')
438
 
            revision_id = revision[0].in_history(work_tree.branch).rev_id
439
 
            tree = work_tree.branch.repository.revision_tree(revision_id)
440
 
                        
441
 
            # We include work_tree as well as 'tree' here
442
 
            # So that doing '-r 10 path/foo' will lookup whatever file
443
 
            # exists now at 'path/foo' even if it has been renamed, as
444
 
            # well as whatever files existed in revision 10 at path/foo
445
 
            trees = [tree, work_tree]
446
 
        else:
447
 
            tree = work_tree
448
 
            trees = [tree]
449
 
 
450
 
        if file_list is not None:
451
 
            file_ids = _mod_tree.find_ids_across_trees(file_list, trees,
452
 
                                                      require_versioned=True)
453
 
            # find_ids_across_trees may include some paths that don't
454
 
            # exist in 'tree'.
455
 
            entries = sorted((tree.id2path(file_id), tree.inventory[file_id])
456
 
                             for file_id in file_ids if file_id in tree)
457
 
        else:
458
 
            entries = tree.inventory.entries()
 
465
        work_tree.lock_read()
 
466
        try:
 
467
            if revision is not None:
 
468
                if len(revision) > 1:
 
469
                    raise errors.BzrCommandError(
 
470
                        'bzr inventory --revision takes exactly one revision'
 
471
                        ' identifier')
 
472
                revision_id = revision[0].as_revision_id(work_tree.branch)
 
473
                tree = work_tree.branch.repository.revision_tree(revision_id)
 
474
 
 
475
                extra_trees = [work_tree]
 
476
                tree.lock_read()
 
477
            else:
 
478
                tree = work_tree
 
479
                extra_trees = []
 
480
 
 
481
            if file_list is not None:
 
482
                file_ids = tree.paths2ids(file_list, trees=extra_trees,
 
483
                                          require_versioned=True)
 
484
                # find_ids_across_trees may include some paths that don't
 
485
                # exist in 'tree'.
 
486
                entries = sorted((tree.id2path(file_id), tree.inventory[file_id])
 
487
                                 for file_id in file_ids if file_id in tree)
 
488
            else:
 
489
                entries = tree.inventory.entries()
 
490
        finally:
 
491
            tree.unlock()
 
492
            if tree is not work_tree:
 
493
                work_tree.unlock()
459
494
 
460
495
        for path, entry in entries:
461
496
            if kind and kind != entry.kind:
470
505
class cmd_mv(Command):
471
506
    """Move or rename a file.
472
507
 
473
 
    usage:
 
508
    :Usage:
474
509
        bzr mv OLDNAME NEWNAME
 
510
 
475
511
        bzr mv SOURCE... DESTINATION
476
512
 
477
513
    If the last argument is a versioned directory, all the other names
488
524
    """
489
525
 
490
526
    takes_args = ['names*']
491
 
    takes_options = [Option("after", help="move only the bzr identifier"
492
 
        " of the file (file has already been moved). Use this flag if"
493
 
        " bzr is not able to detect this itself.")]
 
527
    takes_options = [Option("after", help="Move only the bzr identifier"
 
528
        " of the file, because the file has already been moved."),
 
529
        ]
494
530
    aliases = ['move', 'rename']
495
531
    encoding_type = 'replace'
496
532
 
501
537
        if len(names_list) < 2:
502
538
            raise errors.BzrCommandError("missing file argument")
503
539
        tree, rel_names = tree_files(names_list)
504
 
        
505
 
        if os.path.isdir(names_list[-1]):
 
540
        tree.lock_write()
 
541
        try:
 
542
            self._run(tree, names_list, rel_names, after)
 
543
        finally:
 
544
            tree.unlock()
 
545
 
 
546
    def _run(self, tree, names_list, rel_names, after):
 
547
        into_existing = osutils.isdir(names_list[-1])
 
548
        if into_existing and len(names_list) == 2:
 
549
            # special cases:
 
550
            # a. case-insensitive filesystem and change case of dir
 
551
            # b. move directory after the fact (if the source used to be
 
552
            #    a directory, but now doesn't exist in the working tree
 
553
            #    and the target is an existing directory, just rename it)
 
554
            if (not tree.case_sensitive
 
555
                and rel_names[0].lower() == rel_names[1].lower()):
 
556
                into_existing = False
 
557
            else:
 
558
                inv = tree.inventory
 
559
                from_id = tree.path2id(rel_names[0])
 
560
                if (not osutils.lexists(names_list[0]) and
 
561
                    from_id and inv.get_file_kind(from_id) == "directory"):
 
562
                    into_existing = False
 
563
        # move/rename
 
564
        if into_existing:
506
565
            # move into existing directory
507
566
            for pair in tree.move(rel_names[:-1], rel_names[-1], after=after):
508
567
                self.outf.write("%s => %s\n" % pair)
513
572
                                             ' directory')
514
573
            tree.rename_one(rel_names[0], rel_names[1], after=after)
515
574
            self.outf.write("%s => %s\n" % (rel_names[0], rel_names[1]))
516
 
            
517
 
    
 
575
 
 
576
 
518
577
class cmd_pull(Command):
519
578
    """Turn this branch into a mirror of another branch.
520
579
 
533
592
    that, you can omit the location to use the default.  To change the
534
593
    default, use --remember. The value will only be saved if the remote
535
594
    location can be accessed.
 
595
 
 
596
    Note: The location can be specified either in the form of a branch,
 
597
    or in the form of a path to a file containing a merge directive generated
 
598
    with bzr send.
536
599
    """
537
600
 
538
 
    takes_options = ['remember', 'overwrite', 'revision', 'verbose',
 
601
    _see_also = ['push', 'update', 'status-flags']
 
602
    takes_options = ['remember', 'overwrite', 'revision',
 
603
        custom_help('verbose',
 
604
            help='Show logs of pulled revisions.'),
539
605
        Option('directory',
540
 
            help='branch to pull into, '
541
 
                 'rather than the one containing the working directory',
 
606
            help='Branch to pull into, '
 
607
                 'rather than the one containing the working directory.',
542
608
            short_name='d',
543
609
            type=unicode,
544
610
            ),
550
616
            revision=None, verbose=False,
551
617
            directory=None):
552
618
        # FIXME: too much stuff is in the command class
 
619
        revision_id = None
 
620
        mergeable = None
553
621
        if directory is None:
554
622
            directory = u'.'
555
623
        try:
559
627
            tree_to = None
560
628
            branch_to = Branch.open_containing(directory)[0]
561
629
 
562
 
        reader = None
 
630
        possible_transports = []
563
631
        if location is not None:
564
632
            try:
565
 
                reader = bundle.read_bundle_from_url(location)
 
633
                mergeable = bundle.read_mergeable_from_url(location,
 
634
                    possible_transports=possible_transports)
566
635
            except errors.NotABundle:
567
 
                pass # Continue on considering this url a Branch
 
636
                mergeable = None
568
637
 
569
638
        stored_loc = branch_to.get_parent()
570
639
        if location is None:
574
643
            else:
575
644
                display_url = urlutils.unescape_for_display(stored_loc,
576
645
                        self.outf.encoding)
577
 
                self.outf.write("Using saved location: %s\n" % display_url)
 
646
                if not is_quiet():
 
647
                    self.outf.write("Using saved location: %s\n" % display_url)
578
648
                location = stored_loc
579
649
 
580
 
        if reader is not None:
581
 
            install_bundle(branch_to.repository, reader)
 
650
        if mergeable is not None:
 
651
            if revision is not None:
 
652
                raise errors.BzrCommandError(
 
653
                    'Cannot use -r with merge directives or bundles')
 
654
            mergeable.install_revisions(branch_to.repository)
 
655
            base_revision_id, revision_id, verified = \
 
656
                mergeable.get_merge_request(branch_to.repository)
582
657
            branch_from = branch_to
583
658
        else:
584
 
            branch_from = Branch.open(location)
 
659
            branch_from = Branch.open(location,
 
660
                possible_transports=possible_transports)
585
661
 
586
662
            if branch_to.get_parent() is None or remember:
587
663
                branch_to.set_parent(branch_from.base)
588
664
 
589
 
        rev_id = None
590
 
        if revision is None:
591
 
            if reader is not None:
592
 
                rev_id = reader.target
593
 
        elif len(revision) == 1:
594
 
            rev_id = revision[0].in_history(branch_from).rev_id
595
 
        else:
596
 
            raise errors.BzrCommandError('bzr pull --revision takes one value.')
 
665
        if revision is not None:
 
666
            if len(revision) == 1:
 
667
                revision_id = revision[0].as_revision_id(branch_from)
 
668
            else:
 
669
                raise errors.BzrCommandError(
 
670
                    'bzr pull --revision takes one value.')
597
671
 
598
 
        old_rh = branch_to.revision_history()
 
672
        if verbose:
 
673
            old_rh = branch_to.revision_history()
599
674
        if tree_to is not None:
600
 
            count = tree_to.pull(branch_from, overwrite, rev_id,
601
 
                delta.ChangeReporter(tree_to.inventory))
 
675
            change_reporter = delta._ChangeReporter(
 
676
                unversioned_filter=tree_to.is_ignored)
 
677
            result = tree_to.pull(branch_from, overwrite, revision_id,
 
678
                                  change_reporter,
 
679
                                  possible_transports=possible_transports)
602
680
        else:
603
 
            count = branch_to.pull(branch_from, overwrite, rev_id)
604
 
        note('%d revision(s) pulled.' % (count,))
 
681
            result = branch_to.pull(branch_from, overwrite, revision_id)
605
682
 
 
683
        result.report(self.outf)
606
684
        if verbose:
607
685
            new_rh = branch_to.revision_history()
608
 
            if old_rh != new_rh:
609
 
                # Something changed
610
 
                from bzrlib.log import show_changed_revisions
611
 
                show_changed_revisions(branch_to, old_rh, new_rh,
 
686
            log.show_changed_revisions(branch_to, old_rh, new_rh,
612
687
                                       to_file=self.outf)
613
688
 
614
689
 
638
713
    location can be accessed.
639
714
    """
640
715
 
641
 
    takes_options = ['remember', 'overwrite', 'verbose',
 
716
    _see_also = ['pull', 'update', 'working-trees']
 
717
    takes_options = ['remember', 'overwrite', 'verbose', 'revision',
642
718
        Option('create-prefix',
643
719
               help='Create the path leading up to the branch '
644
 
                    'if it does not already exist'),
 
720
                    'if it does not already exist.'),
645
721
        Option('directory',
646
 
            help='branch to push from, '
647
 
                 'rather than the one containing the working directory',
 
722
            help='Branch to push from, '
 
723
                 'rather than the one containing the working directory.',
648
724
            short_name='d',
649
725
            type=unicode,
650
726
            ),
651
727
        Option('use-existing-dir',
652
728
               help='By default push will fail if the target'
653
729
                    ' directory exists, but does not already'
654
 
                    ' have a control directory. This flag will'
 
730
                    ' have a control directory.  This flag will'
655
731
                    ' allow push to proceed.'),
656
732
        ]
657
733
    takes_args = ['location?']
658
734
    encoding_type = 'replace'
659
735
 
660
736
    def run(self, location=None, remember=False, overwrite=False,
661
 
            create_prefix=False, verbose=False,
 
737
            create_prefix=False, verbose=False, revision=None,
662
738
            use_existing_dir=False,
663
739
            directory=None):
664
740
        # FIXME: Way too big!  Put this into a function called from the
677
753
                location = stored_loc
678
754
 
679
755
        to_transport = transport.get_transport(location)
680
 
        location_url = to_transport.base
681
 
 
682
 
        old_rh = []
683
 
        count = 0
684
756
 
685
757
        br_to = repository_to = dir_to = None
686
758
        try:
702
774
                # Found a branch, so we must have found a repository
703
775
                repository_to = br_to.repository
704
776
 
705
 
        old_rh = []
 
777
        if revision is not None:
 
778
            if len(revision) == 1:
 
779
                revision_id = revision[0].in_history(br_from).rev_id
 
780
            else:
 
781
                raise errors.BzrCommandError(
 
782
                    'bzr push --revision takes one value.')
 
783
        else:
 
784
            revision_id = br_from.last_revision()
 
785
 
 
786
        push_result = None
 
787
        if verbose:
 
788
            old_rh = []
706
789
        if dir_to is None:
 
790
            # The destination doesn't exist; create it.
707
791
            # XXX: Refactor the create_prefix/no_create_prefix code into a
708
792
            #      common helper function
 
793
 
 
794
            def make_directory(transport):
 
795
                transport.mkdir('.')
 
796
                return transport
 
797
 
 
798
            def redirected(redirected_transport, e, redirection_notice):
 
799
                return transport.get_transport(e.get_target_url())
 
800
 
709
801
            try:
710
 
                to_transport.mkdir('.')
 
802
                to_transport = transport.do_catching_redirections(
 
803
                    make_directory, to_transport, redirected)
711
804
            except errors.FileExists:
712
805
                if not use_existing_dir:
713
806
                    raise errors.BzrCommandError("Target directory %s"
721
814
                        "\nYou may supply --create-prefix to create all"
722
815
                        " leading parent directories."
723
816
                        % location)
724
 
 
725
 
                cur_transport = to_transport
726
 
                needed = [cur_transport]
727
 
                # Recurse upwards until we can create a directory successfully
728
 
                while True:
729
 
                    new_transport = cur_transport.clone('..')
730
 
                    if new_transport.base == cur_transport.base:
731
 
                        raise errors.BzrCommandError("Failed to create path"
732
 
                                                     " prefix for %s."
733
 
                                                     % location)
734
 
                    try:
735
 
                        new_transport.mkdir('.')
736
 
                    except errors.NoSuchFile:
737
 
                        needed.append(new_transport)
738
 
                        cur_transport = new_transport
739
 
                    else:
740
 
                        break
741
 
 
742
 
                # Now we only need to create child directories
743
 
                while needed:
744
 
                    cur_transport = needed.pop()
745
 
                    cur_transport.mkdir('.')
746
 
            
 
817
                _create_prefix(to_transport)
 
818
            except errors.TooManyRedirections:
 
819
                raise errors.BzrCommandError("Too many redirections trying "
 
820
                                             "to make %s." % location)
 
821
 
747
822
            # Now the target directory exists, but doesn't have a .bzr
748
823
            # directory. So we need to create it, along with any work to create
749
824
            # all of the dependent branches, etc.
750
 
            dir_to = br_from.bzrdir.clone(location_url,
751
 
                revision_id=br_from.last_revision())
 
825
            dir_to = br_from.bzrdir.clone_on_transport(to_transport,
 
826
                                                       revision_id=revision_id)
752
827
            br_to = dir_to.open_branch()
753
 
            count = br_to.last_revision_info()[0]
 
828
            # TODO: Some more useful message about what was copied
 
829
            note('Created new branch.')
754
830
            # We successfully created the target, remember it
755
831
            if br_from.get_push_location() is None or remember:
756
832
                br_from.set_push_location(br_to.base)
765
841
        elif br_to is None:
766
842
            # We have a repository but no branch, copy the revisions, and then
767
843
            # create a branch.
768
 
            last_revision_id = br_from.last_revision()
769
 
            repository_to.fetch(br_from.repository,
770
 
                                revision_id=last_revision_id)
771
 
            br_to = br_from.clone(dir_to, revision_id=last_revision_id)
772
 
            count = len(br_to.revision_history())
 
844
            repository_to.fetch(br_from.repository, revision_id=revision_id)
 
845
            br_to = br_from.clone(dir_to, revision_id=revision_id)
 
846
            note('Created new branch.')
773
847
            if br_from.get_push_location() is None or remember:
774
848
                br_from.set_push_location(br_to.base)
775
849
        else: # We have a valid to branch
777
851
            # we don't need to successfully push because of possible divergence.
778
852
            if br_from.get_push_location() is None or remember:
779
853
                br_from.set_push_location(br_to.base)
780
 
            old_rh = br_to.revision_history()
 
854
            if verbose:
 
855
                old_rh = br_to.revision_history()
781
856
            try:
782
857
                try:
783
858
                    tree_to = dir_to.open_workingtree()
784
859
                except errors.NotLocalUrl:
785
 
                    warning('This transport does not update the working '
786
 
                            'tree of: %s' % (br_to.base,))
787
 
                    count = br_from.push(br_to, overwrite)
 
860
                    warning("This transport does not update the working " 
 
861
                            "tree of: %s. See 'bzr help working-trees' for "
 
862
                            "more information." % br_to.base)
 
863
                    push_result = br_from.push(br_to, overwrite,
 
864
                                               stop_revision=revision_id)
788
865
                except errors.NoWorkingTree:
789
 
                    count = br_from.push(br_to, overwrite)
 
866
                    push_result = br_from.push(br_to, overwrite,
 
867
                                               stop_revision=revision_id)
790
868
                else:
791
869
                    tree_to.lock_write()
792
870
                    try:
793
 
                        count = br_from.push(tree_to.branch, overwrite)
 
871
                        push_result = br_from.push(tree_to.branch, overwrite,
 
872
                                                   stop_revision=revision_id)
794
873
                        tree_to.update()
795
874
                    finally:
796
875
                        tree_to.unlock()
797
876
            except errors.DivergedBranches:
798
877
                raise errors.BzrCommandError('These branches have diverged.'
799
878
                                        '  Try using "merge" and then "push".')
800
 
        note('%d revision(s) pushed.' % (count,))
801
 
 
802
 
        if verbose:
 
879
        if push_result is not None:
 
880
            push_result.report(self.outf)
 
881
        elif verbose:
803
882
            new_rh = br_to.revision_history()
804
883
            if old_rh != new_rh:
805
884
                # Something changed
806
885
                from bzrlib.log import show_changed_revisions
807
886
                show_changed_revisions(br_to, old_rh, new_rh,
808
887
                                       to_file=self.outf)
 
888
        else:
 
889
            # we probably did a clone rather than a push, so a message was
 
890
            # emitted above
 
891
            pass
809
892
 
810
893
 
811
894
class cmd_branch(Command):
813
896
 
814
897
    If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
815
898
    be used.  In other words, "branch ../foo/bar" will attempt to create ./bar.
 
899
    If the FROM_LOCATION has no / or path separator embedded, the TO_LOCATION
 
900
    is derived from the FROM_LOCATION by stripping a leading scheme or drive
 
901
    identifier, if any. For example, "branch lp:foo-bar" will attempt to
 
902
    create ./foo-bar.
816
903
 
817
904
    To retrieve the branch as of a particular revision, supply the --revision
818
905
    parameter, as in "branch foo/bar -r 5".
 
906
    """
819
907
 
820
 
    --basis is to speed up branching from remote branches.  When specified, it
821
 
    copies all the file-contents, inventory and revision data from the basis
822
 
    branch before copying anything from the remote branch.
823
 
    """
 
908
    _see_also = ['checkout']
824
909
    takes_args = ['from_location', 'to_location?']
825
 
    takes_options = ['revision', 'basis']
 
910
    takes_options = ['revision', Option('hardlink',
 
911
        help='Hard-link working tree files where possible.')]
826
912
    aliases = ['get', 'clone']
827
913
 
828
 
    def run(self, from_location, to_location=None, revision=None, basis=None):
 
914
    def run(self, from_location, to_location=None, revision=None,
 
915
            hardlink=False):
 
916
        from bzrlib.tag import _merge_tags_if_possible
829
917
        if revision is None:
830
918
            revision = [None]
831
919
        elif len(revision) > 1:
832
920
            raise errors.BzrCommandError(
833
921
                'bzr branch --revision takes exactly 1 revision value')
834
922
 
835
 
        br_from = Branch.open(from_location)
 
923
        accelerator_tree, br_from = bzrdir.BzrDir.open_tree_or_branch(
 
924
            from_location)
836
925
        br_from.lock_read()
837
926
        try:
838
 
            if basis is not None:
839
 
                basis_dir = bzrdir.BzrDir.open_containing(basis)[0]
840
 
            else:
841
 
                basis_dir = None
842
927
            if len(revision) == 1 and revision[0] is not None:
843
 
                revision_id = revision[0].in_history(br_from)[1]
 
928
                revision_id = revision[0].as_revision_id(br_from)
844
929
            else:
845
930
                # FIXME - wt.last_revision, fallback to branch, fall back to
846
931
                # None or perhaps NULL_REVISION to mean copy nothing
847
932
                # RBC 20060209
848
933
                revision_id = br_from.last_revision()
849
934
            if to_location is None:
850
 
                to_location = os.path.basename(from_location.rstrip("/\\"))
 
935
                to_location = urlutils.derive_to_location(from_location)
851
936
                name = None
852
937
            else:
853
938
                name = os.path.basename(to_location) + '\n'
863
948
                                             % to_location)
864
949
            try:
865
950
                # preserve whatever source format we have.
866
 
                dir = br_from.bzrdir.sprout(to_transport.base,
867
 
                        revision_id, basis_dir)
 
951
                dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
 
952
                                            possible_transports=[to_transport],
 
953
                                            accelerator_tree=accelerator_tree,
 
954
                                            hardlink=hardlink)
868
955
                branch = dir.open_branch()
869
956
            except errors.NoSuchRevision:
870
957
                to_transport.delete_tree('.')
871
958
                msg = "The branch %s has no revision %s." % (from_location, revision[0])
872
959
                raise errors.BzrCommandError(msg)
873
 
            except errors.UnlistableBranch:
874
 
                osutils.rmtree(to_location)
875
 
                msg = "The branch %s cannot be used as a --basis" % (basis,)
876
 
                raise errors.BzrCommandError(msg)
877
960
            if name:
878
961
                branch.control_files.put_utf8('branch-name', name)
 
962
            _merge_tags_if_possible(br_from, branch)
879
963
            note('Branched %d revision(s).' % branch.revno())
880
964
        finally:
881
965
            br_from.unlock()
891
975
    
892
976
    If the TO_LOCATION is omitted, the last component of the BRANCH_LOCATION will
893
977
    be used.  In other words, "checkout ../foo/bar" will attempt to create ./bar.
 
978
    If the BRANCH_LOCATION has no / or path separator embedded, the TO_LOCATION
 
979
    is derived from the BRANCH_LOCATION by stripping a leading scheme or drive
 
980
    identifier, if any. For example, "checkout lp:foo-bar" will attempt to
 
981
    create ./foo-bar.
894
982
 
895
983
    To retrieve the branch as of a particular revision, supply the --revision
896
984
    parameter, as in "checkout foo/bar -r 5". Note that this will be immediately
897
985
    out of date [so you cannot commit] but it may be useful (i.e. to examine old
898
986
    code.)
899
 
 
900
 
    --basis is to speed up checking out from remote branches.  When specified, it
901
 
    uses the inventory and file contents from the basis branch in preference to the
902
 
    branch being checked out.
903
 
 
904
 
    See "help checkouts" for more information on checkouts.
905
987
    """
 
988
 
 
989
    _see_also = ['checkouts', 'branch']
906
990
    takes_args = ['branch_location?', 'to_location?']
907
 
    takes_options = ['revision', # , 'basis']
 
991
    takes_options = ['revision',
908
992
                     Option('lightweight',
909
 
                            help="perform a lightweight checkout. Lightweight "
 
993
                            help="Perform a lightweight checkout.  Lightweight "
910
994
                                 "checkouts depend on access to the branch for "
911
 
                                 "every operation. Normal checkouts can perform "
 
995
                                 "every operation.  Normal checkouts can perform "
912
996
                                 "common operations like diff and status without "
913
997
                                 "such access, and also support local commits."
914
998
                            ),
 
999
                     Option('files-from', type=str,
 
1000
                            help="Get file contents from this tree."),
 
1001
                     Option('hardlink',
 
1002
                            help='Hard-link working tree files where possible.'
 
1003
                            ),
915
1004
                     ]
916
1005
    aliases = ['co']
917
1006
 
918
 
    def run(self, branch_location=None, to_location=None, revision=None, basis=None,
919
 
            lightweight=False):
 
1007
    def run(self, branch_location=None, to_location=None, revision=None,
 
1008
            lightweight=False, files_from=None, hardlink=False):
920
1009
        if revision is None:
921
1010
            revision = [None]
922
1011
        elif len(revision) > 1:
925
1014
        if branch_location is None:
926
1015
            branch_location = osutils.getcwd()
927
1016
            to_location = branch_location
928
 
        source = Branch.open(branch_location)
 
1017
        accelerator_tree, source = bzrdir.BzrDir.open_tree_or_branch(
 
1018
            branch_location)
 
1019
        if files_from is not None:
 
1020
            accelerator_tree = WorkingTree.open(files_from)
929
1021
        if len(revision) == 1 and revision[0] is not None:
930
 
            revision_id = revision[0].in_history(source)[1]
 
1022
            revision_id = revision[0].as_revision_id(source)
931
1023
        else:
932
1024
            revision_id = None
933
1025
        if to_location is None:
934
 
            to_location = os.path.basename(branch_location.rstrip("/\\"))
 
1026
            to_location = urlutils.derive_to_location(branch_location)
935
1027
        # if the source and to_location are the same, 
936
1028
        # and there is no working tree,
937
1029
        # then reconstitute a branch
940
1032
            try:
941
1033
                source.bzrdir.open_workingtree()
942
1034
            except errors.NoWorkingTree:
943
 
                source.bzrdir.create_workingtree()
 
1035
                source.bzrdir.create_workingtree(revision_id)
944
1036
                return
945
 
        try:
946
 
            os.mkdir(to_location)
947
 
        except OSError, e:
948
 
            if e.errno == errno.EEXIST:
949
 
                raise errors.BzrCommandError('Target directory "%s" already'
950
 
                                             ' exists.' % to_location)
951
 
            if e.errno == errno.ENOENT:
952
 
                raise errors.BzrCommandError('Parent of "%s" does not exist.'
953
 
                                             % to_location)
954
 
            else:
955
 
                raise
956
 
        source.create_checkout(to_location, revision_id, lightweight)
 
1037
        source.create_checkout(to_location, revision_id, lightweight,
 
1038
                               accelerator_tree, hardlink)
957
1039
 
958
1040
 
959
1041
class cmd_renames(Command):
962
1044
    # TODO: Option to show renames between two historical versions.
963
1045
 
964
1046
    # TODO: Only show renames under dir, rather than in the whole branch.
 
1047
    _see_also = ['status']
965
1048
    takes_args = ['dir?']
966
1049
 
967
1050
    @display_command
968
1051
    def run(self, dir=u'.'):
969
1052
        tree = WorkingTree.open_containing(dir)[0]
970
 
        old_inv = tree.basis_tree().inventory
971
 
        new_inv = tree.read_working_inventory()
972
 
        renames = list(_mod_tree.find_renames(old_inv, new_inv))
973
 
        renames.sort()
974
 
        for old_name, new_name in renames:
975
 
            self.outf.write("%s => %s\n" % (old_name, new_name))
 
1053
        tree.lock_read()
 
1054
        try:
 
1055
            new_inv = tree.inventory
 
1056
            old_tree = tree.basis_tree()
 
1057
            old_tree.lock_read()
 
1058
            try:
 
1059
                old_inv = old_tree.inventory
 
1060
                renames = list(_mod_tree.find_renames(old_inv, new_inv))
 
1061
                renames.sort()
 
1062
                for old_name, new_name in renames:
 
1063
                    self.outf.write("%s => %s\n" % (old_name, new_name))
 
1064
            finally:
 
1065
                old_tree.unlock()
 
1066
        finally:
 
1067
            tree.unlock()
976
1068
 
977
1069
 
978
1070
class cmd_update(Command):
985
1077
    If you want to discard your local changes, you can just do a 
986
1078
    'bzr revert' instead of 'bzr commit' after the update.
987
1079
    """
 
1080
 
 
1081
    _see_also = ['pull', 'working-trees', 'status-flags']
988
1082
    takes_args = ['dir?']
989
1083
    aliases = ['up']
990
1084
 
991
1085
    def run(self, dir='.'):
992
1086
        tree = WorkingTree.open_containing(dir)[0]
993
 
        master = tree.branch.get_master_branch()
 
1087
        possible_transports = []
 
1088
        master = tree.branch.get_master_branch(
 
1089
            possible_transports=possible_transports)
994
1090
        if master is not None:
995
1091
            tree.lock_write()
996
1092
        else:
997
1093
            tree.lock_tree_write()
998
1094
        try:
999
1095
            existing_pending_merges = tree.get_parent_ids()[1:]
1000
 
            last_rev = tree.last_revision()
1001
 
            if last_rev == tree.branch.last_revision():
 
1096
            last_rev = _mod_revision.ensure_null(tree.last_revision())
 
1097
            if last_rev == _mod_revision.ensure_null(
 
1098
                tree.branch.last_revision()):
1002
1099
                # may be up to date, check master too.
1003
 
                master = tree.branch.get_master_branch()
1004
 
                if master is None or last_rev == master.last_revision():
 
1100
                if master is None or last_rev == _mod_revision.ensure_null(
 
1101
                    master.last_revision()):
1005
1102
                    revno = tree.branch.revision_id_to_revno(last_rev)
1006
1103
                    note("Tree is up to date at revision %d." % (revno,))
1007
1104
                    return 0
1008
 
            conflicts = tree.update()
1009
 
            revno = tree.branch.revision_id_to_revno(tree.last_revision())
 
1105
            conflicts = tree.update(
 
1106
                delta._ChangeReporter(unversioned_filter=tree.is_ignored),
 
1107
                possible_transports=possible_transports)
 
1108
            revno = tree.branch.revision_id_to_revno(
 
1109
                _mod_revision.ensure_null(tree.last_revision()))
1010
1110
            note('Updated to revision %d.' % (revno,))
1011
1111
            if tree.get_parent_ids()[1:] != existing_pending_merges:
1012
1112
                note('Your local commits will now show as pending merges with '
1028
1128
 
1029
1129
    Branches and working trees will also report any missing revisions.
1030
1130
    """
 
1131
    _see_also = ['revno', 'working-trees', 'repositories']
1031
1132
    takes_args = ['location?']
1032
1133
    takes_options = ['verbose']
 
1134
    encoding_type = 'replace'
1033
1135
 
1034
1136
    @display_command
1035
1137
    def run(self, location=None, verbose=False):
 
1138
        if verbose:
 
1139
            noise_level = 2
 
1140
        else:
 
1141
            noise_level = 0
1036
1142
        from bzrlib.info import show_bzrdir_info
1037
1143
        show_bzrdir_info(bzrdir.BzrDir.open_containing(location)[0],
1038
 
                         verbose=verbose)
 
1144
                         verbose=noise_level, outfile=self.outf)
1039
1145
 
1040
1146
 
1041
1147
class cmd_remove(Command):
1042
 
    """Make a file unversioned.
 
1148
    """Remove files or directories.
1043
1149
 
1044
 
    This makes bzr stop tracking changes to a versioned file.  It does
1045
 
    not delete the working copy.
 
1150
    This makes bzr stop tracking changes to the specified files and
 
1151
    delete them if they can easily be recovered using revert.
1046
1152
 
1047
1153
    You can specify one or more files, and/or --new.  If you specify --new,
1048
1154
    only 'added' files will be removed.  If you specify both, then new files
1050
1156
    also new, they will also be removed.
1051
1157
    """
1052
1158
    takes_args = ['file*']
1053
 
    takes_options = ['verbose', Option('new', help='remove newly-added files')]
 
1159
    takes_options = ['verbose',
 
1160
        Option('new', help='Remove newly-added files.'),
 
1161
        RegistryOption.from_kwargs('file-deletion-strategy',
 
1162
            'The file deletion mode to be used.',
 
1163
            title='Deletion Strategy', value_switches=True, enum_switch=False,
 
1164
            safe='Only delete files if they can be'
 
1165
                 ' safely recovered (default).',
 
1166
            keep="Don't delete any files.",
 
1167
            force='Delete all the specified files, even if they can not be '
 
1168
                'recovered and even if they are non-empty directories.')]
1054
1169
    aliases = ['rm']
1055
1170
    encoding_type = 'replace'
1056
 
    
1057
 
    def run(self, file_list, verbose=False, new=False):
 
1171
 
 
1172
    def run(self, file_list, verbose=False, new=False,
 
1173
        file_deletion_strategy='safe'):
1058
1174
        tree, file_list = tree_files(file_list)
1059
 
        if new is False:
1060
 
            if file_list is None:
1061
 
                raise errors.BzrCommandError('Specify one or more files to'
1062
 
                                             ' remove, or use --new.')
1063
 
        else:
 
1175
 
 
1176
        if file_list is not None:
 
1177
            file_list = [f for f in file_list]
 
1178
        elif not new:
 
1179
            raise errors.BzrCommandError('Specify one or more files to'
 
1180
            ' remove, or use --new.')
 
1181
 
 
1182
        if new:
1064
1183
            added = tree.changes_from(tree.basis_tree(),
1065
1184
                specific_files=file_list).added
1066
1185
            file_list = sorted([f[0] for f in added], reverse=True)
1067
1186
            if len(file_list) == 0:
1068
1187
                raise errors.BzrCommandError('No matching files.')
1069
 
        tree.remove(file_list, verbose=verbose, to_file=self.outf)
 
1188
        tree.remove(file_list, verbose=verbose, to_file=self.outf,
 
1189
            keep_files=file_deletion_strategy=='keep',
 
1190
            force=file_deletion_strategy=='force')
1070
1191
 
1071
1192
 
1072
1193
class cmd_file_id(Command):
1078
1199
    """
1079
1200
 
1080
1201
    hidden = True
 
1202
    _see_also = ['inventory', 'ls']
1081
1203
    takes_args = ['filename']
1082
1204
 
1083
1205
    @display_command
1084
1206
    def run(self, filename):
1085
1207
        tree, relpath = WorkingTree.open_containing(filename)
1086
 
        i = tree.inventory.path2id(relpath)
 
1208
        i = tree.path2id(relpath)
1087
1209
        if i is None:
1088
1210
            raise errors.NotVersionedError(filename)
1089
1211
        else:
1103
1225
    @display_command
1104
1226
    def run(self, filename):
1105
1227
        tree, relpath = WorkingTree.open_containing(filename)
1106
 
        inv = tree.inventory
1107
 
        fid = inv.path2id(relpath)
 
1228
        fid = tree.path2id(relpath)
1108
1229
        if fid is None:
1109
1230
            raise errors.NotVersionedError(filename)
1110
 
        for fip in inv.get_idpath(fid):
1111
 
            self.outf.write(fip + '\n')
 
1231
        segments = osutils.splitpath(relpath)
 
1232
        for pos in range(1, len(segments) + 1):
 
1233
            path = osutils.joinpath(segments[:pos])
 
1234
            self.outf.write("%s\n" % tree.path2id(path))
1112
1235
 
1113
1236
 
1114
1237
class cmd_reconcile(Command):
1129
1252
 
1130
1253
    The branch *MUST* be on a listable system such as local disk or sftp.
1131
1254
    """
 
1255
 
 
1256
    _see_also = ['check']
1132
1257
    takes_args = ['branch?']
1133
1258
 
1134
1259
    def run(self, branch="."):
1139
1264
 
1140
1265
class cmd_revision_history(Command):
1141
1266
    """Display the list of revision ids on a branch."""
 
1267
 
 
1268
    _see_also = ['log']
1142
1269
    takes_args = ['location?']
1143
1270
 
1144
1271
    hidden = True
1153
1280
 
1154
1281
class cmd_ancestry(Command):
1155
1282
    """List all revisions merged into this branch."""
 
1283
 
 
1284
    _see_also = ['log', 'revision-history']
1156
1285
    takes_args = ['location?']
1157
1286
 
1158
1287
    hidden = True
1183
1312
 
1184
1313
    If there is a repository in a parent directory of the location, then 
1185
1314
    the history of the branch will be stored in the repository.  Otherwise
1186
 
    init creates a standalone branch which carries its own history in 
1187
 
    .bzr.
 
1315
    init creates a standalone branch which carries its own history
 
1316
    in the .bzr directory.
1188
1317
 
1189
1318
    If there is already a branch at the location but it has no working tree,
1190
1319
    the tree can be populated with 'bzr checkout'.
1191
1320
 
1192
 
    Recipe for importing a tree of files:
 
1321
    Recipe for importing a tree of files::
 
1322
 
1193
1323
        cd ~/project
1194
1324
        bzr init
1195
1325
        bzr add .
1196
1326
        bzr status
1197
 
        bzr commit -m 'imported project'
 
1327
        bzr commit -m "imported project"
1198
1328
    """
 
1329
 
 
1330
    _see_also = ['init-repository', 'branch', 'checkout']
1199
1331
    takes_args = ['location?']
1200
1332
    takes_options = [
 
1333
        Option('create-prefix',
 
1334
               help='Create the path leading up to the branch '
 
1335
                    'if it does not already exist.'),
1201
1336
         RegistryOption('format',
1202
1337
                help='Specify a format for this branch. '
1203
1338
                'See "help formats".',
1210
1345
                help='Never change revnos or the existing log.'
1211
1346
                '  Append revisions to it only.')
1212
1347
         ]
1213
 
    def run(self, location=None, format=None, append_revisions_only=False):
 
1348
    def run(self, location=None, format=None, append_revisions_only=False,
 
1349
            create_prefix=False):
1214
1350
        if format is None:
1215
1351
            format = bzrdir.format_registry.make_bzrdir('default')
1216
1352
        if location is None:
1223
1359
        # Just using os.mkdir, since I don't
1224
1360
        # believe that we want to create a bunch of
1225
1361
        # locations if the user supplies an extended path
1226
 
        # TODO: create-prefix
1227
 
        try:
1228
 
            to_transport.mkdir('.')
1229
 
        except errors.FileExists:
1230
 
            pass
1231
 
                    
1232
 
        try:
1233
 
            existing_bzrdir = bzrdir.BzrDir.open(location)
 
1362
        try:
 
1363
            to_transport.ensure_base()
 
1364
        except errors.NoSuchFile:
 
1365
            if not create_prefix:
 
1366
                raise errors.BzrCommandError("Parent directory of %s"
 
1367
                    " does not exist."
 
1368
                    "\nYou may supply --create-prefix to create all"
 
1369
                    " leading parent directories."
 
1370
                    % location)
 
1371
            _create_prefix(to_transport)
 
1372
 
 
1373
        try:
 
1374
            existing_bzrdir = bzrdir.BzrDir.open_from_transport(to_transport)
1234
1375
        except errors.NotBranchError:
1235
1376
            # really a NotBzrDir error...
1236
 
            branch = bzrdir.BzrDir.create_branch_convenience(location,
1237
 
                                                             format=format)
 
1377
            create_branch = bzrdir.BzrDir.create_branch_convenience
 
1378
            branch = create_branch(to_transport.base, format=format,
 
1379
                                   possible_transports=[to_transport])
1238
1380
        else:
1239
1381
            from bzrlib.transport.local import LocalTransport
1240
1382
            if existing_bzrdir.has_branch():
1256
1398
class cmd_init_repository(Command):
1257
1399
    """Create a shared repository to hold branches.
1258
1400
 
1259
 
    New branches created under the repository directory will store their revisions
1260
 
    in the repository, not in the branch directory, if the branch format supports
1261
 
    shared storage.
1262
 
 
1263
 
    example:
1264
 
        bzr init-repo repo
1265
 
        bzr init repo/trunk
1266
 
        bzr checkout --lightweight repo/trunk trunk-checkout
1267
 
        cd trunk-checkout
1268
 
        (add files here)
 
1401
    New branches created under the repository directory will store their
 
1402
    revisions in the repository, not in the branch directory.
 
1403
 
 
1404
    If the --no-trees option is used then the branches in the repository
 
1405
    will not have working trees by default.
 
1406
 
 
1407
    :Examples:
 
1408
        Create a shared repositories holding just branches::
 
1409
 
 
1410
            bzr init-repo --no-trees repo
 
1411
            bzr init repo/trunk
 
1412
 
 
1413
        Make a lightweight checkout elsewhere::
 
1414
 
 
1415
            bzr checkout --lightweight repo/trunk trunk-checkout
 
1416
            cd trunk-checkout
 
1417
            (add files here)
1269
1418
    """
 
1419
 
 
1420
    _see_also = ['init', 'branch', 'checkout', 'repositories']
1270
1421
    takes_args = ["location"]
1271
1422
    takes_options = [RegistryOption('format',
1272
1423
                            help='Specify a format for this repository. See'
1273
 
                                 ' "bzr help formats" for details',
 
1424
                                 ' "bzr help formats" for details.',
1274
1425
                            registry=bzrdir.format_registry,
1275
1426
                            converter=bzrdir.format_registry.make_bzrdir,
1276
1427
                            value_switches=True, title='Repository format'),
1277
 
                     Option('trees',
1278
 
                             help='Allows branches in repository to have'
1279
 
                             ' a working tree')]
 
1428
                     Option('no-trees',
 
1429
                             help='Branches in the repository will default to'
 
1430
                                  ' not having a working tree.'),
 
1431
                    ]
1280
1432
    aliases = ["init-repo"]
1281
 
    def run(self, location, format=None, trees=False):
 
1433
 
 
1434
    def run(self, location, format=None, no_trees=False):
1282
1435
        if format is None:
1283
1436
            format = bzrdir.format_registry.make_bzrdir('default')
1284
1437
 
1286
1439
            location = '.'
1287
1440
 
1288
1441
        to_transport = transport.get_transport(location)
1289
 
        try:
1290
 
            to_transport.mkdir('.')
1291
 
        except errors.FileExists:
1292
 
            pass
 
1442
        to_transport.ensure_base()
1293
1443
 
1294
1444
        newdir = format.initialize_on_transport(to_transport)
1295
1445
        repo = newdir.create_repository(shared=True)
1296
 
        repo.set_make_working_trees(trees)
 
1446
        repo.set_make_working_trees(not no_trees)
1297
1447
 
1298
1448
 
1299
1449
class cmd_diff(Command):
1300
 
    """Show differences in the working tree or between revisions.
 
1450
    """Show differences in the working tree, between revisions or branches.
1301
1451
    
1302
 
    If files are listed, only the changes in those files are listed.
1303
 
    Otherwise, all changes for the tree are listed.
 
1452
    If no arguments are given, all changes for the current tree are listed.
 
1453
    If files are given, only the changes in those files are listed.
 
1454
    Remote and multiple branches can be compared by using the --old and
 
1455
    --new options. If not provided, the default for both is derived from
 
1456
    the first argument, if any, or the current tree if no arguments are
 
1457
    given.
1304
1458
 
1305
1459
    "bzr diff -p1" is equivalent to "bzr diff --prefix old/:new/", and
1306
1460
    produces patches suitable for "patch -p1".
1307
1461
 
1308
 
    examples:
1309
 
        bzr diff
1310
 
            Shows the difference in the working tree versus the last commit
1311
 
        bzr diff -r1
1312
 
            Difference between the working tree and revision 1
1313
 
        bzr diff -r1..2
1314
 
            Difference between revision 2 and revision 1
1315
 
        bzr diff --diff-prefix old/:new/
1316
 
            Same as 'bzr diff' but prefix paths with old/ and new/
1317
 
        bzr diff bzr.mine bzr.dev
1318
 
            Show the differences between the two working trees
1319
 
        bzr diff foo.c
1320
 
            Show just the differences for 'foo.c'
 
1462
    :Exit values:
 
1463
        1 - changed
 
1464
        2 - unrepresentable changes
 
1465
        3 - error
 
1466
        0 - no change
 
1467
 
 
1468
    :Examples:
 
1469
        Shows the difference in the working tree versus the last commit::
 
1470
 
 
1471
            bzr diff
 
1472
 
 
1473
        Difference between the working tree and revision 1::
 
1474
 
 
1475
            bzr diff -r1
 
1476
 
 
1477
        Difference between revision 2 and revision 1::
 
1478
 
 
1479
            bzr diff -r1..2
 
1480
 
 
1481
        Difference between revision 2 and revision 1 for branch xxx::
 
1482
 
 
1483
            bzr diff -r1..2 xxx
 
1484
 
 
1485
        Show just the differences for file NEWS::
 
1486
 
 
1487
            bzr diff NEWS
 
1488
 
 
1489
        Show the differences in working tree xxx for file NEWS::
 
1490
 
 
1491
            bzr diff xxx/NEWS
 
1492
 
 
1493
        Show the differences from branch xxx to this working tree:
 
1494
 
 
1495
            bzr diff --old xxx
 
1496
 
 
1497
        Show the differences between two branches for file NEWS::
 
1498
 
 
1499
            bzr diff --old xxx --new yyy NEWS
 
1500
 
 
1501
        Same as 'bzr diff' but prefix paths with old/ and new/::
 
1502
 
 
1503
            bzr diff --prefix old/:new/
1321
1504
    """
1322
 
    # TODO: Option to use external diff command; could be GNU diff, wdiff,
1323
 
    #       or a graphical diff.
1324
 
 
1325
 
    # TODO: Python difflib is not exactly the same as unidiff; should
1326
 
    #       either fix it up or prefer to use an external diff.
1327
 
 
1328
 
    # TODO: Selected-file diff is inefficient and doesn't show you
1329
 
    #       deleted files.
1330
 
 
1331
 
    # TODO: This probably handles non-Unix newlines poorly.
1332
 
 
 
1505
    _see_also = ['status']
1333
1506
    takes_args = ['file*']
1334
 
    takes_options = ['revision', 'diff-options',
 
1507
    takes_options = [
 
1508
        Option('diff-options', type=str,
 
1509
               help='Pass these options to the external diff program.'),
1335
1510
        Option('prefix', type=str,
1336
1511
               short_name='p',
1337
 
               help='Set prefixes to added to old and new filenames, as '
1338
 
                    'two values separated by a colon.'),
 
1512
               help='Set prefixes added to old and new filenames, as '
 
1513
                    'two values separated by a colon. (eg "old/:new/").'),
 
1514
        Option('old',
 
1515
            help='Branch/tree to compare from.',
 
1516
            type=unicode,
 
1517
            ),
 
1518
        Option('new',
 
1519
            help='Branch/tree to compare to.',
 
1520
            type=unicode,
 
1521
            ),
 
1522
        'revision',
 
1523
        'change',
 
1524
        Option('using',
 
1525
            help='Use this command to compare files.',
 
1526
            type=unicode,
 
1527
            ),
1339
1528
        ]
1340
1529
    aliases = ['di', 'dif']
1341
1530
    encoding_type = 'exact'
1342
1531
 
1343
1532
    @display_command
1344
1533
    def run(self, revision=None, file_list=None, diff_options=None,
1345
 
            prefix=None):
1346
 
        from bzrlib.diff import diff_cmd_helper, show_diff_trees
 
1534
            prefix=None, old=None, new=None, using=None):
 
1535
        from bzrlib.diff import _get_trees_to_diff, show_diff_trees
1347
1536
 
1348
1537
        if (prefix is None) or (prefix == '0'):
1349
1538
            # diff -p0 format
1355
1544
        elif ':' in prefix:
1356
1545
            old_label, new_label = prefix.split(":")
1357
1546
        else:
1358
 
            raise BzrCommandError(
1359
 
                "--prefix expects two values separated by a colon")
 
1547
            raise errors.BzrCommandError(
 
1548
                '--prefix expects two values separated by a colon'
 
1549
                ' (eg "old/:new/")')
1360
1550
 
1361
1551
        if revision and len(revision) > 2:
1362
1552
            raise errors.BzrCommandError('bzr diff --revision takes exactly'
1363
1553
                                         ' one or two revision specifiers')
1364
 
        
1365
 
        try:
1366
 
            tree1, file_list = internal_tree_files(file_list)
1367
 
            tree2 = None
1368
 
            b = None
1369
 
            b2 = None
1370
 
        except errors.FileInWrongBranch:
1371
 
            if len(file_list) != 2:
1372
 
                raise errors.BzrCommandError("Files are in different branches")
1373
 
 
1374
 
            tree1, file1 = WorkingTree.open_containing(file_list[0])
1375
 
            tree2, file2 = WorkingTree.open_containing(file_list[1])
1376
 
            if file1 != "" or file2 != "":
1377
 
                # FIXME diff those two files. rbc 20051123
1378
 
                raise errors.BzrCommandError("Files are in different branches")
1379
 
            file_list = None
1380
 
        except errors.NotBranchError:
1381
 
            if (revision is not None and len(revision) == 2
1382
 
                and not revision[0].needs_branch()
1383
 
                and not revision[1].needs_branch()):
1384
 
                # If both revision specs include a branch, we can
1385
 
                # diff them without needing a local working tree
1386
 
                tree1, tree2 = None, None
1387
 
            else:
1388
 
                raise
1389
 
 
1390
 
        if tree2 is not None:
1391
 
            if revision is not None:
1392
 
                # FIXME: but there should be a clean way to diff between
1393
 
                # non-default versions of two trees, it's not hard to do
1394
 
                # internally...
1395
 
                raise errors.BzrCommandError(
1396
 
                        "Sorry, diffing arbitrary revisions across branches "
1397
 
                        "is not implemented yet")
1398
 
            return show_diff_trees(tree1, tree2, sys.stdout, 
1399
 
                                   specific_files=file_list,
1400
 
                                   external_diff_options=diff_options,
1401
 
                                   old_label=old_label, new_label=new_label)
1402
 
 
1403
 
        return diff_cmd_helper(tree1, file_list, diff_options,
1404
 
                               revision_specs=revision,
1405
 
                               old_label=old_label, new_label=new_label)
 
1554
 
 
1555
        old_tree, new_tree, specific_files, extra_trees = \
 
1556
                _get_trees_to_diff(file_list, revision, old, new)
 
1557
        return show_diff_trees(old_tree, new_tree, sys.stdout, 
 
1558
                               specific_files=specific_files,
 
1559
                               external_diff_options=diff_options,
 
1560
                               old_label=old_label, new_label=new_label,
 
1561
                               extra_trees=extra_trees, using=using)
1406
1562
 
1407
1563
 
1408
1564
class cmd_deleted(Command):
1414
1570
    # directories with readdir, rather than stating each one.  Same
1415
1571
    # level of effort but possibly much less IO.  (Or possibly not,
1416
1572
    # if the directories are very large...)
 
1573
    _see_also = ['status', 'ls']
1417
1574
    takes_options = ['show-ids']
1418
1575
 
1419
1576
    @display_command
1420
1577
    def run(self, show_ids=False):
1421
1578
        tree = WorkingTree.open_containing(u'.')[0]
1422
 
        old = tree.basis_tree()
1423
 
        for path, ie in old.inventory.iter_entries():
1424
 
            if not tree.has_id(ie.file_id):
1425
 
                self.outf.write(path)
1426
 
                if show_ids:
1427
 
                    self.outf.write(' ')
1428
 
                    self.outf.write(ie.file_id)
1429
 
                self.outf.write('\n')
 
1579
        tree.lock_read()
 
1580
        try:
 
1581
            old = tree.basis_tree()
 
1582
            old.lock_read()
 
1583
            try:
 
1584
                for path, ie in old.inventory.iter_entries():
 
1585
                    if not tree.has_id(ie.file_id):
 
1586
                        self.outf.write(path)
 
1587
                        if show_ids:
 
1588
                            self.outf.write(' ')
 
1589
                            self.outf.write(ie.file_id)
 
1590
                        self.outf.write('\n')
 
1591
            finally:
 
1592
                old.unlock()
 
1593
        finally:
 
1594
            tree.unlock()
1430
1595
 
1431
1596
 
1432
1597
class cmd_modified(Command):
1433
1598
    """List files modified in working tree.
1434
 
 
1435
 
    See also: "bzr status".
1436
1599
    """
1437
1600
 
1438
1601
    hidden = True
 
1602
    _see_also = ['status', 'ls']
1439
1603
 
1440
1604
    @display_command
1441
1605
    def run(self):
1447
1611
 
1448
1612
class cmd_added(Command):
1449
1613
    """List files added in working tree.
1450
 
 
1451
 
    See also: "bzr status".
1452
1614
    """
1453
1615
 
1454
1616
    hidden = True
 
1617
    _see_also = ['status', 'ls']
1455
1618
 
1456
1619
    @display_command
1457
1620
    def run(self):
1458
1621
        wt = WorkingTree.open_containing(u'.')[0]
1459
 
        basis_inv = wt.basis_tree().inventory
1460
 
        inv = wt.inventory
1461
 
        for file_id in inv:
1462
 
            if file_id in basis_inv:
1463
 
                continue
1464
 
            if inv.is_root(file_id) and len(basis_inv) == 0:
1465
 
                continue
1466
 
            path = inv.id2path(file_id)
1467
 
            if not os.access(osutils.abspath(path), os.F_OK):
1468
 
                continue
1469
 
            self.outf.write(path + '\n')
 
1622
        wt.lock_read()
 
1623
        try:
 
1624
            basis = wt.basis_tree()
 
1625
            basis.lock_read()
 
1626
            try:
 
1627
                basis_inv = basis.inventory
 
1628
                inv = wt.inventory
 
1629
                for file_id in inv:
 
1630
                    if file_id in basis_inv:
 
1631
                        continue
 
1632
                    if inv.is_root(file_id) and len(basis_inv) == 0:
 
1633
                        continue
 
1634
                    path = inv.id2path(file_id)
 
1635
                    if not os.access(osutils.abspath(path), os.F_OK):
 
1636
                        continue
 
1637
                    self.outf.write(path + '\n')
 
1638
            finally:
 
1639
                basis.unlock()
 
1640
        finally:
 
1641
            wt.unlock()
1470
1642
 
1471
1643
 
1472
1644
class cmd_root(Command):
1474
1646
 
1475
1647
    The root is the nearest enclosing directory with a .bzr control
1476
1648
    directory."""
 
1649
 
1477
1650
    takes_args = ['filename?']
1478
1651
    @display_command
1479
1652
    def run(self, filename=None):
1482
1655
        self.outf.write(tree.basedir + '\n')
1483
1656
 
1484
1657
 
 
1658
def _parse_limit(limitstring):
 
1659
    try:
 
1660
        return int(limitstring)
 
1661
    except ValueError:
 
1662
        msg = "The limit argument must be an integer."
 
1663
        raise errors.BzrCommandError(msg)
 
1664
 
 
1665
 
1485
1666
class cmd_log(Command):
1486
1667
    """Show log of a branch, file, or directory.
1487
1668
 
1491
1672
    -r revision requests a specific revision, -r ..end or -r begin.. are
1492
1673
    also valid.
1493
1674
 
1494
 
    examples:
1495
 
        bzr log
1496
 
        bzr log foo.c
1497
 
        bzr log -r -10.. http://server/branch
 
1675
    :Examples:
 
1676
        Log the current branch::
 
1677
 
 
1678
            bzr log
 
1679
 
 
1680
        Log a file::
 
1681
 
 
1682
            bzr log foo.c
 
1683
 
 
1684
        Log the last 10 revisions of a branch::
 
1685
 
 
1686
            bzr log -r -10.. http://server/branch
1498
1687
    """
1499
1688
 
1500
1689
    # TODO: Make --revision support uuid: and hash: [future tag:] notation.
1501
1690
 
1502
1691
    takes_args = ['location?']
1503
 
    takes_options = [Option('forward', 
1504
 
                            help='show from oldest to newest'),
1505
 
                     'timezone', 
1506
 
                     Option('verbose', 
1507
 
                             short_name='v',
1508
 
                             help='show files changed in each revision'),
1509
 
                     'show-ids', 'revision',
1510
 
                     'log-format',
1511
 
                     Option('message',
1512
 
                            short_name='m',
1513
 
                            help='show revisions whose message matches this regexp',
1514
 
                            type=str),
1515
 
                     ]
 
1692
    takes_options = [
 
1693
            Option('forward',
 
1694
                   help='Show from oldest to newest.'),
 
1695
            Option('timezone',
 
1696
                   type=str,
 
1697
                   help='Display timezone as local, original, or utc.'),
 
1698
            custom_help('verbose',
 
1699
                   help='Show files changed in each revision.'),
 
1700
            'show-ids',
 
1701
            'revision',
 
1702
            'log-format',
 
1703
            Option('message',
 
1704
                   short_name='m',
 
1705
                   help='Show revisions whose message matches this '
 
1706
                        'regular expression.',
 
1707
                   type=str),
 
1708
            Option('limit',
 
1709
                   short_name='l',
 
1710
                   help='Limit the output to the first N revisions.',
 
1711
                   argname='N',
 
1712
                   type=_parse_limit),
 
1713
            ]
1516
1714
    encoding_type = 'replace'
1517
1715
 
1518
1716
    @display_command
1522
1720
            forward=False,
1523
1721
            revision=None,
1524
1722
            log_format=None,
1525
 
            message=None):
 
1723
            message=None,
 
1724
            limit=None):
1526
1725
        from bzrlib.log import show_log
1527
1726
        assert message is None or isinstance(message, basestring), \
1528
1727
            "invalid message argument %r" % message
1538
1737
            if fp != '':
1539
1738
                if tree is None:
1540
1739
                    tree = b.basis_tree()
1541
 
                inv = tree.inventory
1542
 
                file_id = inv.path2id(fp)
 
1740
                file_id = tree.path2id(fp)
1543
1741
                if file_id is None:
1544
1742
                    raise errors.BzrCommandError(
1545
1743
                        "Path does not have any revision history: %s" %
1561
1759
                rev1 = None
1562
1760
                rev2 = None
1563
1761
            elif len(revision) == 1:
1564
 
                rev1 = rev2 = revision[0].in_history(b).revno
 
1762
                rev1 = rev2 = revision[0].in_history(b)
1565
1763
            elif len(revision) == 2:
1566
1764
                if revision[1].get_branch() != revision[0].get_branch():
1567
1765
                    # b is taken from revision[0].get_branch(), and
1570
1768
                    raise errors.BzrCommandError(
1571
1769
                        "Log doesn't accept two revisions in different"
1572
1770
                        " branches.")
1573
 
                if revision[0].spec is None:
1574
 
                    # missing begin-range means first revision
1575
 
                    rev1 = 1
1576
 
                else:
1577
 
                    rev1 = revision[0].in_history(b).revno
1578
 
 
1579
 
                if revision[1].spec is None:
1580
 
                    # missing end-range means last known revision
1581
 
                    rev2 = b.revno()
1582
 
                else:
1583
 
                    rev2 = revision[1].in_history(b).revno
 
1771
                rev1 = revision[0].in_history(b)
 
1772
                rev2 = revision[1].in_history(b)
1584
1773
            else:
1585
1774
                raise errors.BzrCommandError(
1586
1775
                    'bzr log --revision takes one or two values.')
1587
1776
 
1588
 
            # By this point, the revision numbers are converted to the +ve
1589
 
            # form if they were supplied in the -ve form, so we can do
1590
 
            # this comparison in relative safety
1591
 
            if rev1 > rev2:
1592
 
                (rev2, rev1) = (rev1, rev2)
1593
 
 
1594
1777
            if log_format is None:
1595
1778
                log_format = log.log_formatter_registry.get_default(b)
1596
1779
 
1604
1787
                     direction=direction,
1605
1788
                     start_revision=rev1,
1606
1789
                     end_revision=rev2,
1607
 
                     search=message)
 
1790
                     search=message,
 
1791
                     limit=limit)
1608
1792
        finally:
1609
1793
            b.unlock()
1610
1794
 
1633
1817
    def run(self, filename):
1634
1818
        tree, relpath = WorkingTree.open_containing(filename)
1635
1819
        b = tree.branch
1636
 
        inv = tree.read_working_inventory()
1637
 
        file_id = inv.path2id(relpath)
 
1820
        file_id = tree.path2id(relpath)
1638
1821
        for revno, revision_id, what in log.find_touching_revisions(b, file_id):
1639
1822
            self.outf.write("%6d %s\n" % (revno, what))
1640
1823
 
1643
1826
    """List files in a tree.
1644
1827
    """
1645
1828
 
 
1829
    _see_also = ['status', 'cat']
1646
1830
    takes_args = ['path?']
1647
1831
    # TODO: Take a revision or remote path and list that tree instead.
1648
 
    takes_options = ['verbose', 'revision',
1649
 
                     Option('non-recursive',
1650
 
                            help='don\'t recurse into sub-directories'),
1651
 
                     Option('from-root',
1652
 
                            help='Print all paths from the root of the branch.'),
1653
 
                     Option('unknown', help='Print unknown files'),
1654
 
                     Option('versioned', help='Print versioned files'),
1655
 
                     Option('ignored', help='Print ignored files'),
1656
 
 
1657
 
                     Option('null', help='Null separate the files'),
1658
 
                     'kind', 'show-ids'
1659
 
                    ]
 
1832
    takes_options = [
 
1833
            'verbose',
 
1834
            'revision',
 
1835
            Option('non-recursive',
 
1836
                   help='Don\'t recurse into subdirectories.'),
 
1837
            Option('from-root',
 
1838
                   help='Print paths relative to the root of the branch.'),
 
1839
            Option('unknown', help='Print unknown files.'),
 
1840
            Option('versioned', help='Print versioned files.'),
 
1841
            Option('ignored', help='Print ignored files.'),
 
1842
            Option('null',
 
1843
                   help='Write an ascii NUL (\\0) separator '
 
1844
                   'between files rather than a newline.'),
 
1845
            Option('kind',
 
1846
                   help='List entries of a particular kind: file, directory, symlink.',
 
1847
                   type=unicode),
 
1848
            'show-ids',
 
1849
            ]
1660
1850
    @display_command
1661
 
    def run(self, revision=None, verbose=False, 
 
1851
    def run(self, revision=None, verbose=False,
1662
1852
            non_recursive=False, from_root=False,
1663
1853
            unknown=False, versioned=False, ignored=False,
1664
1854
            null=False, kind=None, show_ids=False, path=None):
1689
1879
            relpath += '/'
1690
1880
        if revision is not None:
1691
1881
            tree = branch.repository.revision_tree(
1692
 
                revision[0].in_history(branch).rev_id)
 
1882
                revision[0].as_revision_id(branch))
1693
1883
        elif tree is None:
1694
1884
            tree = branch.basis_tree()
1695
1885
 
1732
1922
 
1733
1923
class cmd_unknowns(Command):
1734
1924
    """List unknown files.
1735
 
 
1736
 
    See also: "bzr ls --unknown".
1737
1925
    """
1738
1926
 
1739
1927
    hidden = True
 
1928
    _see_also = ['ls']
1740
1929
 
1741
1930
    @display_command
1742
1931
    def run(self):
1757
1946
 
1758
1947
    Ignore patterns specifying absolute paths are not allowed.
1759
1948
 
1760
 
    Ignore patterns may include globbing wildcards such as:
 
1949
    Ignore patterns may include globbing wildcards such as::
 
1950
 
1761
1951
      ? - Matches any single character except '/'
1762
1952
      * - Matches 0 or more characters except '/'
1763
1953
      /**/ - Matches 0 or more directories in a path
1771
1961
    Note: ignore patterns containing shell wildcards must be quoted from 
1772
1962
    the shell on Unix.
1773
1963
 
1774
 
    examples:
1775
 
        bzr ignore ./Makefile
1776
 
        bzr ignore '*.class'
1777
 
        bzr ignore 'lib/**/*.o'
1778
 
        bzr ignore 'RE:lib/.*\.o'
 
1964
    :Examples:
 
1965
        Ignore the top level Makefile::
 
1966
 
 
1967
            bzr ignore ./Makefile
 
1968
 
 
1969
        Ignore class files in all directories::
 
1970
 
 
1971
            bzr ignore "*.class"
 
1972
 
 
1973
        Ignore .o files under the lib directory::
 
1974
 
 
1975
            bzr ignore "lib/**/*.o"
 
1976
 
 
1977
        Ignore .o files under the lib directory::
 
1978
 
 
1979
            bzr ignore "RE:lib/.*\.o"
 
1980
 
 
1981
        Ignore everything but the "debian" toplevel directory::
 
1982
 
 
1983
            bzr ignore "RE:(?!debian/).*"
1779
1984
    """
 
1985
 
 
1986
    _see_also = ['status', 'ignored']
1780
1987
    takes_args = ['name_pattern*']
1781
1988
    takes_options = [
1782
 
                     Option('old-default-rules',
1783
 
                            help='Out the ignore rules bzr < 0.9 always used.')
1784
 
                     ]
 
1989
        Option('old-default-rules',
 
1990
               help='Write out the ignore rules bzr < 0.9 always used.')
 
1991
        ]
1785
1992
    
1786
1993
    def run(self, name_pattern_list=None, old_default_rules=None):
1787
1994
        from bzrlib.atomicfile import AtomicFile
1793
2000
        if not name_pattern_list:
1794
2001
            raise errors.BzrCommandError("ignore requires at least one "
1795
2002
                                  "NAME_PATTERN or --old-default-rules")
 
2003
        name_pattern_list = [globbing.normalize_pattern(p) 
 
2004
                             for p in name_pattern_list]
1796
2005
        for name_pattern in name_pattern_list:
1797
 
            if name_pattern[0] == '/':
 
2006
            if (name_pattern[0] == '/' or 
 
2007
                (len(name_pattern) > 1 and name_pattern[1] == ':')):
1798
2008
                raise errors.BzrCommandError(
1799
2009
                    "NAME_PATTERN should not be an absolute path")
1800
2010
        tree, relpath = WorkingTree.open_containing(u'.')
1814
2024
        if igns and igns[-1] != '\n':
1815
2025
            igns += '\n'
1816
2026
        for name_pattern in name_pattern_list:
1817
 
            igns += name_pattern.rstrip('/') + '\n'
 
2027
            igns += name_pattern + '\n'
1818
2028
 
1819
2029
        f = AtomicFile(ifn, 'wb')
1820
2030
        try:
1823
2033
        finally:
1824
2034
            f.close()
1825
2035
 
1826
 
        inv = tree.inventory
1827
 
        if inv.path2id('.bzrignore'):
1828
 
            mutter('.bzrignore is already versioned')
1829
 
        else:
1830
 
            mutter('need to make new .bzrignore file versioned')
 
2036
        if not tree.path2id('.bzrignore'):
1831
2037
            tree.add(['.bzrignore'])
1832
2038
 
 
2039
        ignored = globbing.Globster(name_pattern_list)
 
2040
        matches = []
 
2041
        tree.lock_read()
 
2042
        for entry in tree.list_files():
 
2043
            id = entry[3]
 
2044
            if id is not None:
 
2045
                filename = entry[0]
 
2046
                if ignored.match(filename):
 
2047
                    matches.append(filename.encode('utf-8'))
 
2048
        tree.unlock()
 
2049
        if len(matches) > 0:
 
2050
            print "Warning: the following files are version controlled and" \
 
2051
                  " match your ignore pattern:\n%s" % ("\n".join(matches),)
1833
2052
 
1834
2053
class cmd_ignored(Command):
1835
2054
    """List ignored files and the patterns that matched them.
1836
 
 
1837
 
    See also: bzr ignore"""
 
2055
    """
 
2056
 
 
2057
    encoding_type = 'replace'
 
2058
    _see_also = ['ignore']
 
2059
 
1838
2060
    @display_command
1839
2061
    def run(self):
1840
2062
        tree = WorkingTree.open_containing(u'.')[0]
1845
2067
                    continue
1846
2068
                ## XXX: Slightly inefficient since this was already calculated
1847
2069
                pat = tree.is_ignored(path)
1848
 
                print '%-50s %s' % (path, pat)
 
2070
                self.outf.write('%-50s %s\n' % (path, pat))
1849
2071
        finally:
1850
2072
            tree.unlock()
1851
2073
 
1853
2075
class cmd_lookup_revision(Command):
1854
2076
    """Lookup the revision-id from a revision-number
1855
2077
 
1856
 
    example:
 
2078
    :Examples:
1857
2079
        bzr lookup-revision 33
1858
2080
    """
1859
2081
    hidden = True
1870
2092
 
1871
2093
 
1872
2094
class cmd_export(Command):
1873
 
    """Export past revision to destination directory.
 
2095
    """Export current or past revision to a destination directory or archive.
1874
2096
 
1875
2097
    If no revision is specified this exports the last committed revision.
1876
2098
 
1878
2100
    given, try to find the format with the extension. If no extension
1879
2101
    is found exports to a directory (equivalent to --format=dir).
1880
2102
 
1881
 
    Root may be the top directory for tar, tgz and tbz2 formats. If none
1882
 
    is given, the top directory will be the root name of the file.
1883
 
 
1884
 
    If branch is omitted then the branch containing the CWD will be used.
1885
 
 
1886
 
    Note: export of tree with non-ascii filenames to zip is not supported.
1887
 
 
1888
 
     Supported formats       Autodetected by extension
1889
 
     -----------------       -------------------------
1890
 
         dir                            -
 
2103
    If root is supplied, it will be used as the root directory inside
 
2104
    container formats (tar, zip, etc). If it is not supplied it will default
 
2105
    to the exported filename. The root option has no effect for 'dir' format.
 
2106
 
 
2107
    If branch is omitted then the branch containing the current working
 
2108
    directory will be used.
 
2109
 
 
2110
    Note: Export of tree with non-ASCII filenames to zip is not supported.
 
2111
 
 
2112
      =================       =========================
 
2113
      Supported formats       Autodetected by extension
 
2114
      =================       =========================
 
2115
         dir                         (none)
1891
2116
         tar                          .tar
1892
2117
         tbz2                    .tar.bz2, .tbz2
1893
2118
         tgz                      .tar.gz, .tgz
1894
2119
         zip                          .zip
 
2120
      =================       =========================
1895
2121
    """
1896
2122
    takes_args = ['dest', 'branch?']
1897
 
    takes_options = ['revision', 'format', 'root']
 
2123
    takes_options = [
 
2124
        Option('format',
 
2125
               help="Type of file to export to.",
 
2126
               type=unicode),
 
2127
        'revision',
 
2128
        Option('root',
 
2129
               type=str,
 
2130
               help="Name of the root directory inside the exported file."),
 
2131
        ]
1898
2132
    def run(self, dest, branch=None, revision=None, format=None, root=None):
1899
2133
        from bzrlib.export import export
1900
2134
 
1910
2144
        else:
1911
2145
            if len(revision) != 1:
1912
2146
                raise errors.BzrCommandError('bzr export --revision takes exactly 1 argument')
1913
 
            rev_id = revision[0].in_history(b).rev_id
 
2147
            rev_id = revision[0].as_revision_id(b)
1914
2148
        t = b.repository.revision_tree(rev_id)
1915
2149
        try:
1916
2150
            export(t, dest, format, root)
1919
2153
 
1920
2154
 
1921
2155
class cmd_cat(Command):
1922
 
    """Write a file's text from a previous revision."""
1923
 
 
1924
 
    takes_options = ['revision', 'name-from-revision']
 
2156
    """Write the contents of a file as of a given revision to standard output.
 
2157
 
 
2158
    If no revision is nominated, the last revision is used.
 
2159
 
 
2160
    Note: Take care to redirect standard output when using this command on a
 
2161
    binary file. 
 
2162
    """
 
2163
 
 
2164
    _see_also = ['ls']
 
2165
    takes_options = [
 
2166
        Option('name-from-revision', help='The path name in the old tree.'),
 
2167
        'revision',
 
2168
        ]
1925
2169
    takes_args = ['filename']
1926
2170
    encoding_type = 'exact'
1927
2171
 
1929
2173
    def run(self, filename, revision=None, name_from_revision=False):
1930
2174
        if revision is not None and len(revision) != 1:
1931
2175
            raise errors.BzrCommandError("bzr cat --revision takes exactly"
1932
 
                                        " one number")
1933
 
 
1934
 
        tree = None
 
2176
                                         " one revision specifier")
 
2177
        tree, branch, relpath = \
 
2178
            bzrdir.BzrDir.open_containing_tree_or_branch(filename)
 
2179
        branch.lock_read()
1935
2180
        try:
1936
 
            tree, relpath = WorkingTree.open_containing(filename)
1937
 
            b = tree.branch
1938
 
        except (errors.NotBranchError, errors.NotLocalUrl):
1939
 
            pass
 
2181
            return self._run(tree, branch, relpath, filename, revision,
 
2182
                             name_from_revision)
 
2183
        finally:
 
2184
            branch.unlock()
1940
2185
 
1941
 
        if revision is not None and revision[0].get_branch() is not None:
1942
 
            b = Branch.open(revision[0].get_branch())
 
2186
    def _run(self, tree, b, relpath, filename, revision, name_from_revision):
1943
2187
        if tree is None:
1944
 
            b, relpath = Branch.open_containing(filename)
1945
2188
            tree = b.basis_tree()
1946
2189
        if revision is None:
1947
2190
            revision_id = b.last_revision()
1948
2191
        else:
1949
 
            revision_id = revision[0].in_history(b).rev_id
 
2192
            revision_id = revision[0].as_revision_id(b)
1950
2193
 
1951
2194
        cur_file_id = tree.path2id(relpath)
1952
2195
        rev_tree = b.repository.revision_tree(revision_id)
1985
2228
    committed.  If a directory is specified then the directory and everything 
1986
2229
    within it is committed.
1987
2230
 
 
2231
    If author of the change is not the same person as the committer, you can
 
2232
    specify the author's name using the --author option. The name should be
 
2233
    in the same format as a committer-id, e.g. "John Doe <jdoe@example.com>".
 
2234
 
1988
2235
    A selected-file commit may fail in some cases where the committed
1989
 
    tree would be invalid, such as trying to commit a file in a
1990
 
    newly-added directory that is not itself committed.
 
2236
    tree would be invalid. Consider::
 
2237
 
 
2238
      bzr init foo
 
2239
      mkdir foo/bar
 
2240
      bzr add foo/bar
 
2241
      bzr commit foo -m "committing foo"
 
2242
      bzr mv foo/bar foo/baz
 
2243
      mkdir foo/bar
 
2244
      bzr add foo/bar
 
2245
      bzr commit foo/bar -m "committing bar but not baz"
 
2246
 
 
2247
    In the example above, the last commit will fail by design. This gives
 
2248
    the user the opportunity to decide whether they want to commit the
 
2249
    rename at the same time, separately first, or not at all. (As a general
 
2250
    rule, when in doubt, Bazaar has a policy of Doing the Safe Thing.)
 
2251
 
 
2252
    Note: A selected-file commit after a merge is not yet supported.
1991
2253
    """
1992
2254
    # TODO: Run hooks on tree to-be-committed, and after commit.
1993
2255
 
1998
2260
 
1999
2261
    # XXX: verbose currently does nothing
2000
2262
 
 
2263
    _see_also = ['bugs', 'uncommit']
2001
2264
    takes_args = ['selected*']
2002
 
    takes_options = ['message', 'verbose', 
2003
 
                     Option('unchanged',
2004
 
                            help='commit even if nothing has changed'),
2005
 
                     Option('file', type=str, 
2006
 
                            short_name='F',
2007
 
                            argname='msgfile',
2008
 
                            help='file containing commit message'),
2009
 
                     Option('strict',
2010
 
                            help="refuse to commit if there are unknown "
2011
 
                            "files in the working tree."),
2012
 
                     Option('local',
2013
 
                            help="perform a local only commit in a bound "
2014
 
                                 "branch. Such commits are not pushed to "
2015
 
                                 "the master branch until a normal commit "
2016
 
                                 "is performed."
2017
 
                            ),
2018
 
                     ]
 
2265
    takes_options = [
 
2266
            Option('message', type=unicode,
 
2267
                   short_name='m',
 
2268
                   help="Description of the new revision."),
 
2269
            'verbose',
 
2270
             Option('unchanged',
 
2271
                    help='Commit even if nothing has changed.'),
 
2272
             Option('file', type=str,
 
2273
                    short_name='F',
 
2274
                    argname='msgfile',
 
2275
                    help='Take commit message from this file.'),
 
2276
             Option('strict',
 
2277
                    help="Refuse to commit if there are unknown "
 
2278
                    "files in the working tree."),
 
2279
             ListOption('fixes', type=str,
 
2280
                    help="Mark a bug as being fixed by this revision."),
 
2281
             Option('author', type=unicode,
 
2282
                    help="Set the author's name, if it's different "
 
2283
                         "from the committer."),
 
2284
             Option('local',
 
2285
                    help="Perform a local commit in a bound "
 
2286
                         "branch.  Local commits are not pushed to "
 
2287
                         "the master branch until a normal commit "
 
2288
                         "is performed."
 
2289
                    ),
 
2290
              Option('show-diff',
 
2291
                     help='When no message is supplied, show the diff along'
 
2292
                     ' with the status summary in the message editor.'),
 
2293
             ]
2019
2294
    aliases = ['ci', 'checkin']
2020
2295
 
2021
 
    def run(self, message=None, file=None, verbose=True, selected_list=None,
2022
 
            unchanged=False, strict=False, local=False):
2023
 
        from bzrlib.commit import (NullCommitReporter, ReportCommitToLog)
2024
 
        from bzrlib.errors import (PointlessCommit, ConflictsInTree,
2025
 
                StrictCommitFailed)
2026
 
        from bzrlib.msgeditor import edit_commit_message, \
2027
 
                make_commit_message_template
 
2296
    def _get_bug_fix_properties(self, fixes, branch):
 
2297
        properties = []
 
2298
        # Configure the properties for bug fixing attributes.
 
2299
        for fixed_bug in fixes:
 
2300
            tokens = fixed_bug.split(':')
 
2301
            if len(tokens) != 2:
 
2302
                raise errors.BzrCommandError(
 
2303
                    "Invalid bug %s. Must be in the form of 'tag:id'. "
 
2304
                    "Commit refused." % fixed_bug)
 
2305
            tag, bug_id = tokens
 
2306
            try:
 
2307
                bug_url = bugtracker.get_bug_url(tag, branch, bug_id)
 
2308
            except errors.UnknownBugTrackerAbbreviation:
 
2309
                raise errors.BzrCommandError(
 
2310
                    'Unrecognized bug %s. Commit refused.' % fixed_bug)
 
2311
            except errors.MalformedBugIdentifier:
 
2312
                raise errors.BzrCommandError(
 
2313
                    "Invalid bug identifier for %s. Commit refused."
 
2314
                    % fixed_bug)
 
2315
            properties.append('%s fixed' % bug_url)
 
2316
        return '\n'.join(properties)
 
2317
 
 
2318
    def run(self, message=None, file=None, verbose=False, selected_list=None,
 
2319
            unchanged=False, strict=False, local=False, fixes=None,
 
2320
            author=None, show_diff=False):
 
2321
        from bzrlib.errors import (
 
2322
            PointlessCommit,
 
2323
            ConflictsInTree,
 
2324
            StrictCommitFailed
 
2325
        )
 
2326
        from bzrlib.msgeditor import (
 
2327
            edit_commit_message_encoded,
 
2328
            make_commit_message_template_encoded
 
2329
        )
2028
2330
 
2029
2331
        # TODO: Need a blackbox test for invoking the external editor; may be
2030
2332
        # slightly problematic to run this cross-platform.
2031
2333
 
2032
2334
        # TODO: do more checks that the commit will succeed before 
2033
2335
        # spending the user's valuable time typing a commit message.
 
2336
 
 
2337
        properties = {}
 
2338
 
2034
2339
        tree, selected_list = tree_files(selected_list)
2035
2340
        if selected_list == ['']:
2036
2341
            # workaround - commit of root of tree should be exactly the same
2038
2343
            # selected-file merge commit is not done yet
2039
2344
            selected_list = []
2040
2345
 
 
2346
        if fixes is None:
 
2347
            fixes = []
 
2348
        bug_property = self._get_bug_fix_properties(fixes, tree.branch)
 
2349
        if bug_property:
 
2350
            properties['bugs'] = bug_property
 
2351
 
2041
2352
        if local and not tree.branch.get_bound_location():
2042
2353
            raise errors.LocalRequiresBoundBranch()
2043
2354
 
2045
2356
            """Callback to get commit message"""
2046
2357
            my_message = message
2047
2358
            if my_message is None and not file:
2048
 
                template = make_commit_message_template(tree, selected_list)
2049
 
                my_message = edit_commit_message(template)
 
2359
                t = make_commit_message_template_encoded(tree,
 
2360
                        selected_list, diff=show_diff,
 
2361
                        output_encoding=bzrlib.user_encoding)
 
2362
                my_message = edit_commit_message_encoded(t)
2050
2363
                if my_message is None:
2051
2364
                    raise errors.BzrCommandError("please specify a commit"
2052
2365
                        " message with either --message or --file")
2059
2372
            if my_message == "":
2060
2373
                raise errors.BzrCommandError("empty commit message specified")
2061
2374
            return my_message
2062
 
        
2063
 
        if verbose:
2064
 
            reporter = ReportCommitToLog()
2065
 
        else:
2066
 
            reporter = NullCommitReporter()
2067
2375
 
2068
2376
        try:
2069
2377
            tree.commit(message_callback=get_message,
2070
2378
                        specific_files=selected_list,
2071
2379
                        allow_pointless=unchanged, strict=strict, local=local,
2072
 
                        reporter=reporter)
 
2380
                        reporter=None, verbose=verbose, revprops=properties,
 
2381
                        author=author)
2073
2382
        except PointlessCommit:
2074
2383
            # FIXME: This should really happen before the file is read in;
2075
2384
            # perhaps prepare the commit; get the message; then actually commit
2094
2403
 
2095
2404
    This command checks various invariants about the branch storage to
2096
2405
    detect data corruption or bzr bugs.
 
2406
 
 
2407
    Output fields:
 
2408
 
 
2409
        revisions: This is just the number of revisions checked.  It doesn't
 
2410
            indicate a problem.
 
2411
        versionedfiles: This is just the number of versionedfiles checked.  It
 
2412
            doesn't indicate a problem.
 
2413
        unreferenced ancestors: Texts that are ancestors of other texts, but
 
2414
            are not properly referenced by the revision ancestry.  This is a
 
2415
            subtle problem that Bazaar can work around.
 
2416
        unique file texts: This is the total number of unique file contents
 
2417
            seen in the checked revisions.  It does not indicate a problem.
 
2418
        repeated file texts: This is the total number of repeated texts seen
 
2419
            in the checked revisions.  Texts can be repeated when their file
 
2420
            entries are modified, but the file contents are not.  It does not
 
2421
            indicate a problem.
2097
2422
    """
 
2423
 
 
2424
    _see_also = ['reconcile']
2098
2425
    takes_args = ['branch?']
2099
2426
    takes_options = ['verbose']
2100
2427
 
2101
2428
    def run(self, branch=None, verbose=False):
2102
2429
        from bzrlib.check import check
2103
2430
        if branch is None:
2104
 
            tree = WorkingTree.open_containing()[0]
2105
 
            branch = tree.branch
2106
 
        else:
2107
 
            branch = Branch.open(branch)
2108
 
        check(branch, verbose)
 
2431
            branch_obj = Branch.open_containing('.')[0]
 
2432
        else:
 
2433
            branch_obj = Branch.open(branch)
 
2434
        check(branch_obj, verbose)
 
2435
        # bit hacky, check the tree parent is accurate
 
2436
        try:
 
2437
            if branch is None:
 
2438
                tree = WorkingTree.open_containing('.')[0]
 
2439
            else:
 
2440
                tree = WorkingTree.open(branch)
 
2441
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
2442
            pass
 
2443
        else:
 
2444
            # This is a primitive 'check' for tree state. Currently this is not
 
2445
            # integrated into the main check logic as yet.
 
2446
            tree.lock_read()
 
2447
            try:
 
2448
                tree_basis = tree.basis_tree()
 
2449
                tree_basis.lock_read()
 
2450
                try:
 
2451
                    repo_basis = tree.branch.repository.revision_tree(
 
2452
                        tree.last_revision())
 
2453
                    if len(list(repo_basis.iter_changes(tree_basis))):
 
2454
                        raise errors.BzrCheckError(
 
2455
                            "Mismatched basis inventory content.")
 
2456
                    tree._validate()
 
2457
                finally:
 
2458
                    tree_basis.unlock()
 
2459
            finally:
 
2460
                tree.unlock()
2109
2461
 
2110
2462
 
2111
2463
class cmd_upgrade(Command):
2115
2467
    this command. When the default format has changed you may also be warned
2116
2468
    during other operations to upgrade.
2117
2469
    """
 
2470
 
 
2471
    _see_also = ['check']
2118
2472
    takes_args = ['url?']
2119
2473
    takes_options = [
2120
2474
                    RegistryOption('format',
2121
2475
                        help='Upgrade to a specific format.  See "bzr help'
2122
 
                             ' formats" for details',
 
2476
                             ' formats" for details.',
2123
2477
                        registry=bzrdir.format_registry,
2124
2478
                        converter=bzrdir.format_registry.make_bzrdir,
2125
2479
                        value_switches=True, title='Branch format'),
2126
2480
                    ]
2127
2481
 
2128
 
 
2129
2482
    def run(self, url='.', format=None):
2130
2483
        from bzrlib.upgrade import upgrade
2131
2484
        if format is None:
2136
2489
class cmd_whoami(Command):
2137
2490
    """Show or set bzr user id.
2138
2491
    
2139
 
    examples:
2140
 
        bzr whoami --email
2141
 
        bzr whoami 'Frank Chu <fchu@example.com>'
 
2492
    :Examples:
 
2493
        Show the email of the current user::
 
2494
 
 
2495
            bzr whoami --email
 
2496
 
 
2497
        Set the current user::
 
2498
 
 
2499
            bzr whoami "Frank Chu <fchu@example.com>"
2142
2500
    """
2143
2501
    takes_options = [ Option('email',
2144
 
                             help='display email address only'),
 
2502
                             help='Display email address only.'),
2145
2503
                      Option('branch',
2146
 
                             help='set identity for the current branch instead of '
2147
 
                                  'globally'),
 
2504
                             help='Set identity for the current branch instead of '
 
2505
                                  'globally.'),
2148
2506
                    ]
2149
2507
    takes_args = ['name?']
2150
2508
    encoding_type = 'replace'
2184
2542
    If unset, the tree root directory name is used as the nickname
2185
2543
    To print the current nickname, execute with no argument.  
2186
2544
    """
 
2545
 
 
2546
    _see_also = ['info']
2187
2547
    takes_args = ['nickname?']
2188
2548
    def run(self, nickname=None):
2189
2549
        branch = Branch.open_containing(u'.')[0]
2194
2554
 
2195
2555
    @display_command
2196
2556
    def printme(self, branch):
2197
 
        print branch.nick 
 
2557
        print branch.nick
2198
2558
 
2199
2559
 
2200
2560
class cmd_selftest(Command):
2201
2561
    """Run internal test suite.
2202
2562
    
2203
 
    This creates temporary test directories in the working directory, but not
2204
 
    existing data is affected.  These directories are deleted if the tests
2205
 
    pass, or left behind to help in debugging if they fail and --keep-output
2206
 
    is specified.
2207
 
    
2208
2563
    If arguments are given, they are regular expressions that say which tests
2209
2564
    should run.  Tests matching any expression are run, and other tests are
2210
2565
    not run.
2213
2568
    all other tests are run.  This is useful if you have been working in a
2214
2569
    particular area, but want to make sure nothing else was broken.
2215
2570
 
 
2571
    If --exclude is given, tests that match that regular expression are
 
2572
    excluded, regardless of whether they match --first or not.
 
2573
 
 
2574
    To help catch accidential dependencies between tests, the --randomize
 
2575
    option is useful. In most cases, the argument used is the word 'now'.
 
2576
    Note that the seed used for the random number generator is displayed
 
2577
    when this option is used. The seed can be explicitly passed as the
 
2578
    argument to this option if required. This enables reproduction of the
 
2579
    actual ordering used if and when an order sensitive problem is encountered.
 
2580
 
 
2581
    If --list-only is given, the tests that would be run are listed. This is
 
2582
    useful when combined with --first, --exclude and/or --randomize to
 
2583
    understand their impact. The test harness reports "Listed nn tests in ..."
 
2584
    instead of "Ran nn tests in ..." when list mode is enabled.
 
2585
 
2216
2586
    If the global option '--no-plugins' is given, plugins are not loaded
2217
2587
    before running the selftests.  This has two effects: features provided or
2218
2588
    modified by plugins will not be tested, and tests provided by plugins will
2219
2589
    not be run.
2220
2590
 
2221
 
    examples::
2222
 
        bzr selftest ignore
2223
 
            run only tests relating to 'ignore'
2224
 
        bzr --no-plugins selftest -v
2225
 
            disable plugins and list tests as they're run
 
2591
    Tests that need working space on disk use a common temporary directory, 
 
2592
    typically inside $TMPDIR or /tmp.
 
2593
 
 
2594
    :Examples:
 
2595
        Run only tests relating to 'ignore'::
 
2596
 
 
2597
            bzr selftest ignore
 
2598
 
 
2599
        Disable plugins and list tests as they're run::
 
2600
 
 
2601
            bzr --no-plugins selftest -v
2226
2602
    """
2227
 
    # TODO: --list should give a list of all available tests
2228
 
 
2229
2603
    # NB: this is used from the class without creating an instance, which is
2230
2604
    # why it does not have a self parameter.
2231
2605
    def get_transport_type(typestring):
2246
2620
    hidden = True
2247
2621
    takes_args = ['testspecs*']
2248
2622
    takes_options = ['verbose',
2249
 
                     Option('one', help='stop when one test fails'),
2250
 
                     Option('keep-output', 
2251
 
                            help='keep output directories when tests fail'),
2252
 
                     Option('transport', 
 
2623
                     Option('one',
 
2624
                             help='Stop when one test fails.',
 
2625
                             short_name='1',
 
2626
                             ),
 
2627
                     Option('transport',
2253
2628
                            help='Use a different transport by default '
2254
2629
                                 'throughout the test suite.',
2255
2630
                            type=get_transport_type),
2256
 
                     Option('benchmark', help='run the bzr bencharks.'),
 
2631
                     Option('benchmark',
 
2632
                            help='Run the benchmarks rather than selftests.'),
2257
2633
                     Option('lsprof-timed',
2258
 
                            help='generate lsprof output for benchmarked'
 
2634
                            help='Generate lsprof output for benchmarked'
2259
2635
                                 ' sections of code.'),
2260
2636
                     Option('cache-dir', type=str,
2261
 
                            help='a directory to cache intermediate'
2262
 
                                 ' benchmark steps'),
2263
 
                     Option('clean-output',
2264
 
                            help='clean temporary tests directories'
2265
 
                                 ' without running tests'),
 
2637
                            help='Cache intermediate benchmark output in this '
 
2638
                                 'directory.'),
2266
2639
                     Option('first',
2267
 
                            help='run all tests, but run specified tests first',
2268
 
                            )
 
2640
                            help='Run all tests, but run specified tests first.',
 
2641
                            short_name='f',
 
2642
                            ),
 
2643
                     Option('list-only',
 
2644
                            help='List the tests instead of running them.'),
 
2645
                     Option('randomize', type=str, argname="SEED",
 
2646
                            help='Randomize the order of tests using the given'
 
2647
                                 ' seed or "now" for the current time.'),
 
2648
                     Option('exclude', type=str, argname="PATTERN",
 
2649
                            short_name='x',
 
2650
                            help='Exclude tests that match this regular'
 
2651
                                 ' expression.'),
 
2652
                     Option('strict', help='Fail on missing dependencies or '
 
2653
                            'known failures.'),
 
2654
                     Option('load-list', type=str, argname='TESTLISTFILE',
 
2655
                            help='Load a test id list from a text file.'),
2269
2656
                     ]
2270
2657
    encoding_type = 'replace'
2271
2658
 
2272
 
    def run(self, testspecs_list=None, verbose=None, one=False,
2273
 
            keep_output=False, transport=None, benchmark=None,
2274
 
            lsprof_timed=None, cache_dir=None, clean_output=False,
2275
 
            first=False):
 
2659
    def run(self, testspecs_list=None, verbose=False, one=False,
 
2660
            transport=None, benchmark=None,
 
2661
            lsprof_timed=None, cache_dir=None,
 
2662
            first=False, list_only=False,
 
2663
            randomize=None, exclude=None, strict=False,
 
2664
            load_list=None):
2276
2665
        import bzrlib.ui
2277
2666
        from bzrlib.tests import selftest
2278
2667
        import bzrlib.benchmarks as benchmarks
2279
2668
        from bzrlib.benchmarks import tree_creator
2280
2669
 
2281
 
        if clean_output:
2282
 
            from bzrlib.tests import clean_selftest_output
2283
 
            clean_selftest_output()
2284
 
            return 0
2285
 
 
2286
2670
        if cache_dir is not None:
2287
2671
            tree_creator.TreeCreator.CACHE_ROOT = osutils.abspath(cache_dir)
2288
 
        print '%10s: %s' % ('bzr', osutils.realpath(sys.argv[0]))
2289
 
        print '%10s: %s' % ('bzrlib', bzrlib.__path__[0])
 
2672
        if not list_only:
 
2673
            print 'testing: %s' % (osutils.realpath(sys.argv[0]),)
 
2674
            print '   %s (%s python%s)' % (
 
2675
                    bzrlib.__path__[0],
 
2676
                    bzrlib.version_string,
 
2677
                    bzrlib._format_version_tuple(sys.version_info),
 
2678
                    )
2290
2679
        print
2291
2680
        if testspecs_list is not None:
2292
2681
            pattern = '|'.join(testspecs_list)
2294
2683
            pattern = ".*"
2295
2684
        if benchmark:
2296
2685
            test_suite_factory = benchmarks.test_suite
2297
 
            if verbose is None:
2298
 
                verbose = True
 
2686
            # Unless user explicitly asks for quiet, be verbose in benchmarks
 
2687
            verbose = not is_quiet()
2299
2688
            # TODO: should possibly lock the history file...
2300
2689
            benchfile = open(".perf_history", "at", buffering=1)
2301
2690
        else:
2302
2691
            test_suite_factory = None
2303
 
            if verbose is None:
2304
 
                verbose = False
2305
2692
            benchfile = None
2306
2693
        try:
2307
 
            result = selftest(verbose=verbose, 
 
2694
            result = selftest(verbose=verbose,
2308
2695
                              pattern=pattern,
2309
 
                              stop_on_failure=one, 
2310
 
                              keep_output=keep_output,
 
2696
                              stop_on_failure=one,
2311
2697
                              transport=transport,
2312
2698
                              test_suite_factory=test_suite_factory,
2313
2699
                              lsprof_timed=lsprof_timed,
2314
2700
                              bench_history=benchfile,
2315
2701
                              matching_tests_first=first,
 
2702
                              list_only=list_only,
 
2703
                              random_seed=randomize,
 
2704
                              exclude_pattern=exclude,
 
2705
                              strict=strict,
 
2706
                              load_list=load_list,
2316
2707
                              )
2317
2708
        finally:
2318
2709
            if benchfile is not None:
2319
2710
                benchfile.close()
2320
2711
        if result:
2321
 
            info('tests passed')
 
2712
            note('tests passed')
2322
2713
        else:
2323
 
            info('tests failed')
 
2714
            note('tests failed')
2324
2715
        return int(not result)
2325
2716
 
2326
2717
 
2327
2718
class cmd_version(Command):
2328
2719
    """Show version of bzr."""
2329
2720
 
 
2721
    encoding_type = 'replace'
 
2722
    takes_options = [
 
2723
        Option("short", help="Print just the version number."),
 
2724
        ]
 
2725
 
2330
2726
    @display_command
2331
 
    def run(self):
 
2727
    def run(self, short=False):
2332
2728
        from bzrlib.version import show_version
2333
 
        show_version()
 
2729
        if short:
 
2730
            self.outf.write(bzrlib.version_string + '\n')
 
2731
        else:
 
2732
            show_version(to_file=self.outf)
2334
2733
 
2335
2734
 
2336
2735
class cmd_rocks(Command):
2340
2739
 
2341
2740
    @display_command
2342
2741
    def run(self):
2343
 
        print "it sure does!"
 
2742
        print "It sure does!"
2344
2743
 
2345
2744
 
2346
2745
class cmd_find_merge_base(Command):
2352
2751
    
2353
2752
    @display_command
2354
2753
    def run(self, branch, other):
2355
 
        from bzrlib.revision import MultipleRevisionSources
 
2754
        from bzrlib.revision import ensure_null
2356
2755
        
2357
2756
        branch1 = Branch.open_containing(branch)[0]
2358
2757
        branch2 = Branch.open_containing(other)[0]
2359
 
 
2360
 
        last1 = branch1.last_revision()
2361
 
        last2 = branch2.last_revision()
2362
 
 
2363
 
        source = MultipleRevisionSources(branch1.repository, 
2364
 
                                         branch2.repository)
2365
 
        
2366
 
        base_rev_id = common_ancestor(last1, last2, source)
2367
 
 
2368
 
        print 'merge base is revision %s' % base_rev_id
 
2758
        branch1.lock_read()
 
2759
        try:
 
2760
            branch2.lock_read()
 
2761
            try:
 
2762
                last1 = ensure_null(branch1.last_revision())
 
2763
                last2 = ensure_null(branch2.last_revision())
 
2764
 
 
2765
                graph = branch1.repository.get_graph(branch2.repository)
 
2766
                base_rev_id = graph.find_unique_lca(last1, last2)
 
2767
 
 
2768
                print 'merge base is revision %s' % base_rev_id
 
2769
            finally:
 
2770
                branch2.unlock()
 
2771
        finally:
 
2772
            branch1.unlock()
2369
2773
 
2370
2774
 
2371
2775
class cmd_merge(Command):
2372
2776
    """Perform a three-way merge.
2373
2777
    
2374
 
    The branch is the branch you will merge from.  By default, it will merge
2375
 
    the latest revision.  If you specify a revision, that revision will be
2376
 
    merged.  If you specify two revisions, the first will be used as a BASE,
2377
 
    and the second one as OTHER.  Revision numbers are always relative to the
2378
 
    specified branch.
 
2778
    The source of the merge can be specified either in the form of a branch,
 
2779
    or in the form of a path to a file containing a merge directive generated
 
2780
    with bzr send. If neither is specified, the default is the upstream branch
 
2781
    or the branch most recently merged using --remember.
 
2782
 
 
2783
    When merging a branch, by default the tip will be merged. To pick a different
 
2784
    revision, pass --revision. If you specify two values, the first will be used as
 
2785
    BASE and the second one as OTHER. Merging individual revisions, or a subset of
 
2786
    available revisions, like this is commonly referred to as "cherrypicking".
 
2787
 
 
2788
    Revision numbers are always relative to the branch being merged.
2379
2789
 
2380
2790
    By default, bzr will try to merge in all new work from the other
2381
2791
    branch, automatically determining an appropriate base.  If this
2396
2806
    The results of the merge are placed into the destination working
2397
2807
    directory, where they can be reviewed (with bzr diff), tested, and then
2398
2808
    committed to record the result of the merge.
2399
 
 
2400
 
    Examples:
2401
 
 
2402
 
    To merge the latest revision from bzr.dev
2403
 
    bzr merge ../bzr.dev
2404
 
 
2405
 
    To merge changes up to and including revision 82 from bzr.dev
2406
 
    bzr merge -r 82 ../bzr.dev
2407
 
 
2408
 
    To merge the changes introduced by 82, without previous changes:
2409
 
    bzr merge -r 81..82 ../bzr.dev
2410
2809
    
2411
2810
    merge refuses to run if there are any uncommitted changes, unless
2412
2811
    --force is given.
2413
2812
 
2414
 
    The following merge types are available:
 
2813
    :Examples:
 
2814
        To merge the latest revision from bzr.dev::
 
2815
 
 
2816
            bzr merge ../bzr.dev
 
2817
 
 
2818
        To merge changes up to and including revision 82 from bzr.dev::
 
2819
 
 
2820
            bzr merge -r 82 ../bzr.dev
 
2821
 
 
2822
        To merge the changes introduced by 82, without previous changes::
 
2823
 
 
2824
            bzr merge -r 81..82 ../bzr.dev
 
2825
 
 
2826
        To apply a merge directive contained in in /tmp/merge:
 
2827
 
 
2828
            bzr merge /tmp/merge
2415
2829
    """
2416
 
    takes_args = ['branch?']
2417
 
    takes_options = ['revision', 'force', 'merge-type', 'reprocess', 'remember',
 
2830
 
 
2831
    encoding_type = 'exact'
 
2832
    _see_also = ['update', 'remerge', 'status-flags']
 
2833
    takes_args = ['location?']
 
2834
    takes_options = [
 
2835
        'change',
 
2836
        'revision',
 
2837
        Option('force',
 
2838
               help='Merge even if the destination tree has uncommitted changes.'),
 
2839
        'merge-type',
 
2840
        'reprocess',
 
2841
        'remember',
2418
2842
        Option('show-base', help="Show base revision text in "
2419
 
               "conflicts"),
 
2843
               "conflicts."),
2420
2844
        Option('uncommitted', help='Apply uncommitted changes'
2421
 
               ' from a working copy, instead of branch changes'),
 
2845
               ' from a working copy, instead of branch changes.'),
2422
2846
        Option('pull', help='If the destination is already'
2423
2847
                ' completely merged into the source, pull from the'
2424
 
                ' source rather than merging. When this happens,'
 
2848
                ' source rather than merging.  When this happens,'
2425
2849
                ' you do not need to commit the result.'),
2426
2850
        Option('directory',
2427
 
            help='branch to merge into, '
2428
 
                 'rather than the one containing the working directory',
2429
 
            short_name='d',
2430
 
            type=unicode,
2431
 
            ),
 
2851
               help='Branch to merge into, '
 
2852
                    'rather than the one containing the working directory.',
 
2853
               short_name='d',
 
2854
               type=unicode,
 
2855
               ),
 
2856
        Option('preview', help='Instead of merging, show a diff of the merge.')
2432
2857
    ]
2433
2858
 
2434
 
    def run(self, branch=None, revision=None, force=False, merge_type=None,
2435
 
            show_base=False, reprocess=False, remember=False,
 
2859
    def run(self, location=None, revision=None, force=False,
 
2860
            merge_type=None, show_base=False, reprocess=False, remember=False,
2436
2861
            uncommitted=False, pull=False,
2437
2862
            directory=None,
 
2863
            preview=False,
2438
2864
            ):
2439
2865
        if merge_type is None:
2440
2866
            merge_type = _mod_merge.Merge3Merger
2441
2867
 
2442
2868
        if directory is None: directory = u'.'
 
2869
        possible_transports = []
 
2870
        merger = None
 
2871
        allow_pending = True
 
2872
        verified = 'inapplicable'
2443
2873
        tree = WorkingTree.open_containing(directory)[0]
2444
 
        change_reporter = delta.ChangeReporter(tree.inventory)
2445
 
 
2446
 
        if branch is not None:
2447
 
            try:
2448
 
                reader = bundle.read_bundle_from_url(branch)
2449
 
            except errors.NotABundle:
2450
 
                pass # Continue on considering this url a Branch
2451
 
            else:
2452
 
                conflicts = merge_bundle(reader, tree, not force, merge_type,
2453
 
                                         reprocess, show_base, change_reporter)
2454
 
                if conflicts == 0:
2455
 
                    return 0
 
2874
        change_reporter = delta._ChangeReporter(
 
2875
            unversioned_filter=tree.is_ignored)
 
2876
        cleanups = []
 
2877
        try:
 
2878
            pb = ui.ui_factory.nested_progress_bar()
 
2879
            cleanups.append(pb.finished)
 
2880
            tree.lock_write()
 
2881
            cleanups.append(tree.unlock)
 
2882
            if location is not None:
 
2883
                try:
 
2884
                    mergeable = bundle.read_mergeable_from_url(location,
 
2885
                        possible_transports=possible_transports)
 
2886
                except errors.NotABundle:
 
2887
                    mergeable = None
2456
2888
                else:
2457
 
                    return 1
2458
 
 
2459
 
        if revision is None \
2460
 
                or len(revision) < 1 or revision[0].needs_branch():
2461
 
            branch = self._get_remembered_parent(tree, branch, 'Merging from')
2462
 
 
2463
 
        if revision is None or len(revision) < 1:
2464
 
            if uncommitted:
2465
 
                base = [branch, -1]
2466
 
                other = [branch, None]
2467
 
            else:
2468
 
                base = [None, None]
2469
 
                other = [branch, -1]
2470
 
            other_branch, path = Branch.open_containing(branch)
2471
 
        else:
2472
 
            if uncommitted:
2473
 
                raise errors.BzrCommandError('Cannot use --uncommitted and'
2474
 
                                             ' --revision at the same time.')
2475
 
            branch = revision[0].get_branch() or branch
2476
 
            if len(revision) == 1:
2477
 
                base = [None, None]
2478
 
                other_branch, path = Branch.open_containing(branch)
2479
 
                revno = revision[0].in_history(other_branch).revno
2480
 
                other = [branch, revno]
2481
 
            else:
2482
 
                assert len(revision) == 2
2483
 
                if None in revision:
2484
 
                    raise errors.BzrCommandError(
2485
 
                        "Merge doesn't permit empty revision specifier.")
2486
 
                base_branch, path = Branch.open_containing(branch)
2487
 
                branch1 = revision[1].get_branch() or branch
2488
 
                other_branch, path1 = Branch.open_containing(branch1)
2489
 
                if revision[0].get_branch() is not None:
2490
 
                    # then path was obtained from it, and is None.
2491
 
                    path = path1
2492
 
 
2493
 
                base = [branch, revision[0].in_history(base_branch).revno]
2494
 
                other = [branch1, revision[1].in_history(other_branch).revno]
2495
 
 
2496
 
        if tree.branch.get_parent() is None or remember:
2497
 
            tree.branch.set_parent(other_branch.base)
2498
 
 
2499
 
        if path != "":
2500
 
            interesting_files = [path]
2501
 
        else:
2502
 
            interesting_files = None
2503
 
        pb = ui.ui_factory.nested_progress_bar()
2504
 
        try:
2505
 
            try:
2506
 
                conflict_count = _merge_helper(
2507
 
                    other, base, check_clean=(not force),
2508
 
                    merge_type=merge_type,
2509
 
                    reprocess=reprocess,
2510
 
                    show_base=show_base,
2511
 
                    pull=pull,
2512
 
                    this_dir=directory,
2513
 
                    pb=pb, file_list=interesting_files,
2514
 
                    change_reporter=change_reporter)
2515
 
            finally:
2516
 
                pb.finished()
2517
 
            if conflict_count != 0:
2518
 
                return 1
2519
 
            else:
 
2889
                    if uncommitted:
 
2890
                        raise errors.BzrCommandError('Cannot use --uncommitted'
 
2891
                            ' with bundles or merge directives.')
 
2892
 
 
2893
                    if revision is not None:
 
2894
                        raise errors.BzrCommandError(
 
2895
                            'Cannot use -r with merge directives or bundles')
 
2896
                    merger, verified = _mod_merge.Merger.from_mergeable(tree,
 
2897
                       mergeable, pb)
 
2898
 
 
2899
            if merger is None and uncommitted:
 
2900
                if revision is not None and len(revision) > 0:
 
2901
                    raise errors.BzrCommandError('Cannot use --uncommitted and'
 
2902
                        ' --revision at the same time.')
 
2903
                location = self._select_branch_location(tree, location)[0]
 
2904
                other_tree, other_path = WorkingTree.open_containing(location)
 
2905
                merger = _mod_merge.Merger.from_uncommitted(tree, other_tree,
 
2906
                    pb)
 
2907
                allow_pending = False
 
2908
                if other_path != '':
 
2909
                    merger.interesting_files = [other_path]
 
2910
 
 
2911
            if merger is None:
 
2912
                merger, allow_pending = self._get_merger_from_branch(tree,
 
2913
                    location, revision, remember, possible_transports, pb)
 
2914
 
 
2915
            merger.merge_type = merge_type
 
2916
            merger.reprocess = reprocess
 
2917
            merger.show_base = show_base
 
2918
            self.sanity_check_merger(merger)
 
2919
            if (merger.base_rev_id == merger.other_rev_id and
 
2920
                merger.other_rev_id != None):
 
2921
                note('Nothing to do.')
2520
2922
                return 0
2521
 
        except errors.AmbiguousBase, e:
2522
 
            m = ("sorry, bzr can't determine the right merge base yet\n"
2523
 
                 "candidates are:\n  "
2524
 
                 + "\n  ".join(e.bases)
2525
 
                 + "\n"
2526
 
                 "please specify an explicit base with -r,\n"
2527
 
                 "and (if you want) report this to the bzr developers\n")
2528
 
            log_error(m)
2529
 
 
2530
 
    # TODO: move up to common parent; this isn't merge-specific anymore. 
2531
 
    def _get_remembered_parent(self, tree, supplied_location, verb_string):
 
2923
            if pull:
 
2924
                if merger.interesting_files is not None:
 
2925
                    raise errors.BzrCommandError('Cannot pull individual files')
 
2926
                if (merger.base_rev_id == tree.last_revision()):
 
2927
                    result = tree.pull(merger.other_branch, False,
 
2928
                                       merger.other_rev_id)
 
2929
                    result.report(self.outf)
 
2930
                    return 0
 
2931
            merger.check_basis(not force)
 
2932
            if preview:
 
2933
                return self._do_preview(merger)
 
2934
            else:
 
2935
                return self._do_merge(merger, change_reporter, allow_pending,
 
2936
                                      verified)
 
2937
        finally:
 
2938
            for cleanup in reversed(cleanups):
 
2939
                cleanup()
 
2940
 
 
2941
    def _do_preview(self, merger):
 
2942
        from bzrlib.diff import show_diff_trees
 
2943
        tree_merger = merger.make_merger()
 
2944
        tt = tree_merger.make_preview_transform()
 
2945
        try:
 
2946
            result_tree = tt.get_preview_tree()
 
2947
            show_diff_trees(merger.this_tree, result_tree, self.outf,
 
2948
                            old_label='', new_label='')
 
2949
        finally:
 
2950
            tt.finalize()
 
2951
 
 
2952
    def _do_merge(self, merger, change_reporter, allow_pending, verified):
 
2953
        merger.change_reporter = change_reporter
 
2954
        conflict_count = merger.do_merge()
 
2955
        if allow_pending:
 
2956
            merger.set_pending()
 
2957
        if verified == 'failed':
 
2958
            warning('Preview patch does not match changes')
 
2959
        if conflict_count != 0:
 
2960
            return 1
 
2961
        else:
 
2962
            return 0
 
2963
 
 
2964
    def sanity_check_merger(self, merger):
 
2965
        if (merger.show_base and
 
2966
            not merger.merge_type is _mod_merge.Merge3Merger):
 
2967
            raise errors.BzrCommandError("Show-base is not supported for this"
 
2968
                                         " merge type. %s" % merger.merge_type)
 
2969
        if merger.reprocess and not merger.merge_type.supports_reprocess:
 
2970
            raise errors.BzrCommandError("Conflict reduction is not supported"
 
2971
                                         " for merge type %s." %
 
2972
                                         merger.merge_type)
 
2973
        if merger.reprocess and merger.show_base:
 
2974
            raise errors.BzrCommandError("Cannot do conflict reduction and"
 
2975
                                         " show base.")
 
2976
 
 
2977
    def _get_merger_from_branch(self, tree, location, revision, remember,
 
2978
                                possible_transports, pb):
 
2979
        """Produce a merger from a location, assuming it refers to a branch."""
 
2980
        from bzrlib.tag import _merge_tags_if_possible
 
2981
        assert revision is None or len(revision) < 3
 
2982
        # find the branch locations
 
2983
        other_loc, user_location = self._select_branch_location(tree, location,
 
2984
            revision, -1)
 
2985
        if revision is not None and len(revision) == 2:
 
2986
            base_loc, _unused = self._select_branch_location(tree,
 
2987
                location, revision, 0)
 
2988
        else:
 
2989
            base_loc = other_loc
 
2990
        # Open the branches
 
2991
        other_branch, other_path = Branch.open_containing(other_loc,
 
2992
            possible_transports)
 
2993
        if base_loc == other_loc:
 
2994
            base_branch = other_branch
 
2995
        else:
 
2996
            base_branch, base_path = Branch.open_containing(base_loc,
 
2997
                possible_transports)
 
2998
        # Find the revision ids
 
2999
        if revision is None or len(revision) < 1 or revision[-1] is None:
 
3000
            other_revision_id = _mod_revision.ensure_null(
 
3001
                other_branch.last_revision())
 
3002
        else:
 
3003
            other_revision_id = revision[-1].as_revision_id(other_branch)
 
3004
        if (revision is not None and len(revision) == 2
 
3005
            and revision[0] is not None):
 
3006
            base_revision_id = revision[0].as_revision_id(base_branch)
 
3007
        else:
 
3008
            base_revision_id = None
 
3009
        # Remember where we merge from
 
3010
        if ((remember or tree.branch.get_submit_branch() is None) and
 
3011
             user_location is not None):
 
3012
            tree.branch.set_submit_branch(other_branch.base)
 
3013
        _merge_tags_if_possible(other_branch, tree.branch)
 
3014
        merger = _mod_merge.Merger.from_revision_ids(pb, tree,
 
3015
            other_revision_id, base_revision_id, other_branch, base_branch)
 
3016
        if other_path != '':
 
3017
            allow_pending = False
 
3018
            merger.interesting_files = [other_path]
 
3019
        else:
 
3020
            allow_pending = True
 
3021
        return merger, allow_pending
 
3022
 
 
3023
    def _select_branch_location(self, tree, user_location, revision=None,
 
3024
                                index=None):
 
3025
        """Select a branch location, according to possible inputs.
 
3026
 
 
3027
        If provided, branches from ``revision`` are preferred.  (Both
 
3028
        ``revision`` and ``index`` must be supplied.)
 
3029
 
 
3030
        Otherwise, the ``location`` parameter is used.  If it is None, then the
 
3031
        ``submit`` or ``parent`` location is used, and a note is printed.
 
3032
 
 
3033
        :param tree: The working tree to select a branch for merging into
 
3034
        :param location: The location entered by the user
 
3035
        :param revision: The revision parameter to the command
 
3036
        :param index: The index to use for the revision parameter.  Negative
 
3037
            indices are permitted.
 
3038
        :return: (selected_location, user_location).  The default location
 
3039
            will be the user-entered location.
 
3040
        """
 
3041
        if (revision is not None and index is not None
 
3042
            and revision[index] is not None):
 
3043
            branch = revision[index].get_branch()
 
3044
            if branch is not None:
 
3045
                return branch, branch
 
3046
        if user_location is None:
 
3047
            location = self._get_remembered(tree, 'Merging from')
 
3048
        else:
 
3049
            location = user_location
 
3050
        return location, user_location
 
3051
 
 
3052
    def _get_remembered(self, tree, verb_string):
2532
3053
        """Use tree.branch's parent if none was supplied.
2533
3054
 
2534
3055
        Report if the remembered location was used.
2535
3056
        """
2536
 
        if supplied_location is not None:
2537
 
            return supplied_location
2538
 
        stored_location = tree.branch.get_parent()
 
3057
        stored_location = tree.branch.get_submit_branch()
 
3058
        if stored_location is None:
 
3059
            stored_location = tree.branch.get_parent()
2539
3060
        mutter("%s", stored_location)
2540
3061
        if stored_location is None:
2541
3062
            raise errors.BzrCommandError("No location specified or remembered")
2542
 
        display_url = urlutils.unescape_for_display(stored_location, self.outf.encoding)
2543
 
        self.outf.write("%s remembered location %s\n" % (verb_string, display_url))
 
3063
        display_url = urlutils.unescape_for_display(stored_location, 'utf-8')
 
3064
        note(u"%s remembered location %s", verb_string, display_url)
2544
3065
        return stored_location
2545
3066
 
2546
3067
 
2555
3076
    merge.  The difference is that remerge can (only) be run when there is a
2556
3077
    pending merge, and it lets you specify particular files.
2557
3078
 
2558
 
    Examples:
2559
 
    $ bzr remerge --show-base
 
3079
    :Examples:
2560
3080
        Re-do the merge of all conflicted files, and show the base text in
2561
 
        conflict regions, in addition to the usual THIS and OTHER texts.
 
3081
        conflict regions, in addition to the usual THIS and OTHER texts::
 
3082
      
 
3083
            bzr remerge --show-base
2562
3084
 
2563
 
    $ bzr remerge --merge-type weave --reprocess foobar
2564
3085
        Re-do the merge of "foobar", using the weave merge algorithm, with
2565
 
        additional processing to reduce the size of conflict regions.
2566
 
    
2567
 
    The following merge types are available:"""
 
3086
        additional processing to reduce the size of conflict regions::
 
3087
      
 
3088
            bzr remerge --merge-type weave --reprocess foobar
 
3089
    """
2568
3090
    takes_args = ['file*']
2569
 
    takes_options = ['merge-type', 'reprocess',
2570
 
                     Option('show-base', help="Show base revision text in "
2571
 
                            "conflicts")]
 
3091
    takes_options = [
 
3092
            'merge-type',
 
3093
            'reprocess',
 
3094
            Option('show-base',
 
3095
                   help="Show base revision text in conflicts."),
 
3096
            ]
2572
3097
 
2573
3098
    def run(self, file_list=None, merge_type=None, show_base=False,
2574
3099
            reprocess=False):
2583
3108
                                             " merges.  Not cherrypicking or"
2584
3109
                                             " multi-merges.")
2585
3110
            repository = tree.branch.repository
2586
 
            base_revision = common_ancestor(parents[0],
2587
 
                                            parents[1], repository)
2588
 
            base_tree = repository.revision_tree(base_revision)
2589
 
            other_tree = repository.revision_tree(parents[1])
2590
3111
            interesting_ids = None
2591
3112
            new_conflicts = []
2592
3113
            conflicts = tree.conflicts()
2617
3138
                    restore(tree.abspath(filename))
2618
3139
                except errors.NotConflicted:
2619
3140
                    pass
2620
 
            conflicts = _mod_merge.merge_inner(
2621
 
                                      tree.branch, other_tree, base_tree,
2622
 
                                      this_tree=tree,
2623
 
                                      interesting_ids=interesting_ids,
2624
 
                                      other_rev_id=parents[1],
2625
 
                                      merge_type=merge_type,
2626
 
                                      show_base=show_base,
2627
 
                                      reprocess=reprocess)
 
3141
            # Disable pending merges, because the file texts we are remerging
 
3142
            # have not had those merges performed.  If we use the wrong parents
 
3143
            # list, we imply that the working tree text has seen and rejected
 
3144
            # all the changes from the other tree, when in fact those changes
 
3145
            # have not yet been seen.
 
3146
            pb = ui.ui_factory.nested_progress_bar()
 
3147
            tree.set_parent_ids(parents[:1])
 
3148
            try:
 
3149
                merger = _mod_merge.Merger.from_revision_ids(pb,
 
3150
                                                             tree, parents[1])
 
3151
                merger.interesting_ids = interesting_ids
 
3152
                merger.merge_type = merge_type
 
3153
                merger.show_base = show_base
 
3154
                merger.reprocess = reprocess
 
3155
                conflicts = merger.do_merge()
 
3156
            finally:
 
3157
                tree.set_parent_ids(parents)
 
3158
                pb.finished()
2628
3159
        finally:
2629
3160
            tree.unlock()
2630
3161
        if conflicts > 0:
2641
3172
    last committed revision is used.
2642
3173
 
2643
3174
    To remove only some changes, without reverting to a prior version, use
2644
 
    merge instead.  For example, "merge . --r-2..-3" will remove the changes
2645
 
    introduced by -2, without affecting the changes introduced by -1.  Or
2646
 
    to remove certain changes on a hunk-by-hunk basis, see the Shelf plugin.
 
3175
    merge instead.  For example, "merge . --revision -2..-3" will remove the
 
3176
    changes introduced by -2, without affecting the changes introduced by -1.
 
3177
    Or to remove certain changes on a hunk-by-hunk basis, see the Shelf plugin.
2647
3178
    
2648
3179
    By default, any files that have been manually changed will be backed up
2649
3180
    first.  (Files changed only by merge are not backed up.)  Backup files have
2653
3184
    from the target revision.  So you can use revert to "undelete" a file by
2654
3185
    name.  If you name a directory, all the contents of that directory will be
2655
3186
    reverted.
 
3187
 
 
3188
    Any files that have been newly added since that revision will be deleted,
 
3189
    with a backup kept if appropriate.  Directories containing unknown files
 
3190
    will not be deleted.
 
3191
 
 
3192
    The working tree contains a list of pending merged revisions, which will
 
3193
    be included as parents in the next commit.  Normally, revert clears that
 
3194
    list as well as reverting the files.  If any files are specified, revert
 
3195
    leaves the pending merge list alone and reverts only the files.  Use "bzr
 
3196
    revert ." in the tree root to revert all files but keep the merge record,
 
3197
    and "bzr revert --forget-merges" to clear the pending merge list without
 
3198
    reverting any files.
2656
3199
    """
2657
 
    takes_options = ['revision', 'no-backup']
 
3200
 
 
3201
    _see_also = ['cat', 'export']
 
3202
    takes_options = [
 
3203
        'revision',
 
3204
        Option('no-backup', "Do not save backups of reverted files."),
 
3205
        Option('forget-merges',
 
3206
               'Remove pending merge marker, without changing any files.'),
 
3207
        ]
2658
3208
    takes_args = ['file*']
2659
 
    aliases = ['merge-revert']
2660
3209
 
2661
 
    def run(self, revision=None, no_backup=False, file_list=None):
2662
 
        if file_list is not None:
2663
 
            if len(file_list) == 0:
2664
 
                raise errors.BzrCommandError("No files specified")
 
3210
    def run(self, revision=None, no_backup=False, file_list=None,
 
3211
            forget_merges=None):
 
3212
        tree, file_list = tree_files(file_list)
 
3213
        if forget_merges:
 
3214
            tree.set_parent_ids(tree.get_parent_ids()[:1])
2665
3215
        else:
2666
 
            file_list = []
2667
 
        
2668
 
        tree, file_list = tree_files(file_list)
 
3216
            self._revert_tree_to_revision(tree, revision, file_list, no_backup)
 
3217
 
 
3218
    @staticmethod
 
3219
    def _revert_tree_to_revision(tree, revision, file_list, no_backup):
2669
3220
        if revision is None:
2670
 
            # FIXME should be tree.last_revision
2671
3221
            rev_id = tree.last_revision()
2672
3222
        elif len(revision) != 1:
2673
3223
            raise errors.BzrCommandError('bzr revert --revision takes exactly 1 argument')
2674
3224
        else:
2675
 
            rev_id = revision[0].in_history(tree.branch).rev_id
 
3225
            rev_id = revision[0].as_revision_id(tree.branch)
2676
3226
        pb = ui.ui_factory.nested_progress_bar()
2677
3227
        try:
2678
 
            tree.revert(file_list, 
 
3228
            tree.revert(file_list,
2679
3229
                        tree.branch.repository.revision_tree(rev_id),
2680
3230
                        not no_backup, pb, report_changes=True)
2681
3231
        finally:
2694
3244
 
2695
3245
class cmd_help(Command):
2696
3246
    """Show help on a command or other topic.
 
3247
    """
2697
3248
 
2698
 
    For a list of all available commands, say 'bzr help commands'.
2699
 
    """
2700
 
    takes_options = [Option('long', 'show help on all commands')]
 
3249
    _see_also = ['topics']
 
3250
    takes_options = [
 
3251
            Option('long', 'Show help on all commands.'),
 
3252
            ]
2701
3253
    takes_args = ['topic?']
2702
3254
    aliases = ['?', '--help', '-?', '-h']
2703
3255
    
2740
3292
 
2741
3293
class cmd_missing(Command):
2742
3294
    """Show unmerged/unpulled revisions between two branches.
2743
 
 
 
3295
    
2744
3296
    OTHER_BRANCH may be local or remote.
2745
3297
    """
 
3298
 
 
3299
    _see_also = ['merge', 'pull']
2746
3300
    takes_args = ['other_branch?']
2747
 
    takes_options = [Option('reverse', 'Reverse the order of revisions'),
2748
 
                     Option('mine-only', 
2749
 
                            'Display changes in the local branch only'),
2750
 
                     Option('theirs-only', 
2751
 
                            'Display changes in the remote branch only'), 
2752
 
                     'log-format',
2753
 
                     'show-ids',
2754
 
                     'verbose'
2755
 
                     ]
 
3301
    takes_options = [
 
3302
            Option('reverse', 'Reverse the order of revisions.'),
 
3303
            Option('mine-only',
 
3304
                   'Display changes in the local branch only.'),
 
3305
            Option('this' , 'Same as --mine-only.'),
 
3306
            Option('theirs-only',
 
3307
                   'Display changes in the remote branch only.'),
 
3308
            Option('other', 'Same as --theirs-only.'),
 
3309
            'log-format',
 
3310
            'show-ids',
 
3311
            'verbose'
 
3312
            ]
2756
3313
    encoding_type = 'replace'
2757
3314
 
2758
3315
    @display_command
2759
3316
    def run(self, other_branch=None, reverse=False, mine_only=False,
2760
3317
            theirs_only=False, log_format=None, long=False, short=False, line=False, 
2761
 
            show_ids=False, verbose=False):
2762
 
        from bzrlib.missing import find_unmerged, iter_log_data
2763
 
        from bzrlib.log import log_formatter
 
3318
            show_ids=False, verbose=False, this=False, other=False):
 
3319
        from bzrlib.missing import find_unmerged, iter_log_revisions
 
3320
 
 
3321
        if this:
 
3322
          mine_only = this
 
3323
        if other:
 
3324
          theirs_only = other
 
3325
 
2764
3326
        local_branch = Branch.open_containing(u".")[0]
2765
3327
        parent = local_branch.get_parent()
2766
3328
        if other_branch is None:
2767
3329
            other_branch = parent
2768
3330
            if other_branch is None:
2769
 
                raise errors.BzrCommandError("No peer location known or specified.")
 
3331
                raise errors.BzrCommandError("No peer location known"
 
3332
                                             " or specified.")
2770
3333
            display_url = urlutils.unescape_for_display(parent,
2771
3334
                                                        self.outf.encoding)
2772
 
            print "Using last location: " + display_url
 
3335
            self.outf.write("Using last location: " + display_url + "\n")
2773
3336
 
2774
3337
        remote_branch = Branch.open(other_branch)
2775
3338
        if remote_branch.base == local_branch.base:
2778
3341
        try:
2779
3342
            remote_branch.lock_read()
2780
3343
            try:
2781
 
                local_extra, remote_extra = find_unmerged(local_branch, remote_branch)
2782
 
                if (log_format is None):
2783
 
                    log_format = log.log_formatter_registry.get_default(
2784
 
                        local_branch)
 
3344
                local_extra, remote_extra = find_unmerged(local_branch,
 
3345
                                                          remote_branch)
 
3346
                if log_format is None:
 
3347
                    registry = log.log_formatter_registry
 
3348
                    log_format = registry.get_default(local_branch)
2785
3349
                lf = log_format(to_file=self.outf,
2786
3350
                                show_ids=show_ids,
2787
3351
                                show_timezone='original')
2789
3353
                    local_extra.reverse()
2790
3354
                    remote_extra.reverse()
2791
3355
                if local_extra and not theirs_only:
2792
 
                    print "You have %d extra revision(s):" % len(local_extra)
2793
 
                    for data in iter_log_data(local_extra, local_branch.repository,
2794
 
                                              verbose):
2795
 
                        lf.show(*data)
 
3356
                    self.outf.write("You have %d extra revision(s):\n" %
 
3357
                                    len(local_extra))
 
3358
                    for revision in iter_log_revisions(local_extra,
 
3359
                                        local_branch.repository,
 
3360
                                        verbose):
 
3361
                        lf.log_revision(revision)
2796
3362
                    printed_local = True
2797
3363
                else:
2798
3364
                    printed_local = False
2799
3365
                if remote_extra and not mine_only:
2800
3366
                    if printed_local is True:
2801
 
                        print "\n\n"
2802
 
                    print "You are missing %d revision(s):" % len(remote_extra)
2803
 
                    for data in iter_log_data(remote_extra, remote_branch.repository, 
2804
 
                                              verbose):
2805
 
                        lf.show(*data)
 
3367
                        self.outf.write("\n\n\n")
 
3368
                    self.outf.write("You are missing %d revision(s):\n" %
 
3369
                                    len(remote_extra))
 
3370
                    for revision in iter_log_revisions(remote_extra,
 
3371
                                        remote_branch.repository,
 
3372
                                        verbose):
 
3373
                        lf.log_revision(revision)
2806
3374
                if not remote_extra and not local_extra:
2807
3375
                    status_code = 0
2808
 
                    print "Branches are up to date."
 
3376
                    self.outf.write("Branches are up to date.\n")
2809
3377
                else:
2810
3378
                    status_code = 1
2811
3379
            finally:
2823
3391
        return status_code
2824
3392
 
2825
3393
 
 
3394
class cmd_pack(Command):
 
3395
    """Compress the data within a repository."""
 
3396
 
 
3397
    _see_also = ['repositories']
 
3398
    takes_args = ['branch_or_repo?']
 
3399
 
 
3400
    def run(self, branch_or_repo='.'):
 
3401
        dir = bzrdir.BzrDir.open_containing(branch_or_repo)[0]
 
3402
        try:
 
3403
            branch = dir.open_branch()
 
3404
            repository = branch.repository
 
3405
        except errors.NotBranchError:
 
3406
            repository = dir.open_repository()
 
3407
        repository.pack()
 
3408
 
 
3409
 
2826
3410
class cmd_plugins(Command):
2827
 
    """List plugins"""
2828
 
    hidden = True
 
3411
    """List the installed plugins.
 
3412
    
 
3413
    This command displays the list of installed plugins including
 
3414
    version of plugin and a short description of each.
 
3415
 
 
3416
    --verbose shows the path where each plugin is located.
 
3417
 
 
3418
    A plugin is an external component for Bazaar that extends the
 
3419
    revision control system, by adding or replacing code in Bazaar.
 
3420
    Plugins can do a variety of things, including overriding commands,
 
3421
    adding new commands, providing additional network transports and
 
3422
    customizing log output.
 
3423
 
 
3424
    See the Bazaar web site, http://bazaar-vcs.org, for further
 
3425
    information on plugins including where to find them and how to
 
3426
    install them. Instructions are also provided there on how to
 
3427
    write new plugins using the Python programming language.
 
3428
    """
 
3429
    takes_options = ['verbose']
 
3430
 
2829
3431
    @display_command
2830
 
    def run(self):
 
3432
    def run(self, verbose=False):
2831
3433
        import bzrlib.plugin
2832
3434
        from inspect import getdoc
2833
 
        for name, plugin in bzrlib.plugin.all_plugins().items():
2834
 
            if getattr(plugin, '__path__', None) is not None:
2835
 
                print plugin.__path__[0]
2836
 
            elif getattr(plugin, '__file__', None) is not None:
2837
 
                print plugin.__file__
2838
 
            else:
2839
 
                print repr(plugin)
2840
 
                
2841
 
            d = getdoc(plugin)
 
3435
        result = []
 
3436
        for name, plugin in bzrlib.plugin.plugins().items():
 
3437
            version = plugin.__version__
 
3438
            if version == 'unknown':
 
3439
                version = ''
 
3440
            name_ver = '%s %s' % (name, version)
 
3441
            d = getdoc(plugin.module)
2842
3442
            if d:
2843
 
                print '\t', d.split('\n')[0]
 
3443
                doc = d.split('\n')[0]
 
3444
            else:
 
3445
                doc = '(no description)'
 
3446
            result.append((name_ver, doc, plugin.path()))
 
3447
        for name_ver, doc, path in sorted(result):
 
3448
            print name_ver
 
3449
            print '   ', doc
 
3450
            if verbose:
 
3451
                print '   ', path
 
3452
            print
2844
3453
 
2845
3454
 
2846
3455
class cmd_testament(Command):
2847
3456
    """Show testament (signing-form) of a revision."""
2848
 
    takes_options = ['revision', 
2849
 
                     Option('long', help='Produce long-format testament'), 
2850
 
                     Option('strict', help='Produce a strict-format'
2851
 
                            ' testament')]
 
3457
    takes_options = [
 
3458
            'revision',
 
3459
            Option('long', help='Produce long-format testament.'),
 
3460
            Option('strict',
 
3461
                   help='Produce a strict-format testament.')]
2852
3462
    takes_args = ['branch?']
2853
3463
    @display_command
2854
3464
    def run(self, branch=u'.', revision=None, long=False, strict=False):
2863
3473
            if revision is None:
2864
3474
                rev_id = b.last_revision()
2865
3475
            else:
2866
 
                rev_id = revision[0].in_history(b).rev_id
 
3476
                rev_id = revision[0].as_revision_id(b)
2867
3477
            t = testament_class.from_revision(b.repository, rev_id)
2868
3478
            if long:
2869
3479
                sys.stdout.writelines(t.as_text_lines())
2887
3497
    #       with new uncommitted lines marked
2888
3498
    aliases = ['ann', 'blame', 'praise']
2889
3499
    takes_args = ['filename']
2890
 
    takes_options = [Option('all', help='show annotations on all lines'),
2891
 
                     Option('long', help='show date in annotations'),
 
3500
    takes_options = [Option('all', help='Show annotations on all lines.'),
 
3501
                     Option('long', help='Show commit date in annotations.'),
2892
3502
                     'revision',
2893
3503
                     'show-ids',
2894
3504
                     ]
 
3505
    encoding_type = 'exact'
2895
3506
 
2896
3507
    @display_command
2897
3508
    def run(self, filename, all=False, long=False, revision=None,
2898
3509
            show_ids=False):
2899
3510
        from bzrlib.annotate import annotate_file
2900
 
        tree, relpath = WorkingTree.open_containing(filename)
2901
 
        branch = tree.branch
2902
 
        branch.lock_read()
 
3511
        wt, branch, relpath = \
 
3512
            bzrdir.BzrDir.open_containing_tree_or_branch(filename)
 
3513
        if wt is not None:
 
3514
            wt.lock_read()
 
3515
        else:
 
3516
            branch.lock_read()
2903
3517
        try:
2904
3518
            if revision is None:
2905
3519
                revision_id = branch.last_revision()
2906
3520
            elif len(revision) != 1:
2907
3521
                raise errors.BzrCommandError('bzr annotate --revision takes exactly 1 argument')
2908
3522
            else:
2909
 
                revision_id = revision[0].in_history(branch).rev_id
2910
 
            file_id = tree.inventory.path2id(relpath)
 
3523
                revision_id = revision[0].as_revision_id(branch)
2911
3524
            tree = branch.repository.revision_tree(revision_id)
 
3525
            if wt is not None:
 
3526
                file_id = wt.path2id(relpath)
 
3527
            else:
 
3528
                file_id = tree.path2id(relpath)
 
3529
            if file_id is None:
 
3530
                raise errors.NotVersionedError(filename)
2912
3531
            file_version = tree.inventory[file_id].revision
2913
 
            annotate_file(branch, file_version, file_id, long, all, sys.stdout,
 
3532
            annotate_file(branch, file_version, file_id, long, all, self.outf,
2914
3533
                          show_ids=show_ids)
2915
3534
        finally:
2916
 
            branch.unlock()
 
3535
            if wt is not None:
 
3536
                wt.unlock()
 
3537
            else:
 
3538
                branch.unlock()
2917
3539
 
2918
3540
 
2919
3541
class cmd_re_sign(Command):
2925
3547
    takes_options = ['revision']
2926
3548
    
2927
3549
    def run(self, revision_id_list=None, revision=None):
2928
 
        import bzrlib.gpg as gpg
2929
3550
        if revision_id_list is not None and revision is not None:
2930
3551
            raise errors.BzrCommandError('You can only supply one of revision_id or --revision')
2931
3552
        if revision_id_list is None and revision is None:
2932
3553
            raise errors.BzrCommandError('You must supply either --revision or a revision_id')
2933
3554
        b = WorkingTree.open_containing(u'.')[0].branch
 
3555
        b.lock_write()
 
3556
        try:
 
3557
            return self._run(b, revision_id_list, revision)
 
3558
        finally:
 
3559
            b.unlock()
 
3560
 
 
3561
    def _run(self, b, revision_id_list, revision):
 
3562
        import bzrlib.gpg as gpg
2934
3563
        gpg_strategy = gpg.GPGStrategy(b.get_config())
2935
3564
        if revision_id_list is not None:
2936
 
            for revision_id in revision_id_list:
2937
 
                b.repository.sign_revision(revision_id, gpg_strategy)
 
3565
            b.repository.start_write_group()
 
3566
            try:
 
3567
                for revision_id in revision_id_list:
 
3568
                    b.repository.sign_revision(revision_id, gpg_strategy)
 
3569
            except:
 
3570
                b.repository.abort_write_group()
 
3571
                raise
 
3572
            else:
 
3573
                b.repository.commit_write_group()
2938
3574
        elif revision is not None:
2939
3575
            if len(revision) == 1:
2940
3576
                revno, rev_id = revision[0].in_history(b)
2941
 
                b.repository.sign_revision(rev_id, gpg_strategy)
 
3577
                b.repository.start_write_group()
 
3578
                try:
 
3579
                    b.repository.sign_revision(rev_id, gpg_strategy)
 
3580
                except:
 
3581
                    b.repository.abort_write_group()
 
3582
                    raise
 
3583
                else:
 
3584
                    b.repository.commit_write_group()
2942
3585
            elif len(revision) == 2:
2943
3586
                # are they both on rh- if so we can walk between them
2944
3587
                # might be nice to have a range helper for arbitrary
2949
3592
                    to_revno = b.revno()
2950
3593
                if from_revno is None or to_revno is None:
2951
3594
                    raise errors.BzrCommandError('Cannot sign a range of non-revision-history revisions')
2952
 
                for revno in range(from_revno, to_revno + 1):
2953
 
                    b.repository.sign_revision(b.get_rev_id(revno), 
2954
 
                                               gpg_strategy)
 
3595
                b.repository.start_write_group()
 
3596
                try:
 
3597
                    for revno in range(from_revno, to_revno + 1):
 
3598
                        b.repository.sign_revision(b.get_rev_id(revno),
 
3599
                                                   gpg_strategy)
 
3600
                except:
 
3601
                    b.repository.abort_write_group()
 
3602
                    raise
 
3603
                else:
 
3604
                    b.repository.commit_write_group()
2955
3605
            else:
2956
3606
                raise errors.BzrCommandError('Please supply either one revision, or a range.')
2957
3607
 
2961
3611
 
2962
3612
    Once converted into a checkout, commits must succeed on the master branch
2963
3613
    before they will be applied to the local branch.
2964
 
 
2965
 
    See "help checkouts" for more information on checkouts.
2966
3614
    """
2967
3615
 
 
3616
    _see_also = ['checkouts', 'unbind']
2968
3617
    takes_args = ['location?']
2969
3618
    takes_options = []
2970
3619
 
2993
3642
 
2994
3643
    After unbinding, the local branch is considered independent and subsequent
2995
3644
    commits will be local only.
2996
 
 
2997
 
    See "help checkouts" for more information on checkouts.
2998
3645
    """
2999
3646
 
 
3647
    _see_also = ['checkouts', 'bind']
3000
3648
    takes_args = []
3001
3649
    takes_options = []
3002
3650
 
3012
3660
    --verbose will print out what is being removed.
3013
3661
    --dry-run will go through all the motions, but not actually
3014
3662
    remove anything.
3015
 
    
 
3663
 
 
3664
    If --revision is specified, uncommit revisions to leave the branch at the
 
3665
    specified revision.  For example, "bzr uncommit -r 15" will leave the
 
3666
    branch at revision 15.
 
3667
 
3016
3668
    In the future, uncommit will create a revision bundle, which can then
3017
3669
    be re-applied.
3018
3670
    """
3021
3673
    # unreferenced information in 'branch-as-repository' branches.
3022
3674
    # TODO: jam 20060108 Add the ability for uncommit to remove unreferenced
3023
3675
    # information in shared branches as well.
 
3676
    _see_also = ['commit']
3024
3677
    takes_options = ['verbose', 'revision',
3025
 
                    Option('dry-run', help='Don\'t actually make changes'),
3026
 
                    Option('force', help='Say yes to all questions.')]
 
3678
                    Option('dry-run', help='Don\'t actually make changes.'),
 
3679
                    Option('force', help='Say yes to all questions.'),
 
3680
                    Option('local',
 
3681
                           help="Only remove the commits from the local branch"
 
3682
                                " when in a checkout."
 
3683
                           ),
 
3684
                    ]
3027
3685
    takes_args = ['location?']
3028
3686
    aliases = []
 
3687
    encoding_type = 'replace'
3029
3688
 
3030
3689
    def run(self, location=None,
3031
3690
            dry_run=False, verbose=False,
3032
 
            revision=None, force=False):
3033
 
        from bzrlib.log import log_formatter, show_log
3034
 
        import sys
3035
 
        from bzrlib.uncommit import uncommit
3036
 
 
 
3691
            revision=None, force=False, local=False):
3037
3692
        if location is None:
3038
3693
            location = u'.'
3039
3694
        control, relpath = bzrdir.BzrDir.open_containing(location)
3044
3699
            tree = None
3045
3700
            b = control.open_branch()
3046
3701
 
 
3702
        if tree is not None:
 
3703
            tree.lock_write()
 
3704
        else:
 
3705
            b.lock_write()
 
3706
        try:
 
3707
            return self._run(b, tree, dry_run, verbose, revision, force,
 
3708
                             local=local)
 
3709
        finally:
 
3710
            if tree is not None:
 
3711
                tree.unlock()
 
3712
            else:
 
3713
                b.unlock()
 
3714
 
 
3715
    def _run(self, b, tree, dry_run, verbose, revision, force, local=False):
 
3716
        from bzrlib.log import log_formatter, show_log
 
3717
        from bzrlib.uncommit import uncommit
 
3718
 
 
3719
        last_revno, last_rev_id = b.last_revision_info()
 
3720
 
3047
3721
        rev_id = None
3048
3722
        if revision is None:
3049
 
            revno = b.revno()
 
3723
            revno = last_revno
 
3724
            rev_id = last_rev_id
3050
3725
        else:
3051
3726
            # 'bzr uncommit -r 10' actually means uncommit
3052
3727
            # so that the final tree is at revno 10.
3053
3728
            # but bzrlib.uncommit.uncommit() actually uncommits
3054
3729
            # the revisions that are supplied.
3055
3730
            # So we need to offset it by one
3056
 
            revno = revision[0].in_history(b).revno+1
 
3731
            revno = revision[0].in_history(b).revno + 1
 
3732
            if revno <= last_revno:
 
3733
                rev_id = b.get_rev_id(revno)
3057
3734
 
3058
 
        if revno <= b.revno():
3059
 
            rev_id = b.get_rev_id(revno)
3060
 
        if rev_id is None:
 
3735
        if rev_id is None or _mod_revision.is_null(rev_id):
3061
3736
            self.outf.write('No revisions to uncommit.\n')
3062
3737
            return 1
3063
3738
 
3070
3745
                 verbose=False,
3071
3746
                 direction='forward',
3072
3747
                 start_revision=revno,
3073
 
                 end_revision=b.revno())
 
3748
                 end_revision=last_revno)
3074
3749
 
3075
3750
        if dry_run:
3076
3751
            print 'Dry-run, pretending to remove the above revisions.'
3085
3760
                    return 0
3086
3761
 
3087
3762
        uncommit(b, tree=tree, dry_run=dry_run, verbose=verbose,
3088
 
                revno=revno)
 
3763
                 revno=revno, local=local)
3089
3764
 
3090
3765
 
3091
3766
class cmd_break_lock(Command):
3096
3771
 
3097
3772
    You can get information on what locks are open via the 'bzr info' command.
3098
3773
    
3099
 
    example:
 
3774
    :Examples:
3100
3775
        bzr break-lock
3101
3776
    """
3102
3777
    takes_args = ['location?']
3132
3807
 
3133
3808
    takes_options = [
3134
3809
        Option('inet',
3135
 
               help='serve on stdin/out for use from inetd or sshd'),
 
3810
               help='Serve on stdin/out for use from inetd or sshd.'),
3136
3811
        Option('port',
3137
 
               help='listen for connections on nominated port of the form '
3138
 
                    '[hostname:]portnumber. Passing 0 as the port number will '
3139
 
                    'result in a dynamically allocated port.',
 
3812
               help='Listen for connections on nominated port of the form '
 
3813
                    '[hostname:]portnumber.  Passing 0 as the port number will '
 
3814
                    'result in a dynamically allocated port.  The default port is '
 
3815
                    '4155.',
3140
3816
               type=str),
3141
3817
        Option('directory',
3142
 
               help='serve contents of directory',
 
3818
               help='Serve contents of this directory.',
3143
3819
               type=unicode),
3144
3820
        Option('allow-writes',
3145
 
               help='By default the server is a readonly server. Supplying '
 
3821
               help='By default the server is a readonly server.  Supplying '
3146
3822
                    '--allow-writes enables write access to the contents of '
3147
 
                    'the served directory and below. '
 
3823
                    'the served directory and below.'
3148
3824
                ),
3149
3825
        ]
3150
3826
 
3151
3827
    def run(self, port=None, inet=False, directory=None, allow_writes=False):
3152
 
        from bzrlib.transport import smart
 
3828
        from bzrlib import lockdir
 
3829
        from bzrlib.smart import medium, server
3153
3830
        from bzrlib.transport import get_transport
 
3831
        from bzrlib.transport.chroot import ChrootServer
3154
3832
        if directory is None:
3155
3833
            directory = os.getcwd()
3156
3834
        url = urlutils.local_path_to_url(directory)
3157
3835
        if not allow_writes:
3158
3836
            url = 'readonly+' + url
3159
 
        t = get_transport(url)
 
3837
        chroot_server = ChrootServer(get_transport(url))
 
3838
        chroot_server.setUp()
 
3839
        t = get_transport(chroot_server.get_url())
3160
3840
        if inet:
3161
 
            server = smart.SmartServerPipeStreamMedium(sys.stdin, sys.stdout, t)
3162
 
        elif port is not None:
3163
 
            if ':' in port:
3164
 
                host, port = port.split(':')
 
3841
            smart_server = medium.SmartServerPipeStreamMedium(
 
3842
                sys.stdin, sys.stdout, t)
 
3843
        else:
 
3844
            host = medium.BZR_DEFAULT_INTERFACE
 
3845
            if port is None:
 
3846
                port = medium.BZR_DEFAULT_PORT
3165
3847
            else:
3166
 
                host = '127.0.0.1'
3167
 
            server = smart.SmartTCPServer(t, host=host, port=int(port))
3168
 
            print 'listening on port: ', server.port
 
3848
                if ':' in port:
 
3849
                    host, port = port.split(':')
 
3850
                port = int(port)
 
3851
            smart_server = server.SmartTCPServer(t, host=host, port=port)
 
3852
            print 'listening on port: ', smart_server.port
3169
3853
            sys.stdout.flush()
3170
 
        else:
3171
 
            raise errors.BzrCommandError("bzr serve requires one of --inet or --port")
3172
 
        server.serve()
3173
 
 
3174
 
 
3175
 
# command-line interpretation helper for merge-related commands
3176
 
def _merge_helper(other_revision, base_revision,
3177
 
                  check_clean=True, ignore_zero=False,
3178
 
                  this_dir=None, backup_files=False,
3179
 
                  merge_type=None,
3180
 
                  file_list=None, show_base=False, reprocess=False,
3181
 
                  pull=False,
3182
 
                  pb=DummyProgress(),
3183
 
                  change_reporter=None):
3184
 
    """Merge changes into a tree.
3185
 
 
3186
 
    base_revision
3187
 
        list(path, revno) Base for three-way merge.  
3188
 
        If [None, None] then a base will be automatically determined.
3189
 
    other_revision
3190
 
        list(path, revno) Other revision for three-way merge.
3191
 
    this_dir
3192
 
        Directory to merge changes into; '.' by default.
3193
 
    check_clean
3194
 
        If true, this_dir must have no uncommitted changes before the
3195
 
        merge begins.
3196
 
    ignore_zero - If true, suppress the "zero conflicts" message when 
3197
 
        there are no conflicts; should be set when doing something we expect
3198
 
        to complete perfectly.
3199
 
    file_list - If supplied, merge only changes to selected files.
3200
 
 
3201
 
    All available ancestors of other_revision and base_revision are
3202
 
    automatically pulled into the branch.
3203
 
 
3204
 
    The revno may be -1 to indicate the last revision on the branch, which is
3205
 
    the typical case.
3206
 
 
3207
 
    This function is intended for use from the command line; programmatic
3208
 
    clients might prefer to call merge.merge_inner(), which has less magic 
3209
 
    behavior.
3210
 
    """
3211
 
    # Loading it late, so that we don't always have to import bzrlib.merge
3212
 
    if merge_type is None:
3213
 
        merge_type = _mod_merge.Merge3Merger
3214
 
    if this_dir is None:
3215
 
        this_dir = u'.'
3216
 
    this_tree = WorkingTree.open_containing(this_dir)[0]
3217
 
    if show_base and not merge_type is _mod_merge.Merge3Merger:
3218
 
        raise errors.BzrCommandError("Show-base is not supported for this merge"
3219
 
                                     " type. %s" % merge_type)
3220
 
    if reprocess and not merge_type.supports_reprocess:
3221
 
        raise errors.BzrCommandError("Conflict reduction is not supported for merge"
3222
 
                                     " type %s." % merge_type)
3223
 
    if reprocess and show_base:
3224
 
        raise errors.BzrCommandError("Cannot do conflict reduction and show base.")
3225
 
    try:
3226
 
        merger = _mod_merge.Merger(this_tree.branch, this_tree=this_tree,
3227
 
                                   pb=pb, change_reporter=change_reporter)
3228
 
        merger.pp = ProgressPhase("Merge phase", 5, pb)
3229
 
        merger.pp.next_phase()
3230
 
        merger.check_basis(check_clean)
3231
 
        merger.set_other(other_revision)
3232
 
        merger.pp.next_phase()
3233
 
        merger.set_base(base_revision)
3234
 
        if merger.base_rev_id == merger.other_rev_id:
3235
 
            note('Nothing to do.')
3236
 
            return 0
3237
 
        if file_list is None:
3238
 
            if pull and merger.base_rev_id == merger.this_rev_id:
3239
 
                count = merger.this_tree.pull(merger.this_branch,
3240
 
                        False, merger.other_rev_id)
3241
 
                note('%d revision(s) pulled.' % (count,))
3242
 
                return 0
3243
 
        merger.backup_files = backup_files
3244
 
        merger.merge_type = merge_type 
3245
 
        merger.set_interesting_files(file_list)
3246
 
        merger.show_base = show_base 
3247
 
        merger.reprocess = reprocess
3248
 
        conflicts = merger.do_merge()
3249
 
        if file_list is None:
3250
 
            merger.set_pending()
3251
 
    finally:
3252
 
        pb.clear()
3253
 
    return conflicts
3254
 
 
3255
 
 
3256
 
# Compatibility
3257
 
merge = _merge_helper
 
3854
        # for the duration of this server, no UI output is permitted.
 
3855
        # note that this may cause problems with blackbox tests. This should
 
3856
        # be changed with care though, as we dont want to use bandwidth sending
 
3857
        # progress over stderr to smart server clients!
 
3858
        old_factory = ui.ui_factory
 
3859
        old_lockdir_timeout = lockdir._DEFAULT_TIMEOUT_SECONDS
 
3860
        try:
 
3861
            ui.ui_factory = ui.SilentUIFactory()
 
3862
            lockdir._DEFAULT_TIMEOUT_SECONDS = 0
 
3863
            smart_server.serve()
 
3864
        finally:
 
3865
            ui.ui_factory = old_factory
 
3866
            lockdir._DEFAULT_TIMEOUT_SECONDS = old_lockdir_timeout
 
3867
 
 
3868
 
 
3869
class cmd_join(Command):
 
3870
    """Combine a subtree into its containing tree.
 
3871
    
 
3872
    This command is for experimental use only.  It requires the target tree
 
3873
    to be in dirstate-with-subtree format, which cannot be converted into
 
3874
    earlier formats.
 
3875
 
 
3876
    The TREE argument should be an independent tree, inside another tree, but
 
3877
    not part of it.  (Such trees can be produced by "bzr split", but also by
 
3878
    running "bzr branch" with the target inside a tree.)
 
3879
 
 
3880
    The result is a combined tree, with the subtree no longer an independant
 
3881
    part.  This is marked as a merge of the subtree into the containing tree,
 
3882
    and all history is preserved.
 
3883
 
 
3884
    If --reference is specified, the subtree retains its independence.  It can
 
3885
    be branched by itself, and can be part of multiple projects at the same
 
3886
    time.  But operations performed in the containing tree, such as commit
 
3887
    and merge, will recurse into the subtree.
 
3888
    """
 
3889
 
 
3890
    _see_also = ['split']
 
3891
    takes_args = ['tree']
 
3892
    takes_options = [
 
3893
            Option('reference', help='Join by reference.'),
 
3894
            ]
 
3895
    hidden = True
 
3896
 
 
3897
    def run(self, tree, reference=False):
 
3898
        sub_tree = WorkingTree.open(tree)
 
3899
        parent_dir = osutils.dirname(sub_tree.basedir)
 
3900
        containing_tree = WorkingTree.open_containing(parent_dir)[0]
 
3901
        repo = containing_tree.branch.repository
 
3902
        if not repo.supports_rich_root():
 
3903
            raise errors.BzrCommandError(
 
3904
                "Can't join trees because %s doesn't support rich root data.\n"
 
3905
                "You can use bzr upgrade on the repository."
 
3906
                % (repo,))
 
3907
        if reference:
 
3908
            try:
 
3909
                containing_tree.add_reference(sub_tree)
 
3910
            except errors.BadReferenceTarget, e:
 
3911
                # XXX: Would be better to just raise a nicely printable
 
3912
                # exception from the real origin.  Also below.  mbp 20070306
 
3913
                raise errors.BzrCommandError("Cannot join %s.  %s" %
 
3914
                                             (tree, e.reason))
 
3915
        else:
 
3916
            try:
 
3917
                containing_tree.subsume(sub_tree)
 
3918
            except errors.BadSubsumeSource, e:
 
3919
                raise errors.BzrCommandError("Cannot join %s.  %s" % 
 
3920
                                             (tree, e.reason))
 
3921
 
 
3922
 
 
3923
class cmd_split(Command):
 
3924
    """Split a subdirectory of a tree into a separate tree.
 
3925
 
 
3926
    This command will produce a target tree in a format that supports
 
3927
    rich roots, like 'rich-root' or 'rich-root-pack'.  These formats cannot be
 
3928
    converted into earlier formats like 'dirstate-tags'.
 
3929
 
 
3930
    The TREE argument should be a subdirectory of a working tree.  That
 
3931
    subdirectory will be converted into an independent tree, with its own
 
3932
    branch.  Commits in the top-level tree will not apply to the new subtree.
 
3933
    """
 
3934
 
 
3935
    # join is not un-hidden yet
 
3936
    #_see_also = ['join']
 
3937
    takes_args = ['tree']
 
3938
 
 
3939
    def run(self, tree):
 
3940
        containing_tree, subdir = WorkingTree.open_containing(tree)
 
3941
        sub_id = containing_tree.path2id(subdir)
 
3942
        if sub_id is None:
 
3943
            raise errors.NotVersionedError(subdir)
 
3944
        try:
 
3945
            containing_tree.extract(sub_id)
 
3946
        except errors.RootNotRich:
 
3947
            raise errors.UpgradeRequired(containing_tree.branch.base)
 
3948
 
 
3949
 
 
3950
class cmd_merge_directive(Command):
 
3951
    """Generate a merge directive for auto-merge tools.
 
3952
 
 
3953
    A directive requests a merge to be performed, and also provides all the
 
3954
    information necessary to do so.  This means it must either include a
 
3955
    revision bundle, or the location of a branch containing the desired
 
3956
    revision.
 
3957
 
 
3958
    A submit branch (the location to merge into) must be supplied the first
 
3959
    time the command is issued.  After it has been supplied once, it will
 
3960
    be remembered as the default.
 
3961
 
 
3962
    A public branch is optional if a revision bundle is supplied, but required
 
3963
    if --diff or --plain is specified.  It will be remembered as the default
 
3964
    after the first use.
 
3965
    """
 
3966
 
 
3967
    takes_args = ['submit_branch?', 'public_branch?']
 
3968
 
 
3969
    hidden = True
 
3970
 
 
3971
    _see_also = ['send']
 
3972
 
 
3973
    takes_options = [
 
3974
        RegistryOption.from_kwargs('patch-type',
 
3975
            'The type of patch to include in the directive.',
 
3976
            title='Patch type',
 
3977
            value_switches=True,
 
3978
            enum_switch=False,
 
3979
            bundle='Bazaar revision bundle (default).',
 
3980
            diff='Normal unified diff.',
 
3981
            plain='No patch, just directive.'),
 
3982
        Option('sign', help='GPG-sign the directive.'), 'revision',
 
3983
        Option('mail-to', type=str,
 
3984
            help='Instead of printing the directive, email to this address.'),
 
3985
        Option('message', type=str, short_name='m',
 
3986
            help='Message to use when committing this merge.')
 
3987
        ]
 
3988
 
 
3989
    encoding_type = 'exact'
 
3990
 
 
3991
    def run(self, submit_branch=None, public_branch=None, patch_type='bundle',
 
3992
            sign=False, revision=None, mail_to=None, message=None):
 
3993
        from bzrlib.revision import ensure_null, NULL_REVISION
 
3994
        include_patch, include_bundle = {
 
3995
            'plain': (False, False),
 
3996
            'diff': (True, False),
 
3997
            'bundle': (True, True),
 
3998
            }[patch_type]
 
3999
        branch = Branch.open('.')
 
4000
        stored_submit_branch = branch.get_submit_branch()
 
4001
        if submit_branch is None:
 
4002
            submit_branch = stored_submit_branch
 
4003
        else:
 
4004
            if stored_submit_branch is None:
 
4005
                branch.set_submit_branch(submit_branch)
 
4006
        if submit_branch is None:
 
4007
            submit_branch = branch.get_parent()
 
4008
        if submit_branch is None:
 
4009
            raise errors.BzrCommandError('No submit branch specified or known')
 
4010
 
 
4011
        stored_public_branch = branch.get_public_branch()
 
4012
        if public_branch is None:
 
4013
            public_branch = stored_public_branch
 
4014
        elif stored_public_branch is None:
 
4015
            branch.set_public_branch(public_branch)
 
4016
        if not include_bundle and public_branch is None:
 
4017
            raise errors.BzrCommandError('No public branch specified or'
 
4018
                                         ' known')
 
4019
        base_revision_id = None
 
4020
        if revision is not None:
 
4021
            if len(revision) > 2:
 
4022
                raise errors.BzrCommandError('bzr merge-directive takes '
 
4023
                    'at most two one revision identifiers')
 
4024
            revision_id = revision[-1].as_revision_id(branch)
 
4025
            if len(revision) == 2:
 
4026
                base_revision_id = revision[0].as_revision_id(branch)
 
4027
        else:
 
4028
            revision_id = branch.last_revision()
 
4029
        revision_id = ensure_null(revision_id)
 
4030
        if revision_id == NULL_REVISION:
 
4031
            raise errors.BzrCommandError('No revisions to bundle.')
 
4032
        directive = merge_directive.MergeDirective2.from_objects(
 
4033
            branch.repository, revision_id, time.time(),
 
4034
            osutils.local_time_offset(), submit_branch,
 
4035
            public_branch=public_branch, include_patch=include_patch,
 
4036
            include_bundle=include_bundle, message=message,
 
4037
            base_revision_id=base_revision_id)
 
4038
        if mail_to is None:
 
4039
            if sign:
 
4040
                self.outf.write(directive.to_signed(branch))
 
4041
            else:
 
4042
                self.outf.writelines(directive.to_lines())
 
4043
        else:
 
4044
            message = directive.to_email(mail_to, branch, sign)
 
4045
            s = SMTPConnection(branch.get_config())
 
4046
            s.send_email(message)
 
4047
 
 
4048
 
 
4049
class cmd_send(Command):
 
4050
    """Mail or create a merge-directive for submiting changes.
 
4051
 
 
4052
    A merge directive provides many things needed for requesting merges:
 
4053
 
 
4054
    * A machine-readable description of the merge to perform
 
4055
 
 
4056
    * An optional patch that is a preview of the changes requested
 
4057
 
 
4058
    * An optional bundle of revision data, so that the changes can be applied
 
4059
      directly from the merge directive, without retrieving data from a
 
4060
      branch.
 
4061
 
 
4062
    If --no-bundle is specified, then public_branch is needed (and must be
 
4063
    up-to-date), so that the receiver can perform the merge using the
 
4064
    public_branch.  The public_branch is always included if known, so that
 
4065
    people can check it later.
 
4066
 
 
4067
    The submit branch defaults to the parent, but can be overridden.  Both
 
4068
    submit branch and public branch will be remembered if supplied.
 
4069
 
 
4070
    If a public_branch is known for the submit_branch, that public submit
 
4071
    branch is used in the merge instructions.  This means that a local mirror
 
4072
    can be used as your actual submit branch, once you have set public_branch
 
4073
    for that mirror.
 
4074
 
 
4075
    Mail is sent using your preferred mail program.  This should be transparent
 
4076
    on Windows (it uses MAPI).  On Linux, it requires the xdg-email utility.
 
4077
    If the preferred client can't be found (or used), your editor will be used.
 
4078
    
 
4079
    To use a specific mail program, set the mail_client configuration option.
 
4080
    (For Thunderbird 1.5, this works around some bugs.)  Supported values for
 
4081
    specific clients are "evolution", "kmail", "mutt", and "thunderbird";
 
4082
    generic options are "default", "editor", "mapi", and "xdg-email".
 
4083
 
 
4084
    If mail is being sent, a to address is required.  This can be supplied
 
4085
    either on the commandline, by setting the submit_to configuration
 
4086
    option in the branch itself or the child_submit_to configuration option 
 
4087
    in the submit branch.
 
4088
 
 
4089
    Two formats are currently supported: "4" uses revision bundle format 4 and
 
4090
    merge directive format 2.  It is significantly faster and smaller than
 
4091
    older formats.  It is compatible with Bazaar 0.19 and later.  It is the
 
4092
    default.  "0.9" uses revision bundle format 0.9 and merge directive
 
4093
    format 1.  It is compatible with Bazaar 0.12 - 0.18.
 
4094
    
 
4095
    Merge directives are applied using the merge command or the pull command.
 
4096
    """
 
4097
 
 
4098
    encoding_type = 'exact'
 
4099
 
 
4100
    _see_also = ['merge', 'pull']
 
4101
 
 
4102
    takes_args = ['submit_branch?', 'public_branch?']
 
4103
 
 
4104
    takes_options = [
 
4105
        Option('no-bundle',
 
4106
               help='Do not include a bundle in the merge directive.'),
 
4107
        Option('no-patch', help='Do not include a preview patch in the merge'
 
4108
               ' directive.'),
 
4109
        Option('remember',
 
4110
               help='Remember submit and public branch.'),
 
4111
        Option('from',
 
4112
               help='Branch to generate the submission from, '
 
4113
               'rather than the one containing the working directory.',
 
4114
               short_name='f',
 
4115
               type=unicode),
 
4116
        Option('output', short_name='o',
 
4117
               help='Write merge directive to this file; '
 
4118
                    'use - for stdout.',
 
4119
               type=unicode),
 
4120
        Option('mail-to', help='Mail the request to this address.',
 
4121
               type=unicode),
 
4122
        'revision',
 
4123
        'message',
 
4124
        RegistryOption.from_kwargs('format',
 
4125
        'Use the specified output format.',
 
4126
        **{'4': 'Bundle format 4, Merge Directive 2 (default)',
 
4127
           '0.9': 'Bundle format 0.9, Merge Directive 1',})
 
4128
        ]
 
4129
 
 
4130
    def run(self, submit_branch=None, public_branch=None, no_bundle=False,
 
4131
            no_patch=False, revision=None, remember=False, output=None,
 
4132
            format='4', mail_to=None, message=None, **kwargs):
 
4133
        return self._run(submit_branch, revision, public_branch, remember,
 
4134
                         format, no_bundle, no_patch, output,
 
4135
                         kwargs.get('from', '.'), mail_to, message)
 
4136
 
 
4137
    def _run(self, submit_branch, revision, public_branch, remember, format,
 
4138
             no_bundle, no_patch, output, from_, mail_to, message):
 
4139
        from bzrlib.revision import NULL_REVISION
 
4140
        branch = Branch.open_containing(from_)[0]
 
4141
        if output is None:
 
4142
            outfile = StringIO()
 
4143
        elif output == '-':
 
4144
            outfile = self.outf
 
4145
        else:
 
4146
            outfile = open(output, 'wb')
 
4147
        # we may need to write data into branch's repository to calculate
 
4148
        # the data to send.
 
4149
        branch.lock_write()
 
4150
        try:
 
4151
            if output is None:
 
4152
                config = branch.get_config()
 
4153
                if mail_to is None:
 
4154
                    mail_to = config.get_user_option('submit_to')
 
4155
                mail_client = config.get_mail_client()
 
4156
            if remember and submit_branch is None:
 
4157
                raise errors.BzrCommandError(
 
4158
                    '--remember requires a branch to be specified.')
 
4159
            stored_submit_branch = branch.get_submit_branch()
 
4160
            remembered_submit_branch = False
 
4161
            if submit_branch is None:
 
4162
                submit_branch = stored_submit_branch
 
4163
                remembered_submit_branch = True
 
4164
            else:
 
4165
                if stored_submit_branch is None or remember:
 
4166
                    branch.set_submit_branch(submit_branch)
 
4167
            if submit_branch is None:
 
4168
                submit_branch = branch.get_parent()
 
4169
                remembered_submit_branch = True
 
4170
            if submit_branch is None:
 
4171
                raise errors.BzrCommandError('No submit branch known or'
 
4172
                                             ' specified')
 
4173
            if remembered_submit_branch:
 
4174
                note('Using saved location: %s', submit_branch)
 
4175
 
 
4176
            if mail_to is None:
 
4177
                submit_config = Branch.open(submit_branch).get_config()
 
4178
                mail_to = submit_config.get_user_option("child_submit_to")
 
4179
 
 
4180
            stored_public_branch = branch.get_public_branch()
 
4181
            if public_branch is None:
 
4182
                public_branch = stored_public_branch
 
4183
            elif stored_public_branch is None or remember:
 
4184
                branch.set_public_branch(public_branch)
 
4185
            if no_bundle and public_branch is None:
 
4186
                raise errors.BzrCommandError('No public branch specified or'
 
4187
                                             ' known')
 
4188
            base_revision_id = None
 
4189
            revision_id = None
 
4190
            if revision is not None:
 
4191
                if len(revision) > 2:
 
4192
                    raise errors.BzrCommandError('bzr send takes '
 
4193
                        'at most two one revision identifiers')
 
4194
                revision_id = revision[-1].as_revision_id(branch)
 
4195
                if len(revision) == 2:
 
4196
                    base_revision_id = revision[0].as_revision_id(branch)
 
4197
            if revision_id is None:
 
4198
                revision_id = branch.last_revision()
 
4199
            if revision_id == NULL_REVISION:
 
4200
                raise errors.BzrCommandError('No revisions to submit.')
 
4201
            if format == '4':
 
4202
                directive = merge_directive.MergeDirective2.from_objects(
 
4203
                    branch.repository, revision_id, time.time(),
 
4204
                    osutils.local_time_offset(), submit_branch,
 
4205
                    public_branch=public_branch, include_patch=not no_patch,
 
4206
                    include_bundle=not no_bundle, message=message,
 
4207
                    base_revision_id=base_revision_id)
 
4208
            elif format == '0.9':
 
4209
                if not no_bundle:
 
4210
                    if not no_patch:
 
4211
                        patch_type = 'bundle'
 
4212
                    else:
 
4213
                        raise errors.BzrCommandError('Format 0.9 does not'
 
4214
                            ' permit bundle with no patch')
 
4215
                else:
 
4216
                    if not no_patch:
 
4217
                        patch_type = 'diff'
 
4218
                    else:
 
4219
                        patch_type = None
 
4220
                directive = merge_directive.MergeDirective.from_objects(
 
4221
                    branch.repository, revision_id, time.time(),
 
4222
                    osutils.local_time_offset(), submit_branch,
 
4223
                    public_branch=public_branch, patch_type=patch_type,
 
4224
                    message=message)
 
4225
 
 
4226
            outfile.writelines(directive.to_lines())
 
4227
            if output is None:
 
4228
                subject = '[MERGE] '
 
4229
                if message is not None:
 
4230
                    subject += message
 
4231
                else:
 
4232
                    revision = branch.repository.get_revision(revision_id)
 
4233
                    subject += revision.get_summary()
 
4234
                basename = directive.get_disk_name(branch)
 
4235
                mail_client.compose_merge_request(mail_to, subject,
 
4236
                                                  outfile.getvalue(), basename)
 
4237
        finally:
 
4238
            if output != '-':
 
4239
                outfile.close()
 
4240
            branch.unlock()
 
4241
 
 
4242
 
 
4243
class cmd_bundle_revisions(cmd_send):
 
4244
 
 
4245
    """Create a merge-directive for submiting changes.
 
4246
 
 
4247
    A merge directive provides many things needed for requesting merges:
 
4248
 
 
4249
    * A machine-readable description of the merge to perform
 
4250
 
 
4251
    * An optional patch that is a preview of the changes requested
 
4252
 
 
4253
    * An optional bundle of revision data, so that the changes can be applied
 
4254
      directly from the merge directive, without retrieving data from a
 
4255
      branch.
 
4256
 
 
4257
    If --no-bundle is specified, then public_branch is needed (and must be
 
4258
    up-to-date), so that the receiver can perform the merge using the
 
4259
    public_branch.  The public_branch is always included if known, so that
 
4260
    people can check it later.
 
4261
 
 
4262
    The submit branch defaults to the parent, but can be overridden.  Both
 
4263
    submit branch and public branch will be remembered if supplied.
 
4264
 
 
4265
    If a public_branch is known for the submit_branch, that public submit
 
4266
    branch is used in the merge instructions.  This means that a local mirror
 
4267
    can be used as your actual submit branch, once you have set public_branch
 
4268
    for that mirror.
 
4269
 
 
4270
    Two formats are currently supported: "4" uses revision bundle format 4 and
 
4271
    merge directive format 2.  It is significantly faster and smaller than
 
4272
    older formats.  It is compatible with Bazaar 0.19 and later.  It is the
 
4273
    default.  "0.9" uses revision bundle format 0.9 and merge directive
 
4274
    format 1.  It is compatible with Bazaar 0.12 - 0.18.
 
4275
    """
 
4276
 
 
4277
    takes_options = [
 
4278
        Option('no-bundle',
 
4279
               help='Do not include a bundle in the merge directive.'),
 
4280
        Option('no-patch', help='Do not include a preview patch in the merge'
 
4281
               ' directive.'),
 
4282
        Option('remember',
 
4283
               help='Remember submit and public branch.'),
 
4284
        Option('from',
 
4285
               help='Branch to generate the submission from, '
 
4286
               'rather than the one containing the working directory.',
 
4287
               short_name='f',
 
4288
               type=unicode),
 
4289
        Option('output', short_name='o', help='Write directive to this file.',
 
4290
               type=unicode),
 
4291
        'revision',
 
4292
        RegistryOption.from_kwargs('format',
 
4293
        'Use the specified output format.',
 
4294
        **{'4': 'Bundle format 4, Merge Directive 2 (default)',
 
4295
           '0.9': 'Bundle format 0.9, Merge Directive 1',})
 
4296
        ]
 
4297
    aliases = ['bundle']
 
4298
 
 
4299
    _see_also = ['send', 'merge']
 
4300
 
 
4301
    hidden = True
 
4302
 
 
4303
    def run(self, submit_branch=None, public_branch=None, no_bundle=False,
 
4304
            no_patch=False, revision=None, remember=False, output=None,
 
4305
            format='4', **kwargs):
 
4306
        if output is None:
 
4307
            output = '-'
 
4308
        return self._run(submit_branch, revision, public_branch, remember,
 
4309
                         format, no_bundle, no_patch, output,
 
4310
                         kwargs.get('from', '.'), None, None)
 
4311
 
 
4312
 
 
4313
class cmd_tag(Command):
 
4314
    """Create, remove or modify a tag naming a revision.
 
4315
    
 
4316
    Tags give human-meaningful names to revisions.  Commands that take a -r
 
4317
    (--revision) option can be given -rtag:X, where X is any previously
 
4318
    created tag.
 
4319
 
 
4320
    Tags are stored in the branch.  Tags are copied from one branch to another
 
4321
    along when you branch, push, pull or merge.
 
4322
 
 
4323
    It is an error to give a tag name that already exists unless you pass 
 
4324
    --force, in which case the tag is moved to point to the new revision.
 
4325
    """
 
4326
 
 
4327
    _see_also = ['commit', 'tags']
 
4328
    takes_args = ['tag_name']
 
4329
    takes_options = [
 
4330
        Option('delete',
 
4331
            help='Delete this tag rather than placing it.',
 
4332
            ),
 
4333
        Option('directory',
 
4334
            help='Branch in which to place the tag.',
 
4335
            short_name='d',
 
4336
            type=unicode,
 
4337
            ),
 
4338
        Option('force',
 
4339
            help='Replace existing tags.',
 
4340
            ),
 
4341
        'revision',
 
4342
        ]
 
4343
 
 
4344
    def run(self, tag_name,
 
4345
            delete=None,
 
4346
            directory='.',
 
4347
            force=None,
 
4348
            revision=None,
 
4349
            ):
 
4350
        branch, relpath = Branch.open_containing(directory)
 
4351
        branch.lock_write()
 
4352
        try:
 
4353
            if delete:
 
4354
                branch.tags.delete_tag(tag_name)
 
4355
                self.outf.write('Deleted tag %s.\n' % tag_name)
 
4356
            else:
 
4357
                if revision:
 
4358
                    if len(revision) != 1:
 
4359
                        raise errors.BzrCommandError(
 
4360
                            "Tags can only be placed on a single revision, "
 
4361
                            "not on a range")
 
4362
                    revision_id = revision[0].as_revision_id(branch)
 
4363
                else:
 
4364
                    revision_id = branch.last_revision()
 
4365
                if (not force) and branch.tags.has_tag(tag_name):
 
4366
                    raise errors.TagAlreadyExists(tag_name)
 
4367
                branch.tags.set_tag(tag_name, revision_id)
 
4368
                self.outf.write('Created tag %s.\n' % tag_name)
 
4369
        finally:
 
4370
            branch.unlock()
 
4371
 
 
4372
 
 
4373
class cmd_tags(Command):
 
4374
    """List tags.
 
4375
 
 
4376
    This command shows a table of tag names and the revisions they reference.
 
4377
    """
 
4378
 
 
4379
    _see_also = ['tag']
 
4380
    takes_options = [
 
4381
        Option('directory',
 
4382
            help='Branch whose tags should be displayed.',
 
4383
            short_name='d',
 
4384
            type=unicode,
 
4385
            ),
 
4386
        RegistryOption.from_kwargs('sort',
 
4387
            'Sort tags by different criteria.', title='Sorting',
 
4388
            alpha='Sort tags lexicographically (default).',
 
4389
            time='Sort tags chronologically.',
 
4390
            ),
 
4391
        'show-ids',
 
4392
    ]
 
4393
 
 
4394
    @display_command
 
4395
    def run(self,
 
4396
            directory='.',
 
4397
            sort='alpha',
 
4398
            show_ids=False,
 
4399
            ):
 
4400
        branch, relpath = Branch.open_containing(directory)
 
4401
        tags = branch.tags.get_tag_dict().items()
 
4402
        if sort == 'alpha':
 
4403
            tags.sort()
 
4404
        elif sort == 'time':
 
4405
            timestamps = {}
 
4406
            for tag, revid in tags:
 
4407
                try:
 
4408
                    revobj = branch.repository.get_revision(revid)
 
4409
                except errors.NoSuchRevision:
 
4410
                    timestamp = sys.maxint # place them at the end
 
4411
                else:
 
4412
                    timestamp = revobj.timestamp
 
4413
                timestamps[revid] = timestamp
 
4414
            tags.sort(key=lambda x: timestamps[x[1]])
 
4415
        if not show_ids:
 
4416
            # [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
 
4417
            revno_map = branch.get_revision_id_to_revno_map()
 
4418
            tags = [ (tag, '.'.join(map(str, revno_map.get(revid, ('?',)))))
 
4419
                        for tag, revid in tags ]
 
4420
        for tag, revspec in tags:
 
4421
            self.outf.write('%-20s %s\n' % (tag, revspec))
 
4422
 
 
4423
 
 
4424
class cmd_reconfigure(Command):
 
4425
    """Reconfigure the type of a bzr directory.
 
4426
 
 
4427
    A target configuration must be specified.
 
4428
 
 
4429
    For checkouts, the bind-to location will be auto-detected if not specified.
 
4430
    The order of preference is
 
4431
    1. For a lightweight checkout, the current bound location.
 
4432
    2. For branches that used to be checkouts, the previously-bound location.
 
4433
    3. The push location.
 
4434
    4. The parent location.
 
4435
    If none of these is available, --bind-to must be specified.
 
4436
    """
 
4437
 
 
4438
    takes_args = ['location?']
 
4439
    takes_options = [RegistryOption.from_kwargs('target_type',
 
4440
                     title='Target type',
 
4441
                     help='The type to reconfigure the directory to.',
 
4442
                     value_switches=True, enum_switch=False,
 
4443
                     branch='Reconfigure to a branch.',
 
4444
                     tree='Reconfigure to a tree.',
 
4445
                     checkout='Reconfigure to a checkout.',
 
4446
                     lightweight_checkout='Reconfigure to a lightweight'
 
4447
                     ' checkout.',
 
4448
                     standalone='Reconfigure to be standalone.',
 
4449
                     use_shared='Reconfigure to use a shared repository.'),
 
4450
                     Option('bind-to', help='Branch to bind checkout to.',
 
4451
                            type=str),
 
4452
                     Option('force',
 
4453
                        help='Perform reconfiguration even if local changes'
 
4454
                        ' will be lost.')
 
4455
                     ]
 
4456
 
 
4457
    def run(self, location=None, target_type=None, bind_to=None, force=False):
 
4458
        directory = bzrdir.BzrDir.open(location)
 
4459
        if target_type is None:
 
4460
            raise errors.BzrCommandError('No target configuration specified')
 
4461
        elif target_type == 'branch':
 
4462
            reconfiguration = reconfigure.Reconfigure.to_branch(directory)
 
4463
        elif target_type == 'tree':
 
4464
            reconfiguration = reconfigure.Reconfigure.to_tree(directory)
 
4465
        elif target_type == 'checkout':
 
4466
            reconfiguration = reconfigure.Reconfigure.to_checkout(directory,
 
4467
                                                                  bind_to)
 
4468
        elif target_type == 'lightweight-checkout':
 
4469
            reconfiguration = reconfigure.Reconfigure.to_lightweight_checkout(
 
4470
                directory, bind_to)
 
4471
        elif target_type == 'use-shared':
 
4472
            reconfiguration = reconfigure.Reconfigure.to_use_shared(directory)
 
4473
        elif target_type == 'standalone':
 
4474
            reconfiguration = reconfigure.Reconfigure.to_standalone(directory)
 
4475
        reconfiguration.apply(force)
 
4476
 
 
4477
 
 
4478
class cmd_switch(Command):
 
4479
    """Set the branch of a checkout and update.
 
4480
    
 
4481
    For lightweight checkouts, this changes the branch being referenced.
 
4482
    For heavyweight checkouts, this checks that there are no local commits
 
4483
    versus the current bound branch, then it makes the local branch a mirror
 
4484
    of the new location and binds to it.
 
4485
    
 
4486
    In both cases, the working tree is updated and uncommitted changes
 
4487
    are merged. The user can commit or revert these as they desire.
 
4488
 
 
4489
    Pending merges need to be committed or reverted before using switch.
 
4490
 
 
4491
    The path to the branch to switch to can be specified relative to the parent
 
4492
    directory of the current branch. For example, if you are currently in a
 
4493
    checkout of /path/to/branch, specifying 'newbranch' will find a branch at
 
4494
    /path/to/newbranch.
 
4495
    """
 
4496
 
 
4497
    takes_args = ['to_location']
 
4498
    takes_options = [Option('force',
 
4499
                        help='Switch even if local commits will be lost.')
 
4500
                     ]
 
4501
 
 
4502
    def run(self, to_location, force=False):
 
4503
        from bzrlib import switch
 
4504
        tree_location = '.'
 
4505
        control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
 
4506
        try:
 
4507
            to_branch = Branch.open(to_location)
 
4508
        except errors.NotBranchError:
 
4509
            to_branch = Branch.open(
 
4510
                control_dir.open_branch().base + '../' + to_location)
 
4511
        switch.switch(control_dir, to_branch, force)
 
4512
        note('Switched to branch: %s',
 
4513
            urlutils.unescape_for_display(to_branch.base, 'utf-8'))
 
4514
 
 
4515
 
 
4516
class cmd_hooks(Command):
 
4517
    """Show a branch's currently registered hooks.
 
4518
    """
 
4519
 
 
4520
    hidden = True
 
4521
    takes_args = ['path?']
 
4522
 
 
4523
    def run(self, path=None):
 
4524
        if path is None:
 
4525
            path = '.'
 
4526
        branch_hooks = Branch.open(path).hooks
 
4527
        for hook_type in branch_hooks:
 
4528
            hooks = branch_hooks[hook_type]
 
4529
            self.outf.write("%s:\n" % (hook_type,))
 
4530
            if hooks:
 
4531
                for hook in hooks:
 
4532
                    self.outf.write("  %s\n" %
 
4533
                                    (branch_hooks.get_hook_name(hook),))
 
4534
            else:
 
4535
                self.outf.write("  <no hooks installed>\n")
 
4536
 
 
4537
 
 
4538
def _create_prefix(cur_transport):
 
4539
    needed = [cur_transport]
 
4540
    # Recurse upwards until we can create a directory successfully
 
4541
    while True:
 
4542
        new_transport = cur_transport.clone('..')
 
4543
        if new_transport.base == cur_transport.base:
 
4544
            raise errors.BzrCommandError(
 
4545
                "Failed to create path prefix for %s."
 
4546
                % cur_transport.base)
 
4547
        try:
 
4548
            new_transport.mkdir('.')
 
4549
        except errors.NoSuchFile:
 
4550
            needed.append(new_transport)
 
4551
            cur_transport = new_transport
 
4552
        else:
 
4553
            break
 
4554
    # Now we only need to create child directories
 
4555
    while needed:
 
4556
        cur_transport = needed.pop()
 
4557
        cur_transport.ensure_base()
3258
4558
 
3259
4559
 
3260
4560
# these get imported and then picked up by the scan for cmd_*
3264
4564
# details were needed.
3265
4565
from bzrlib.cmd_version_info import cmd_version_info
3266
4566
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore
3267
 
from bzrlib.bundle.commands import cmd_bundle_revisions
 
4567
from bzrlib.bundle.commands import (
 
4568
    cmd_bundle_info,
 
4569
    )
3268
4570
from bzrlib.sign_my_commits import cmd_sign_my_commits
3269
 
from bzrlib.weave_commands import cmd_weave_list, cmd_weave_join, \
 
4571
from bzrlib.weave_commands import cmd_versionedfile_list, cmd_weave_join, \
3270
4572
        cmd_weave_plan_merge, cmd_weave_merge_text