/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/builtins.py

First attempt to merge .dev and resolve the conflicts (but tests are 
failing)

Show diffs side-by-side

added added

removed removed

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