~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/builtins.py

Merge sftp-leaks into catch-them-all resolving conflicts

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009 Canonical Ltd
 
1
# Copyright (C) 2005-2010 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
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
"""builtin bzr commands"""
18
18
 
31
31
    bundle,
32
32
    btree_index,
33
33
    bzrdir,
 
34
    directory_service,
34
35
    delta,
35
36
    config,
36
37
    errors,
37
38
    globbing,
 
39
    hooks,
38
40
    log,
39
41
    merge as _mod_merge,
40
42
    merge_directive,
41
43
    osutils,
42
44
    reconfigure,
 
45
    rename_map,
43
46
    revision as _mod_revision,
 
47
    static_tuple,
44
48
    symbol_versioning,
 
49
    timestamp,
45
50
    transport,
46
 
    tree as _mod_tree,
47
51
    ui,
48
52
    urlutils,
 
53
    views,
49
54
    )
50
55
from bzrlib.branch import Branch
51
56
from bzrlib.conflicts import ConflictList
 
57
from bzrlib.transport import memory
52
58
from bzrlib.revisionspec import RevisionSpec, RevisionInfo
53
59
from bzrlib.smtp_connection import SMTPConnection
54
60
from bzrlib.workingtree import WorkingTree
55
61
""")
56
62
 
57
 
from bzrlib.commands import Command, display_command
 
63
from bzrlib.commands import (
 
64
    Command,
 
65
    builtin_command_registry,
 
66
    display_command,
 
67
    )
58
68
from bzrlib.option import (
59
69
    ListOption,
60
70
    Option,
65
75
from bzrlib.trace import mutter, note, warning, is_quiet, get_verbosity_level
66
76
 
67
77
 
68
 
def tree_files(file_list, default_branch=u'.', canonicalize=True):
 
78
def tree_files(file_list, default_branch=u'.', canonicalize=True,
 
79
    apply_view=True):
69
80
    try:
70
 
        return internal_tree_files(file_list, default_branch, canonicalize)
 
81
        return internal_tree_files(file_list, default_branch, canonicalize,
 
82
            apply_view)
71
83
    except errors.FileInWrongBranch, e:
72
84
        raise errors.BzrCommandError("%s is not in the same branch as %s" %
73
85
                                     (e.path, file_list[0]))
74
86
 
75
87
 
 
88
def tree_files_for_add(file_list):
 
89
    """
 
90
    Return a tree and list of absolute paths from a file list.
 
91
 
 
92
    Similar to tree_files, but add handles files a bit differently, so it a
 
93
    custom implementation.  In particular, MutableTreeTree.smart_add expects
 
94
    absolute paths, which it immediately converts to relative paths.
 
95
    """
 
96
    # FIXME Would be nice to just return the relative paths like
 
97
    # internal_tree_files does, but there are a large number of unit tests
 
98
    # that assume the current interface to mutabletree.smart_add
 
99
    if file_list:
 
100
        tree, relpath = WorkingTree.open_containing(file_list[0])
 
101
        if tree.supports_views():
 
102
            view_files = tree.views.lookup_view()
 
103
            if view_files:
 
104
                for filename in file_list:
 
105
                    if not osutils.is_inside_any(view_files, filename):
 
106
                        raise errors.FileOutsideView(filename, view_files)
 
107
        file_list = file_list[:]
 
108
        file_list[0] = tree.abspath(relpath)
 
109
    else:
 
110
        tree = WorkingTree.open_containing(u'.')[0]
 
111
        if tree.supports_views():
 
112
            view_files = tree.views.lookup_view()
 
113
            if view_files:
 
114
                file_list = view_files
 
115
                view_str = views.view_display_str(view_files)
 
116
                note("Ignoring files outside view. View is %s" % view_str)
 
117
    return tree, file_list
 
118
 
 
119
 
76
120
def _get_one_revision(command_name, revisions):
77
121
    if revisions is None:
78
122
        return None
84
128
 
85
129
 
86
130
def _get_one_revision_tree(command_name, revisions, branch=None, tree=None):
 
131
    """Get a revision tree. Not suitable for commands that change the tree.
 
132
    
 
133
    Specifically, the basis tree in dirstate trees is coupled to the dirstate
 
134
    and doing a commit/uncommit/pull will at best fail due to changing the
 
135
    basis revision data.
 
136
 
 
137
    If tree is passed in, it should be already locked, for lifetime management
 
138
    of the trees internal cached state.
 
139
    """
87
140
    if branch is None:
88
141
        branch = tree.branch
89
142
    if revisions is None:
99
152
 
100
153
# XXX: Bad function name; should possibly also be a class method of
101
154
# WorkingTree rather than a function.
102
 
def internal_tree_files(file_list, default_branch=u'.', canonicalize=True):
 
155
def internal_tree_files(file_list, default_branch=u'.', canonicalize=True,
 
156
    apply_view=True):
103
157
    """Convert command-line paths to a WorkingTree and relative paths.
104
158
 
105
159
    This is typically used for command-line processors that take one or
107
161
 
108
162
    The filenames given are not required to exist.
109
163
 
110
 
    :param file_list: Filenames to convert.  
 
164
    :param file_list: Filenames to convert.
111
165
 
112
166
    :param default_branch: Fallback tree path to use if file_list is empty or
113
167
        None.
114
168
 
 
169
    :param apply_view: if True and a view is set, apply it or check that
 
170
        specified files are within it
 
171
 
115
172
    :return: workingtree, [relative_paths]
116
173
    """
117
174
    if file_list is None or len(file_list) == 0:
118
 
        return WorkingTree.open_containing(default_branch)[0], file_list
 
175
        tree = WorkingTree.open_containing(default_branch)[0]
 
176
        if tree.supports_views() and apply_view:
 
177
            view_files = tree.views.lookup_view()
 
178
            if view_files:
 
179
                file_list = view_files
 
180
                view_str = views.view_display_str(view_files)
 
181
                note("Ignoring files outside view. View is %s" % view_str)
 
182
        return tree, file_list
119
183
    tree = WorkingTree.open_containing(osutils.realpath(file_list[0]))[0]
120
 
    return tree, safe_relpath_files(tree, file_list, canonicalize)
121
 
 
122
 
 
123
 
def safe_relpath_files(tree, file_list, canonicalize=True):
 
184
    return tree, safe_relpath_files(tree, file_list, canonicalize,
 
185
        apply_view=apply_view)
 
186
 
 
187
 
 
188
def safe_relpath_files(tree, file_list, canonicalize=True, apply_view=True):
124
189
    """Convert file_list into a list of relpaths in tree.
125
190
 
126
191
    :param tree: A tree to operate on.
127
192
    :param file_list: A list of user provided paths or None.
 
193
    :param apply_view: if True and a view is set, apply it or check that
 
194
        specified files are within it
128
195
    :return: A list of relative paths.
129
196
    :raises errors.PathNotChild: When a provided path is in a different tree
130
197
        than tree.
131
198
    """
132
199
    if file_list is None:
133
200
        return None
 
201
    if tree.supports_views() and apply_view:
 
202
        view_files = tree.views.lookup_view()
 
203
    else:
 
204
        view_files = []
134
205
    new_list = []
135
206
    # tree.relpath exists as a "thunk" to osutils, but canonical_relpath
136
207
    # doesn't - fix that up here before we enter the loop.
140
211
        fixer = tree.relpath
141
212
    for filename in file_list:
142
213
        try:
143
 
            new_list.append(fixer(osutils.dereference_path(filename)))
 
214
            relpath = fixer(osutils.dereference_path(filename))
 
215
            if  view_files and not osutils.is_inside_any(view_files, relpath):
 
216
                raise errors.FileOutsideView(filename, view_files)
 
217
            new_list.append(relpath)
144
218
        except errors.PathNotChild:
145
219
            raise errors.FileInWrongBranch(tree.branch, filename)
146
220
    return new_list
147
221
 
148
222
 
 
223
def _get_view_info_for_change_reporter(tree):
 
224
    """Get the view information from a tree for change reporting."""
 
225
    view_info = None
 
226
    try:
 
227
        current_view = tree.views.get_view_info()[0]
 
228
        if current_view is not None:
 
229
            view_info = (current_view, tree.views.lookup_view())
 
230
    except errors.ViewsNotSupported:
 
231
        pass
 
232
    return view_info
 
233
 
 
234
 
 
235
def _open_directory_or_containing_tree_or_branch(filename, directory):
 
236
    """Open the tree or branch containing the specified file, unless
 
237
    the --directory option is used to specify a different branch."""
 
238
    if directory is not None:
 
239
        return (None, Branch.open(directory), filename)
 
240
    return bzrdir.BzrDir.open_containing_tree_or_branch(filename)
 
241
 
 
242
 
149
243
# TODO: Make sure no commands unconditionally use the working directory as a
150
244
# branch.  If a filename argument is used, the first of them should be used to
151
245
# specify the branch.  (Perhaps this can be factored out into some kind of
153
247
# opens the branch?)
154
248
 
155
249
class cmd_status(Command):
156
 
    """Display status summary.
 
250
    __doc__ = """Display status summary.
157
251
 
158
252
    This reports on versioned and unknown files, reporting them
159
253
    grouped by state.  Possible states are:
179
273
    unknown
180
274
        Not versioned and not matching an ignore pattern.
181
275
 
 
276
    Additionally for directories, symlinks and files with an executable
 
277
    bit, Bazaar indicates their type using a trailing character: '/', '@'
 
278
    or '*' respectively.
 
279
 
182
280
    To see ignored files use 'bzr ignored'.  For details on the
183
281
    changes to file texts, use 'bzr diff'.
184
 
    
 
282
 
185
283
    Note that --short or -S gives status flags for each item, similar
186
284
    to Subversion's status command. To get output similar to svn -q,
187
285
    use bzr status -SV.
199
297
    If a revision argument is given, the status is calculated against
200
298
    that revision, or between two revisions if two are provided.
201
299
    """
202
 
    
 
300
 
203
301
    # TODO: --no-recurse, --recurse options
204
 
    
 
302
 
205
303
    takes_args = ['file*']
206
304
    takes_options = ['show-ids', 'revision', 'change', 'verbose',
207
305
                     Option('short', help='Use short status indicators.',
215
313
 
216
314
    encoding_type = 'replace'
217
315
    _see_also = ['diff', 'revert', 'status-flags']
218
 
    
 
316
 
219
317
    @display_command
220
318
    def run(self, show_ids=False, file_list=None, revision=None, short=False,
221
319
            versioned=False, no_pending=False, verbose=False):
242
340
 
243
341
 
244
342
class cmd_cat_revision(Command):
245
 
    """Write out metadata for a revision.
246
 
    
 
343
    __doc__ = """Write out metadata for a revision.
 
344
 
247
345
    The revision to print can either be specified by a specific
248
346
    revision identifier, or you can use --revision.
249
347
    """
250
348
 
251
349
    hidden = True
252
350
    takes_args = ['revision_id?']
253
 
    takes_options = ['revision']
 
351
    takes_options = ['directory', 'revision']
254
352
    # cat-revision is more for frontends so should be exact
255
353
    encoding = 'strict'
256
 
    
 
354
 
 
355
    def print_revision(self, revisions, revid):
 
356
        stream = revisions.get_record_stream([(revid,)], 'unordered', True)
 
357
        record = stream.next()
 
358
        if record.storage_kind == 'absent':
 
359
            raise errors.NoSuchRevision(revisions, revid)
 
360
        revtext = record.get_bytes_as('fulltext')
 
361
        self.outf.write(revtext.decode('utf-8'))
 
362
 
257
363
    @display_command
258
 
    def run(self, revision_id=None, revision=None):
 
364
    def run(self, revision_id=None, revision=None, directory=u'.'):
259
365
        if revision_id is not None and revision is not None:
260
366
            raise errors.BzrCommandError('You can only supply one of'
261
367
                                         ' revision_id or --revision')
262
368
        if revision_id is None and revision is None:
263
369
            raise errors.BzrCommandError('You must supply either'
264
370
                                         ' --revision or a revision_id')
265
 
        b = WorkingTree.open_containing(u'.')[0].branch
266
 
 
267
 
        # TODO: jam 20060112 should cat-revision always output utf-8?
268
 
        if revision_id is not None:
269
 
            revision_id = osutils.safe_revision_id(revision_id, warn=False)
270
 
            try:
271
 
                self.outf.write(b.repository.get_revision_xml(revision_id).decode('utf-8'))
272
 
            except errors.NoSuchRevision:
273
 
                msg = "The repository %s contains no revision %s." % (b.repository.base,
274
 
                    revision_id)
275
 
                raise errors.BzrCommandError(msg)
276
 
        elif revision is not None:
277
 
            for rev in revision:
278
 
                if rev is None:
279
 
                    raise errors.BzrCommandError('You cannot specify a NULL'
280
 
                                                 ' revision.')
281
 
                rev_id = rev.as_revision_id(b)
282
 
                self.outf.write(b.repository.get_revision_xml(rev_id).decode('utf-8'))
283
 
 
 
371
        b = WorkingTree.open_containing(directory)[0].branch
 
372
 
 
373
        revisions = b.repository.revisions
 
374
        if revisions is None:
 
375
            raise errors.BzrCommandError('Repository %r does not support '
 
376
                'access to raw revision texts')
 
377
 
 
378
        b.repository.lock_read()
 
379
        try:
 
380
            # TODO: jam 20060112 should cat-revision always output utf-8?
 
381
            if revision_id is not None:
 
382
                revision_id = osutils.safe_revision_id(revision_id, warn=False)
 
383
                try:
 
384
                    self.print_revision(revisions, revision_id)
 
385
                except errors.NoSuchRevision:
 
386
                    msg = "The repository %s contains no revision %s." % (
 
387
                        b.repository.base, revision_id)
 
388
                    raise errors.BzrCommandError(msg)
 
389
            elif revision is not None:
 
390
                for rev in revision:
 
391
                    if rev is None:
 
392
                        raise errors.BzrCommandError(
 
393
                            'You cannot specify a NULL revision.')
 
394
                    rev_id = rev.as_revision_id(b)
 
395
                    self.print_revision(revisions, rev_id)
 
396
        finally:
 
397
            b.repository.unlock()
 
398
        
284
399
 
285
400
class cmd_dump_btree(Command):
286
 
    """Dump the contents of a btree index file to stdout.
 
401
    __doc__ = """Dump the contents of a btree index file to stdout.
287
402
 
288
403
    PATH is a btree index file, it can be any URL. This includes things like
289
404
    .bzr/repository/pack-names, or .bzr/repository/indices/a34b3a...ca4a4.iix
353
468
        for node in bt.iter_all_entries():
354
469
            # Node is made up of:
355
470
            # (index, key, value, [references])
356
 
            self.outf.write('%s\n' % (node[1:],))
 
471
            try:
 
472
                refs = node[3]
 
473
            except IndexError:
 
474
                refs_as_tuples = None
 
475
            else:
 
476
                refs_as_tuples = static_tuple.as_tuples(refs)
 
477
            as_tuple = (tuple(node[1]), node[2], refs_as_tuples)
 
478
            self.outf.write('%s\n' % (as_tuple,))
357
479
 
358
480
 
359
481
class cmd_remove_tree(Command):
360
 
    """Remove the working tree from a given branch/checkout.
 
482
    __doc__ = """Remove the working tree from a given branch/checkout.
361
483
 
362
484
    Since a lightweight checkout is little more than a working tree
363
485
    this will refuse to run against one.
365
487
    To re-create the working tree, use "bzr checkout".
366
488
    """
367
489
    _see_also = ['checkout', 'working-trees']
368
 
    takes_args = ['location?']
 
490
    takes_args = ['location*']
369
491
    takes_options = [
370
492
        Option('force',
371
493
               help='Remove the working tree even if it has '
372
 
                    'uncommitted changes.'),
 
494
                    'uncommitted or shelved changes.'),
373
495
        ]
374
496
 
375
 
    def run(self, location='.', force=False):
376
 
        d = bzrdir.BzrDir.open(location)
377
 
        
378
 
        try:
379
 
            working = d.open_workingtree()
380
 
        except errors.NoWorkingTree:
381
 
            raise errors.BzrCommandError("No working tree to remove")
382
 
        except errors.NotLocalUrl:
383
 
            raise errors.BzrCommandError("You cannot remove the working tree of a "
384
 
                                         "remote path")
385
 
        if not force:
386
 
            changes = working.changes_from(working.basis_tree())
387
 
            if changes.has_changed():
388
 
                raise errors.UncommittedChanges(working)
389
 
 
390
 
        working_path = working.bzrdir.root_transport.base
391
 
        branch_path = working.branch.bzrdir.root_transport.base
392
 
        if working_path != branch_path:
393
 
            raise errors.BzrCommandError("You cannot remove the working tree from "
394
 
                                         "a lightweight checkout")
395
 
        
396
 
        d.destroy_workingtree()
397
 
        
 
497
    def run(self, location_list, force=False):
 
498
        if not location_list:
 
499
            location_list=['.']
 
500
 
 
501
        for location in location_list:
 
502
            d = bzrdir.BzrDir.open(location)
 
503
            
 
504
            try:
 
505
                working = d.open_workingtree()
 
506
            except errors.NoWorkingTree:
 
507
                raise errors.BzrCommandError("No working tree to remove")
 
508
            except errors.NotLocalUrl:
 
509
                raise errors.BzrCommandError("You cannot remove the working tree"
 
510
                                             " of a remote path")
 
511
            if not force:
 
512
                if (working.has_changes()):
 
513
                    raise errors.UncommittedChanges(working)
 
514
                if working.get_shelf_manager().last_shelf() is not None:
 
515
                    raise errors.ShelvedChanges(working)
 
516
 
 
517
            if working.user_url != working.branch.user_url:
 
518
                raise errors.BzrCommandError("You cannot remove the working tree"
 
519
                                             " from a lightweight checkout")
 
520
 
 
521
            d.destroy_workingtree()
 
522
 
398
523
 
399
524
class cmd_revno(Command):
400
 
    """Show current revision number.
 
525
    __doc__ = """Show current revision number.
401
526
 
402
527
    This is equal to the number of revisions on this branch.
403
528
    """
404
529
 
405
530
    _see_also = ['info']
406
531
    takes_args = ['location?']
 
532
    takes_options = [
 
533
        Option('tree', help='Show revno of working tree'),
 
534
        ]
407
535
 
408
536
    @display_command
409
 
    def run(self, location=u'.'):
410
 
        self.outf.write(str(Branch.open_containing(location)[0].revno()))
411
 
        self.outf.write('\n')
 
537
    def run(self, tree=False, location=u'.'):
 
538
        if tree:
 
539
            try:
 
540
                wt = WorkingTree.open_containing(location)[0]
 
541
                self.add_cleanup(wt.lock_read().unlock)
 
542
            except (errors.NoWorkingTree, errors.NotLocalUrl):
 
543
                raise errors.NoWorkingTree(location)
 
544
            revid = wt.last_revision()
 
545
            try:
 
546
                revno_t = wt.branch.revision_id_to_dotted_revno(revid)
 
547
            except errors.NoSuchRevision:
 
548
                revno_t = ('???',)
 
549
            revno = ".".join(str(n) for n in revno_t)
 
550
        else:
 
551
            b = Branch.open_containing(location)[0]
 
552
            self.add_cleanup(b.lock_read().unlock)
 
553
            revno = b.revno()
 
554
        self.cleanup_now()
 
555
        self.outf.write(str(revno) + '\n')
412
556
 
413
557
 
414
558
class cmd_revision_info(Command):
415
 
    """Show revision number and revision id for a given revision identifier.
 
559
    __doc__ = """Show revision number and revision id for a given revision identifier.
416
560
    """
417
561
    hidden = True
418
562
    takes_args = ['revision_info*']
419
563
    takes_options = [
420
564
        'revision',
421
 
        Option('directory',
 
565
        custom_help('directory',
422
566
            help='Branch to examine, '
423
 
                 'rather than the one containing the working directory.',
424
 
            short_name='d',
425
 
            type=unicode,
426
 
            ),
 
567
                 'rather than the one containing the working directory.'),
 
568
        Option('tree', help='Show revno of working tree'),
427
569
        ]
428
570
 
429
571
    @display_command
430
 
    def run(self, revision=None, directory=u'.', revision_info_list=[]):
 
572
    def run(self, revision=None, directory=u'.', tree=False,
 
573
            revision_info_list=[]):
431
574
 
432
 
        revs = []
 
575
        try:
 
576
            wt = WorkingTree.open_containing(directory)[0]
 
577
            b = wt.branch
 
578
            self.add_cleanup(wt.lock_read().unlock)
 
579
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
580
            wt = None
 
581
            b = Branch.open_containing(directory)[0]
 
582
            self.add_cleanup(b.lock_read().unlock)
 
583
        revision_ids = []
433
584
        if revision is not None:
434
 
            revs.extend(revision)
 
585
            revision_ids.extend(rev.as_revision_id(b) for rev in revision)
435
586
        if revision_info_list is not None:
436
 
            for rev in revision_info_list:
437
 
                revs.append(RevisionSpec.from_string(rev))
438
 
 
439
 
        b = Branch.open_containing(directory)[0]
440
 
 
441
 
        if len(revs) == 0:
442
 
            revs.append(RevisionSpec.from_string('-1'))
443
 
 
444
 
        for rev in revs:
445
 
            revision_id = rev.as_revision_id(b)
 
587
            for rev_str in revision_info_list:
 
588
                rev_spec = RevisionSpec.from_string(rev_str)
 
589
                revision_ids.append(rev_spec.as_revision_id(b))
 
590
        # No arguments supplied, default to the last revision
 
591
        if len(revision_ids) == 0:
 
592
            if tree:
 
593
                if wt is None:
 
594
                    raise errors.NoWorkingTree(directory)
 
595
                revision_ids.append(wt.last_revision())
 
596
            else:
 
597
                revision_ids.append(b.last_revision())
 
598
 
 
599
        revinfos = []
 
600
        maxlen = 0
 
601
        for revision_id in revision_ids:
446
602
            try:
447
 
                revno = '%4d' % (b.revision_id_to_revno(revision_id))
 
603
                dotted_revno = b.revision_id_to_dotted_revno(revision_id)
 
604
                revno = '.'.join(str(i) for i in dotted_revno)
448
605
            except errors.NoSuchRevision:
449
 
                dotted_map = b.get_revision_id_to_revno_map()
450
 
                revno = '.'.join(str(i) for i in dotted_map[revision_id])
451
 
            print '%s %s' % (revno, revision_id)
452
 
 
453
 
    
 
606
                revno = '???'
 
607
            maxlen = max(maxlen, len(revno))
 
608
            revinfos.append([revno, revision_id])
 
609
 
 
610
        self.cleanup_now()
 
611
        for ri in revinfos:
 
612
            self.outf.write('%*s %s\n' % (maxlen, ri[0], ri[1]))
 
613
 
 
614
 
454
615
class cmd_add(Command):
455
 
    """Add specified files or directories.
 
616
    __doc__ = """Add specified files or directories.
456
617
 
457
618
    In non-recursive mode, all the named items are added, regardless
458
619
    of whether they were previously ignored.  A warning is given if
474
635
    you should never need to explicitly add a directory, they'll just
475
636
    get added when you add a file in the directory.
476
637
 
477
 
    --dry-run will show which files would be added, but not actually 
 
638
    --dry-run will show which files would be added, but not actually
478
639
    add them.
479
640
 
480
641
    --file-ids-from will try to use the file ids from the supplied path.
484
645
    branches that will be merged later (without showing the two different
485
646
    adds as a conflict). It is also useful when merging another project
486
647
    into a subdirectory of this one.
 
648
    
 
649
    Any files matching patterns in the ignore list will not be added
 
650
    unless they are explicitly mentioned.
487
651
    """
488
652
    takes_args = ['file*']
489
653
    takes_options = [
497
661
               help='Lookup file ids from this tree.'),
498
662
        ]
499
663
    encoding_type = 'replace'
500
 
    _see_also = ['remove']
 
664
    _see_also = ['remove', 'ignore']
501
665
 
502
666
    def run(self, file_list, no_recurse=False, dry_run=False, verbose=False,
503
667
            file_ids_from=None):
520
684
                should_print=(not is_quiet()))
521
685
 
522
686
        if base_tree:
523
 
            base_tree.lock_read()
524
 
        try:
525
 
            file_list = self._maybe_expand_globs(file_list)
526
 
            if file_list:
527
 
                tree = WorkingTree.open_containing(file_list[0])[0]
528
 
            else:
529
 
                tree = WorkingTree.open_containing(u'.')[0]
530
 
            added, ignored = tree.smart_add(file_list, not
531
 
                no_recurse, action=action, save=not dry_run)
532
 
        finally:
533
 
            if base_tree is not None:
534
 
                base_tree.unlock()
535
 
        if not is_quiet() and len(added) > 0:
536
 
            self.outf.write('add completed\n')
 
687
            self.add_cleanup(base_tree.lock_read().unlock)
 
688
        tree, file_list = tree_files_for_add(file_list)
 
689
        added, ignored = tree.smart_add(file_list, not
 
690
            no_recurse, action=action, save=not dry_run)
 
691
        self.cleanup_now()
537
692
        if len(ignored) > 0:
538
693
            if verbose:
539
694
                for glob in sorted(ignored.keys()):
540
695
                    for path in ignored[glob]:
541
 
                        self.outf.write("ignored %s matching \"%s\"\n" 
 
696
                        self.outf.write("ignored %s matching \"%s\"\n"
542
697
                                        % (path, glob))
543
 
            else:
544
 
                match_len = 0
545
 
                for glob, paths in ignored.items():
546
 
                    match_len += len(paths)
547
 
                self.outf.write("ignored %d file(s).\n" % match_len)
548
 
            self.outf.write("If you wish to add some of these files,"
549
 
                            " please add them by name.\n")
550
698
 
551
699
 
552
700
class cmd_mkdir(Command):
553
 
    """Create a new versioned directory.
 
701
    __doc__ = """Create a new versioned directory.
554
702
 
555
703
    This is equivalent to creating the directory and then adding it.
556
704
    """
560
708
 
561
709
    def run(self, dir_list):
562
710
        for d in dir_list:
563
 
            os.mkdir(d)
564
711
            wt, dd = WorkingTree.open_containing(d)
565
 
            wt.add([dd])
566
 
            self.outf.write('added %s\n' % d)
 
712
            base = os.path.dirname(dd)
 
713
            id = wt.path2id(base)
 
714
            if id != None:
 
715
                os.mkdir(d)
 
716
                wt.add([dd])
 
717
                self.outf.write('added %s\n' % d)
 
718
            else:
 
719
                raise errors.NotVersionedError(path=base)
567
720
 
568
721
 
569
722
class cmd_relpath(Command):
570
 
    """Show path of a file relative to root"""
 
723
    __doc__ = """Show path of a file relative to root"""
571
724
 
572
725
    takes_args = ['filename']
573
726
    hidden = True
574
 
    
 
727
 
575
728
    @display_command
576
729
    def run(self, filename):
577
730
        # TODO: jam 20050106 Can relpath return a munged path if
582
735
 
583
736
 
584
737
class cmd_inventory(Command):
585
 
    """Show inventory of the current working copy or a revision.
 
738
    __doc__ = """Show inventory of the current working copy or a revision.
586
739
 
587
740
    It is possible to limit the output to a particular entry
588
741
    type using the --kind option.  For example: --kind file.
609
762
 
610
763
        revision = _get_one_revision('inventory', revision)
611
764
        work_tree, file_list = tree_files(file_list)
612
 
        work_tree.lock_read()
613
 
        try:
614
 
            if revision is not None:
615
 
                tree = revision.as_tree(work_tree.branch)
616
 
 
617
 
                extra_trees = [work_tree]
618
 
                tree.lock_read()
619
 
            else:
620
 
                tree = work_tree
621
 
                extra_trees = []
622
 
 
623
 
            if file_list is not None:
624
 
                file_ids = tree.paths2ids(file_list, trees=extra_trees,
625
 
                                          require_versioned=True)
626
 
                # find_ids_across_trees may include some paths that don't
627
 
                # exist in 'tree'.
628
 
                entries = sorted((tree.id2path(file_id), tree.inventory[file_id])
629
 
                                 for file_id in file_ids if file_id in tree)
630
 
            else:
631
 
                entries = tree.inventory.entries()
632
 
        finally:
633
 
            tree.unlock()
634
 
            if tree is not work_tree:
635
 
                work_tree.unlock()
636
 
 
 
765
        self.add_cleanup(work_tree.lock_read().unlock)
 
766
        if revision is not None:
 
767
            tree = revision.as_tree(work_tree.branch)
 
768
 
 
769
            extra_trees = [work_tree]
 
770
            self.add_cleanup(tree.lock_read().unlock)
 
771
        else:
 
772
            tree = work_tree
 
773
            extra_trees = []
 
774
 
 
775
        if file_list is not None:
 
776
            file_ids = tree.paths2ids(file_list, trees=extra_trees,
 
777
                                      require_versioned=True)
 
778
            # find_ids_across_trees may include some paths that don't
 
779
            # exist in 'tree'.
 
780
            entries = sorted((tree.id2path(file_id), tree.inventory[file_id])
 
781
                             for file_id in file_ids if file_id in tree)
 
782
        else:
 
783
            entries = tree.inventory.entries()
 
784
 
 
785
        self.cleanup_now()
637
786
        for path, entry in entries:
638
787
            if kind and kind != entry.kind:
639
788
                continue
645
794
 
646
795
 
647
796
class cmd_mv(Command):
648
 
    """Move or rename a file.
 
797
    __doc__ = """Move or rename a file.
649
798
 
650
799
    :Usage:
651
800
        bzr mv OLDNAME NEWNAME
668
817
    takes_args = ['names*']
669
818
    takes_options = [Option("after", help="Move only the bzr identifier"
670
819
        " of the file, because the file has already been moved."),
 
820
        Option('auto', help='Automatically guess renames.'),
 
821
        Option('dry-run', help='Avoid making changes when guessing renames.'),
671
822
        ]
672
823
    aliases = ['move', 'rename']
673
824
    encoding_type = 'replace'
674
825
 
675
 
    def run(self, names_list, after=False):
 
826
    def run(self, names_list, after=False, auto=False, dry_run=False):
 
827
        if auto:
 
828
            return self.run_auto(names_list, after, dry_run)
 
829
        elif dry_run:
 
830
            raise errors.BzrCommandError('--dry-run requires --auto.')
676
831
        if names_list is None:
677
832
            names_list = []
678
 
 
679
833
        if len(names_list) < 2:
680
834
            raise errors.BzrCommandError("missing file argument")
681
835
        tree, rel_names = tree_files(names_list, canonicalize=False)
682
 
        tree.lock_write()
683
 
        try:
684
 
            self._run(tree, names_list, rel_names, after)
685
 
        finally:
686
 
            tree.unlock()
 
836
        self.add_cleanup(tree.lock_tree_write().unlock)
 
837
        self._run(tree, names_list, rel_names, after)
 
838
 
 
839
    def run_auto(self, names_list, after, dry_run):
 
840
        if names_list is not None and len(names_list) > 1:
 
841
            raise errors.BzrCommandError('Only one path may be specified to'
 
842
                                         ' --auto.')
 
843
        if after:
 
844
            raise errors.BzrCommandError('--after cannot be specified with'
 
845
                                         ' --auto.')
 
846
        work_tree, file_list = tree_files(names_list, default_branch='.')
 
847
        self.add_cleanup(work_tree.lock_tree_write().unlock)
 
848
        rename_map.RenameMap.guess_renames(work_tree, dry_run)
687
849
 
688
850
    def _run(self, tree, names_list, rel_names, after):
689
851
        into_existing = osutils.isdir(names_list[-1])
710
872
            # All entries reference existing inventory items, so fix them up
711
873
            # for cicp file-systems.
712
874
            rel_names = tree.get_canonical_inventory_paths(rel_names)
713
 
            for pair in tree.move(rel_names[:-1], rel_names[-1], after=after):
714
 
                self.outf.write("%s => %s\n" % pair)
 
875
            for src, dest in tree.move(rel_names[:-1], rel_names[-1], after=after):
 
876
                if not is_quiet():
 
877
                    self.outf.write("%s => %s\n" % (src, dest))
715
878
        else:
716
879
            if len(names_list) != 2:
717
880
                raise errors.BzrCommandError('to mv multiple files the'
748
911
                        # pathjoin with an empty tail adds a slash, which breaks
749
912
                        # relpath :(
750
913
                        dest_parent_fq = tree.basedir
751
 
    
 
914
 
752
915
                    dest_tail = osutils.canonical_relpath(
753
916
                                    dest_parent_fq,
754
917
                                    osutils.pathjoin(dest_parent_fq, spec_tail))
761
924
            dest = osutils.pathjoin(dest_parent, dest_tail)
762
925
            mutter("attempting to move %s => %s", src, dest)
763
926
            tree.rename_one(src, dest, after=after)
764
 
            self.outf.write("%s => %s\n" % (src, dest))
 
927
            if not is_quiet():
 
928
                self.outf.write("%s => %s\n" % (src, dest))
765
929
 
766
930
 
767
931
class cmd_pull(Command):
768
 
    """Turn this branch into a mirror of another branch.
 
932
    __doc__ = """Turn this branch into a mirror of another branch.
769
933
 
770
 
    This command only works on branches that have not diverged.  Branches are
771
 
    considered diverged if the destination branch's most recent commit is one
772
 
    that has not been merged (directly or indirectly) into the parent.
 
934
    By default, this command only works on branches that have not diverged.
 
935
    Branches are considered diverged if the destination branch's most recent 
 
936
    commit is one that has not been merged (directly or indirectly) into the 
 
937
    parent.
773
938
 
774
939
    If branches have diverged, you can use 'bzr merge' to integrate the changes
775
940
    from one into the other.  Once one branch has merged, the other should
776
941
    be able to pull it again.
777
942
 
778
 
    If you want to forget your local changes and just update your branch to
779
 
    match the remote one, use pull --overwrite.
 
943
    If you want to replace your local changes and just want your branch to
 
944
    match the remote one, use pull --overwrite. This will work even if the two
 
945
    branches have diverged.
780
946
 
781
947
    If there is no default location set, the first pull will set it.  After
782
948
    that, you can omit the location to use the default.  To change the
788
954
    with bzr send.
789
955
    """
790
956
 
791
 
    _see_also = ['push', 'update', 'status-flags']
 
957
    _see_also = ['push', 'update', 'status-flags', 'send']
792
958
    takes_options = ['remember', 'overwrite', 'revision',
793
959
        custom_help('verbose',
794
960
            help='Show logs of pulled revisions.'),
795
 
        Option('directory',
 
961
        custom_help('directory',
796
962
            help='Branch to pull into, '
797
 
                 'rather than the one containing the working directory.',
798
 
            short_name='d',
799
 
            type=unicode,
 
963
                 'rather than the one containing the working directory.'),
 
964
        Option('local',
 
965
            help="Perform a local pull in a bound "
 
966
                 "branch.  Local pulls are not applied to "
 
967
                 "the master branch."
800
968
            ),
801
969
        ]
802
970
    takes_args = ['location?']
804
972
 
805
973
    def run(self, location=None, remember=False, overwrite=False,
806
974
            revision=None, verbose=False,
807
 
            directory=None):
 
975
            directory=None, local=False):
808
976
        # FIXME: too much stuff is in the command class
809
977
        revision_id = None
810
978
        mergeable = None
813
981
        try:
814
982
            tree_to = WorkingTree.open_containing(directory)[0]
815
983
            branch_to = tree_to.branch
 
984
            self.add_cleanup(tree_to.lock_write().unlock)
816
985
        except errors.NoWorkingTree:
817
986
            tree_to = None
818
987
            branch_to = Branch.open_containing(directory)[0]
 
988
            self.add_cleanup(branch_to.lock_write().unlock)
 
989
 
 
990
        if local and not branch_to.get_bound_location():
 
991
            raise errors.LocalRequiresBoundBranch()
819
992
 
820
993
        possible_transports = []
821
994
        if location is not None:
849
1022
        else:
850
1023
            branch_from = Branch.open(location,
851
1024
                possible_transports=possible_transports)
 
1025
            self.add_cleanup(branch_from.lock_read().unlock)
852
1026
 
853
1027
            if branch_to.get_parent() is None or remember:
854
1028
                branch_to.set_parent(branch_from.base)
856
1030
        if revision is not None:
857
1031
            revision_id = revision.as_revision_id(branch_from)
858
1032
 
859
 
        branch_to.lock_write()
860
 
        try:
861
 
            if tree_to is not None:
862
 
                change_reporter = delta._ChangeReporter(
863
 
                    unversioned_filter=tree_to.is_ignored)
864
 
                result = tree_to.pull(branch_from, overwrite, revision_id,
865
 
                                      change_reporter,
866
 
                                      possible_transports=possible_transports)
867
 
            else:
868
 
                result = branch_to.pull(branch_from, overwrite, revision_id)
 
1033
        if tree_to is not None:
 
1034
            view_info = _get_view_info_for_change_reporter(tree_to)
 
1035
            change_reporter = delta._ChangeReporter(
 
1036
                unversioned_filter=tree_to.is_ignored,
 
1037
                view_info=view_info)
 
1038
            result = tree_to.pull(
 
1039
                branch_from, overwrite, revision_id, change_reporter,
 
1040
                possible_transports=possible_transports, local=local)
 
1041
        else:
 
1042
            result = branch_to.pull(
 
1043
                branch_from, overwrite, revision_id, local=local)
869
1044
 
870
 
            result.report(self.outf)
871
 
            if verbose and result.old_revid != result.new_revid:
872
 
                log.show_branch_change(branch_to, self.outf, result.old_revno,
873
 
                                       result.old_revid)
874
 
        finally:
875
 
            branch_to.unlock()
 
1045
        result.report(self.outf)
 
1046
        if verbose and result.old_revid != result.new_revid:
 
1047
            log.show_branch_change(
 
1048
                branch_to, self.outf, result.old_revno,
 
1049
                result.old_revid)
876
1050
 
877
1051
 
878
1052
class cmd_push(Command):
879
 
    """Update a mirror of this branch.
880
 
    
 
1053
    __doc__ = """Update a mirror of this branch.
 
1054
 
881
1055
    The target branch will not have its working tree populated because this
882
1056
    is both expensive, and is not supported on remote file systems.
883
 
    
 
1057
 
884
1058
    Some smart servers or protocols *may* put the working tree in place in
885
1059
    the future.
886
1060
 
890
1064
 
891
1065
    If branches have diverged, you can use 'bzr push --overwrite' to replace
892
1066
    the other branch completely, discarding its unmerged changes.
893
 
    
 
1067
 
894
1068
    If you want to ensure you have the different changes in the other branch,
895
1069
    do a merge (see bzr help merge) from the other branch, and commit that.
896
1070
    After that you will be able to do a push without '--overwrite'.
906
1080
        Option('create-prefix',
907
1081
               help='Create the path leading up to the branch '
908
1082
                    'if it does not already exist.'),
909
 
        Option('directory',
 
1083
        custom_help('directory',
910
1084
            help='Branch to push from, '
911
 
                 'rather than the one containing the working directory.',
912
 
            short_name='d',
913
 
            type=unicode,
914
 
            ),
 
1085
                 'rather than the one containing the working directory.'),
915
1086
        Option('use-existing-dir',
916
1087
               help='By default push will fail if the target'
917
1088
                    ' directory exists, but does not already'
925
1096
                'for the commit history. Only the work not present in the '
926
1097
                'referenced branch is included in the branch created.',
927
1098
            type=unicode),
 
1099
        Option('strict',
 
1100
               help='Refuse to push if there are uncommitted changes in'
 
1101
               ' the working tree, --no-strict disables the check.'),
928
1102
        ]
929
1103
    takes_args = ['location?']
930
1104
    encoding_type = 'replace'
932
1106
    def run(self, location=None, remember=False, overwrite=False,
933
1107
        create_prefix=False, verbose=False, revision=None,
934
1108
        use_existing_dir=False, directory=None, stacked_on=None,
935
 
        stacked=False):
 
1109
        stacked=False, strict=None):
936
1110
        from bzrlib.push import _show_push_branch
937
1111
 
938
 
        # Get the source branch and revision_id
939
1112
        if directory is None:
940
1113
            directory = '.'
941
 
        br_from = Branch.open_containing(directory)[0]
 
1114
        # Get the source branch
 
1115
        (tree, br_from,
 
1116
         _unused) = bzrdir.BzrDir.open_containing_tree_or_branch(directory)
 
1117
        # Get the tip's revision_id
942
1118
        revision = _get_one_revision('push', revision)
943
1119
        if revision is not None:
944
1120
            revision_id = revision.in_history(br_from).rev_id
945
1121
        else:
946
 
            revision_id = br_from.last_revision()
947
 
 
 
1122
            revision_id = None
 
1123
        if tree is not None and revision_id is None:
 
1124
            tree.check_changed_or_out_of_date(
 
1125
                strict, 'push_strict',
 
1126
                more_error='Use --no-strict to force the push.',
 
1127
                more_warning='Uncommitted changes will not be pushed.')
948
1128
        # Get the stacked_on branch, if any
949
1129
        if stacked_on is not None:
950
1130
            stacked_on = urlutils.normalize_url(stacked_on)
982
1162
 
983
1163
 
984
1164
class cmd_branch(Command):
985
 
    """Create a new copy of a branch.
 
1165
    __doc__ = """Create a new branch that is a copy of an existing branch.
986
1166
 
987
1167
    If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
988
1168
    be used.  In other words, "branch ../foo/bar" will attempt to create ./bar.
1001
1181
        help='Hard-link working tree files where possible.'),
1002
1182
        Option('no-tree',
1003
1183
            help="Create a branch without a working-tree."),
 
1184
        Option('switch',
 
1185
            help="Switch the checkout in the current directory "
 
1186
                 "to the new branch."),
1004
1187
        Option('stacked',
1005
1188
            help='Create a stacked branch referring to the source branch. '
1006
1189
                'The new branch will depend on the availability of the source '
1007
1190
                'branch for all operations.'),
1008
1191
        Option('standalone',
1009
1192
               help='Do not use a shared repository, even if available.'),
 
1193
        Option('use-existing-dir',
 
1194
               help='By default branch will fail if the target'
 
1195
                    ' directory exists, but does not already'
 
1196
                    ' have a control directory.  This flag will'
 
1197
                    ' allow branch to proceed.'),
 
1198
        Option('bind',
 
1199
            help="Bind new branch to from location."),
1010
1200
        ]
1011
1201
    aliases = ['get', 'clone']
1012
1202
 
1013
1203
    def run(self, from_location, to_location=None, revision=None,
1014
 
            hardlink=False, stacked=False, standalone=False, no_tree=False):
 
1204
            hardlink=False, stacked=False, standalone=False, no_tree=False,
 
1205
            use_existing_dir=False, switch=False, bind=False):
 
1206
        from bzrlib import switch as _mod_switch
1015
1207
        from bzrlib.tag import _merge_tags_if_possible
1016
 
 
1017
1208
        accelerator_tree, br_from = bzrdir.BzrDir.open_tree_or_branch(
1018
1209
            from_location)
1019
1210
        revision = _get_one_revision('branch', revision)
1020
 
        br_from.lock_read()
 
1211
        self.add_cleanup(br_from.lock_read().unlock)
 
1212
        if revision is not None:
 
1213
            revision_id = revision.as_revision_id(br_from)
 
1214
        else:
 
1215
            # FIXME - wt.last_revision, fallback to branch, fall back to
 
1216
            # None or perhaps NULL_REVISION to mean copy nothing
 
1217
            # RBC 20060209
 
1218
            revision_id = br_from.last_revision()
 
1219
        if to_location is None:
 
1220
            to_location = urlutils.derive_to_location(from_location)
 
1221
        to_transport = transport.get_transport(to_location)
1021
1222
        try:
1022
 
            if revision is not None:
1023
 
                revision_id = revision.as_revision_id(br_from)
 
1223
            to_transport.mkdir('.')
 
1224
        except errors.FileExists:
 
1225
            if not use_existing_dir:
 
1226
                raise errors.BzrCommandError('Target directory "%s" '
 
1227
                    'already exists.' % to_location)
1024
1228
            else:
1025
 
                # FIXME - wt.last_revision, fallback to branch, fall back to
1026
 
                # None or perhaps NULL_REVISION to mean copy nothing
1027
 
                # RBC 20060209
1028
 
                revision_id = br_from.last_revision()
1029
 
            if to_location is None:
1030
 
                to_location = urlutils.derive_to_location(from_location)
1031
 
            to_transport = transport.get_transport(to_location)
1032
 
            try:
1033
 
                to_transport.mkdir('.')
1034
 
            except errors.FileExists:
1035
 
                raise errors.BzrCommandError('Target directory "%s" already'
1036
 
                                             ' exists.' % to_location)
1037
 
            except errors.NoSuchFile:
1038
 
                raise errors.BzrCommandError('Parent of "%s" does not exist.'
1039
 
                                             % to_location)
1040
 
            try:
1041
 
                # preserve whatever source format we have.
1042
 
                dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
1043
 
                                            possible_transports=[to_transport],
1044
 
                                            accelerator_tree=accelerator_tree,
1045
 
                                            hardlink=hardlink, stacked=stacked,
1046
 
                                            force_new_repo=standalone,
1047
 
                                            create_tree_if_local=not no_tree,
1048
 
                                            source_branch=br_from)
1049
 
                branch = dir.open_branch()
1050
 
            except errors.NoSuchRevision:
1051
 
                to_transport.delete_tree('.')
1052
 
                msg = "The branch %s has no revision %s." % (from_location,
1053
 
                    revision)
1054
 
                raise errors.BzrCommandError(msg)
1055
 
            _merge_tags_if_possible(br_from, branch)
1056
 
            # If the source branch is stacked, the new branch may
1057
 
            # be stacked whether we asked for that explicitly or not.
1058
 
            # We therefore need a try/except here and not just 'if stacked:'
1059
 
            try:
1060
 
                note('Created new stacked branch referring to %s.' %
1061
 
                    branch.get_stacked_on_url())
1062
 
            except (errors.NotStacked, errors.UnstackableBranchFormat,
1063
 
                errors.UnstackableRepositoryFormat), e:
1064
 
                note('Branched %d revision(s).' % branch.revno())
1065
 
        finally:
1066
 
            br_from.unlock()
 
1229
                try:
 
1230
                    bzrdir.BzrDir.open_from_transport(to_transport)
 
1231
                except errors.NotBranchError:
 
1232
                    pass
 
1233
                else:
 
1234
                    raise errors.AlreadyBranchError(to_location)
 
1235
        except errors.NoSuchFile:
 
1236
            raise errors.BzrCommandError('Parent of "%s" does not exist.'
 
1237
                                         % to_location)
 
1238
        try:
 
1239
            # preserve whatever source format we have.
 
1240
            dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
 
1241
                                        possible_transports=[to_transport],
 
1242
                                        accelerator_tree=accelerator_tree,
 
1243
                                        hardlink=hardlink, stacked=stacked,
 
1244
                                        force_new_repo=standalone,
 
1245
                                        create_tree_if_local=not no_tree,
 
1246
                                        source_branch=br_from)
 
1247
            branch = dir.open_branch()
 
1248
        except errors.NoSuchRevision:
 
1249
            to_transport.delete_tree('.')
 
1250
            msg = "The branch %s has no revision %s." % (from_location,
 
1251
                revision)
 
1252
            raise errors.BzrCommandError(msg)
 
1253
        _merge_tags_if_possible(br_from, branch)
 
1254
        # If the source branch is stacked, the new branch may
 
1255
        # be stacked whether we asked for that explicitly or not.
 
1256
        # We therefore need a try/except here and not just 'if stacked:'
 
1257
        try:
 
1258
            note('Created new stacked branch referring to %s.' %
 
1259
                branch.get_stacked_on_url())
 
1260
        except (errors.NotStacked, errors.UnstackableBranchFormat,
 
1261
            errors.UnstackableRepositoryFormat), e:
 
1262
            note('Branched %d revision(s).' % branch.revno())
 
1263
        if bind:
 
1264
            # Bind to the parent
 
1265
            parent_branch = Branch.open(from_location)
 
1266
            branch.bind(parent_branch)
 
1267
            note('New branch bound to %s' % from_location)
 
1268
        if switch:
 
1269
            # Switch to the new branch
 
1270
            wt, _ = WorkingTree.open_containing('.')
 
1271
            _mod_switch.switch(wt.bzrdir, branch)
 
1272
            note('Switched to branch: %s',
 
1273
                urlutils.unescape_for_display(branch.base, 'utf-8'))
1067
1274
 
1068
1275
 
1069
1276
class cmd_checkout(Command):
1070
 
    """Create a new checkout of an existing branch.
 
1277
    __doc__ = """Create a new checkout of an existing branch.
1071
1278
 
1072
1279
    If BRANCH_LOCATION is omitted, checkout will reconstitute a working tree for
1073
1280
    the branch found in '.'. This is useful if you have removed the working tree
1074
1281
    or if it was never created - i.e. if you pushed the branch to its current
1075
1282
    location using SFTP.
1076
 
    
 
1283
 
1077
1284
    If the TO_LOCATION is omitted, the last component of the BRANCH_LOCATION will
1078
1285
    be used.  In other words, "checkout ../foo/bar" will attempt to create ./bar.
1079
1286
    If the BRANCH_LOCATION has no / or path separator embedded, the TO_LOCATION
1121
1328
            revision_id = None
1122
1329
        if to_location is None:
1123
1330
            to_location = urlutils.derive_to_location(branch_location)
1124
 
        # if the source and to_location are the same, 
 
1331
        # if the source and to_location are the same,
1125
1332
        # and there is no working tree,
1126
1333
        # then reconstitute a branch
1127
1334
        if (osutils.abspath(to_location) ==
1136
1343
 
1137
1344
 
1138
1345
class cmd_renames(Command):
1139
 
    """Show list of renamed files.
 
1346
    __doc__ = """Show list of renamed files.
1140
1347
    """
1141
1348
    # TODO: Option to show renames between two historical versions.
1142
1349
 
1147
1354
    @display_command
1148
1355
    def run(self, dir=u'.'):
1149
1356
        tree = WorkingTree.open_containing(dir)[0]
1150
 
        tree.lock_read()
1151
 
        try:
1152
 
            new_inv = tree.inventory
1153
 
            old_tree = tree.basis_tree()
1154
 
            old_tree.lock_read()
1155
 
            try:
1156
 
                old_inv = old_tree.inventory
1157
 
                renames = []
1158
 
                iterator = tree.iter_changes(old_tree, include_unchanged=True)
1159
 
                for f, paths, c, v, p, n, k, e in iterator:
1160
 
                    if paths[0] == paths[1]:
1161
 
                        continue
1162
 
                    if None in (paths):
1163
 
                        continue
1164
 
                    renames.append(paths)
1165
 
                renames.sort()
1166
 
                for old_name, new_name in renames:
1167
 
                    self.outf.write("%s => %s\n" % (old_name, new_name))
1168
 
            finally:
1169
 
                old_tree.unlock()
1170
 
        finally:
1171
 
            tree.unlock()
 
1357
        self.add_cleanup(tree.lock_read().unlock)
 
1358
        new_inv = tree.inventory
 
1359
        old_tree = tree.basis_tree()
 
1360
        self.add_cleanup(old_tree.lock_read().unlock)
 
1361
        old_inv = old_tree.inventory
 
1362
        renames = []
 
1363
        iterator = tree.iter_changes(old_tree, include_unchanged=True)
 
1364
        for f, paths, c, v, p, n, k, e in iterator:
 
1365
            if paths[0] == paths[1]:
 
1366
                continue
 
1367
            if None in (paths):
 
1368
                continue
 
1369
            renames.append(paths)
 
1370
        renames.sort()
 
1371
        for old_name, new_name in renames:
 
1372
            self.outf.write("%s => %s\n" % (old_name, new_name))
1172
1373
 
1173
1374
 
1174
1375
class cmd_update(Command):
1175
 
    """Update a tree to have the latest code committed to its branch.
1176
 
    
 
1376
    __doc__ = """Update a tree to have the latest code committed to its branch.
 
1377
 
1177
1378
    This will perform a merge into the working tree, and may generate
1178
 
    conflicts. If you have any local changes, you will still 
 
1379
    conflicts. If you have any local changes, you will still
1179
1380
    need to commit them after the update for the update to be complete.
1180
 
    
1181
 
    If you want to discard your local changes, you can just do a 
 
1381
 
 
1382
    If you want to discard your local changes, you can just do a
1182
1383
    'bzr revert' instead of 'bzr commit' after the update.
 
1384
 
 
1385
    If the tree's branch is bound to a master branch, it will also update
 
1386
    the branch from the master.
1183
1387
    """
1184
1388
 
1185
1389
    _see_also = ['pull', 'working-trees', 'status-flags']
1186
1390
    takes_args = ['dir?']
 
1391
    takes_options = ['revision']
1187
1392
    aliases = ['up']
1188
1393
 
1189
 
    def run(self, dir='.'):
 
1394
    def run(self, dir='.', revision=None):
 
1395
        if revision is not None and len(revision) != 1:
 
1396
            raise errors.BzrCommandError(
 
1397
                        "bzr update --revision takes exactly one revision")
1190
1398
        tree = WorkingTree.open_containing(dir)[0]
 
1399
        branch = tree.branch
1191
1400
        possible_transports = []
1192
 
        master = tree.branch.get_master_branch(
 
1401
        master = branch.get_master_branch(
1193
1402
            possible_transports=possible_transports)
1194
1403
        if master is not None:
 
1404
            branch_location = master.base
1195
1405
            tree.lock_write()
1196
1406
        else:
 
1407
            branch_location = tree.branch.base
1197
1408
            tree.lock_tree_write()
 
1409
        self.add_cleanup(tree.unlock)
 
1410
        # get rid of the final '/' and be ready for display
 
1411
        branch_location = urlutils.unescape_for_display(
 
1412
            branch_location.rstrip('/'),
 
1413
            self.outf.encoding)
 
1414
        existing_pending_merges = tree.get_parent_ids()[1:]
 
1415
        if master is None:
 
1416
            old_tip = None
 
1417
        else:
 
1418
            # may need to fetch data into a heavyweight checkout
 
1419
            # XXX: this may take some time, maybe we should display a
 
1420
            # message
 
1421
            old_tip = branch.update(possible_transports)
 
1422
        if revision is not None:
 
1423
            revision_id = revision[0].as_revision_id(branch)
 
1424
        else:
 
1425
            revision_id = branch.last_revision()
 
1426
        if revision_id == _mod_revision.ensure_null(tree.last_revision()):
 
1427
            revno = branch.revision_id_to_dotted_revno(revision_id)
 
1428
            note("Tree is up to date at revision %s of branch %s" %
 
1429
                ('.'.join(map(str, revno)), branch_location))
 
1430
            return 0
 
1431
        view_info = _get_view_info_for_change_reporter(tree)
 
1432
        change_reporter = delta._ChangeReporter(
 
1433
            unversioned_filter=tree.is_ignored,
 
1434
            view_info=view_info)
1198
1435
        try:
1199
 
            existing_pending_merges = tree.get_parent_ids()[1:]
1200
 
            last_rev = _mod_revision.ensure_null(tree.last_revision())
1201
 
            if last_rev == _mod_revision.ensure_null(
1202
 
                tree.branch.last_revision()):
1203
 
                # may be up to date, check master too.
1204
 
                if master is None or last_rev == _mod_revision.ensure_null(
1205
 
                    master.last_revision()):
1206
 
                    revno = tree.branch.revision_id_to_revno(last_rev)
1207
 
                    note("Tree is up to date at revision %d." % (revno,))
1208
 
                    return 0
1209
1436
            conflicts = tree.update(
1210
 
                delta._ChangeReporter(unversioned_filter=tree.is_ignored),
1211
 
                possible_transports=possible_transports)
1212
 
            revno = tree.branch.revision_id_to_revno(
1213
 
                _mod_revision.ensure_null(tree.last_revision()))
1214
 
            note('Updated to revision %d.' % (revno,))
1215
 
            if tree.get_parent_ids()[1:] != existing_pending_merges:
1216
 
                note('Your local commits will now show as pending merges with '
1217
 
                     "'bzr status', and can be committed with 'bzr commit'.")
1218
 
            if conflicts != 0:
1219
 
                return 1
1220
 
            else:
1221
 
                return 0
1222
 
        finally:
1223
 
            tree.unlock()
 
1437
                change_reporter,
 
1438
                possible_transports=possible_transports,
 
1439
                revision=revision_id,
 
1440
                old_tip=old_tip)
 
1441
        except errors.NoSuchRevision, e:
 
1442
            raise errors.BzrCommandError(
 
1443
                                  "branch has no revision %s\n"
 
1444
                                  "bzr update --revision only works"
 
1445
                                  " for a revision in the branch history"
 
1446
                                  % (e.revision))
 
1447
        revno = tree.branch.revision_id_to_dotted_revno(
 
1448
            _mod_revision.ensure_null(tree.last_revision()))
 
1449
        note('Updated to revision %s of branch %s' %
 
1450
             ('.'.join(map(str, revno)), branch_location))
 
1451
        parent_ids = tree.get_parent_ids()
 
1452
        if parent_ids[1:] and parent_ids[1:] != existing_pending_merges:
 
1453
            note('Your local commits will now show as pending merges with '
 
1454
                 "'bzr status', and can be committed with 'bzr commit'.")
 
1455
        if conflicts != 0:
 
1456
            return 1
 
1457
        else:
 
1458
            return 0
1224
1459
 
1225
1460
 
1226
1461
class cmd_info(Command):
1227
 
    """Show information about a working tree, branch or repository.
 
1462
    __doc__ = """Show information about a working tree, branch or repository.
1228
1463
 
1229
1464
    This command will show all known locations and formats associated to the
1230
 
    tree, branch or repository.  Statistical information is included with
1231
 
    each report.
 
1465
    tree, branch or repository.
 
1466
 
 
1467
    In verbose mode, statistical information is included with each report.
 
1468
    To see extended statistic information, use a verbosity level of 2 or
 
1469
    higher by specifying the verbose option multiple times, e.g. -vv.
1232
1470
 
1233
1471
    Branches and working trees will also report any missing revisions.
 
1472
 
 
1473
    :Examples:
 
1474
 
 
1475
      Display information on the format and related locations:
 
1476
 
 
1477
        bzr info
 
1478
 
 
1479
      Display the above together with extended format information and
 
1480
      basic statistics (like the number of files in the working tree and
 
1481
      number of revisions in the branch and repository):
 
1482
 
 
1483
        bzr info -v
 
1484
 
 
1485
      Display the above together with number of committers to the branch:
 
1486
 
 
1487
        bzr info -vv
1234
1488
    """
1235
1489
    _see_also = ['revno', 'working-trees', 'repositories']
1236
1490
    takes_args = ['location?']
1240
1494
    @display_command
1241
1495
    def run(self, location=None, verbose=False):
1242
1496
        if verbose:
1243
 
            noise_level = 2
 
1497
            noise_level = get_verbosity_level()
1244
1498
        else:
1245
1499
            noise_level = 0
1246
1500
        from bzrlib.info import show_bzrdir_info
1249
1503
 
1250
1504
 
1251
1505
class cmd_remove(Command):
1252
 
    """Remove files or directories.
 
1506
    __doc__ = """Remove files or directories.
1253
1507
 
1254
1508
    This makes bzr stop tracking changes to the specified files. bzr will delete
1255
1509
    them if they can easily be recovered using revert. If no options or
1264
1518
            title='Deletion Strategy', value_switches=True, enum_switch=False,
1265
1519
            safe='Only delete files if they can be'
1266
1520
                 ' safely recovered (default).',
1267
 
            keep="Don't delete any files.",
 
1521
            keep='Delete from bzr but leave the working copy.',
1268
1522
            force='Delete all the specified files, even if they can not be '
1269
1523
                'recovered and even if they are non-empty directories.')]
1270
1524
    aliases = ['rm', 'del']
1277
1531
        if file_list is not None:
1278
1532
            file_list = [f for f in file_list]
1279
1533
 
1280
 
        tree.lock_write()
1281
 
        try:
1282
 
            # Heuristics should probably all move into tree.remove_smart or
1283
 
            # some such?
1284
 
            if new:
1285
 
                added = tree.changes_from(tree.basis_tree(),
1286
 
                    specific_files=file_list).added
1287
 
                file_list = sorted([f[0] for f in added], reverse=True)
1288
 
                if len(file_list) == 0:
1289
 
                    raise errors.BzrCommandError('No matching files.')
1290
 
            elif file_list is None:
1291
 
                # missing files show up in iter_changes(basis) as
1292
 
                # versioned-with-no-kind.
1293
 
                missing = []
1294
 
                for change in tree.iter_changes(tree.basis_tree()):
1295
 
                    # Find paths in the working tree that have no kind:
1296
 
                    if change[1][1] is not None and change[6][1] is None:
1297
 
                        missing.append(change[1][1])
1298
 
                file_list = sorted(missing, reverse=True)
1299
 
                file_deletion_strategy = 'keep'
1300
 
            tree.remove(file_list, verbose=verbose, to_file=self.outf,
1301
 
                keep_files=file_deletion_strategy=='keep',
1302
 
                force=file_deletion_strategy=='force')
1303
 
        finally:
1304
 
            tree.unlock()
 
1534
        self.add_cleanup(tree.lock_write().unlock)
 
1535
        # Heuristics should probably all move into tree.remove_smart or
 
1536
        # some such?
 
1537
        if new:
 
1538
            added = tree.changes_from(tree.basis_tree(),
 
1539
                specific_files=file_list).added
 
1540
            file_list = sorted([f[0] for f in added], reverse=True)
 
1541
            if len(file_list) == 0:
 
1542
                raise errors.BzrCommandError('No matching files.')
 
1543
        elif file_list is None:
 
1544
            # missing files show up in iter_changes(basis) as
 
1545
            # versioned-with-no-kind.
 
1546
            missing = []
 
1547
            for change in tree.iter_changes(tree.basis_tree()):
 
1548
                # Find paths in the working tree that have no kind:
 
1549
                if change[1][1] is not None and change[6][1] is None:
 
1550
                    missing.append(change[1][1])
 
1551
            file_list = sorted(missing, reverse=True)
 
1552
            file_deletion_strategy = 'keep'
 
1553
        tree.remove(file_list, verbose=verbose, to_file=self.outf,
 
1554
            keep_files=file_deletion_strategy=='keep',
 
1555
            force=file_deletion_strategy=='force')
1305
1556
 
1306
1557
 
1307
1558
class cmd_file_id(Command):
1308
 
    """Print file_id of a particular file or directory.
 
1559
    __doc__ = """Print file_id of a particular file or directory.
1309
1560
 
1310
1561
    The file_id is assigned when the file is first added and remains the
1311
1562
    same through all revisions where the file exists, even when it is
1327
1578
 
1328
1579
 
1329
1580
class cmd_file_path(Command):
1330
 
    """Print path of file_ids to a file or directory.
 
1581
    __doc__ = """Print path of file_ids to a file or directory.
1331
1582
 
1332
1583
    This prints one line for each directory down to the target,
1333
1584
    starting at the branch root.
1349
1600
 
1350
1601
 
1351
1602
class cmd_reconcile(Command):
1352
 
    """Reconcile bzr metadata in a branch.
 
1603
    __doc__ = """Reconcile bzr metadata in a branch.
1353
1604
 
1354
1605
    This can correct data mismatches that may have been caused by
1355
1606
    previous ghost operations or bzr upgrades. You should only
1356
 
    need to run this command if 'bzr check' or a bzr developer 
 
1607
    need to run this command if 'bzr check' or a bzr developer
1357
1608
    advises you to run it.
1358
1609
 
1359
1610
    If a second branch is provided, cross-branch reconciliation is
1361
1612
    id which was not present in very early bzr versions is represented
1362
1613
    correctly in both branches.
1363
1614
 
1364
 
    At the same time it is run it may recompress data resulting in 
 
1615
    At the same time it is run it may recompress data resulting in
1365
1616
    a potential saving in disk space or performance gain.
1366
1617
 
1367
1618
    The branch *MUST* be on a listable system such as local disk or sftp.
1377
1628
 
1378
1629
 
1379
1630
class cmd_revision_history(Command):
1380
 
    """Display the list of revision ids on a branch."""
 
1631
    __doc__ = """Display the list of revision ids on a branch."""
1381
1632
 
1382
1633
    _see_also = ['log']
1383
1634
    takes_args = ['location?']
1393
1644
 
1394
1645
 
1395
1646
class cmd_ancestry(Command):
1396
 
    """List all revisions merged into this branch."""
 
1647
    __doc__ = """List all revisions merged into this branch."""
1397
1648
 
1398
1649
    _see_also = ['log', 'revision-history']
1399
1650
    takes_args = ['location?']
1418
1669
 
1419
1670
 
1420
1671
class cmd_init(Command):
1421
 
    """Make a directory into a versioned branch.
 
1672
    __doc__ = """Make a directory into a versioned branch.
1422
1673
 
1423
1674
    Use this to create an empty branch, or before importing an
1424
1675
    existing project.
1425
1676
 
1426
 
    If there is a repository in a parent directory of the location, then 
 
1677
    If there is a repository in a parent directory of the location, then
1427
1678
    the history of the branch will be stored in the repository.  Otherwise
1428
1679
    init creates a standalone branch which carries its own history
1429
1680
    in the .bzr directory.
1452
1703
                lazy_registry=('bzrlib.bzrdir', 'format_registry'),
1453
1704
                converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
1454
1705
                value_switches=True,
1455
 
                title="Branch Format",
 
1706
                title="Branch format",
1456
1707
                ),
1457
1708
         Option('append-revisions-only',
1458
1709
                help='Never change revnos or the existing log.'
1481
1732
                    "\nYou may supply --create-prefix to create all"
1482
1733
                    " leading parent directories."
1483
1734
                    % location)
1484
 
            _create_prefix(to_transport)
 
1735
            to_transport.create_prefix()
1485
1736
 
1486
1737
        try:
1487
1738
            a_bzrdir = bzrdir.BzrDir.open_from_transport(to_transport)
1505
1756
                branch.set_append_revisions_only(True)
1506
1757
            except errors.UpgradeRequired:
1507
1758
                raise errors.BzrCommandError('This branch format cannot be set'
1508
 
                    ' to append-revisions-only.  Try --experimental-branch6')
 
1759
                    ' to append-revisions-only.  Try --default.')
1509
1760
        if not is_quiet():
1510
1761
            from bzrlib.info import describe_layout, describe_format
1511
1762
            try:
1527
1778
 
1528
1779
 
1529
1780
class cmd_init_repository(Command):
1530
 
    """Create a shared repository to hold branches.
 
1781
    __doc__ = """Create a shared repository for branches to share storage space.
1531
1782
 
1532
1783
    New branches created under the repository directory will store their
1533
 
    revisions in the repository, not in the branch directory.
 
1784
    revisions in the repository, not in the branch directory.  For branches
 
1785
    with shared history, this reduces the amount of storage needed and 
 
1786
    speeds up the creation of new branches.
1534
1787
 
1535
 
    If the --no-trees option is used then the branches in the repository
1536
 
    will not have working trees by default.
 
1788
    If the --no-trees option is given then the branches in the repository
 
1789
    will not have working trees by default.  They will still exist as 
 
1790
    directories on disk, but they will not have separate copies of the 
 
1791
    files at a certain revision.  This can be useful for repositories that
 
1792
    store branches which are interacted with through checkouts or remote
 
1793
    branches, such as on a server.
1537
1794
 
1538
1795
    :Examples:
1539
 
        Create a shared repositories holding just branches::
 
1796
        Create a shared repository holding just branches::
1540
1797
 
1541
1798
            bzr init-repo --no-trees repo
1542
1799
            bzr init repo/trunk
1581
1838
 
1582
1839
 
1583
1840
class cmd_diff(Command):
1584
 
    """Show differences in the working tree, between revisions or branches.
1585
 
    
 
1841
    __doc__ = """Show differences in the working tree, between revisions or branches.
 
1842
 
1586
1843
    If no arguments are given, all changes for the current tree are listed.
1587
1844
    If files are given, only the changes in those files are listed.
1588
1845
    Remote and multiple branches can be compared by using the --old and
1608
1865
 
1609
1866
            bzr diff -r1
1610
1867
 
1611
 
        Difference between revision 2 and revision 1::
1612
 
 
1613
 
            bzr diff -r1..2
1614
 
 
1615
 
        Difference between revision 2 and revision 1 for branch xxx::
1616
 
 
1617
 
            bzr diff -r1..2 xxx
 
1868
        Difference between revision 3 and revision 1::
 
1869
 
 
1870
            bzr diff -r1..3
 
1871
 
 
1872
        Difference between revision 3 and revision 1 for branch xxx::
 
1873
 
 
1874
            bzr diff -r1..3 xxx
 
1875
 
 
1876
        To see the changes introduced in revision X::
 
1877
        
 
1878
            bzr diff -cX
 
1879
 
 
1880
        Note that in the case of a merge, the -c option shows the changes
 
1881
        compared to the left hand parent. To see the changes against
 
1882
        another parent, use::
 
1883
 
 
1884
            bzr diff -r<chosen_parent>..X
 
1885
 
 
1886
        The changes introduced by revision 2 (equivalent to -r1..2)::
 
1887
 
 
1888
            bzr diff -c2
1618
1889
 
1619
1890
        Show just the differences for file NEWS::
1620
1891
 
1659
1930
            help='Use this command to compare files.',
1660
1931
            type=unicode,
1661
1932
            ),
 
1933
        RegistryOption('format',
 
1934
            help='Diff format to use.',
 
1935
            lazy_registry=('bzrlib.diff', 'format_registry'),
 
1936
            value_switches=False, title='Diff format'),
1662
1937
        ]
1663
1938
    aliases = ['di', 'dif']
1664
1939
    encoding_type = 'exact'
1665
1940
 
1666
1941
    @display_command
1667
1942
    def run(self, revision=None, file_list=None, diff_options=None,
1668
 
            prefix=None, old=None, new=None, using=None):
1669
 
        from bzrlib.diff import _get_trees_to_diff, show_diff_trees
 
1943
            prefix=None, old=None, new=None, using=None, format=None):
 
1944
        from bzrlib.diff import (get_trees_and_branches_to_diff_locked,
 
1945
            show_diff_trees)
1670
1946
 
1671
1947
        if (prefix is None) or (prefix == '0'):
1672
1948
            # diff -p0 format
1686
1962
            raise errors.BzrCommandError('bzr diff --revision takes exactly'
1687
1963
                                         ' one or two revision specifiers')
1688
1964
 
1689
 
        old_tree, new_tree, specific_files, extra_trees = \
1690
 
                _get_trees_to_diff(file_list, revision, old, new)
1691
 
        return show_diff_trees(old_tree, new_tree, sys.stdout, 
 
1965
        if using is not None and format is not None:
 
1966
            raise errors.BzrCommandError('--using and --format are mutually '
 
1967
                'exclusive.')
 
1968
 
 
1969
        (old_tree, new_tree,
 
1970
         old_branch, new_branch,
 
1971
         specific_files, extra_trees) = get_trees_and_branches_to_diff_locked(
 
1972
            file_list, revision, old, new, self.add_cleanup, apply_view=True)
 
1973
        # GNU diff on Windows uses ANSI encoding for filenames
 
1974
        path_encoding = osutils.get_diff_header_encoding()
 
1975
        return show_diff_trees(old_tree, new_tree, sys.stdout,
1692
1976
                               specific_files=specific_files,
1693
1977
                               external_diff_options=diff_options,
1694
1978
                               old_label=old_label, new_label=new_label,
1695
 
                               extra_trees=extra_trees, using=using)
 
1979
                               extra_trees=extra_trees,
 
1980
                               path_encoding=path_encoding,
 
1981
                               using=using,
 
1982
                               format_cls=format)
1696
1983
 
1697
1984
 
1698
1985
class cmd_deleted(Command):
1699
 
    """List files deleted in the working tree.
 
1986
    __doc__ = """List files deleted in the working tree.
1700
1987
    """
1701
1988
    # TODO: Show files deleted since a previous revision, or
1702
1989
    # between two revisions.
1705
1992
    # level of effort but possibly much less IO.  (Or possibly not,
1706
1993
    # if the directories are very large...)
1707
1994
    _see_also = ['status', 'ls']
1708
 
    takes_options = ['show-ids']
 
1995
    takes_options = ['directory', 'show-ids']
1709
1996
 
1710
1997
    @display_command
1711
 
    def run(self, show_ids=False):
1712
 
        tree = WorkingTree.open_containing(u'.')[0]
1713
 
        tree.lock_read()
1714
 
        try:
1715
 
            old = tree.basis_tree()
1716
 
            old.lock_read()
1717
 
            try:
1718
 
                for path, ie in old.inventory.iter_entries():
1719
 
                    if not tree.has_id(ie.file_id):
1720
 
                        self.outf.write(path)
1721
 
                        if show_ids:
1722
 
                            self.outf.write(' ')
1723
 
                            self.outf.write(ie.file_id)
1724
 
                        self.outf.write('\n')
1725
 
            finally:
1726
 
                old.unlock()
1727
 
        finally:
1728
 
            tree.unlock()
 
1998
    def run(self, show_ids=False, directory=u'.'):
 
1999
        tree = WorkingTree.open_containing(directory)[0]
 
2000
        self.add_cleanup(tree.lock_read().unlock)
 
2001
        old = tree.basis_tree()
 
2002
        self.add_cleanup(old.lock_read().unlock)
 
2003
        for path, ie in old.inventory.iter_entries():
 
2004
            if not tree.has_id(ie.file_id):
 
2005
                self.outf.write(path)
 
2006
                if show_ids:
 
2007
                    self.outf.write(' ')
 
2008
                    self.outf.write(ie.file_id)
 
2009
                self.outf.write('\n')
1729
2010
 
1730
2011
 
1731
2012
class cmd_modified(Command):
1732
 
    """List files modified in working tree.
 
2013
    __doc__ = """List files modified in working tree.
1733
2014
    """
1734
2015
 
1735
2016
    hidden = True
1736
2017
    _see_also = ['status', 'ls']
1737
 
    takes_options = [
1738
 
            Option('null',
1739
 
                   help='Write an ascii NUL (\\0) separator '
1740
 
                   'between files rather than a newline.')
1741
 
            ]
 
2018
    takes_options = ['directory', 'null']
1742
2019
 
1743
2020
    @display_command
1744
 
    def run(self, null=False):
1745
 
        tree = WorkingTree.open_containing(u'.')[0]
 
2021
    def run(self, null=False, directory=u'.'):
 
2022
        tree = WorkingTree.open_containing(directory)[0]
1746
2023
        td = tree.changes_from(tree.basis_tree())
1747
2024
        for path, id, kind, text_modified, meta_modified in td.modified:
1748
2025
            if null:
1752
2029
 
1753
2030
 
1754
2031
class cmd_added(Command):
1755
 
    """List files added in working tree.
 
2032
    __doc__ = """List files added in working tree.
1756
2033
    """
1757
2034
 
1758
2035
    hidden = True
1759
2036
    _see_also = ['status', 'ls']
1760
 
    takes_options = [
1761
 
            Option('null',
1762
 
                   help='Write an ascii NUL (\\0) separator '
1763
 
                   'between files rather than a newline.')
1764
 
            ]
 
2037
    takes_options = ['directory', 'null']
1765
2038
 
1766
2039
    @display_command
1767
 
    def run(self, null=False):
1768
 
        wt = WorkingTree.open_containing(u'.')[0]
1769
 
        wt.lock_read()
1770
 
        try:
1771
 
            basis = wt.basis_tree()
1772
 
            basis.lock_read()
1773
 
            try:
1774
 
                basis_inv = basis.inventory
1775
 
                inv = wt.inventory
1776
 
                for file_id in inv:
1777
 
                    if file_id in basis_inv:
1778
 
                        continue
1779
 
                    if inv.is_root(file_id) and len(basis_inv) == 0:
1780
 
                        continue
1781
 
                    path = inv.id2path(file_id)
1782
 
                    if not os.access(osutils.abspath(path), os.F_OK):
1783
 
                        continue
1784
 
                    if null:
1785
 
                        self.outf.write(path + '\0')
1786
 
                    else:
1787
 
                        self.outf.write(osutils.quotefn(path) + '\n')
1788
 
            finally:
1789
 
                basis.unlock()
1790
 
        finally:
1791
 
            wt.unlock()
 
2040
    def run(self, null=False, directory=u'.'):
 
2041
        wt = WorkingTree.open_containing(directory)[0]
 
2042
        self.add_cleanup(wt.lock_read().unlock)
 
2043
        basis = wt.basis_tree()
 
2044
        self.add_cleanup(basis.lock_read().unlock)
 
2045
        basis_inv = basis.inventory
 
2046
        inv = wt.inventory
 
2047
        for file_id in inv:
 
2048
            if file_id in basis_inv:
 
2049
                continue
 
2050
            if inv.is_root(file_id) and len(basis_inv) == 0:
 
2051
                continue
 
2052
            path = inv.id2path(file_id)
 
2053
            if not os.access(osutils.pathjoin(wt.basedir, path), os.F_OK):
 
2054
                continue
 
2055
            if null:
 
2056
                self.outf.write(path + '\0')
 
2057
            else:
 
2058
                self.outf.write(osutils.quotefn(path) + '\n')
1792
2059
 
1793
2060
 
1794
2061
class cmd_root(Command):
1795
 
    """Show the tree root directory.
 
2062
    __doc__ = """Show the tree root directory.
1796
2063
 
1797
2064
    The root is the nearest enclosing directory with a .bzr control
1798
2065
    directory."""
1822
2089
 
1823
2090
 
1824
2091
class cmd_log(Command):
1825
 
    """Show historical log for a branch or subset of a branch.
 
2092
    __doc__ = """Show historical log for a branch or subset of a branch.
1826
2093
 
1827
2094
    log is bzr's default tool for exploring the history of a branch.
1828
2095
    The branch to use is taken from the first parameter. If no parameters
1841
2108
    were merged.
1842
2109
 
1843
2110
    :Output control:
1844
 
 
 
2111
 
1845
2112
      The log format controls how information about each revision is
1846
2113
      displayed. The standard log formats are called ``long``, ``short``
1847
2114
      and ``line``. The default is long. See ``bzr help log-formats``
1849
2116
 
1850
2117
      The following options can be used to control what information is
1851
2118
      displayed::
1852
 
  
 
2119
 
1853
2120
        -l N        display a maximum of N revisions
1854
2121
        -n N        display N levels of revisions (0 for all, 1 for collapsed)
1855
2122
        -v          display a status summary (delta) for each revision
1856
2123
        -p          display a diff (patch) for each revision
1857
2124
        --show-ids  display revision-ids (and file-ids), not just revnos
1858
 
  
 
2125
 
1859
2126
      Note that the default number of levels to display is a function of the
1860
 
      log format. If the -n option is not used, ``short`` and ``line`` show
1861
 
      just the top level (mainline) while ``long`` shows all levels of merged
1862
 
      revisions.
1863
 
  
 
2127
      log format. If the -n option is not used, the standard log formats show
 
2128
      just the top level (mainline).
 
2129
 
1864
2130
      Status summaries are shown using status flags like A, M, etc. To see
1865
2131
      the changes explained using words like ``added`` and ``modified``
1866
2132
      instead, use the -vv option.
1867
 
  
 
2133
 
1868
2134
    :Ordering control:
1869
 
  
 
2135
 
1870
2136
      To display revisions from oldest to newest, use the --forward option.
1871
2137
      In most cases, using this option will have little impact on the total
1872
2138
      time taken to produce a log, though --forward does not incrementally
1873
2139
      display revisions like --reverse does when it can.
1874
 
  
 
2140
 
1875
2141
    :Revision filtering:
1876
 
  
 
2142
 
1877
2143
      The -r option can be used to specify what revision or range of revisions
1878
2144
      to filter against. The various forms are shown below::
1879
 
  
 
2145
 
1880
2146
        -rX      display revision X
1881
2147
        -rX..    display revision X and later
1882
2148
        -r..Y    display up to and including revision Y
1883
2149
        -rX..Y   display from X to Y inclusive
1884
 
  
 
2150
 
1885
2151
      See ``bzr help revisionspec`` for details on how to specify X and Y.
1886
2152
      Some common examples are given below::
1887
 
  
 
2153
 
1888
2154
        -r-1                show just the tip
1889
2155
        -r-10..             show the last 10 mainline revisions
1890
2156
        -rsubmit:..         show what's new on this branch
1891
2157
        -rancestor:path..   show changes since the common ancestor of this
1892
2158
                            branch and the one at location path
1893
2159
        -rdate:yesterday..  show changes since yesterday
1894
 
  
 
2160
 
1895
2161
      When logging a range of revisions using -rX..Y, log starts at
1896
2162
      revision Y and searches back in history through the primary
1897
2163
      ("left-hand") parents until it finds X. When logging just the
1900
2166
      a nested merge revision and the log will be truncated accordingly.
1901
2167
 
1902
2168
    :Path filtering:
1903
 
  
1904
 
      If a parameter is given and it's not a branch, the log will be filtered
1905
 
      to show only those revisions that changed the nominated file or
1906
 
      directory.
1907
 
  
 
2169
 
 
2170
      If parameters are given and the first one is not a branch, the log
 
2171
      will be filtered to show only those revisions that changed the
 
2172
      nominated files or directories.
 
2173
 
1908
2174
      Filenames are interpreted within their historical context. To log a
1909
2175
      deleted file, specify a revision range so that the file existed at
1910
2176
      the end or start of the range.
1911
 
  
 
2177
 
1912
2178
      Historical context is also important when interpreting pathnames of
1913
2179
      renamed files/directories. Consider the following example:
1914
 
  
 
2180
 
1915
2181
      * revision 1: add tutorial.txt
1916
2182
      * revision 2: modify tutorial.txt
1917
2183
      * revision 3: rename tutorial.txt to guide.txt; add tutorial.txt
1918
 
  
 
2184
 
1919
2185
      In this case:
1920
 
  
 
2186
 
1921
2187
      * ``bzr log guide.txt`` will log the file added in revision 1
1922
 
  
 
2188
 
1923
2189
      * ``bzr log tutorial.txt`` will log the new file added in revision 3
1924
 
  
 
2190
 
1925
2191
      * ``bzr log -r2 -p tutorial.txt`` will show the changes made to
1926
2192
        the original file in revision 2.
1927
 
  
 
2193
 
1928
2194
      * ``bzr log -r2 -p guide.txt`` will display an error message as there
1929
2195
        was no file called guide.txt in revision 2.
1930
 
  
 
2196
 
1931
2197
      Renames are always followed by log. By design, there is no need to
1932
2198
      explicitly ask for this (and no way to stop logging a file back
1933
2199
      until it was last renamed).
1934
 
  
1935
 
      Note: If the path is a directory, only revisions that directly changed
1936
 
      that directory object are currently shown. This is considered a bug.
1937
 
      (Support for filtering against multiple files and for files within a
1938
 
      directory is under development.)
1939
 
  
 
2200
 
1940
2201
    :Other filtering:
1941
 
  
 
2202
 
1942
2203
      The --message option can be used for finding revisions that match a
1943
2204
      regular expression in a commit message.
1944
 
  
 
2205
 
1945
2206
    :Tips & tricks:
1946
 
  
 
2207
 
1947
2208
      GUI tools and IDEs are often better at exploring history than command
1948
 
      line tools. You may prefer qlog or glog from the QBzr and Bzr-Gtk packages
1949
 
      respectively for example. (TortoiseBzr uses qlog for displaying logs.) See
1950
 
      http://bazaar-vcs.org/BzrPlugins and http://bazaar-vcs.org/IDEIntegration.
1951
 
  
1952
 
      Web interfaces are often better at exploring history than command line
1953
 
      tools, particularly for branches on servers. You may prefer Loggerhead
1954
 
      or one of its alternatives. See http://bazaar-vcs.org/WebInterface.
1955
 
  
 
2209
      line tools: you may prefer qlog or viz from qbzr or bzr-gtk, the
 
2210
      bzr-explorer shell, or the Loggerhead web interface.  See the Plugin
 
2211
      Guide <http://doc.bazaar.canonical.com/plugins/en/> and
 
2212
      <http://wiki.bazaar.canonical.com/IDEIntegration>.  
 
2213
 
1956
2214
      You may find it useful to add the aliases below to ``bazaar.conf``::
1957
 
  
 
2215
 
1958
2216
        [ALIASES]
1959
 
        tip = log -r-1 -n1
1960
 
        top = log -r-10.. --short --forward
1961
 
        show = log -v -p -n1 --long
1962
 
  
 
2217
        tip = log -r-1
 
2218
        top = log -l10 --line
 
2219
        show = log -v -p
 
2220
 
1963
2221
      ``bzr tip`` will then show the latest revision while ``bzr top``
1964
2222
      will show the last 10 mainline revisions. To see the details of a
1965
2223
      particular revision X,  ``bzr show -rX``.
1966
 
  
1967
 
      As many GUI tools and Web interfaces do, you may prefer viewing
1968
 
      history collapsed initially. If you are interested in looking deeper
1969
 
      into a particular merge X, use ``bzr log -n0 -rX``. If you like
1970
 
      working this way, you may wish to either:
1971
 
  
1972
 
      * change your default log format to short (or line)
1973
 
      * add this alias: log = log -n1
1974
 
  
 
2224
 
 
2225
      If you are interested in looking deeper into a particular merge X,
 
2226
      use ``bzr log -n0 -rX``.
 
2227
 
1975
2228
      ``bzr log -v`` on a branch with lots of history is currently
1976
2229
      very slow. A fix for this issue is currently under development.
1977
2230
      With or without that fix, it is recommended that a revision range
1978
2231
      be given when using the -v option.
1979
 
  
 
2232
 
1980
2233
      bzr has a generic full-text matching plugin, bzr-search, that can be
1981
2234
      used to find revisions matching user names, commit messages, etc.
1982
2235
      Among other features, this plugin can find all revisions containing
1983
2236
      a list of words but not others.
1984
 
  
 
2237
 
1985
2238
      When exploring non-mainline history on large projects with deep
1986
2239
      history, the performance of log can be greatly improved by installing
1987
 
      the revnocache plugin. This plugin buffers historical information
 
2240
      the historycache plugin. This plugin buffers historical information
1988
2241
      trading disk space for faster speed.
1989
2242
    """
1990
 
    takes_args = ['location?']
 
2243
    takes_args = ['file*']
1991
2244
    _see_also = ['log-formats', 'revisionspec']
1992
2245
    takes_options = [
1993
2246
            Option('forward',
2003
2256
                   help='Show just the specified revision.'
2004
2257
                   ' See also "help revisionspec".'),
2005
2258
            'log-format',
 
2259
            RegistryOption('authors',
 
2260
                'What names to list as authors - first, all or committer.',
 
2261
                title='Authors',
 
2262
                lazy_registry=('bzrlib.log', 'author_list_registry'),
 
2263
            ),
2006
2264
            Option('levels',
2007
2265
                   short_name='n',
2008
2266
                   help='Number of levels to display - 0 for all, 1 for flat.',
2021
2279
            Option('show-diff',
2022
2280
                   short_name='p',
2023
2281
                   help='Show changes made in each revision as a patch.'),
 
2282
            Option('include-merges',
 
2283
                   help='Show merged revisions like --levels 0 does.'),
 
2284
            Option('exclude-common-ancestry',
 
2285
                   help='Display only the revisions that are not part'
 
2286
                   ' of both ancestries (require -rX..Y)'
 
2287
                   )
2024
2288
            ]
2025
2289
    encoding_type = 'replace'
2026
2290
 
2027
2291
    @display_command
2028
 
    def run(self, location=None, timezone='original',
 
2292
    def run(self, file_list=None, timezone='original',
2029
2293
            verbose=False,
2030
2294
            show_ids=False,
2031
2295
            forward=False,
2035
2299
            levels=None,
2036
2300
            message=None,
2037
2301
            limit=None,
2038
 
            show_diff=False):
2039
 
        from bzrlib.log import show_log, _get_fileid_to_log
 
2302
            show_diff=False,
 
2303
            include_merges=False,
 
2304
            authors=None,
 
2305
            exclude_common_ancestry=False,
 
2306
            ):
 
2307
        from bzrlib.log import (
 
2308
            Logger,
 
2309
            make_log_request_dict,
 
2310
            _get_info_for_log_files,
 
2311
            )
2040
2312
        direction = (forward and 'forward') or 'reverse'
 
2313
        if (exclude_common_ancestry
 
2314
            and (revision is None or len(revision) != 2)):
 
2315
            raise errors.BzrCommandError(
 
2316
                '--exclude-common-ancestry requires -r with two revisions')
 
2317
        if include_merges:
 
2318
            if levels is None:
 
2319
                levels = 0
 
2320
            else:
 
2321
                raise errors.BzrCommandError(
 
2322
                    '--levels and --include-merges are mutually exclusive')
2041
2323
 
2042
2324
        if change is not None:
2043
2325
            if len(change) > 1:
2048
2330
            else:
2049
2331
                revision = change
2050
2332
 
2051
 
        # log everything
2052
 
        file_id = None
2053
 
        if location:
2054
 
            # find the file id to log:
2055
 
 
2056
 
            tree, b, fp = bzrdir.BzrDir.open_containing_tree_or_branch(
2057
 
                location)
2058
 
            if fp != '':
2059
 
                file_id = _get_fileid_to_log(revision, tree, b, fp)
 
2333
        file_ids = []
 
2334
        filter_by_dir = False
 
2335
        if file_list:
 
2336
            # find the file ids to log and check for directory filtering
 
2337
            b, file_info_list, rev1, rev2 = _get_info_for_log_files(
 
2338
                revision, file_list, self.add_cleanup)
 
2339
            for relpath, file_id, kind in file_info_list:
2060
2340
                if file_id is None:
2061
2341
                    raise errors.BzrCommandError(
2062
2342
                        "Path unknown at end or start of revision range: %s" %
2063
 
                        location)
 
2343
                        relpath)
 
2344
                # If the relpath is the top of the tree, we log everything
 
2345
                if relpath == '':
 
2346
                    file_ids = []
 
2347
                    break
 
2348
                else:
 
2349
                    file_ids.append(file_id)
 
2350
                filter_by_dir = filter_by_dir or (
 
2351
                    kind in ['directory', 'tree-reference'])
2064
2352
        else:
2065
 
            # local dir only
2066
 
            # FIXME ? log the current subdir only RBC 20060203 
 
2353
            # log everything
 
2354
            # FIXME ? log the current subdir only RBC 20060203
2067
2355
            if revision is not None \
2068
2356
                    and len(revision) > 0 and revision[0].get_branch():
2069
2357
                location = revision[0].get_branch()
2071
2359
                location = '.'
2072
2360
            dir, relpath = bzrdir.BzrDir.open_containing(location)
2073
2361
            b = dir.open_branch()
2074
 
 
2075
 
        b.lock_read()
2076
 
        try:
 
2362
            self.add_cleanup(b.lock_read().unlock)
2077
2363
            rev1, rev2 = _get_revision_range(revision, b, self.name())
2078
 
            if log_format is None:
2079
 
                log_format = log.log_formatter_registry.get_default(b)
2080
 
 
2081
 
            lf = log_format(show_ids=show_ids, to_file=self.outf,
2082
 
                            show_timezone=timezone,
2083
 
                            delta_format=get_verbosity_level(),
2084
 
                            levels=levels)
2085
 
 
2086
 
            show_log(b,
2087
 
                     lf,
2088
 
                     file_id,
2089
 
                     verbose=verbose,
2090
 
                     direction=direction,
2091
 
                     start_revision=rev1,
2092
 
                     end_revision=rev2,
2093
 
                     search=message,
2094
 
                     limit=limit,
2095
 
                     show_diff=show_diff)
2096
 
        finally:
2097
 
            b.unlock()
 
2364
 
 
2365
        # Decide on the type of delta & diff filtering to use
 
2366
        # TODO: add an --all-files option to make this configurable & consistent
 
2367
        if not verbose:
 
2368
            delta_type = None
 
2369
        else:
 
2370
            delta_type = 'full'
 
2371
        if not show_diff:
 
2372
            diff_type = None
 
2373
        elif file_ids:
 
2374
            diff_type = 'partial'
 
2375
        else:
 
2376
            diff_type = 'full'
 
2377
 
 
2378
        # Build the log formatter
 
2379
        if log_format is None:
 
2380
            log_format = log.log_formatter_registry.get_default(b)
 
2381
        # Make a non-encoding output to include the diffs - bug 328007
 
2382
        unencoded_output = ui.ui_factory.make_output_stream(encoding_type='exact')
 
2383
        lf = log_format(show_ids=show_ids, to_file=self.outf,
 
2384
                        to_exact_file=unencoded_output,
 
2385
                        show_timezone=timezone,
 
2386
                        delta_format=get_verbosity_level(),
 
2387
                        levels=levels,
 
2388
                        show_advice=levels is None,
 
2389
                        author_list_handler=authors)
 
2390
 
 
2391
        # Choose the algorithm for doing the logging. It's annoying
 
2392
        # having multiple code paths like this but necessary until
 
2393
        # the underlying repository format is faster at generating
 
2394
        # deltas or can provide everything we need from the indices.
 
2395
        # The default algorithm - match-using-deltas - works for
 
2396
        # multiple files and directories and is faster for small
 
2397
        # amounts of history (200 revisions say). However, it's too
 
2398
        # slow for logging a single file in a repository with deep
 
2399
        # history, i.e. > 10K revisions. In the spirit of "do no
 
2400
        # evil when adding features", we continue to use the
 
2401
        # original algorithm - per-file-graph - for the "single
 
2402
        # file that isn't a directory without showing a delta" case.
 
2403
        partial_history = revision and b.repository._format.supports_chks
 
2404
        match_using_deltas = (len(file_ids) != 1 or filter_by_dir
 
2405
            or delta_type or partial_history)
 
2406
 
 
2407
        # Build the LogRequest and execute it
 
2408
        if len(file_ids) == 0:
 
2409
            file_ids = None
 
2410
        rqst = make_log_request_dict(
 
2411
            direction=direction, specific_fileids=file_ids,
 
2412
            start_revision=rev1, end_revision=rev2, limit=limit,
 
2413
            message_search=message, delta_type=delta_type,
 
2414
            diff_type=diff_type, _match_using_deltas=match_using_deltas,
 
2415
            exclude_common_ancestry=exclude_common_ancestry,
 
2416
            )
 
2417
        Logger(b, rqst).show(lf)
2098
2418
 
2099
2419
 
2100
2420
def _get_revision_range(revisionspec_list, branch, command_name):
2101
2421
    """Take the input of a revision option and turn it into a revision range.
2102
2422
 
2103
2423
    It returns RevisionInfo objects which can be used to obtain the rev_id's
2104
 
    of the desired revisons. It does some user input validations.
 
2424
    of the desired revisions. It does some user input validations.
2105
2425
    """
2106
2426
    if revisionspec_list is None:
2107
2427
        rev1 = None
2118
2438
            raise errors.BzrCommandError(
2119
2439
                "bzr %s doesn't accept two revisions in different"
2120
2440
                " branches." % command_name)
2121
 
        rev1 = start_spec.in_history(branch)
 
2441
        if start_spec.spec is None:
 
2442
            # Avoid loading all the history.
 
2443
            rev1 = RevisionInfo(branch, None, None)
 
2444
        else:
 
2445
            rev1 = start_spec.in_history(branch)
2122
2446
        # Avoid loading all of history when we know a missing
2123
2447
        # end of range means the last revision ...
2124
2448
        if end_spec.spec is None:
2153
2477
 
2154
2478
 
2155
2479
class cmd_touching_revisions(Command):
2156
 
    """Return revision-ids which affected a particular file.
 
2480
    __doc__ = """Return revision-ids which affected a particular file.
2157
2481
 
2158
2482
    A more user-friendly interface is "bzr log FILE".
2159
2483
    """
2164
2488
    @display_command
2165
2489
    def run(self, filename):
2166
2490
        tree, relpath = WorkingTree.open_containing(filename)
 
2491
        file_id = tree.path2id(relpath)
2167
2492
        b = tree.branch
2168
 
        file_id = tree.path2id(relpath)
2169
 
        for revno, revision_id, what in log.find_touching_revisions(b, file_id):
 
2493
        self.add_cleanup(b.lock_read().unlock)
 
2494
        touching_revs = log.find_touching_revisions(b, file_id)
 
2495
        for revno, revision_id, what in touching_revs:
2170
2496
            self.outf.write("%6d %s\n" % (revno, what))
2171
2497
 
2172
2498
 
2173
2499
class cmd_ls(Command):
2174
 
    """List files in a tree.
 
2500
    __doc__ = """List files in a tree.
2175
2501
    """
2176
2502
 
2177
2503
    _see_also = ['status', 'cat']
2178
2504
    takes_args = ['path?']
2179
 
    # TODO: Take a revision or remote path and list that tree instead.
2180
2505
    takes_options = [
2181
2506
            'verbose',
2182
2507
            'revision',
2183
 
            Option('non-recursive',
2184
 
                   help='Don\'t recurse into subdirectories.'),
 
2508
            Option('recursive', short_name='R',
 
2509
                   help='Recurse into subdirectories.'),
2185
2510
            Option('from-root',
2186
2511
                   help='Print paths relative to the root of the branch.'),
2187
 
            Option('unknown', help='Print unknown files.'),
 
2512
            Option('unknown', short_name='u',
 
2513
                help='Print unknown files.'),
2188
2514
            Option('versioned', help='Print versioned files.',
2189
2515
                   short_name='V'),
2190
 
            Option('ignored', help='Print ignored files.'),
2191
 
            Option('null',
2192
 
                   help='Write an ascii NUL (\\0) separator '
2193
 
                   'between files rather than a newline.'),
2194
 
            Option('kind',
 
2516
            Option('ignored', short_name='i',
 
2517
                help='Print ignored files.'),
 
2518
            Option('kind', short_name='k',
2195
2519
                   help='List entries of a particular kind: file, directory, symlink.',
2196
2520
                   type=unicode),
 
2521
            'null',
2197
2522
            'show-ids',
 
2523
            'directory',
2198
2524
            ]
2199
2525
    @display_command
2200
2526
    def run(self, revision=None, verbose=False,
2201
 
            non_recursive=False, from_root=False,
 
2527
            recursive=False, from_root=False,
2202
2528
            unknown=False, versioned=False, ignored=False,
2203
 
            null=False, kind=None, show_ids=False, path=None):
 
2529
            null=False, kind=None, show_ids=False, path=None, directory=None):
2204
2530
 
2205
2531
        if kind and kind not in ('file', 'directory', 'symlink'):
2206
2532
            raise errors.BzrCommandError('invalid kind specified')
2213
2539
 
2214
2540
        if path is None:
2215
2541
            fs_path = '.'
2216
 
            prefix = ''
2217
2542
        else:
2218
2543
            if from_root:
2219
2544
                raise errors.BzrCommandError('cannot specify both --from-root'
2220
2545
                                             ' and PATH')
2221
2546
            fs_path = path
2222
 
            prefix = path
2223
 
        tree, branch, relpath = bzrdir.BzrDir.open_containing_tree_or_branch(
2224
 
            fs_path)
 
2547
        tree, branch, relpath = \
 
2548
            _open_directory_or_containing_tree_or_branch(fs_path, directory)
 
2549
 
 
2550
        # Calculate the prefix to use
 
2551
        prefix = None
2225
2552
        if from_root:
2226
 
            relpath = u''
2227
 
        elif relpath:
2228
 
            relpath += '/'
 
2553
            if relpath:
 
2554
                prefix = relpath + '/'
 
2555
        elif fs_path != '.' and not fs_path.endswith('/'):
 
2556
            prefix = fs_path + '/'
 
2557
 
2229
2558
        if revision is not None or tree is None:
2230
2559
            tree = _get_one_revision_tree('ls', revision, branch=branch)
2231
2560
 
2232
 
        tree.lock_read()
2233
 
        try:
2234
 
            for fp, fc, fkind, fid, entry in tree.list_files(include_root=False):
2235
 
                if fp.startswith(relpath):
2236
 
                    fp = osutils.pathjoin(prefix, fp[len(relpath):])
2237
 
                    if non_recursive and '/' in fp:
2238
 
                        continue
2239
 
                    if not all and not selection[fc]:
2240
 
                        continue
2241
 
                    if kind is not None and fkind != kind:
2242
 
                        continue
2243
 
                    kindch = entry.kind_character()
2244
 
                    outstring = fp + kindch
2245
 
                    if verbose:
2246
 
                        outstring = '%-8s %s' % (fc, outstring)
2247
 
                        if show_ids and fid is not None:
2248
 
                            outstring = "%-50s %s" % (outstring, fid)
2249
 
                        self.outf.write(outstring + '\n')
2250
 
                    elif null:
2251
 
                        self.outf.write(fp + '\0')
2252
 
                        if show_ids:
2253
 
                            if fid is not None:
2254
 
                                self.outf.write(fid)
2255
 
                            self.outf.write('\0')
2256
 
                        self.outf.flush()
2257
 
                    else:
2258
 
                        if fid is not None:
2259
 
                            my_id = fid
2260
 
                        else:
2261
 
                            my_id = ''
2262
 
                        if show_ids:
2263
 
                            self.outf.write('%-50s %s\n' % (outstring, my_id))
2264
 
                        else:
2265
 
                            self.outf.write(outstring + '\n')
2266
 
        finally:
2267
 
            tree.unlock()
 
2561
        apply_view = False
 
2562
        if isinstance(tree, WorkingTree) and tree.supports_views():
 
2563
            view_files = tree.views.lookup_view()
 
2564
            if view_files:
 
2565
                apply_view = True
 
2566
                view_str = views.view_display_str(view_files)
 
2567
                note("Ignoring files outside view. View is %s" % view_str)
 
2568
 
 
2569
        self.add_cleanup(tree.lock_read().unlock)
 
2570
        for fp, fc, fkind, fid, entry in tree.list_files(include_root=False,
 
2571
            from_dir=relpath, recursive=recursive):
 
2572
            # Apply additional masking
 
2573
            if not all and not selection[fc]:
 
2574
                continue
 
2575
            if kind is not None and fkind != kind:
 
2576
                continue
 
2577
            if apply_view:
 
2578
                try:
 
2579
                    if relpath:
 
2580
                        fullpath = osutils.pathjoin(relpath, fp)
 
2581
                    else:
 
2582
                        fullpath = fp
 
2583
                    views.check_path_in_view(tree, fullpath)
 
2584
                except errors.FileOutsideView:
 
2585
                    continue
 
2586
 
 
2587
            # Output the entry
 
2588
            if prefix:
 
2589
                fp = osutils.pathjoin(prefix, fp)
 
2590
            kindch = entry.kind_character()
 
2591
            outstring = fp + kindch
 
2592
            ui.ui_factory.clear_term()
 
2593
            if verbose:
 
2594
                outstring = '%-8s %s' % (fc, outstring)
 
2595
                if show_ids and fid is not None:
 
2596
                    outstring = "%-50s %s" % (outstring, fid)
 
2597
                self.outf.write(outstring + '\n')
 
2598
            elif null:
 
2599
                self.outf.write(fp + '\0')
 
2600
                if show_ids:
 
2601
                    if fid is not None:
 
2602
                        self.outf.write(fid)
 
2603
                    self.outf.write('\0')
 
2604
                self.outf.flush()
 
2605
            else:
 
2606
                if show_ids:
 
2607
                    if fid is not None:
 
2608
                        my_id = fid
 
2609
                    else:
 
2610
                        my_id = ''
 
2611
                    self.outf.write('%-50s %s\n' % (outstring, my_id))
 
2612
                else:
 
2613
                    self.outf.write(outstring + '\n')
2268
2614
 
2269
2615
 
2270
2616
class cmd_unknowns(Command):
2271
 
    """List unknown files.
 
2617
    __doc__ = """List unknown files.
2272
2618
    """
2273
2619
 
2274
2620
    hidden = True
2275
2621
    _see_also = ['ls']
 
2622
    takes_options = ['directory']
2276
2623
 
2277
2624
    @display_command
2278
 
    def run(self):
2279
 
        for f in WorkingTree.open_containing(u'.')[0].unknowns():
 
2625
    def run(self, directory=u'.'):
 
2626
        for f in WorkingTree.open_containing(directory)[0].unknowns():
2280
2627
            self.outf.write(osutils.quotefn(f) + '\n')
2281
2628
 
2282
2629
 
2283
2630
class cmd_ignore(Command):
2284
 
    """Ignore specified files or patterns.
 
2631
    __doc__ = """Ignore specified files or patterns.
2285
2632
 
2286
2633
    See ``bzr help patterns`` for details on the syntax of patterns.
2287
2634
 
 
2635
    If a .bzrignore file does not exist, the ignore command
 
2636
    will create one and add the specified files or patterns to the newly
 
2637
    created file. The ignore command will also automatically add the 
 
2638
    .bzrignore file to be versioned. Creating a .bzrignore file without
 
2639
    the use of the ignore command will require an explicit add command.
 
2640
 
2288
2641
    To remove patterns from the ignore list, edit the .bzrignore file.
2289
2642
    After adding, editing or deleting that file either indirectly by
2290
2643
    using this command or directly by using an editor, be sure to commit
2291
2644
    it.
2292
 
 
2293
 
    Note: ignore patterns containing shell wildcards must be quoted from 
 
2645
    
 
2646
    Bazaar also supports a global ignore file ~/.bazaar/ignore. On Windows
 
2647
    the global ignore file can be found in the application data directory as
 
2648
    C:\\Documents and Settings\\<user>\\Application Data\\Bazaar\\2.0\\ignore.
 
2649
    Global ignores are not touched by this command. The global ignore file
 
2650
    can be edited directly using an editor.
 
2651
 
 
2652
    Patterns prefixed with '!' are exceptions to ignore patterns and take
 
2653
    precedence over regular ignores.  Such exceptions are used to specify
 
2654
    files that should be versioned which would otherwise be ignored.
 
2655
    
 
2656
    Patterns prefixed with '!!' act as regular ignore patterns, but have
 
2657
    precedence over the '!' exception patterns.
 
2658
 
 
2659
    Note: ignore patterns containing shell wildcards must be quoted from
2294
2660
    the shell on Unix.
2295
2661
 
2296
2662
    :Examples:
2298
2664
 
2299
2665
            bzr ignore ./Makefile
2300
2666
 
2301
 
        Ignore class files in all directories::
 
2667
        Ignore .class files in all directories...::
2302
2668
 
2303
2669
            bzr ignore "*.class"
2304
2670
 
 
2671
        ...but do not ignore "special.class"::
 
2672
 
 
2673
            bzr ignore "!special.class"
 
2674
 
2305
2675
        Ignore .o files under the lib directory::
2306
2676
 
2307
2677
            bzr ignore "lib/**/*.o"
2313
2683
        Ignore everything but the "debian" toplevel directory::
2314
2684
 
2315
2685
            bzr ignore "RE:(?!debian/).*"
 
2686
        
 
2687
        Ignore everything except the "local" toplevel directory,
 
2688
        but always ignore "*~" autosave files, even under local/::
 
2689
        
 
2690
            bzr ignore "*"
 
2691
            bzr ignore "!./local"
 
2692
            bzr ignore "!!*~"
2316
2693
    """
2317
2694
 
2318
2695
    _see_also = ['status', 'ignored', 'patterns']
2319
2696
    takes_args = ['name_pattern*']
2320
 
    takes_options = [
2321
 
        Option('old-default-rules',
2322
 
               help='Write out the ignore rules bzr < 0.9 always used.')
 
2697
    takes_options = ['directory',
 
2698
        Option('default-rules',
 
2699
               help='Display the default ignore rules that bzr uses.')
2323
2700
        ]
2324
 
    
2325
 
    def run(self, name_pattern_list=None, old_default_rules=None):
 
2701
 
 
2702
    def run(self, name_pattern_list=None, default_rules=None,
 
2703
            directory=u'.'):
2326
2704
        from bzrlib import ignores
2327
 
        if old_default_rules is not None:
2328
 
            # dump the rules and exit
2329
 
            for pattern in ignores.OLD_DEFAULTS:
2330
 
                print pattern
 
2705
        if default_rules is not None:
 
2706
            # dump the default rules and exit
 
2707
            for pattern in ignores.USER_DEFAULTS:
 
2708
                self.outf.write("%s\n" % pattern)
2331
2709
            return
2332
2710
        if not name_pattern_list:
2333
2711
            raise errors.BzrCommandError("ignore requires at least one "
2334
 
                                  "NAME_PATTERN or --old-default-rules")
2335
 
        name_pattern_list = [globbing.normalize_pattern(p) 
 
2712
                "NAME_PATTERN or --default-rules.")
 
2713
        name_pattern_list = [globbing.normalize_pattern(p)
2336
2714
                             for p in name_pattern_list]
2337
2715
        for name_pattern in name_pattern_list:
2338
 
            if (name_pattern[0] == '/' or 
 
2716
            if (name_pattern[0] == '/' or
2339
2717
                (len(name_pattern) > 1 and name_pattern[1] == ':')):
2340
2718
                raise errors.BzrCommandError(
2341
2719
                    "NAME_PATTERN should not be an absolute path")
2342
 
        tree, relpath = WorkingTree.open_containing(u'.')
 
2720
        tree, relpath = WorkingTree.open_containing(directory)
2343
2721
        ignores.tree_ignores_add_patterns(tree, name_pattern_list)
2344
2722
        ignored = globbing.Globster(name_pattern_list)
2345
2723
        matches = []
2349
2727
            if id is not None:
2350
2728
                filename = entry[0]
2351
2729
                if ignored.match(filename):
2352
 
                    matches.append(filename.encode('utf-8'))
 
2730
                    matches.append(filename)
2353
2731
        tree.unlock()
2354
2732
        if len(matches) > 0:
2355
 
            print "Warning: the following files are version controlled and" \
2356
 
                  " match your ignore pattern:\n%s" % ("\n".join(matches),)
 
2733
            self.outf.write("Warning: the following files are version controlled and"
 
2734
                  " match your ignore pattern:\n%s"
 
2735
                  "\nThese files will continue to be version controlled"
 
2736
                  " unless you 'bzr remove' them.\n" % ("\n".join(matches),))
2357
2737
 
2358
2738
 
2359
2739
class cmd_ignored(Command):
2360
 
    """List ignored files and the patterns that matched them.
 
2740
    __doc__ = """List ignored files and the patterns that matched them.
2361
2741
 
2362
2742
    List all the ignored files and the ignore pattern that caused the file to
2363
2743
    be ignored.
2369
2749
 
2370
2750
    encoding_type = 'replace'
2371
2751
    _see_also = ['ignore', 'ls']
 
2752
    takes_options = ['directory']
2372
2753
 
2373
2754
    @display_command
2374
 
    def run(self):
2375
 
        tree = WorkingTree.open_containing(u'.')[0]
2376
 
        tree.lock_read()
2377
 
        try:
2378
 
            for path, file_class, kind, file_id, entry in tree.list_files():
2379
 
                if file_class != 'I':
2380
 
                    continue
2381
 
                ## XXX: Slightly inefficient since this was already calculated
2382
 
                pat = tree.is_ignored(path)
2383
 
                self.outf.write('%-50s %s\n' % (path, pat))
2384
 
        finally:
2385
 
            tree.unlock()
 
2755
    def run(self, directory=u'.'):
 
2756
        tree = WorkingTree.open_containing(directory)[0]
 
2757
        self.add_cleanup(tree.lock_read().unlock)
 
2758
        for path, file_class, kind, file_id, entry in tree.list_files():
 
2759
            if file_class != 'I':
 
2760
                continue
 
2761
            ## XXX: Slightly inefficient since this was already calculated
 
2762
            pat = tree.is_ignored(path)
 
2763
            self.outf.write('%-50s %s\n' % (path, pat))
2386
2764
 
2387
2765
 
2388
2766
class cmd_lookup_revision(Command):
2389
 
    """Lookup the revision-id from a revision-number
 
2767
    __doc__ = """Lookup the revision-id from a revision-number
2390
2768
 
2391
2769
    :Examples:
2392
2770
        bzr lookup-revision 33
2393
2771
    """
2394
2772
    hidden = True
2395
2773
    takes_args = ['revno']
2396
 
    
 
2774
    takes_options = ['directory']
 
2775
 
2397
2776
    @display_command
2398
 
    def run(self, revno):
 
2777
    def run(self, revno, directory=u'.'):
2399
2778
        try:
2400
2779
            revno = int(revno)
2401
2780
        except ValueError:
2402
 
            raise errors.BzrCommandError("not a valid revision-number: %r" % revno)
2403
 
 
2404
 
        print WorkingTree.open_containing(u'.')[0].branch.get_rev_id(revno)
 
2781
            raise errors.BzrCommandError("not a valid revision-number: %r"
 
2782
                                         % revno)
 
2783
        revid = WorkingTree.open_containing(directory)[0].branch.get_rev_id(revno)
 
2784
        self.outf.write("%s\n" % revid)
2405
2785
 
2406
2786
 
2407
2787
class cmd_export(Command):
2408
 
    """Export current or past revision to a destination directory or archive.
 
2788
    __doc__ = """Export current or past revision to a destination directory or archive.
2409
2789
 
2410
2790
    If no revision is specified this exports the last committed revision.
2411
2791
 
2433
2813
      =================       =========================
2434
2814
    """
2435
2815
    takes_args = ['dest', 'branch_or_subdir?']
2436
 
    takes_options = [
 
2816
    takes_options = ['directory',
2437
2817
        Option('format',
2438
2818
               help="Type of file to export to.",
2439
2819
               type=unicode),
2440
2820
        'revision',
 
2821
        Option('filters', help='Apply content filters to export the '
 
2822
                'convenient form.'),
2441
2823
        Option('root',
2442
2824
               type=str,
2443
2825
               help="Name of the root directory inside the exported file."),
 
2826
        Option('per-file-timestamps',
 
2827
               help='Set modification time of files to that of the last '
 
2828
                    'revision in which it was changed.'),
2444
2829
        ]
2445
2830
    def run(self, dest, branch_or_subdir=None, revision=None, format=None,
2446
 
        root=None):
 
2831
        root=None, filters=False, per_file_timestamps=False, directory=u'.'):
2447
2832
        from bzrlib.export import export
2448
2833
 
2449
2834
        if branch_or_subdir is None:
2450
 
            tree = WorkingTree.open_containing(u'.')[0]
 
2835
            tree = WorkingTree.open_containing(directory)[0]
2451
2836
            b = tree.branch
2452
2837
            subdir = None
2453
2838
        else:
2456
2841
 
2457
2842
        rev_tree = _get_one_revision_tree('export', revision, branch=b, tree=tree)
2458
2843
        try:
2459
 
            export(rev_tree, dest, format, root, subdir)
 
2844
            export(rev_tree, dest, format, root, subdir, filtered=filters,
 
2845
                   per_file_timestamps=per_file_timestamps)
2460
2846
        except errors.NoSuchExportFormat, e:
2461
2847
            raise errors.BzrCommandError('Unsupported export format: %s' % e.format)
2462
2848
 
2463
2849
 
2464
2850
class cmd_cat(Command):
2465
 
    """Write the contents of a file as of a given revision to standard output.
 
2851
    __doc__ = """Write the contents of a file as of a given revision to standard output.
2466
2852
 
2467
2853
    If no revision is nominated, the last revision is used.
2468
2854
 
2469
2855
    Note: Take care to redirect standard output when using this command on a
2470
 
    binary file. 
 
2856
    binary file.
2471
2857
    """
2472
2858
 
2473
2859
    _see_also = ['ls']
2474
 
    takes_options = [
 
2860
    takes_options = ['directory',
2475
2861
        Option('name-from-revision', help='The path name in the old tree.'),
 
2862
        Option('filters', help='Apply content filters to display the '
 
2863
                'convenience form.'),
2476
2864
        'revision',
2477
2865
        ]
2478
2866
    takes_args = ['filename']
2479
2867
    encoding_type = 'exact'
2480
2868
 
2481
2869
    @display_command
2482
 
    def run(self, filename, revision=None, name_from_revision=False):
 
2870
    def run(self, filename, revision=None, name_from_revision=False,
 
2871
            filters=False, directory=None):
2483
2872
        if revision is not None and len(revision) != 1:
2484
2873
            raise errors.BzrCommandError("bzr cat --revision takes exactly"
2485
2874
                                         " one revision specifier")
2486
2875
        tree, branch, relpath = \
2487
 
            bzrdir.BzrDir.open_containing_tree_or_branch(filename)
2488
 
        branch.lock_read()
2489
 
        try:
2490
 
            return self._run(tree, branch, relpath, filename, revision,
2491
 
                             name_from_revision)
2492
 
        finally:
2493
 
            branch.unlock()
 
2876
            _open_directory_or_containing_tree_or_branch(filename, directory)
 
2877
        self.add_cleanup(branch.lock_read().unlock)
 
2878
        return self._run(tree, branch, relpath, filename, revision,
 
2879
                         name_from_revision, filters)
2494
2880
 
2495
 
    def _run(self, tree, b, relpath, filename, revision, name_from_revision):
 
2881
    def _run(self, tree, b, relpath, filename, revision, name_from_revision,
 
2882
        filtered):
2496
2883
        if tree is None:
2497
2884
            tree = b.basis_tree()
2498
2885
        rev_tree = _get_one_revision_tree('cat', revision, branch=b)
 
2886
        self.add_cleanup(rev_tree.lock_read().unlock)
2499
2887
 
2500
 
        cur_file_id = tree.path2id(relpath)
2501
2888
        old_file_id = rev_tree.path2id(relpath)
2502
2889
 
2503
2890
        if name_from_revision:
 
2891
            # Try in revision if requested
2504
2892
            if old_file_id is None:
2505
2893
                raise errors.BzrCommandError(
2506
2894
                    "%r is not present in revision %s" % (
2507
2895
                        filename, rev_tree.get_revision_id()))
2508
2896
            else:
2509
2897
                content = rev_tree.get_file_text(old_file_id)
2510
 
        elif cur_file_id is not None:
2511
 
            content = rev_tree.get_file_text(cur_file_id)
2512
 
        elif old_file_id is not None:
2513
 
            content = rev_tree.get_file_text(old_file_id)
2514
 
        else:
2515
 
            raise errors.BzrCommandError(
2516
 
                "%r is not present in revision %s" % (
2517
 
                    filename, rev_tree.get_revision_id()))
2518
 
        self.outf.write(content)
 
2898
        else:
 
2899
            cur_file_id = tree.path2id(relpath)
 
2900
            found = False
 
2901
            if cur_file_id is not None:
 
2902
                # Then try with the actual file id
 
2903
                try:
 
2904
                    content = rev_tree.get_file_text(cur_file_id)
 
2905
                    found = True
 
2906
                except errors.NoSuchId:
 
2907
                    # The actual file id didn't exist at that time
 
2908
                    pass
 
2909
            if not found and old_file_id is not None:
 
2910
                # Finally try with the old file id
 
2911
                content = rev_tree.get_file_text(old_file_id)
 
2912
                found = True
 
2913
            if not found:
 
2914
                # Can't be found anywhere
 
2915
                raise errors.BzrCommandError(
 
2916
                    "%r is not present in revision %s" % (
 
2917
                        filename, rev_tree.get_revision_id()))
 
2918
        if filtered:
 
2919
            from bzrlib.filters import (
 
2920
                ContentFilterContext,
 
2921
                filtered_output_bytes,
 
2922
                )
 
2923
            filters = rev_tree._content_filter_stack(relpath)
 
2924
            chunks = content.splitlines(True)
 
2925
            content = filtered_output_bytes(chunks, filters,
 
2926
                ContentFilterContext(relpath, rev_tree))
 
2927
            self.cleanup_now()
 
2928
            self.outf.writelines(content)
 
2929
        else:
 
2930
            self.cleanup_now()
 
2931
            self.outf.write(content)
2519
2932
 
2520
2933
 
2521
2934
class cmd_local_time_offset(Command):
2522
 
    """Show the offset in seconds from GMT to local time."""
2523
 
    hidden = True    
 
2935
    __doc__ = """Show the offset in seconds from GMT to local time."""
 
2936
    hidden = True
2524
2937
    @display_command
2525
2938
    def run(self):
2526
 
        print osutils.local_time_offset()
 
2939
        self.outf.write("%s\n" % osutils.local_time_offset())
2527
2940
 
2528
2941
 
2529
2942
 
2530
2943
class cmd_commit(Command):
2531
 
    """Commit changes into a new revision.
2532
 
    
2533
 
    If no arguments are given, the entire tree is committed.
2534
 
 
2535
 
    If selected files are specified, only changes to those files are
2536
 
    committed.  If a directory is specified then the directory and everything 
2537
 
    within it is committed.
2538
 
 
2539
 
    When excludes are given, they take precedence over selected files.
2540
 
    For example, too commit only changes within foo, but not changes within
2541
 
    foo/bar::
2542
 
 
2543
 
      bzr commit foo -x foo/bar
2544
 
 
2545
 
    If author of the change is not the same person as the committer, you can
2546
 
    specify the author's name using the --author option. The name should be
2547
 
    in the same format as a committer-id, e.g. "John Doe <jdoe@example.com>".
2548
 
 
2549
 
    A selected-file commit may fail in some cases where the committed
2550
 
    tree would be invalid. Consider::
2551
 
 
2552
 
      bzr init foo
2553
 
      mkdir foo/bar
2554
 
      bzr add foo/bar
2555
 
      bzr commit foo -m "committing foo"
2556
 
      bzr mv foo/bar foo/baz
2557
 
      mkdir foo/bar
2558
 
      bzr add foo/bar
2559
 
      bzr commit foo/bar -m "committing bar but not baz"
2560
 
 
2561
 
    In the example above, the last commit will fail by design. This gives
2562
 
    the user the opportunity to decide whether they want to commit the
2563
 
    rename at the same time, separately first, or not at all. (As a general
2564
 
    rule, when in doubt, Bazaar has a policy of Doing the Safe Thing.)
2565
 
 
2566
 
    Note: A selected-file commit after a merge is not yet supported.
 
2944
    __doc__ = """Commit changes into a new revision.
 
2945
 
 
2946
    An explanatory message needs to be given for each commit. This is
 
2947
    often done by using the --message option (getting the message from the
 
2948
    command line) or by using the --file option (getting the message from
 
2949
    a file). If neither of these options is given, an editor is opened for
 
2950
    the user to enter the message. To see the changed files in the
 
2951
    boilerplate text loaded into the editor, use the --show-diff option.
 
2952
 
 
2953
    By default, the entire tree is committed and the person doing the
 
2954
    commit is assumed to be the author. These defaults can be overridden
 
2955
    as explained below.
 
2956
 
 
2957
    :Selective commits:
 
2958
 
 
2959
      If selected files are specified, only changes to those files are
 
2960
      committed.  If a directory is specified then the directory and
 
2961
      everything within it is committed.
 
2962
  
 
2963
      When excludes are given, they take precedence over selected files.
 
2964
      For example, to commit only changes within foo, but not changes
 
2965
      within foo/bar::
 
2966
  
 
2967
        bzr commit foo -x foo/bar
 
2968
  
 
2969
      A selective commit after a merge is not yet supported.
 
2970
 
 
2971
    :Custom authors:
 
2972
 
 
2973
      If the author of the change is not the same person as the committer,
 
2974
      you can specify the author's name using the --author option. The
 
2975
      name should be in the same format as a committer-id, e.g.
 
2976
      "John Doe <jdoe@example.com>". If there is more than one author of
 
2977
      the change you can specify the option multiple times, once for each
 
2978
      author.
 
2979
  
 
2980
    :Checks:
 
2981
 
 
2982
      A common mistake is to forget to add a new file or directory before
 
2983
      running the commit command. The --strict option checks for unknown
 
2984
      files and aborts the commit if any are found. More advanced pre-commit
 
2985
      checks can be implemented by defining hooks. See ``bzr help hooks``
 
2986
      for details.
 
2987
 
 
2988
    :Things to note:
 
2989
 
 
2990
      If you accidentially commit the wrong changes or make a spelling
 
2991
      mistake in the commit message say, you can use the uncommit command
 
2992
      to undo it. See ``bzr help uncommit`` for details.
 
2993
 
 
2994
      Hooks can also be configured to run after a commit. This allows you
 
2995
      to trigger updates to external systems like bug trackers. The --fixes
 
2996
      option can be used to record the association between a revision and
 
2997
      one or more bugs. See ``bzr help bugs`` for details.
 
2998
 
 
2999
      A selective commit may fail in some cases where the committed
 
3000
      tree would be invalid. Consider::
 
3001
  
 
3002
        bzr init foo
 
3003
        mkdir foo/bar
 
3004
        bzr add foo/bar
 
3005
        bzr commit foo -m "committing foo"
 
3006
        bzr mv foo/bar foo/baz
 
3007
        mkdir foo/bar
 
3008
        bzr add foo/bar
 
3009
        bzr commit foo/bar -m "committing bar but not baz"
 
3010
  
 
3011
      In the example above, the last commit will fail by design. This gives
 
3012
      the user the opportunity to decide whether they want to commit the
 
3013
      rename at the same time, separately first, or not at all. (As a general
 
3014
      rule, when in doubt, Bazaar has a policy of Doing the Safe Thing.)
2567
3015
    """
2568
3016
    # TODO: Run hooks on tree to-be-committed, and after commit.
2569
3017
 
2574
3022
 
2575
3023
    # XXX: verbose currently does nothing
2576
3024
 
2577
 
    _see_also = ['bugs', 'uncommit']
 
3025
    _see_also = ['add', 'bugs', 'hooks', 'uncommit']
2578
3026
    takes_args = ['selected*']
2579
3027
    takes_options = [
2580
3028
            ListOption('exclude', type=str, short_name='x',
2592
3040
             Option('strict',
2593
3041
                    help="Refuse to commit if there are unknown "
2594
3042
                    "files in the working tree."),
 
3043
             Option('commit-time', type=str,
 
3044
                    help="Manually set a commit time using commit date "
 
3045
                    "format, e.g. '2009-10-10 08:00:00 +0100'."),
2595
3046
             ListOption('fixes', type=str,
2596
 
                    help="Mark a bug as being fixed by this revision."),
2597
 
             Option('author', type=unicode,
 
3047
                    help="Mark a bug as being fixed by this revision "
 
3048
                         "(see \"bzr help bugs\")."),
 
3049
             ListOption('author', type=unicode,
2598
3050
                    help="Set the author's name, if it's different "
2599
3051
                         "from the committer."),
2600
3052
             Option('local',
2603
3055
                         "the master branch until a normal commit "
2604
3056
                         "is performed."
2605
3057
                    ),
2606
 
              Option('show-diff',
2607
 
                     help='When no message is supplied, show the diff along'
2608
 
                     ' with the status summary in the message editor.'),
 
3058
             Option('show-diff', short_name='p',
 
3059
                    help='When no message is supplied, show the diff along'
 
3060
                    ' with the status summary in the message editor.'),
2609
3061
             ]
2610
3062
    aliases = ['ci', 'checkin']
2611
3063
 
2612
 
    def _get_bug_fix_properties(self, fixes, branch):
2613
 
        properties = []
 
3064
    def _iter_bug_fix_urls(self, fixes, branch):
2614
3065
        # Configure the properties for bug fixing attributes.
2615
3066
        for fixed_bug in fixes:
2616
3067
            tokens = fixed_bug.split(':')
2617
3068
            if len(tokens) != 2:
2618
3069
                raise errors.BzrCommandError(
2619
 
                    "Invalid bug %s. Must be in the form of 'tag:id'. "
2620
 
                    "Commit refused." % fixed_bug)
 
3070
                    "Invalid bug %s. Must be in the form of 'tracker:id'. "
 
3071
                    "See \"bzr help bugs\" for more information on this "
 
3072
                    "feature.\nCommit refused." % fixed_bug)
2621
3073
            tag, bug_id = tokens
2622
3074
            try:
2623
 
                bug_url = bugtracker.get_bug_url(tag, branch, bug_id)
 
3075
                yield bugtracker.get_bug_url(tag, branch, bug_id)
2624
3076
            except errors.UnknownBugTrackerAbbreviation:
2625
3077
                raise errors.BzrCommandError(
2626
3078
                    'Unrecognized bug %s. Commit refused.' % fixed_bug)
2627
 
            except errors.MalformedBugIdentifier:
 
3079
            except errors.MalformedBugIdentifier, e:
2628
3080
                raise errors.BzrCommandError(
2629
 
                    "Invalid bug identifier for %s. Commit refused."
2630
 
                    % fixed_bug)
2631
 
            properties.append('%s fixed' % bug_url)
2632
 
        return '\n'.join(properties)
 
3081
                    "%s\nCommit refused." % (str(e),))
2633
3082
 
2634
3083
    def run(self, message=None, file=None, verbose=False, selected_list=None,
2635
3084
            unchanged=False, strict=False, local=False, fixes=None,
2636
 
            author=None, show_diff=False, exclude=None):
 
3085
            author=None, show_diff=False, exclude=None, commit_time=None):
2637
3086
        from bzrlib.errors import (
2638
3087
            PointlessCommit,
2639
3088
            ConflictsInTree,
2645
3094
            make_commit_message_template_encoded
2646
3095
        )
2647
3096
 
 
3097
        commit_stamp = offset = None
 
3098
        if commit_time is not None:
 
3099
            try:
 
3100
                commit_stamp, offset = timestamp.parse_patch_date(commit_time)
 
3101
            except ValueError, e:
 
3102
                raise errors.BzrCommandError(
 
3103
                    "Could not parse --commit-time: " + str(e))
 
3104
 
2648
3105
        # TODO: Need a blackbox test for invoking the external editor; may be
2649
3106
        # slightly problematic to run this cross-platform.
2650
3107
 
2651
 
        # TODO: do more checks that the commit will succeed before 
 
3108
        # TODO: do more checks that the commit will succeed before
2652
3109
        # spending the user's valuable time typing a commit message.
2653
3110
 
2654
3111
        properties = {}
2662
3119
 
2663
3120
        if fixes is None:
2664
3121
            fixes = []
2665
 
        bug_property = self._get_bug_fix_properties(fixes, tree.branch)
 
3122
        bug_property = bugtracker.encode_fixes_bug_urls(
 
3123
            self._iter_bug_fix_urls(fixes, tree.branch))
2666
3124
        if bug_property:
2667
3125
            properties['bugs'] = bug_property
2668
3126
 
2669
3127
        if local and not tree.branch.get_bound_location():
2670
3128
            raise errors.LocalRequiresBoundBranch()
2671
3129
 
 
3130
        if message is not None:
 
3131
            try:
 
3132
                file_exists = osutils.lexists(message)
 
3133
            except UnicodeError:
 
3134
                # The commit message contains unicode characters that can't be
 
3135
                # represented in the filesystem encoding, so that can't be a
 
3136
                # file.
 
3137
                file_exists = False
 
3138
            if file_exists:
 
3139
                warning_msg = (
 
3140
                    'The commit message is a file name: "%(f)s".\n'
 
3141
                    '(use --file "%(f)s" to take commit message from that file)'
 
3142
                    % { 'f': message })
 
3143
                ui.ui_factory.show_warning(warning_msg)
 
3144
            if '\r' in message:
 
3145
                message = message.replace('\r\n', '\n')
 
3146
                message = message.replace('\r', '\n')
 
3147
            if file:
 
3148
                raise errors.BzrCommandError(
 
3149
                    "please specify either --message or --file")
 
3150
 
2672
3151
        def get_message(commit_obj):
2673
3152
            """Callback to get commit message"""
2674
 
            my_message = message
2675
 
            if my_message is None and not file:
2676
 
                t = make_commit_message_template_encoded(tree,
 
3153
            if file:
 
3154
                f = codecs.open(file, 'rt', osutils.get_user_encoding())
 
3155
                try:
 
3156
                    my_message = f.read()
 
3157
                finally:
 
3158
                    f.close()
 
3159
            elif message is not None:
 
3160
                my_message = message
 
3161
            else:
 
3162
                # No message supplied: make one up.
 
3163
                # text is the status of the tree
 
3164
                text = make_commit_message_template_encoded(tree,
2677
3165
                        selected_list, diff=show_diff,
2678
3166
                        output_encoding=osutils.get_user_encoding())
 
3167
                # start_message is the template generated from hooks
 
3168
                # XXX: Warning - looks like hooks return unicode,
 
3169
                # make_commit_message_template_encoded returns user encoding.
 
3170
                # We probably want to be using edit_commit_message instead to
 
3171
                # avoid this.
2679
3172
                start_message = generate_commit_message_template(commit_obj)
2680
 
                my_message = edit_commit_message_encoded(t, 
 
3173
                my_message = edit_commit_message_encoded(text,
2681
3174
                    start_message=start_message)
2682
3175
                if my_message is None:
2683
3176
                    raise errors.BzrCommandError("please specify a commit"
2684
3177
                        " message with either --message or --file")
2685
 
            elif my_message and file:
2686
 
                raise errors.BzrCommandError(
2687
 
                    "please specify either --message or --file")
2688
 
            if file:
2689
 
                my_message = codecs.open(file, 'rt',
2690
 
                                         osutils.get_user_encoding()).read()
2691
3178
            if my_message == "":
2692
3179
                raise errors.BzrCommandError("empty commit message specified")
2693
3180
            return my_message
2694
3181
 
 
3182
        # The API permits a commit with a filter of [] to mean 'select nothing'
 
3183
        # but the command line should not do that.
 
3184
        if not selected_list:
 
3185
            selected_list = None
2695
3186
        try:
2696
3187
            tree.commit(message_callback=get_message,
2697
3188
                        specific_files=selected_list,
2698
3189
                        allow_pointless=unchanged, strict=strict, local=local,
2699
3190
                        reporter=None, verbose=verbose, revprops=properties,
2700
 
                        author=author,
 
3191
                        authors=author, timestamp=commit_stamp,
 
3192
                        timezone=offset,
2701
3193
                        exclude=safe_relpath_files(tree, exclude))
2702
3194
        except PointlessCommit:
2703
 
            # FIXME: This should really happen before the file is read in;
2704
 
            # perhaps prepare the commit; get the message; then actually commit
2705
 
            raise errors.BzrCommandError("no changes to commit."
2706
 
                              " use --unchanged to commit anyhow")
 
3195
            raise errors.BzrCommandError("No changes to commit."
 
3196
                              " Use --unchanged to commit anyhow.")
2707
3197
        except ConflictsInTree:
2708
3198
            raise errors.BzrCommandError('Conflicts detected in working '
2709
3199
                'tree.  Use "bzr conflicts" to list, "bzr resolve FILE" to'
2712
3202
            raise errors.BzrCommandError("Commit refused because there are"
2713
3203
                              " unknown files in the working tree.")
2714
3204
        except errors.BoundBranchOutOfDate, e:
2715
 
            raise errors.BzrCommandError(str(e) + "\n"
2716
 
            'To commit to master branch, run update and then commit.\n'
2717
 
            'You can also pass --local to commit to continue working '
2718
 
            'disconnected.')
 
3205
            e.extra_help = ("\n"
 
3206
                'To commit to master branch, run update and then commit.\n'
 
3207
                'You can also pass --local to commit to continue working '
 
3208
                'disconnected.')
 
3209
            raise
2719
3210
 
2720
3211
 
2721
3212
class cmd_check(Command):
2722
 
    """Validate working tree structure, branch consistency and repository history.
 
3213
    __doc__ = """Validate working tree structure, branch consistency and repository history.
2723
3214
 
2724
3215
    This command checks various invariants about branch and repository storage
2725
3216
    to detect data corruption or bzr bugs.
2727
3218
    The working tree and branch checks will only give output if a problem is
2728
3219
    detected. The output fields of the repository check are:
2729
3220
 
2730
 
        revisions: This is just the number of revisions checked.  It doesn't
2731
 
            indicate a problem.
2732
 
        versionedfiles: This is just the number of versionedfiles checked.  It
2733
 
            doesn't indicate a problem.
2734
 
        unreferenced ancestors: Texts that are ancestors of other texts, but
2735
 
            are not properly referenced by the revision ancestry.  This is a
2736
 
            subtle problem that Bazaar can work around.
2737
 
        unique file texts: This is the total number of unique file contents
2738
 
            seen in the checked revisions.  It does not indicate a problem.
2739
 
        repeated file texts: This is the total number of repeated texts seen
2740
 
            in the checked revisions.  Texts can be repeated when their file
2741
 
            entries are modified, but the file contents are not.  It does not
2742
 
            indicate a problem.
 
3221
    revisions
 
3222
        This is just the number of revisions checked.  It doesn't
 
3223
        indicate a problem.
 
3224
 
 
3225
    versionedfiles
 
3226
        This is just the number of versionedfiles checked.  It
 
3227
        doesn't indicate a problem.
 
3228
 
 
3229
    unreferenced ancestors
 
3230
        Texts that are ancestors of other texts, but
 
3231
        are not properly referenced by the revision ancestry.  This is a
 
3232
        subtle problem that Bazaar can work around.
 
3233
 
 
3234
    unique file texts
 
3235
        This is the total number of unique file contents
 
3236
        seen in the checked revisions.  It does not indicate a problem.
 
3237
 
 
3238
    repeated file texts
 
3239
        This is the total number of repeated texts seen
 
3240
        in the checked revisions.  Texts can be repeated when their file
 
3241
        entries are modified, but the file contents are not.  It does not
 
3242
        indicate a problem.
2743
3243
 
2744
3244
    If no restrictions are specified, all Bazaar data that is found at the given
2745
3245
    location will be checked.
2780
3280
 
2781
3281
 
2782
3282
class cmd_upgrade(Command):
2783
 
    """Upgrade branch storage to current format.
 
3283
    __doc__ = """Upgrade branch storage to current format.
2784
3284
 
2785
3285
    The check command or bzr developers may sometimes advise you to run
2786
3286
    this command. When the default format has changed you may also be warned
2800
3300
 
2801
3301
    def run(self, url='.', format=None):
2802
3302
        from bzrlib.upgrade import upgrade
2803
 
        if format is None:
2804
 
            format = bzrdir.format_registry.make_bzrdir('default')
2805
3303
        upgrade(url, format)
2806
3304
 
2807
3305
 
2808
3306
class cmd_whoami(Command):
2809
 
    """Show or set bzr user id.
2810
 
    
 
3307
    __doc__ = """Show or set bzr user id.
 
3308
 
2811
3309
    :Examples:
2812
3310
        Show the email of the current user::
2813
3311
 
2817
3315
 
2818
3316
            bzr whoami "Frank Chu <fchu@example.com>"
2819
3317
    """
2820
 
    takes_options = [ Option('email',
 
3318
    takes_options = [ 'directory',
 
3319
                      Option('email',
2821
3320
                             help='Display email address only.'),
2822
3321
                      Option('branch',
2823
3322
                             help='Set identity for the current branch instead of '
2825
3324
                    ]
2826
3325
    takes_args = ['name?']
2827
3326
    encoding_type = 'replace'
2828
 
    
 
3327
 
2829
3328
    @display_command
2830
 
    def run(self, email=False, branch=False, name=None):
 
3329
    def run(self, email=False, branch=False, name=None, directory=None):
2831
3330
        if name is None:
2832
 
            # use branch if we're inside one; otherwise global config
2833
 
            try:
2834
 
                c = Branch.open_containing('.')[0].get_config()
2835
 
            except errors.NotBranchError:
2836
 
                c = config.GlobalConfig()
 
3331
            if directory is None:
 
3332
                # use branch if we're inside one; otherwise global config
 
3333
                try:
 
3334
                    c = Branch.open_containing(u'.')[0].get_config()
 
3335
                except errors.NotBranchError:
 
3336
                    c = config.GlobalConfig()
 
3337
            else:
 
3338
                c = Branch.open(directory).get_config()
2837
3339
            if email:
2838
3340
                self.outf.write(c.user_email() + '\n')
2839
3341
            else:
2846
3348
        except errors.NoEmailInUsername, e:
2847
3349
            warning('"%s" does not seem to contain an email address.  '
2848
3350
                    'This is allowed, but not recommended.', name)
2849
 
        
 
3351
 
2850
3352
        # use global config unless --branch given
2851
3353
        if branch:
2852
 
            c = Branch.open_containing('.')[0].get_config()
 
3354
            if directory is None:
 
3355
                c = Branch.open_containing(u'.')[0].get_config()
 
3356
            else:
 
3357
                c = Branch.open(directory).get_config()
2853
3358
        else:
2854
3359
            c = config.GlobalConfig()
2855
3360
        c.set_user_option('email', name)
2856
3361
 
2857
3362
 
2858
3363
class cmd_nick(Command):
2859
 
    """Print or set the branch nickname.
 
3364
    __doc__ = """Print or set the branch nickname.
2860
3365
 
2861
3366
    If unset, the tree root directory name is used as the nickname.
2862
3367
    To print the current nickname, execute with no argument.
2867
3372
 
2868
3373
    _see_also = ['info']
2869
3374
    takes_args = ['nickname?']
2870
 
    def run(self, nickname=None):
2871
 
        branch = Branch.open_containing(u'.')[0]
 
3375
    takes_options = ['directory']
 
3376
    def run(self, nickname=None, directory=u'.'):
 
3377
        branch = Branch.open_containing(directory)[0]
2872
3378
        if nickname is None:
2873
3379
            self.printme(branch)
2874
3380
        else:
2876
3382
 
2877
3383
    @display_command
2878
3384
    def printme(self, branch):
2879
 
        print branch.nick
 
3385
        self.outf.write('%s\n' % branch.nick)
2880
3386
 
2881
3387
 
2882
3388
class cmd_alias(Command):
2883
 
    """Set/unset and display aliases.
 
3389
    __doc__ = """Set/unset and display aliases.
2884
3390
 
2885
3391
    :Examples:
2886
3392
        Show the current aliases::
2950
3456
 
2951
3457
 
2952
3458
class cmd_selftest(Command):
2953
 
    """Run internal test suite.
2954
 
    
 
3459
    __doc__ = """Run internal test suite.
 
3460
 
2955
3461
    If arguments are given, they are regular expressions that say which tests
2956
3462
    should run.  Tests matching any expression are run, and other tests are
2957
3463
    not run.
2980
3486
    modified by plugins will not be tested, and tests provided by plugins will
2981
3487
    not be run.
2982
3488
 
2983
 
    Tests that need working space on disk use a common temporary directory, 
 
3489
    Tests that need working space on disk use a common temporary directory,
2984
3490
    typically inside $TMPDIR or /tmp.
2985
3491
 
 
3492
    If you set BZR_TEST_PDB=1 when running selftest, failing tests will drop
 
3493
    into a pdb postmortem session.
 
3494
 
2986
3495
    :Examples:
2987
3496
        Run only tests relating to 'ignore'::
2988
3497
 
2997
3506
    def get_transport_type(typestring):
2998
3507
        """Parse and return a transport specifier."""
2999
3508
        if typestring == "sftp":
3000
 
            from bzrlib.transport.sftp import SFTPAbsoluteServer
3001
 
            return SFTPAbsoluteServer
 
3509
            from bzrlib.tests import stub_sftp
 
3510
            return stub_sftp.SFTPAbsoluteServer
3002
3511
        if typestring == "memory":
3003
 
            from bzrlib.transport.memory import MemoryServer
3004
 
            return MemoryServer
 
3512
            from bzrlib.tests import test_server
 
3513
            return memory.MemoryServer
3005
3514
        if typestring == "fakenfs":
3006
 
            from bzrlib.transport.fakenfs import FakeNFSServer
3007
 
            return FakeNFSServer
 
3515
            from bzrlib.tests import test_server
 
3516
            return test_server.FakeNFSServer
3008
3517
        msg = "No known transport type %s. Supported types are: sftp\n" %\
3009
3518
            (typestring)
3010
3519
        raise errors.BzrCommandError(msg)
3025
3534
                     Option('lsprof-timed',
3026
3535
                            help='Generate lsprof output for benchmarked'
3027
3536
                                 ' sections of code.'),
 
3537
                     Option('lsprof-tests',
 
3538
                            help='Generate lsprof output for each test.'),
3028
3539
                     Option('cache-dir', type=str,
3029
3540
                            help='Cache intermediate benchmark output in this '
3030
3541
                                 'directory.'),
3034
3545
                            ),
3035
3546
                     Option('list-only',
3036
3547
                            help='List the tests instead of running them.'),
 
3548
                     RegistryOption('parallel',
 
3549
                        help="Run the test suite in parallel.",
 
3550
                        lazy_registry=('bzrlib.tests', 'parallel_registry'),
 
3551
                        value_switches=False,
 
3552
                        ),
3037
3553
                     Option('randomize', type=str, argname="SEED",
3038
3554
                            help='Randomize the order of tests using the given'
3039
3555
                                 ' seed or "now" for the current time.'),
3041
3557
                            short_name='x',
3042
3558
                            help='Exclude tests that match this regular'
3043
3559
                                 ' expression.'),
 
3560
                     Option('subunit',
 
3561
                        help='Output test progress via subunit.'),
3044
3562
                     Option('strict', help='Fail on missing dependencies or '
3045
3563
                            'known failures.'),
3046
3564
                     Option('load-list', type=str, argname='TESTLISTFILE',
3063
3581
            lsprof_timed=None, cache_dir=None,
3064
3582
            first=False, list_only=False,
3065
3583
            randomize=None, exclude=None, strict=False,
3066
 
            load_list=None, debugflag=None, starting_with=None):
3067
 
        from bzrlib.tests import selftest
3068
 
        import bzrlib.benchmarks as benchmarks
3069
 
        from bzrlib.benchmarks import tree_creator
 
3584
            load_list=None, debugflag=None, starting_with=None, subunit=False,
 
3585
            parallel=None, lsprof_tests=False):
 
3586
        from bzrlib import (
 
3587
            benchmarks,
 
3588
            tests,
 
3589
            )
3070
3590
 
3071
3591
        # Make deprecation warnings visible, unless -Werror is set
3072
3592
        symbol_versioning.activate_deprecation_warnings(override=False)
3073
3593
 
3074
3594
        if cache_dir is not None:
3075
 
            tree_creator.TreeCreator.CACHE_ROOT = osutils.abspath(cache_dir)
3076
 
        if not list_only:
3077
 
            print 'testing: %s' % (osutils.realpath(sys.argv[0]),)
3078
 
            print '   %s (%s python%s)' % (
3079
 
                    bzrlib.__path__[0],
3080
 
                    bzrlib.version_string,
3081
 
                    bzrlib._format_version_tuple(sys.version_info),
3082
 
                    )
3083
 
        print
 
3595
            benchmarks.tree_creator.TreeCreator.CACHE_ROOT = osutils.abspath(
 
3596
                cache_dir)
3084
3597
        if testspecs_list is not None:
3085
3598
            pattern = '|'.join(testspecs_list)
3086
3599
        else:
3087
3600
            pattern = ".*"
 
3601
        if subunit:
 
3602
            try:
 
3603
                from bzrlib.tests import SubUnitBzrRunner
 
3604
            except ImportError:
 
3605
                raise errors.BzrCommandError("subunit not available. subunit "
 
3606
                    "needs to be installed to use --subunit.")
 
3607
            self.additional_selftest_args['runner_class'] = SubUnitBzrRunner
 
3608
            # On Windows, disable automatic conversion of '\n' to '\r\n' in
 
3609
            # stdout, which would corrupt the subunit stream. 
 
3610
            # FIXME: This has been fixed in subunit trunk (>0.0.5) so the
 
3611
            # following code can be deleted when it's sufficiently deployed
 
3612
            # -- vila/mgz 20100514
 
3613
            if (sys.platform == "win32"
 
3614
                and getattr(sys.stdout, 'fileno', None) is not None):
 
3615
                import msvcrt
 
3616
                msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
 
3617
        if parallel:
 
3618
            self.additional_selftest_args.setdefault(
 
3619
                'suite_decorators', []).append(parallel)
3088
3620
        if benchmark:
3089
3621
            test_suite_factory = benchmarks.test_suite
3090
3622
            # Unless user explicitly asks for quiet, be verbose in benchmarks
3091
3623
            verbose = not is_quiet()
3092
3624
            # TODO: should possibly lock the history file...
3093
3625
            benchfile = open(".perf_history", "at", buffering=1)
 
3626
            self.add_cleanup(benchfile.close)
3094
3627
        else:
3095
3628
            test_suite_factory = None
3096
3629
            benchfile = None
3097
 
        try:
3098
 
            selftest_kwargs = {"verbose": verbose,
3099
 
                              "pattern": pattern,
3100
 
                              "stop_on_failure": one,
3101
 
                              "transport": transport,
3102
 
                              "test_suite_factory": test_suite_factory,
3103
 
                              "lsprof_timed": lsprof_timed,
3104
 
                              "bench_history": benchfile,
3105
 
                              "matching_tests_first": first,
3106
 
                              "list_only": list_only,
3107
 
                              "random_seed": randomize,
3108
 
                              "exclude_pattern": exclude,
3109
 
                              "strict": strict,
3110
 
                              "load_list": load_list,
3111
 
                              "debug_flags": debugflag,
3112
 
                              "starting_with": starting_with
3113
 
                              }
3114
 
            selftest_kwargs.update(self.additional_selftest_args)
3115
 
            result = selftest(**selftest_kwargs)
3116
 
        finally:
3117
 
            if benchfile is not None:
3118
 
                benchfile.close()
3119
 
        if result:
3120
 
            note('tests passed')
3121
 
        else:
3122
 
            note('tests failed')
 
3630
        selftest_kwargs = {"verbose": verbose,
 
3631
                          "pattern": pattern,
 
3632
                          "stop_on_failure": one,
 
3633
                          "transport": transport,
 
3634
                          "test_suite_factory": test_suite_factory,
 
3635
                          "lsprof_timed": lsprof_timed,
 
3636
                          "lsprof_tests": lsprof_tests,
 
3637
                          "bench_history": benchfile,
 
3638
                          "matching_tests_first": first,
 
3639
                          "list_only": list_only,
 
3640
                          "random_seed": randomize,
 
3641
                          "exclude_pattern": exclude,
 
3642
                          "strict": strict,
 
3643
                          "load_list": load_list,
 
3644
                          "debug_flags": debugflag,
 
3645
                          "starting_with": starting_with
 
3646
                          }
 
3647
        selftest_kwargs.update(self.additional_selftest_args)
 
3648
        result = tests.selftest(**selftest_kwargs)
3123
3649
        return int(not result)
3124
3650
 
3125
3651
 
3126
3652
class cmd_version(Command):
3127
 
    """Show version of bzr."""
 
3653
    __doc__ = """Show version of bzr."""
3128
3654
 
3129
3655
    encoding_type = 'replace'
3130
3656
    takes_options = [
3141
3667
 
3142
3668
 
3143
3669
class cmd_rocks(Command):
3144
 
    """Statement of optimism."""
 
3670
    __doc__ = """Statement of optimism."""
3145
3671
 
3146
3672
    hidden = True
3147
3673
 
3148
3674
    @display_command
3149
3675
    def run(self):
3150
 
        print "It sure does!"
 
3676
        self.outf.write("It sure does!\n")
3151
3677
 
3152
3678
 
3153
3679
class cmd_find_merge_base(Command):
3154
 
    """Find and print a base revision for merging two branches."""
 
3680
    __doc__ = """Find and print a base revision for merging two branches."""
3155
3681
    # TODO: Options to specify revisions on either side, as if
3156
3682
    #       merging only part of the history.
3157
3683
    takes_args = ['branch', 'other']
3158
3684
    hidden = True
3159
 
    
 
3685
 
3160
3686
    @display_command
3161
3687
    def run(self, branch, other):
3162
3688
        from bzrlib.revision import ensure_null
3163
 
        
 
3689
 
3164
3690
        branch1 = Branch.open_containing(branch)[0]
3165
3691
        branch2 = Branch.open_containing(other)[0]
3166
 
        branch1.lock_read()
3167
 
        try:
3168
 
            branch2.lock_read()
3169
 
            try:
3170
 
                last1 = ensure_null(branch1.last_revision())
3171
 
                last2 = ensure_null(branch2.last_revision())
3172
 
 
3173
 
                graph = branch1.repository.get_graph(branch2.repository)
3174
 
                base_rev_id = graph.find_unique_lca(last1, last2)
3175
 
 
3176
 
                print 'merge base is revision %s' % base_rev_id
3177
 
            finally:
3178
 
                branch2.unlock()
3179
 
        finally:
3180
 
            branch1.unlock()
 
3692
        self.add_cleanup(branch1.lock_read().unlock)
 
3693
        self.add_cleanup(branch2.lock_read().unlock)
 
3694
        last1 = ensure_null(branch1.last_revision())
 
3695
        last2 = ensure_null(branch2.last_revision())
 
3696
 
 
3697
        graph = branch1.repository.get_graph(branch2.repository)
 
3698
        base_rev_id = graph.find_unique_lca(last1, last2)
 
3699
 
 
3700
        self.outf.write('merge base is revision %s\n' % base_rev_id)
3181
3701
 
3182
3702
 
3183
3703
class cmd_merge(Command):
3184
 
    """Perform a three-way merge.
3185
 
    
 
3704
    __doc__ = """Perform a three-way merge.
 
3705
 
3186
3706
    The source of the merge can be specified either in the form of a branch,
3187
3707
    or in the form of a path to a file containing a merge directive generated
3188
3708
    with bzr send. If neither is specified, the default is the upstream branch
3198
3718
    By default, bzr will try to merge in all new work from the other
3199
3719
    branch, automatically determining an appropriate base.  If this
3200
3720
    fails, you may need to give an explicit base.
3201
 
    
 
3721
 
3202
3722
    Merge will do its best to combine the changes in two branches, but there
3203
3723
    are some kinds of problems only a human can fix.  When it encounters those,
3204
3724
    it will mark a conflict.  A conflict means that you need to fix something,
3214
3734
    The results of the merge are placed into the destination working
3215
3735
    directory, where they can be reviewed (with bzr diff), tested, and then
3216
3736
    committed to record the result of the merge.
3217
 
    
 
3737
 
3218
3738
    merge refuses to run if there are any uncommitted changes, unless
3219
 
    --force is given.
 
3739
    --force is given. The --force option can also be used to create a
 
3740
    merge revision which has more than two parents.
 
3741
 
 
3742
    If one would like to merge changes from the working tree of the other
 
3743
    branch without merging any committed revisions, the --uncommitted option
 
3744
    can be given.
 
3745
 
 
3746
    To select only some changes to merge, use "merge -i", which will prompt
 
3747
    you to apply each diff hunk and file change, similar to "shelve".
3220
3748
 
3221
3749
    :Examples:
3222
3750
        To merge the latest revision from bzr.dev::
3231
3759
 
3232
3760
            bzr merge -r 81..82 ../bzr.dev
3233
3761
 
3234
 
        To apply a merge directive contained in in /tmp/merge:
 
3762
        To apply a merge directive contained in /tmp/merge::
3235
3763
 
3236
3764
            bzr merge /tmp/merge
 
3765
 
 
3766
        To create a merge revision with three parents from two branches
 
3767
        feature1a and feature1b:
 
3768
 
 
3769
            bzr merge ../feature1a
 
3770
            bzr merge ../feature1b --force
 
3771
            bzr commit -m 'revision with three parents'
3237
3772
    """
3238
3773
 
3239
3774
    encoding_type = 'exact'
3240
 
    _see_also = ['update', 'remerge', 'status-flags']
 
3775
    _see_also = ['update', 'remerge', 'status-flags', 'send']
3241
3776
    takes_args = ['location?']
3242
3777
    takes_options = [
3243
3778
        'change',
3255
3790
                ' completely merged into the source, pull from the'
3256
3791
                ' source rather than merging.  When this happens,'
3257
3792
                ' you do not need to commit the result.'),
3258
 
        Option('directory',
 
3793
        custom_help('directory',
3259
3794
               help='Branch to merge into, '
3260
 
                    'rather than the one containing the working directory.',
3261
 
               short_name='d',
3262
 
               type=unicode,
3263
 
               ),
3264
 
        Option('preview', help='Instead of merging, show a diff of the merge.')
 
3795
                    'rather than the one containing the working directory.'),
 
3796
        Option('preview', help='Instead of merging, show a diff of the'
 
3797
               ' merge.'),
 
3798
        Option('interactive', help='Select changes interactively.',
 
3799
            short_name='i')
3265
3800
    ]
3266
3801
 
3267
3802
    def run(self, location=None, revision=None, force=False,
3269
3804
            uncommitted=False, pull=False,
3270
3805
            directory=None,
3271
3806
            preview=False,
 
3807
            interactive=False,
3272
3808
            ):
3273
3809
        if merge_type is None:
3274
3810
            merge_type = _mod_merge.Merge3Merger
3279
3815
        allow_pending = True
3280
3816
        verified = 'inapplicable'
3281
3817
        tree = WorkingTree.open_containing(directory)[0]
 
3818
 
 
3819
        try:
 
3820
            basis_tree = tree.revision_tree(tree.last_revision())
 
3821
        except errors.NoSuchRevision:
 
3822
            basis_tree = tree.basis_tree()
 
3823
 
 
3824
        # die as quickly as possible if there are uncommitted changes
 
3825
        if not force:
 
3826
            if tree.has_changes():
 
3827
                raise errors.UncommittedChanges(tree)
 
3828
 
 
3829
        view_info = _get_view_info_for_change_reporter(tree)
3282
3830
        change_reporter = delta._ChangeReporter(
3283
 
            unversioned_filter=tree.is_ignored)
3284
 
        cleanups = []
3285
 
        try:
3286
 
            pb = ui.ui_factory.nested_progress_bar()
3287
 
            cleanups.append(pb.finished)
3288
 
            tree.lock_write()
3289
 
            cleanups.append(tree.unlock)
3290
 
            if location is not None:
3291
 
                try:
3292
 
                    mergeable = bundle.read_mergeable_from_url(location,
3293
 
                        possible_transports=possible_transports)
3294
 
                except errors.NotABundle:
3295
 
                    mergeable = None
3296
 
                else:
3297
 
                    if uncommitted:
3298
 
                        raise errors.BzrCommandError('Cannot use --uncommitted'
3299
 
                            ' with bundles or merge directives.')
3300
 
 
3301
 
                    if revision is not None:
3302
 
                        raise errors.BzrCommandError(
3303
 
                            'Cannot use -r with merge directives or bundles')
3304
 
                    merger, verified = _mod_merge.Merger.from_mergeable(tree,
3305
 
                       mergeable, pb)
3306
 
 
3307
 
            if merger is None and uncommitted:
3308
 
                if revision is not None and len(revision) > 0:
3309
 
                    raise errors.BzrCommandError('Cannot use --uncommitted and'
3310
 
                        ' --revision at the same time.')
3311
 
                location = self._select_branch_location(tree, location)[0]
3312
 
                other_tree, other_path = WorkingTree.open_containing(location)
3313
 
                merger = _mod_merge.Merger.from_uncommitted(tree, other_tree,
3314
 
                    pb)
3315
 
                allow_pending = False
3316
 
                if other_path != '':
3317
 
                    merger.interesting_files = [other_path]
3318
 
 
3319
 
            if merger is None:
3320
 
                merger, allow_pending = self._get_merger_from_branch(tree,
3321
 
                    location, revision, remember, possible_transports, pb)
3322
 
 
3323
 
            merger.merge_type = merge_type
3324
 
            merger.reprocess = reprocess
3325
 
            merger.show_base = show_base
3326
 
            self.sanity_check_merger(merger)
3327
 
            if (merger.base_rev_id == merger.other_rev_id and
3328
 
                merger.other_rev_id is not None):
3329
 
                note('Nothing to do.')
 
3831
            unversioned_filter=tree.is_ignored, view_info=view_info)
 
3832
        pb = ui.ui_factory.nested_progress_bar()
 
3833
        self.add_cleanup(pb.finished)
 
3834
        self.add_cleanup(tree.lock_write().unlock)
 
3835
        if location is not None:
 
3836
            try:
 
3837
                mergeable = bundle.read_mergeable_from_url(location,
 
3838
                    possible_transports=possible_transports)
 
3839
            except errors.NotABundle:
 
3840
                mergeable = None
 
3841
            else:
 
3842
                if uncommitted:
 
3843
                    raise errors.BzrCommandError('Cannot use --uncommitted'
 
3844
                        ' with bundles or merge directives.')
 
3845
 
 
3846
                if revision is not None:
 
3847
                    raise errors.BzrCommandError(
 
3848
                        'Cannot use -r with merge directives or bundles')
 
3849
                merger, verified = _mod_merge.Merger.from_mergeable(tree,
 
3850
                   mergeable, None)
 
3851
 
 
3852
        if merger is None and uncommitted:
 
3853
            if revision is not None and len(revision) > 0:
 
3854
                raise errors.BzrCommandError('Cannot use --uncommitted and'
 
3855
                    ' --revision at the same time.')
 
3856
            merger = self.get_merger_from_uncommitted(tree, location, None)
 
3857
            allow_pending = False
 
3858
 
 
3859
        if merger is None:
 
3860
            merger, allow_pending = self._get_merger_from_branch(tree,
 
3861
                location, revision, remember, possible_transports, None)
 
3862
 
 
3863
        merger.merge_type = merge_type
 
3864
        merger.reprocess = reprocess
 
3865
        merger.show_base = show_base
 
3866
        self.sanity_check_merger(merger)
 
3867
        if (merger.base_rev_id == merger.other_rev_id and
 
3868
            merger.other_rev_id is not None):
 
3869
            note('Nothing to do.')
 
3870
            return 0
 
3871
        if pull:
 
3872
            if merger.interesting_files is not None:
 
3873
                raise errors.BzrCommandError('Cannot pull individual files')
 
3874
            if (merger.base_rev_id == tree.last_revision()):
 
3875
                result = tree.pull(merger.other_branch, False,
 
3876
                                   merger.other_rev_id)
 
3877
                result.report(self.outf)
3330
3878
                return 0
3331
 
            if pull:
3332
 
                if merger.interesting_files is not None:
3333
 
                    raise errors.BzrCommandError('Cannot pull individual files')
3334
 
                if (merger.base_rev_id == tree.last_revision()):
3335
 
                    result = tree.pull(merger.other_branch, False,
3336
 
                                       merger.other_rev_id)
3337
 
                    result.report(self.outf)
3338
 
                    return 0
3339
 
            merger.check_basis(not force)
3340
 
            if preview:
3341
 
                return self._do_preview(merger)
3342
 
            else:
3343
 
                return self._do_merge(merger, change_reporter, allow_pending,
3344
 
                                      verified)
3345
 
        finally:
3346
 
            for cleanup in reversed(cleanups):
3347
 
                cleanup()
 
3879
        if merger.this_basis is None:
 
3880
            raise errors.BzrCommandError(
 
3881
                "This branch has no commits."
 
3882
                " (perhaps you would prefer 'bzr pull')")
 
3883
        if preview:
 
3884
            return self._do_preview(merger)
 
3885
        elif interactive:
 
3886
            return self._do_interactive(merger)
 
3887
        else:
 
3888
            return self._do_merge(merger, change_reporter, allow_pending,
 
3889
                                  verified)
 
3890
 
 
3891
    def _get_preview(self, merger):
 
3892
        tree_merger = merger.make_merger()
 
3893
        tt = tree_merger.make_preview_transform()
 
3894
        self.add_cleanup(tt.finalize)
 
3895
        result_tree = tt.get_preview_tree()
 
3896
        return result_tree
3348
3897
 
3349
3898
    def _do_preview(self, merger):
3350
3899
        from bzrlib.diff import show_diff_trees
3351
 
        tree_merger = merger.make_merger()
3352
 
        tt = tree_merger.make_preview_transform()
3353
 
        try:
3354
 
            result_tree = tt.get_preview_tree()
3355
 
            show_diff_trees(merger.this_tree, result_tree, self.outf,
3356
 
                            old_label='', new_label='')
3357
 
        finally:
3358
 
            tt.finalize()
 
3900
        result_tree = self._get_preview(merger)
 
3901
        path_encoding = osutils.get_diff_header_encoding()
 
3902
        show_diff_trees(merger.this_tree, result_tree, self.outf,
 
3903
                        old_label='', new_label='',
 
3904
                        path_encoding=path_encoding)
3359
3905
 
3360
3906
    def _do_merge(self, merger, change_reporter, allow_pending, verified):
3361
3907
        merger.change_reporter = change_reporter
3369
3915
        else:
3370
3916
            return 0
3371
3917
 
 
3918
    def _do_interactive(self, merger):
 
3919
        """Perform an interactive merge.
 
3920
 
 
3921
        This works by generating a preview tree of the merge, then using
 
3922
        Shelver to selectively remove the differences between the working tree
 
3923
        and the preview tree.
 
3924
        """
 
3925
        from bzrlib import shelf_ui
 
3926
        result_tree = self._get_preview(merger)
 
3927
        writer = bzrlib.option.diff_writer_registry.get()
 
3928
        shelver = shelf_ui.Shelver(merger.this_tree, result_tree, destroy=True,
 
3929
                                   reporter=shelf_ui.ApplyReporter(),
 
3930
                                   diff_writer=writer(sys.stdout))
 
3931
        try:
 
3932
            shelver.run()
 
3933
        finally:
 
3934
            shelver.finalize()
 
3935
 
3372
3936
    def sanity_check_merger(self, merger):
3373
3937
        if (merger.show_base and
3374
3938
            not merger.merge_type is _mod_merge.Merge3Merger):
3409
3973
            base_branch, base_path = Branch.open_containing(base_loc,
3410
3974
                possible_transports)
3411
3975
        # Find the revision ids
3412
 
        if revision is None or len(revision) < 1 or revision[-1] is None:
 
3976
        other_revision_id = None
 
3977
        base_revision_id = None
 
3978
        if revision is not None:
 
3979
            if len(revision) >= 1:
 
3980
                other_revision_id = revision[-1].as_revision_id(other_branch)
 
3981
            if len(revision) == 2:
 
3982
                base_revision_id = revision[0].as_revision_id(base_branch)
 
3983
        if other_revision_id is None:
3413
3984
            other_revision_id = _mod_revision.ensure_null(
3414
3985
                other_branch.last_revision())
3415
 
        else:
3416
 
            other_revision_id = revision[-1].as_revision_id(other_branch)
3417
 
        if (revision is not None and len(revision) == 2
3418
 
            and revision[0] is not None):
3419
 
            base_revision_id = revision[0].as_revision_id(base_branch)
3420
 
        else:
3421
 
            base_revision_id = None
3422
3986
        # Remember where we merge from
3423
3987
        if ((remember or tree.branch.get_submit_branch() is None) and
3424
3988
             user_location is not None):
3433
3997
            allow_pending = True
3434
3998
        return merger, allow_pending
3435
3999
 
 
4000
    def get_merger_from_uncommitted(self, tree, location, pb):
 
4001
        """Get a merger for uncommitted changes.
 
4002
 
 
4003
        :param tree: The tree the merger should apply to.
 
4004
        :param location: The location containing uncommitted changes.
 
4005
        :param pb: The progress bar to use for showing progress.
 
4006
        """
 
4007
        location = self._select_branch_location(tree, location)[0]
 
4008
        other_tree, other_path = WorkingTree.open_containing(location)
 
4009
        merger = _mod_merge.Merger.from_uncommitted(tree, other_tree, pb)
 
4010
        if other_path != '':
 
4011
            merger.interesting_files = [other_path]
 
4012
        return merger
 
4013
 
3436
4014
    def _select_branch_location(self, tree, user_location, revision=None,
3437
4015
                                index=None):
3438
4016
        """Select a branch location, according to possible inputs.
3482
4060
 
3483
4061
 
3484
4062
class cmd_remerge(Command):
3485
 
    """Redo a merge.
 
4063
    __doc__ = """Redo a merge.
3486
4064
 
3487
4065
    Use this if you want to try a different merge technique while resolving
3488
 
    conflicts.  Some merge techniques are better than others, and remerge 
 
4066
    conflicts.  Some merge techniques are better than others, and remerge
3489
4067
    lets you try different ones on different files.
3490
4068
 
3491
4069
    The options for remerge have the same meaning and defaults as the ones for
3495
4073
    :Examples:
3496
4074
        Re-do the merge of all conflicted files, and show the base text in
3497
4075
        conflict regions, in addition to the usual THIS and OTHER texts::
3498
 
      
 
4076
 
3499
4077
            bzr remerge --show-base
3500
4078
 
3501
4079
        Re-do the merge of "foobar", using the weave merge algorithm, with
3502
4080
        additional processing to reduce the size of conflict regions::
3503
 
      
 
4081
 
3504
4082
            bzr remerge --merge-type weave --reprocess foobar
3505
4083
    """
3506
4084
    takes_args = ['file*']
3513
4091
 
3514
4092
    def run(self, file_list=None, merge_type=None, show_base=False,
3515
4093
            reprocess=False):
 
4094
        from bzrlib.conflicts import restore
3516
4095
        if merge_type is None:
3517
4096
            merge_type = _mod_merge.Merge3Merger
3518
4097
        tree, file_list = tree_files(file_list)
3519
 
        tree.lock_write()
 
4098
        self.add_cleanup(tree.lock_write().unlock)
 
4099
        parents = tree.get_parent_ids()
 
4100
        if len(parents) != 2:
 
4101
            raise errors.BzrCommandError("Sorry, remerge only works after normal"
 
4102
                                         " merges.  Not cherrypicking or"
 
4103
                                         " multi-merges.")
 
4104
        repository = tree.branch.repository
 
4105
        interesting_ids = None
 
4106
        new_conflicts = []
 
4107
        conflicts = tree.conflicts()
 
4108
        if file_list is not None:
 
4109
            interesting_ids = set()
 
4110
            for filename in file_list:
 
4111
                file_id = tree.path2id(filename)
 
4112
                if file_id is None:
 
4113
                    raise errors.NotVersionedError(filename)
 
4114
                interesting_ids.add(file_id)
 
4115
                if tree.kind(file_id) != "directory":
 
4116
                    continue
 
4117
 
 
4118
                for name, ie in tree.inventory.iter_entries(file_id):
 
4119
                    interesting_ids.add(ie.file_id)
 
4120
            new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
 
4121
        else:
 
4122
            # Remerge only supports resolving contents conflicts
 
4123
            allowed_conflicts = ('text conflict', 'contents conflict')
 
4124
            restore_files = [c.path for c in conflicts
 
4125
                             if c.typestring in allowed_conflicts]
 
4126
        _mod_merge.transform_tree(tree, tree.basis_tree(), interesting_ids)
 
4127
        tree.set_conflicts(ConflictList(new_conflicts))
 
4128
        if file_list is not None:
 
4129
            restore_files = file_list
 
4130
        for filename in restore_files:
 
4131
            try:
 
4132
                restore(tree.abspath(filename))
 
4133
            except errors.NotConflicted:
 
4134
                pass
 
4135
        # Disable pending merges, because the file texts we are remerging
 
4136
        # have not had those merges performed.  If we use the wrong parents
 
4137
        # list, we imply that the working tree text has seen and rejected
 
4138
        # all the changes from the other tree, when in fact those changes
 
4139
        # have not yet been seen.
 
4140
        tree.set_parent_ids(parents[:1])
3520
4141
        try:
3521
 
            parents = tree.get_parent_ids()
3522
 
            if len(parents) != 2:
3523
 
                raise errors.BzrCommandError("Sorry, remerge only works after normal"
3524
 
                                             " merges.  Not cherrypicking or"
3525
 
                                             " multi-merges.")
3526
 
            repository = tree.branch.repository
3527
 
            interesting_ids = None
3528
 
            new_conflicts = []
3529
 
            conflicts = tree.conflicts()
3530
 
            if file_list is not None:
3531
 
                interesting_ids = set()
3532
 
                for filename in file_list:
3533
 
                    file_id = tree.path2id(filename)
3534
 
                    if file_id is None:
3535
 
                        raise errors.NotVersionedError(filename)
3536
 
                    interesting_ids.add(file_id)
3537
 
                    if tree.kind(file_id) != "directory":
3538
 
                        continue
3539
 
                    
3540
 
                    for name, ie in tree.inventory.iter_entries(file_id):
3541
 
                        interesting_ids.add(ie.file_id)
3542
 
                new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
3543
 
            else:
3544
 
                # Remerge only supports resolving contents conflicts
3545
 
                allowed_conflicts = ('text conflict', 'contents conflict')
3546
 
                restore_files = [c.path for c in conflicts
3547
 
                                 if c.typestring in allowed_conflicts]
3548
 
            _mod_merge.transform_tree(tree, tree.basis_tree(), interesting_ids)
3549
 
            tree.set_conflicts(ConflictList(new_conflicts))
3550
 
            if file_list is not None:
3551
 
                restore_files = file_list
3552
 
            for filename in restore_files:
3553
 
                try:
3554
 
                    restore(tree.abspath(filename))
3555
 
                except errors.NotConflicted:
3556
 
                    pass
3557
 
            # Disable pending merges, because the file texts we are remerging
3558
 
            # have not had those merges performed.  If we use the wrong parents
3559
 
            # list, we imply that the working tree text has seen and rejected
3560
 
            # all the changes from the other tree, when in fact those changes
3561
 
            # have not yet been seen.
3562
 
            pb = ui.ui_factory.nested_progress_bar()
3563
 
            tree.set_parent_ids(parents[:1])
3564
 
            try:
3565
 
                merger = _mod_merge.Merger.from_revision_ids(pb,
3566
 
                                                             tree, parents[1])
3567
 
                merger.interesting_ids = interesting_ids
3568
 
                merger.merge_type = merge_type
3569
 
                merger.show_base = show_base
3570
 
                merger.reprocess = reprocess
3571
 
                conflicts = merger.do_merge()
3572
 
            finally:
3573
 
                tree.set_parent_ids(parents)
3574
 
                pb.finished()
 
4142
            merger = _mod_merge.Merger.from_revision_ids(None, tree, parents[1])
 
4143
            merger.interesting_ids = interesting_ids
 
4144
            merger.merge_type = merge_type
 
4145
            merger.show_base = show_base
 
4146
            merger.reprocess = reprocess
 
4147
            conflicts = merger.do_merge()
3575
4148
        finally:
3576
 
            tree.unlock()
 
4149
            tree.set_parent_ids(parents)
3577
4150
        if conflicts > 0:
3578
4151
            return 1
3579
4152
        else:
3581
4154
 
3582
4155
 
3583
4156
class cmd_revert(Command):
3584
 
    """Revert files to a previous revision.
 
4157
    __doc__ = """Revert files to a previous revision.
3585
4158
 
3586
4159
    Giving a list of files will revert only those files.  Otherwise, all files
3587
4160
    will be reverted.  If the revision is not specified with '--revision', the
3591
4164
    merge instead.  For example, "merge . --revision -2..-3" will remove the
3592
4165
    changes introduced by -2, without affecting the changes introduced by -1.
3593
4166
    Or to remove certain changes on a hunk-by-hunk basis, see the Shelf plugin.
3594
 
    
 
4167
 
3595
4168
    By default, any files that have been manually changed will be backed up
3596
4169
    first.  (Files changed only by merge are not backed up.)  Backup files have
3597
4170
    '.~#~' appended to their name, where # is a number.
3601
4174
    name.  If you name a directory, all the contents of that directory will be
3602
4175
    reverted.
3603
4176
 
3604
 
    Any files that have been newly added since that revision will be deleted,
3605
 
    with a backup kept if appropriate.  Directories containing unknown files
3606
 
    will not be deleted.
 
4177
    If you have newly added files since the target revision, they will be
 
4178
    removed.  If the files to be removed have been changed, backups will be
 
4179
    created as above.  Directories containing unknown files will not be
 
4180
    deleted.
3607
4181
 
3608
 
    The working tree contains a list of pending merged revisions, which will
3609
 
    be included as parents in the next commit.  Normally, revert clears that
3610
 
    list as well as reverting the files.  If any files are specified, revert
3611
 
    leaves the pending merge list alone and reverts only the files.  Use "bzr
3612
 
    revert ." in the tree root to revert all files but keep the merge record,
3613
 
    and "bzr revert --forget-merges" to clear the pending merge list without
 
4182
    The working tree contains a list of revisions that have been merged but
 
4183
    not yet committed. These revisions will be included as additional parents
 
4184
    of the next commit.  Normally, using revert clears that list as well as
 
4185
    reverting the files.  If any files are specified, revert leaves the list
 
4186
    of uncommitted merges alone and reverts only the files.  Use ``bzr revert
 
4187
    .`` in the tree root to revert all files but keep the recorded merges,
 
4188
    and ``bzr revert --forget-merges`` to clear the pending merge list without
3614
4189
    reverting any files.
 
4190
 
 
4191
    Using "bzr revert --forget-merges", it is possible to apply all of the
 
4192
    changes from a branch in a single revision.  To do this, perform the merge
 
4193
    as desired.  Then doing revert with the "--forget-merges" option will keep
 
4194
    the content of the tree as it was, but it will clear the list of pending
 
4195
    merges.  The next commit will then contain all of the changes that are
 
4196
    present in the other branch, but without any other parent revisions.
 
4197
    Because this technique forgets where these changes originated, it may
 
4198
    cause additional conflicts on later merges involving the same source and
 
4199
    target branches.
3615
4200
    """
3616
4201
 
3617
4202
    _see_also = ['cat', 'export']
3626
4211
    def run(self, revision=None, no_backup=False, file_list=None,
3627
4212
            forget_merges=None):
3628
4213
        tree, file_list = tree_files(file_list)
3629
 
        tree.lock_write()
3630
 
        try:
3631
 
            if forget_merges:
3632
 
                tree.set_parent_ids(tree.get_parent_ids()[:1])
3633
 
            else:
3634
 
                self._revert_tree_to_revision(tree, revision, file_list, no_backup)
3635
 
        finally:
3636
 
            tree.unlock()
 
4214
        self.add_cleanup(tree.lock_tree_write().unlock)
 
4215
        if forget_merges:
 
4216
            tree.set_parent_ids(tree.get_parent_ids()[:1])
 
4217
        else:
 
4218
            self._revert_tree_to_revision(tree, revision, file_list, no_backup)
3637
4219
 
3638
4220
    @staticmethod
3639
4221
    def _revert_tree_to_revision(tree, revision, file_list, no_backup):
3640
4222
        rev_tree = _get_one_revision_tree('revert', revision, tree=tree)
3641
 
        pb = ui.ui_factory.nested_progress_bar()
3642
 
        try:
3643
 
            tree.revert(file_list, rev_tree, not no_backup, pb,
3644
 
                report_changes=True)
3645
 
        finally:
3646
 
            pb.finished()
 
4223
        tree.revert(file_list, rev_tree, not no_backup, None,
 
4224
            report_changes=True)
3647
4225
 
3648
4226
 
3649
4227
class cmd_assert_fail(Command):
3650
 
    """Test reporting of assertion failures"""
 
4228
    __doc__ = """Test reporting of assertion failures"""
3651
4229
    # intended just for use in testing
3652
4230
 
3653
4231
    hidden = True
3657
4235
 
3658
4236
 
3659
4237
class cmd_help(Command):
3660
 
    """Show help on a command or other topic.
 
4238
    __doc__ = """Show help on a command or other topic.
3661
4239
    """
3662
4240
 
3663
4241
    _see_also = ['topics']
3666
4244
            ]
3667
4245
    takes_args = ['topic?']
3668
4246
    aliases = ['?', '--help', '-?', '-h']
3669
 
    
 
4247
 
3670
4248
    @display_command
3671
4249
    def run(self, topic=None, long=False):
3672
4250
        import bzrlib.help
3676
4254
 
3677
4255
 
3678
4256
class cmd_shell_complete(Command):
3679
 
    """Show appropriate completions for context.
 
4257
    __doc__ = """Show appropriate completions for context.
3680
4258
 
3681
4259
    For a list of all available commands, say 'bzr shell-complete'.
3682
4260
    """
3683
4261
    takes_args = ['context?']
3684
4262
    aliases = ['s-c']
3685
4263
    hidden = True
3686
 
    
 
4264
 
3687
4265
    @display_command
3688
4266
    def run(self, context=None):
3689
4267
        import shellcomplete
3691
4269
 
3692
4270
 
3693
4271
class cmd_missing(Command):
3694
 
    """Show unmerged/unpulled revisions between two branches.
 
4272
    __doc__ = """Show unmerged/unpulled revisions between two branches.
3695
4273
 
3696
4274
    OTHER_BRANCH may be local or remote.
3697
4275
 
3698
 
    To filter on a range of revirions, you can use the command -r begin..end
 
4276
    To filter on a range of revisions, you can use the command -r begin..end
3699
4277
    -r revision requests a specific revision, -r ..end or -r begin.. are
3700
4278
    also valid.
 
4279
            
 
4280
    :Exit values:
 
4281
        1 - some missing revisions
 
4282
        0 - no missing revisions
3701
4283
 
3702
4284
    :Examples:
3703
4285
 
3724
4306
    _see_also = ['merge', 'pull']
3725
4307
    takes_args = ['other_branch?']
3726
4308
    takes_options = [
 
4309
        'directory',
3727
4310
        Option('reverse', 'Reverse the order of revisions.'),
3728
4311
        Option('mine-only',
3729
4312
               'Display changes in the local branch only.'),
3741
4324
            type=_parse_revision_str,
3742
4325
            help='Filter on local branch revisions (inclusive). '
3743
4326
                'See "help revisionspec" for details.'),
3744
 
        Option('include-merges', 'Show merged revisions.'),
 
4327
        Option('include-merges',
 
4328
               'Show all revisions in addition to the mainline ones.'),
3745
4329
        ]
3746
4330
    encoding_type = 'replace'
3747
4331
 
3750
4334
            theirs_only=False,
3751
4335
            log_format=None, long=False, short=False, line=False,
3752
4336
            show_ids=False, verbose=False, this=False, other=False,
3753
 
            include_merges=False, revision=None, my_revision=None):
 
4337
            include_merges=False, revision=None, my_revision=None,
 
4338
            directory=u'.'):
3754
4339
        from bzrlib.missing import find_unmerged, iter_log_revisions
3755
4340
        def message(s):
3756
4341
            if not is_quiet():
3769
4354
        elif theirs_only:
3770
4355
            restrict = 'remote'
3771
4356
 
3772
 
        local_branch = Branch.open_containing(u".")[0]
 
4357
        local_branch = Branch.open_containing(directory)[0]
 
4358
        self.add_cleanup(local_branch.lock_read().unlock)
 
4359
 
3773
4360
        parent = local_branch.get_parent()
3774
4361
        if other_branch is None:
3775
4362
            other_branch = parent
3784
4371
        remote_branch = Branch.open(other_branch)
3785
4372
        if remote_branch.base == local_branch.base:
3786
4373
            remote_branch = local_branch
 
4374
        else:
 
4375
            self.add_cleanup(remote_branch.lock_read().unlock)
3787
4376
 
3788
4377
        local_revid_range = _revision_range_to_revid_range(
3789
4378
            _get_revision_range(my_revision, local_branch,
3793
4382
            _get_revision_range(revision,
3794
4383
                remote_branch, self.name()))
3795
4384
 
3796
 
        local_branch.lock_read()
3797
 
        try:
3798
 
            remote_branch.lock_read()
3799
 
            try:
3800
 
                local_extra, remote_extra = find_unmerged(
3801
 
                    local_branch, remote_branch, restrict,
3802
 
                    backward=not reverse,
3803
 
                    include_merges=include_merges,
3804
 
                    local_revid_range=local_revid_range,
3805
 
                    remote_revid_range=remote_revid_range)
3806
 
 
3807
 
                if log_format is None:
3808
 
                    registry = log.log_formatter_registry
3809
 
                    log_format = registry.get_default(local_branch)
3810
 
                lf = log_format(to_file=self.outf,
3811
 
                                show_ids=show_ids,
3812
 
                                show_timezone='original')
3813
 
 
3814
 
                status_code = 0
3815
 
                if local_extra and not theirs_only:
3816
 
                    message("You have %d extra revision(s):\n" %
3817
 
                        len(local_extra))
3818
 
                    for revision in iter_log_revisions(local_extra,
3819
 
                                        local_branch.repository,
3820
 
                                        verbose):
3821
 
                        lf.log_revision(revision)
3822
 
                    printed_local = True
3823
 
                    status_code = 1
3824
 
                else:
3825
 
                    printed_local = False
3826
 
 
3827
 
                if remote_extra and not mine_only:
3828
 
                    if printed_local is True:
3829
 
                        message("\n\n\n")
3830
 
                    message("You are missing %d revision(s):\n" %
3831
 
                        len(remote_extra))
3832
 
                    for revision in iter_log_revisions(remote_extra,
3833
 
                                        remote_branch.repository,
3834
 
                                        verbose):
3835
 
                        lf.log_revision(revision)
3836
 
                    status_code = 1
3837
 
 
3838
 
                if mine_only and not local_extra:
3839
 
                    # We checked local, and found nothing extra
3840
 
                    message('This branch is up to date.\n')
3841
 
                elif theirs_only and not remote_extra:
3842
 
                    # We checked remote, and found nothing extra
3843
 
                    message('Other branch is up to date.\n')
3844
 
                elif not (mine_only or theirs_only or local_extra or
3845
 
                          remote_extra):
3846
 
                    # We checked both branches, and neither one had extra
3847
 
                    # revisions
3848
 
                    message("Branches are up to date.\n")
3849
 
            finally:
3850
 
                remote_branch.unlock()
3851
 
        finally:
3852
 
            local_branch.unlock()
 
4385
        local_extra, remote_extra = find_unmerged(
 
4386
            local_branch, remote_branch, restrict,
 
4387
            backward=not reverse,
 
4388
            include_merges=include_merges,
 
4389
            local_revid_range=local_revid_range,
 
4390
            remote_revid_range=remote_revid_range)
 
4391
 
 
4392
        if log_format is None:
 
4393
            registry = log.log_formatter_registry
 
4394
            log_format = registry.get_default(local_branch)
 
4395
        lf = log_format(to_file=self.outf,
 
4396
                        show_ids=show_ids,
 
4397
                        show_timezone='original')
 
4398
 
 
4399
        status_code = 0
 
4400
        if local_extra and not theirs_only:
 
4401
            message("You have %d extra revision(s):\n" %
 
4402
                len(local_extra))
 
4403
            for revision in iter_log_revisions(local_extra,
 
4404
                                local_branch.repository,
 
4405
                                verbose):
 
4406
                lf.log_revision(revision)
 
4407
            printed_local = True
 
4408
            status_code = 1
 
4409
        else:
 
4410
            printed_local = False
 
4411
 
 
4412
        if remote_extra and not mine_only:
 
4413
            if printed_local is True:
 
4414
                message("\n\n\n")
 
4415
            message("You are missing %d revision(s):\n" %
 
4416
                len(remote_extra))
 
4417
            for revision in iter_log_revisions(remote_extra,
 
4418
                                remote_branch.repository,
 
4419
                                verbose):
 
4420
                lf.log_revision(revision)
 
4421
            status_code = 1
 
4422
 
 
4423
        if mine_only and not local_extra:
 
4424
            # We checked local, and found nothing extra
 
4425
            message('This branch is up to date.\n')
 
4426
        elif theirs_only and not remote_extra:
 
4427
            # We checked remote, and found nothing extra
 
4428
            message('Other branch is up to date.\n')
 
4429
        elif not (mine_only or theirs_only or local_extra or
 
4430
                  remote_extra):
 
4431
            # We checked both branches, and neither one had extra
 
4432
            # revisions
 
4433
            message("Branches are up to date.\n")
 
4434
        self.cleanup_now()
3853
4435
        if not status_code and parent is None and other_branch is not None:
3854
 
            local_branch.lock_write()
3855
 
            try:
3856
 
                # handle race conditions - a parent might be set while we run.
3857
 
                if local_branch.get_parent() is None:
3858
 
                    local_branch.set_parent(remote_branch.base)
3859
 
            finally:
3860
 
                local_branch.unlock()
 
4436
            self.add_cleanup(local_branch.lock_write().unlock)
 
4437
            # handle race conditions - a parent might be set while we run.
 
4438
            if local_branch.get_parent() is None:
 
4439
                local_branch.set_parent(remote_branch.base)
3861
4440
        return status_code
3862
4441
 
3863
4442
 
3864
4443
class cmd_pack(Command):
3865
 
    """Compress the data within a repository."""
 
4444
    __doc__ = """Compress the data within a repository.
 
4445
 
 
4446
    This operation compresses the data within a bazaar repository. As
 
4447
    bazaar supports automatic packing of repository, this operation is
 
4448
    normally not required to be done manually.
 
4449
 
 
4450
    During the pack operation, bazaar takes a backup of existing repository
 
4451
    data, i.e. pack files. This backup is eventually removed by bazaar
 
4452
    automatically when it is safe to do so. To save disk space by removing
 
4453
    the backed up pack files, the --clean-obsolete-packs option may be
 
4454
    used.
 
4455
 
 
4456
    Warning: If you use --clean-obsolete-packs and your machine crashes
 
4457
    during or immediately after repacking, you may be left with a state
 
4458
    where the deletion has been written to disk but the new packs have not
 
4459
    been. In this case the repository may be unusable.
 
4460
    """
3866
4461
 
3867
4462
    _see_also = ['repositories']
3868
4463
    takes_args = ['branch_or_repo?']
 
4464
    takes_options = [
 
4465
        Option('clean-obsolete-packs', 'Delete obsolete packs to save disk space.'),
 
4466
        ]
3869
4467
 
3870
 
    def run(self, branch_or_repo='.'):
 
4468
    def run(self, branch_or_repo='.', clean_obsolete_packs=False):
3871
4469
        dir = bzrdir.BzrDir.open_containing(branch_or_repo)[0]
3872
4470
        try:
3873
4471
            branch = dir.open_branch()
3874
4472
            repository = branch.repository
3875
4473
        except errors.NotBranchError:
3876
4474
            repository = dir.open_repository()
3877
 
        repository.pack()
 
4475
        repository.pack(clean_obsolete_packs=clean_obsolete_packs)
3878
4476
 
3879
4477
 
3880
4478
class cmd_plugins(Command):
3881
 
    """List the installed plugins.
3882
 
    
 
4479
    __doc__ = """List the installed plugins.
 
4480
 
3883
4481
    This command displays the list of installed plugins including
3884
4482
    version of plugin and a short description of each.
3885
4483
 
3891
4489
    adding new commands, providing additional network transports and
3892
4490
    customizing log output.
3893
4491
 
3894
 
    See the Bazaar web site, http://bazaar-vcs.org, for further
3895
 
    information on plugins including where to find them and how to
3896
 
    install them. Instructions are also provided there on how to
3897
 
    write new plugins using the Python programming language.
 
4492
    See the Bazaar Plugin Guide <http://doc.bazaar.canonical.com/plugins/en/>
 
4493
    for further information on plugins including where to find them and how to
 
4494
    install them. Instructions are also provided there on how to write new
 
4495
    plugins using the Python programming language.
3898
4496
    """
3899
4497
    takes_options = ['verbose']
3900
4498
 
3915
4513
                doc = '(no description)'
3916
4514
            result.append((name_ver, doc, plugin.path()))
3917
4515
        for name_ver, doc, path in sorted(result):
3918
 
            print name_ver
3919
 
            print '   ', doc
 
4516
            self.outf.write("%s\n" % name_ver)
 
4517
            self.outf.write("   %s\n" % doc)
3920
4518
            if verbose:
3921
 
                print '   ', path
3922
 
            print
 
4519
                self.outf.write("   %s\n" % path)
 
4520
            self.outf.write("\n")
3923
4521
 
3924
4522
 
3925
4523
class cmd_testament(Command):
3926
 
    """Show testament (signing-form) of a revision."""
 
4524
    __doc__ = """Show testament (signing-form) of a revision."""
3927
4525
    takes_options = [
3928
4526
            'revision',
3929
4527
            Option('long', help='Produce long-format testament.'),
3941
4539
            b = Branch.open_containing(branch)[0]
3942
4540
        else:
3943
4541
            b = Branch.open(branch)
3944
 
        b.lock_read()
3945
 
        try:
3946
 
            if revision is None:
3947
 
                rev_id = b.last_revision()
3948
 
            else:
3949
 
                rev_id = revision[0].as_revision_id(b)
3950
 
            t = testament_class.from_revision(b.repository, rev_id)
3951
 
            if long:
3952
 
                sys.stdout.writelines(t.as_text_lines())
3953
 
            else:
3954
 
                sys.stdout.write(t.as_short_text())
3955
 
        finally:
3956
 
            b.unlock()
 
4542
        self.add_cleanup(b.lock_read().unlock)
 
4543
        if revision is None:
 
4544
            rev_id = b.last_revision()
 
4545
        else:
 
4546
            rev_id = revision[0].as_revision_id(b)
 
4547
        t = testament_class.from_revision(b.repository, rev_id)
 
4548
        if long:
 
4549
            sys.stdout.writelines(t.as_text_lines())
 
4550
        else:
 
4551
            sys.stdout.write(t.as_short_text())
3957
4552
 
3958
4553
 
3959
4554
class cmd_annotate(Command):
3960
 
    """Show the origin of each line in a file.
 
4555
    __doc__ = """Show the origin of each line in a file.
3961
4556
 
3962
4557
    This prints out the given file with an annotation on the left side
3963
4558
    indicating which revision, author and date introduced the change.
3964
4559
 
3965
 
    If the origin is the same for a run of consecutive lines, it is 
 
4560
    If the origin is the same for a run of consecutive lines, it is
3966
4561
    shown only at the top, unless the --all option is given.
3967
4562
    """
3968
4563
    # TODO: annotate directories; showing when each file was last changed
3969
 
    # TODO: if the working copy is modified, show annotations on that 
 
4564
    # TODO: if the working copy is modified, show annotations on that
3970
4565
    #       with new uncommitted lines marked
3971
4566
    aliases = ['ann', 'blame', 'praise']
3972
4567
    takes_args = ['filename']
3974
4569
                     Option('long', help='Show commit date in annotations.'),
3975
4570
                     'revision',
3976
4571
                     'show-ids',
 
4572
                     'directory',
3977
4573
                     ]
3978
4574
    encoding_type = 'exact'
3979
4575
 
3980
4576
    @display_command
3981
4577
    def run(self, filename, all=False, long=False, revision=None,
3982
 
            show_ids=False):
 
4578
            show_ids=False, directory=None):
3983
4579
        from bzrlib.annotate import annotate_file, annotate_file_tree
3984
4580
        wt, branch, relpath = \
3985
 
            bzrdir.BzrDir.open_containing_tree_or_branch(filename)
3986
 
        if wt is not None:
3987
 
            wt.lock_read()
3988
 
        else:
3989
 
            branch.lock_read()
3990
 
        try:
3991
 
            tree = _get_one_revision_tree('annotate', revision, branch=branch)
3992
 
            if wt is not None:
3993
 
                file_id = wt.path2id(relpath)
3994
 
            else:
3995
 
                file_id = tree.path2id(relpath)
3996
 
            if file_id is None:
3997
 
                raise errors.NotVersionedError(filename)
3998
 
            file_version = tree.inventory[file_id].revision
3999
 
            if wt is not None and revision is None:
4000
 
                # If there is a tree and we're not annotating historical
4001
 
                # versions, annotate the working tree's content.
4002
 
                annotate_file_tree(wt, file_id, self.outf, long, all,
4003
 
                    show_ids=show_ids)
4004
 
            else:
4005
 
                annotate_file(branch, file_version, file_id, long, all, self.outf,
4006
 
                              show_ids=show_ids)
4007
 
        finally:
4008
 
            if wt is not None:
4009
 
                wt.unlock()
4010
 
            else:
4011
 
                branch.unlock()
 
4581
            _open_directory_or_containing_tree_or_branch(filename, directory)
 
4582
        if wt is not None:
 
4583
            self.add_cleanup(wt.lock_read().unlock)
 
4584
        else:
 
4585
            self.add_cleanup(branch.lock_read().unlock)
 
4586
        tree = _get_one_revision_tree('annotate', revision, branch=branch)
 
4587
        self.add_cleanup(tree.lock_read().unlock)
 
4588
        if wt is not None:
 
4589
            file_id = wt.path2id(relpath)
 
4590
        else:
 
4591
            file_id = tree.path2id(relpath)
 
4592
        if file_id is None:
 
4593
            raise errors.NotVersionedError(filename)
 
4594
        file_version = tree.inventory[file_id].revision
 
4595
        if wt is not None and revision is None:
 
4596
            # If there is a tree and we're not annotating historical
 
4597
            # versions, annotate the working tree's content.
 
4598
            annotate_file_tree(wt, file_id, self.outf, long, all,
 
4599
                show_ids=show_ids)
 
4600
        else:
 
4601
            annotate_file(branch, file_version, file_id, long, all, self.outf,
 
4602
                          show_ids=show_ids)
4012
4603
 
4013
4604
 
4014
4605
class cmd_re_sign(Command):
4015
 
    """Create a digital signature for an existing revision."""
 
4606
    __doc__ = """Create a digital signature for an existing revision."""
4016
4607
    # TODO be able to replace existing ones.
4017
4608
 
4018
4609
    hidden = True # is this right ?
4019
4610
    takes_args = ['revision_id*']
4020
 
    takes_options = ['revision']
4021
 
    
4022
 
    def run(self, revision_id_list=None, revision=None):
 
4611
    takes_options = ['directory', 'revision']
 
4612
 
 
4613
    def run(self, revision_id_list=None, revision=None, directory=u'.'):
4023
4614
        if revision_id_list is not None and revision is not None:
4024
4615
            raise errors.BzrCommandError('You can only supply one of revision_id or --revision')
4025
4616
        if revision_id_list is None and revision is None:
4026
4617
            raise errors.BzrCommandError('You must supply either --revision or a revision_id')
4027
 
        b = WorkingTree.open_containing(u'.')[0].branch
4028
 
        b.lock_write()
4029
 
        try:
4030
 
            return self._run(b, revision_id_list, revision)
4031
 
        finally:
4032
 
            b.unlock()
 
4618
        b = WorkingTree.open_containing(directory)[0].branch
 
4619
        self.add_cleanup(b.lock_write().unlock)
 
4620
        return self._run(b, revision_id_list, revision)
4033
4621
 
4034
4622
    def _run(self, b, revision_id_list, revision):
4035
4623
        import bzrlib.gpg as gpg
4080
4668
 
4081
4669
 
4082
4670
class cmd_bind(Command):
4083
 
    """Convert the current branch into a checkout of the supplied branch.
 
4671
    __doc__ = """Convert the current branch into a checkout of the supplied branch.
 
4672
    If no branch is supplied, rebind to the last bound location.
4084
4673
 
4085
4674
    Once converted into a checkout, commits must succeed on the master branch
4086
4675
    before they will be applied to the local branch.
4087
4676
 
4088
4677
    Bound branches use the nickname of its master branch unless it is set
4089
 
    locally, in which case binding will update the the local nickname to be
 
4678
    locally, in which case binding will update the local nickname to be
4090
4679
    that of the master.
4091
4680
    """
4092
4681
 
4093
4682
    _see_also = ['checkouts', 'unbind']
4094
4683
    takes_args = ['location?']
4095
 
    takes_options = []
 
4684
    takes_options = ['directory']
4096
4685
 
4097
 
    def run(self, location=None):
4098
 
        b, relpath = Branch.open_containing(u'.')
 
4686
    def run(self, location=None, directory=u'.'):
 
4687
        b, relpath = Branch.open_containing(directory)
4099
4688
        if location is None:
4100
4689
            try:
4101
4690
                location = b.get_old_bound_location()
4104
4693
                    'This format does not remember old locations.')
4105
4694
            else:
4106
4695
                if location is None:
4107
 
                    raise errors.BzrCommandError('No location supplied and no '
4108
 
                        'previous location known')
 
4696
                    if b.get_bound_location() is not None:
 
4697
                        raise errors.BzrCommandError('Branch is already bound')
 
4698
                    else:
 
4699
                        raise errors.BzrCommandError('No location supplied '
 
4700
                            'and no previous location known')
4109
4701
        b_other = Branch.open(location)
4110
4702
        try:
4111
4703
            b.bind(b_other)
4117
4709
 
4118
4710
 
4119
4711
class cmd_unbind(Command):
4120
 
    """Convert the current checkout into a regular branch.
 
4712
    __doc__ = """Convert the current checkout into a regular branch.
4121
4713
 
4122
4714
    After unbinding, the local branch is considered independent and subsequent
4123
4715
    commits will be local only.
4125
4717
 
4126
4718
    _see_also = ['checkouts', 'bind']
4127
4719
    takes_args = []
4128
 
    takes_options = []
 
4720
    takes_options = ['directory']
4129
4721
 
4130
 
    def run(self):
4131
 
        b, relpath = Branch.open_containing(u'.')
 
4722
    def run(self, directory=u'.'):
 
4723
        b, relpath = Branch.open_containing(directory)
4132
4724
        if not b.unbind():
4133
4725
            raise errors.BzrCommandError('Local branch is not bound')
4134
4726
 
4135
4727
 
4136
4728
class cmd_uncommit(Command):
4137
 
    """Remove the last committed revision.
 
4729
    __doc__ = """Remove the last committed revision.
4138
4730
 
4139
4731
    --verbose will print out what is being removed.
4140
4732
    --dry-run will go through all the motions, but not actually
4180
4772
            b = control.open_branch()
4181
4773
 
4182
4774
        if tree is not None:
4183
 
            tree.lock_write()
 
4775
            self.add_cleanup(tree.lock_write().unlock)
4184
4776
        else:
4185
 
            b.lock_write()
4186
 
        try:
4187
 
            return self._run(b, tree, dry_run, verbose, revision, force,
4188
 
                             local=local)
4189
 
        finally:
4190
 
            if tree is not None:
4191
 
                tree.unlock()
4192
 
            else:
4193
 
                b.unlock()
 
4777
            self.add_cleanup(b.lock_write().unlock)
 
4778
        return self._run(b, tree, dry_run, verbose, revision, force, local=local)
4194
4779
 
4195
4780
    def _run(self, b, tree, dry_run, verbose, revision, force, local=False):
4196
4781
        from bzrlib.log import log_formatter, show_log
4228
4813
                 end_revision=last_revno)
4229
4814
 
4230
4815
        if dry_run:
4231
 
            print 'Dry-run, pretending to remove the above revisions.'
4232
 
            if not force:
4233
 
                val = raw_input('Press <enter> to continue')
 
4816
            self.outf.write('Dry-run, pretending to remove'
 
4817
                            ' the above revisions.\n')
4234
4818
        else:
4235
 
            print 'The above revision(s) will be removed.'
4236
 
            if not force:
4237
 
                val = raw_input('Are you sure [y/N]? ')
4238
 
                if val.lower() not in ('y', 'yes'):
4239
 
                    print 'Canceled'
4240
 
                    return 0
 
4819
            self.outf.write('The above revision(s) will be removed.\n')
 
4820
 
 
4821
        if not force:
 
4822
            if not ui.ui_factory.get_boolean('Are you sure'):
 
4823
                self.outf.write('Canceled')
 
4824
                return 0
4241
4825
 
4242
4826
        mutter('Uncommitting from {%s} to {%s}',
4243
4827
               last_rev_id, rev_id)
4244
4828
        uncommit(b, tree=tree, dry_run=dry_run, verbose=verbose,
4245
4829
                 revno=revno, local=local)
4246
 
        note('You can restore the old tip by running:\n'
4247
 
             '  bzr pull . -r revid:%s', last_rev_id)
 
4830
        self.outf.write('You can restore the old tip by running:\n'
 
4831
             '  bzr pull . -r revid:%s\n' % last_rev_id)
4248
4832
 
4249
4833
 
4250
4834
class cmd_break_lock(Command):
4251
 
    """Break a dead lock on a repository, branch or working directory.
 
4835
    __doc__ = """Break a dead lock on a repository, branch or working directory.
4252
4836
 
4253
4837
    CAUTION: Locks should only be broken when you are sure that the process
4254
4838
    holding the lock has been stopped.
4255
4839
 
4256
 
    You can get information on what locks are open via the 'bzr info' command.
4257
 
    
 
4840
    You can get information on what locks are open via the 'bzr info
 
4841
    [location]' command.
 
4842
 
4258
4843
    :Examples:
4259
4844
        bzr break-lock
 
4845
        bzr break-lock bzr+ssh://example.com/bzr/foo
4260
4846
    """
4261
4847
    takes_args = ['location?']
4262
4848
 
4268
4854
            control.break_lock()
4269
4855
        except NotImplementedError:
4270
4856
            pass
4271
 
        
 
4857
 
4272
4858
 
4273
4859
class cmd_wait_until_signalled(Command):
4274
 
    """Test helper for test_start_and_stop_bzr_subprocess_send_signal.
 
4860
    __doc__ = """Test helper for test_start_and_stop_bzr_subprocess_send_signal.
4275
4861
 
4276
4862
    This just prints a line to signal when it is ready, then blocks on stdin.
4277
4863
    """
4285
4871
 
4286
4872
 
4287
4873
class cmd_serve(Command):
4288
 
    """Run the bzr server."""
 
4874
    __doc__ = """Run the bzr server."""
4289
4875
 
4290
4876
    aliases = ['server']
4291
4877
 
4292
4878
    takes_options = [
4293
4879
        Option('inet',
4294
4880
               help='Serve on stdin/out for use from inetd or sshd.'),
 
4881
        RegistryOption('protocol',
 
4882
               help="Protocol to serve.",
 
4883
               lazy_registry=('bzrlib.transport', 'transport_server_registry'),
 
4884
               value_switches=True),
4295
4885
        Option('port',
4296
4886
               help='Listen for connections on nominated port of the form '
4297
4887
                    '[hostname:]portnumber.  Passing 0 as the port number will '
4298
 
                    'result in a dynamically allocated port.  The default port is '
4299
 
                    '4155.',
 
4888
                    'result in a dynamically allocated port.  The default port '
 
4889
                    'depends on the protocol.',
4300
4890
               type=str),
4301
 
        Option('directory',
4302
 
               help='Serve contents of this directory.',
4303
 
               type=unicode),
 
4891
        custom_help('directory',
 
4892
               help='Serve contents of this directory.'),
4304
4893
        Option('allow-writes',
4305
4894
               help='By default the server is a readonly server.  Supplying '
4306
4895
                    '--allow-writes enables write access to the contents of '
4307
 
                    'the served directory and below.'
 
4896
                    'the served directory and below.  Note that ``bzr serve`` '
 
4897
                    'does not perform authentication, so unless some form of '
 
4898
                    'external authentication is arranged supplying this '
 
4899
                    'option leads to global uncontrolled write access to your '
 
4900
                    'file system.'
4308
4901
                ),
4309
4902
        ]
4310
4903
 
4311
 
    def run_smart_server(self, smart_server):
4312
 
        """Run 'smart_server' forever, with no UI output at all."""
4313
 
        # For the duration of this server, no UI output is permitted. note
4314
 
        # that this may cause problems with blackbox tests. This should be
4315
 
        # changed with care though, as we dont want to use bandwidth sending
4316
 
        # progress over stderr to smart server clients!
4317
 
        from bzrlib import lockdir
4318
 
        old_factory = ui.ui_factory
4319
 
        old_lockdir_timeout = lockdir._DEFAULT_TIMEOUT_SECONDS
4320
 
        try:
4321
 
            ui.ui_factory = ui.SilentUIFactory()
4322
 
            lockdir._DEFAULT_TIMEOUT_SECONDS = 0
4323
 
            smart_server.serve()
4324
 
        finally:
4325
 
            ui.ui_factory = old_factory
4326
 
            lockdir._DEFAULT_TIMEOUT_SECONDS = old_lockdir_timeout
4327
 
 
4328
4904
    def get_host_and_port(self, port):
4329
4905
        """Return the host and port to run the smart server on.
4330
4906
 
4331
 
        If 'port' is None, the default host (`medium.BZR_DEFAULT_INTERFACE`)
4332
 
        and port (`medium.BZR_DEFAULT_PORT`) will be used.
 
4907
        If 'port' is None, None will be returned for the host and port.
4333
4908
 
4334
4909
        If 'port' has a colon in it, the string before the colon will be
4335
4910
        interpreted as the host.
4338
4913
        :return: A tuple of (host, port), where 'host' is a host name or IP,
4339
4914
            and port is an integer TCP/IP port.
4340
4915
        """
4341
 
        from bzrlib.smart import medium
4342
 
        host = medium.BZR_DEFAULT_INTERFACE
4343
 
        if port is None:
4344
 
            port = medium.BZR_DEFAULT_PORT
4345
 
        else:
 
4916
        host = None
 
4917
        if port is not None:
4346
4918
            if ':' in port:
4347
4919
                host, port = port.split(':')
4348
4920
            port = int(port)
4349
4921
        return host, port
4350
4922
 
4351
 
    def get_smart_server(self, transport, inet, port):
4352
 
        """Construct a smart server.
4353
 
 
4354
 
        :param transport: The base transport from which branches will be
4355
 
            served.
4356
 
        :param inet: If True, serve over stdin and stdout. Used for running
4357
 
            from inet.
4358
 
        :param port: The port to listen on. By default, it's `
4359
 
            medium.BZR_DEFAULT_PORT`. See `get_host_and_port` for more
4360
 
            information.
4361
 
        :return: A smart server.
4362
 
        """
4363
 
        from bzrlib.smart import medium, server
4364
 
        if inet:
4365
 
            smart_server = medium.SmartServerPipeStreamMedium(
4366
 
                sys.stdin, sys.stdout, transport)
4367
 
        else:
4368
 
            host, port = self.get_host_and_port(port)
4369
 
            smart_server = server.SmartTCPServer(
4370
 
                transport, host=host, port=port)
4371
 
            note('listening on port: %s' % smart_server.port)
4372
 
        return smart_server
4373
 
 
4374
 
    def run(self, port=None, inet=False, directory=None, allow_writes=False):
4375
 
        from bzrlib.transport import get_transport
4376
 
        from bzrlib.transport.chroot import ChrootServer
 
4923
    def run(self, port=None, inet=False, directory=None, allow_writes=False,
 
4924
            protocol=None):
 
4925
        from bzrlib import transport
4377
4926
        if directory is None:
4378
4927
            directory = os.getcwd()
 
4928
        if protocol is None:
 
4929
            protocol = transport.transport_server_registry.get()
 
4930
        host, port = self.get_host_and_port(port)
4379
4931
        url = urlutils.local_path_to_url(directory)
4380
4932
        if not allow_writes:
4381
4933
            url = 'readonly+' + url
4382
 
        chroot_server = ChrootServer(get_transport(url))
4383
 
        chroot_server.setUp()
4384
 
        t = get_transport(chroot_server.get_url())
4385
 
        smart_server = self.get_smart_server(t, inet, port)
4386
 
        self.run_smart_server(smart_server)
 
4934
        t = transport.get_transport(url)
 
4935
        protocol(t, host, port, inet)
4387
4936
 
4388
4937
 
4389
4938
class cmd_join(Command):
4390
 
    """Combine a subtree into its containing tree.
4391
 
    
4392
 
    This command is for experimental use only.  It requires the target tree
4393
 
    to be in dirstate-with-subtree format, which cannot be converted into
4394
 
    earlier formats.
 
4939
    __doc__ = """Combine a tree into its containing tree.
 
4940
 
 
4941
    This command requires the target tree to be in a rich-root format.
4395
4942
 
4396
4943
    The TREE argument should be an independent tree, inside another tree, but
4397
4944
    not part of it.  (Such trees can be produced by "bzr split", but also by
4400
4947
    The result is a combined tree, with the subtree no longer an independant
4401
4948
    part.  This is marked as a merge of the subtree into the containing tree,
4402
4949
    and all history is preserved.
4403
 
 
4404
 
    If --reference is specified, the subtree retains its independence.  It can
4405
 
    be branched by itself, and can be part of multiple projects at the same
4406
 
    time.  But operations performed in the containing tree, such as commit
4407
 
    and merge, will recurse into the subtree.
4408
4950
    """
4409
4951
 
4410
4952
    _see_also = ['split']
4411
4953
    takes_args = ['tree']
4412
4954
    takes_options = [
4413
 
            Option('reference', help='Join by reference.'),
 
4955
            Option('reference', help='Join by reference.', hidden=True),
4414
4956
            ]
4415
 
    hidden = True
4416
4957
 
4417
4958
    def run(self, tree, reference=False):
4418
4959
        sub_tree = WorkingTree.open(tree)
4436
4977
            try:
4437
4978
                containing_tree.subsume(sub_tree)
4438
4979
            except errors.BadSubsumeSource, e:
4439
 
                raise errors.BzrCommandError("Cannot join %s.  %s" % 
 
4980
                raise errors.BzrCommandError("Cannot join %s.  %s" %
4440
4981
                                             (tree, e.reason))
4441
4982
 
4442
4983
 
4443
4984
class cmd_split(Command):
4444
 
    """Split a subdirectory of a tree into a separate tree.
 
4985
    __doc__ = """Split a subdirectory of a tree into a separate tree.
4445
4986
 
4446
4987
    This command will produce a target tree in a format that supports
4447
4988
    rich roots, like 'rich-root' or 'rich-root-pack'.  These formats cannot be
4452
4993
    branch.  Commits in the top-level tree will not apply to the new subtree.
4453
4994
    """
4454
4995
 
4455
 
    # join is not un-hidden yet
4456
 
    #_see_also = ['join']
 
4996
    _see_also = ['join']
4457
4997
    takes_args = ['tree']
4458
4998
 
4459
4999
    def run(self, tree):
4464
5004
        try:
4465
5005
            containing_tree.extract(sub_id)
4466
5006
        except errors.RootNotRich:
4467
 
            raise errors.UpgradeRequired(containing_tree.branch.base)
 
5007
            raise errors.RichRootUpgradeRequired(containing_tree.branch.base)
4468
5008
 
4469
5009
 
4470
5010
class cmd_merge_directive(Command):
4471
 
    """Generate a merge directive for auto-merge tools.
 
5011
    __doc__ = """Generate a merge directive for auto-merge tools.
4472
5012
 
4473
5013
    A directive requests a merge to be performed, and also provides all the
4474
5014
    information necessary to do so.  This means it must either include a
4491
5031
    _see_also = ['send']
4492
5032
 
4493
5033
    takes_options = [
 
5034
        'directory',
4494
5035
        RegistryOption.from_kwargs('patch-type',
4495
5036
            'The type of patch to include in the directive.',
4496
5037
            title='Patch type',
4509
5050
    encoding_type = 'exact'
4510
5051
 
4511
5052
    def run(self, submit_branch=None, public_branch=None, patch_type='bundle',
4512
 
            sign=False, revision=None, mail_to=None, message=None):
 
5053
            sign=False, revision=None, mail_to=None, message=None,
 
5054
            directory=u'.'):
4513
5055
        from bzrlib.revision import ensure_null, NULL_REVISION
4514
5056
        include_patch, include_bundle = {
4515
5057
            'plain': (False, False),
4516
5058
            'diff': (True, False),
4517
5059
            'bundle': (True, True),
4518
5060
            }[patch_type]
4519
 
        branch = Branch.open('.')
 
5061
        branch = Branch.open(directory)
4520
5062
        stored_submit_branch = branch.get_submit_branch()
4521
5063
        if submit_branch is None:
4522
5064
            submit_branch = stored_submit_branch
4567
5109
 
4568
5110
 
4569
5111
class cmd_send(Command):
4570
 
    """Mail or create a merge-directive for submitting changes.
 
5112
    __doc__ = """Mail or create a merge-directive for submitting changes.
4571
5113
 
4572
5114
    A merge directive provides many things needed for requesting merges:
4573
5115
 
4579
5121
      directly from the merge directive, without retrieving data from a
4580
5122
      branch.
4581
5123
 
4582
 
    If --no-bundle is specified, then public_branch is needed (and must be
4583
 
    up-to-date), so that the receiver can perform the merge using the
4584
 
    public_branch.  The public_branch is always included if known, so that
4585
 
    people can check it later.
4586
 
 
4587
 
    The submit branch defaults to the parent, but can be overridden.  Both
4588
 
    submit branch and public branch will be remembered if supplied.
4589
 
 
4590
 
    If a public_branch is known for the submit_branch, that public submit
4591
 
    branch is used in the merge instructions.  This means that a local mirror
4592
 
    can be used as your actual submit branch, once you have set public_branch
4593
 
    for that mirror.
 
5124
    `bzr send` creates a compact data set that, when applied using bzr
 
5125
    merge, has the same effect as merging from the source branch.  
 
5126
    
 
5127
    By default the merge directive is self-contained and can be applied to any
 
5128
    branch containing submit_branch in its ancestory without needing access to
 
5129
    the source branch.
 
5130
    
 
5131
    If --no-bundle is specified, then Bazaar doesn't send the contents of the
 
5132
    revisions, but only a structured request to merge from the
 
5133
    public_location.  In that case the public_branch is needed and it must be
 
5134
    up-to-date and accessible to the recipient.  The public_branch is always
 
5135
    included if known, so that people can check it later.
 
5136
 
 
5137
    The submit branch defaults to the parent of the source branch, but can be
 
5138
    overridden.  Both submit branch and public branch will be remembered in
 
5139
    branch.conf the first time they are used for a particular branch.  The
 
5140
    source branch defaults to that containing the working directory, but can
 
5141
    be changed using --from.
 
5142
 
 
5143
    In order to calculate those changes, bzr must analyse the submit branch.
 
5144
    Therefore it is most efficient for the submit branch to be a local mirror.
 
5145
    If a public location is known for the submit_branch, that location is used
 
5146
    in the merge directive.
 
5147
 
 
5148
    The default behaviour is to send the merge directive by mail, unless -o is
 
5149
    given, in which case it is sent to a file.
4594
5150
 
4595
5151
    Mail is sent using your preferred mail program.  This should be transparent
4596
 
    on Windows (it uses MAPI).  On Linux, it requires the xdg-email utility.
 
5152
    on Windows (it uses MAPI).  On Unix, it requires the xdg-email utility.
4597
5153
    If the preferred client can't be found (or used), your editor will be used.
4598
 
    
 
5154
 
4599
5155
    To use a specific mail program, set the mail_client configuration option.
4600
5156
    (For Thunderbird 1.5, this works around some bugs.)  Supported values for
4601
 
    specific clients are "claws", "evolution", "kmail", "mutt", and
4602
 
    "thunderbird"; generic options are "default", "editor", "emacsclient",
4603
 
    "mapi", and "xdg-email".  Plugins may also add supported clients.
 
5157
    specific clients are "claws", "evolution", "kmail", "mail.app" (MacOS X's
 
5158
    Mail.app), "mutt", and "thunderbird"; generic options are "default",
 
5159
    "editor", "emacsclient", "mapi", and "xdg-email".  Plugins may also add
 
5160
    supported clients.
4604
5161
 
4605
5162
    If mail is being sent, a to address is required.  This can be supplied
4606
5163
    either on the commandline, by setting the submit_to configuration
4607
 
    option in the branch itself or the child_submit_to configuration option 
 
5164
    option in the branch itself or the child_submit_to configuration option
4608
5165
    in the submit branch.
4609
5166
 
4610
5167
    Two formats are currently supported: "4" uses revision bundle format 4 and
4612
5169
    older formats.  It is compatible with Bazaar 0.19 and later.  It is the
4613
5170
    default.  "0.9" uses revision bundle format 0.9 and merge directive
4614
5171
    format 1.  It is compatible with Bazaar 0.12 - 0.18.
4615
 
    
4616
 
    Merge directives are applied using the merge command or the pull command.
 
5172
 
 
5173
    The merge directives created by bzr send may be applied using bzr merge or
 
5174
    bzr pull by specifying a file containing a merge directive as the location.
 
5175
 
 
5176
    bzr send makes extensive use of public locations to map local locations into
 
5177
    URLs that can be used by other people.  See `bzr help configuration` to
 
5178
    set them, and use `bzr info` to display them.
4617
5179
    """
4618
5180
 
4619
5181
    encoding_type = 'exact'
4635
5197
               short_name='f',
4636
5198
               type=unicode),
4637
5199
        Option('output', short_name='o',
4638
 
               help='Write merge directive to this file; '
 
5200
               help='Write merge directive to this file or directory; '
4639
5201
                    'use - for stdout.',
4640
5202
               type=unicode),
 
5203
        Option('strict',
 
5204
               help='Refuse to send if there are uncommitted changes in'
 
5205
               ' the working tree, --no-strict disables the check.'),
4641
5206
        Option('mail-to', help='Mail the request to this address.',
4642
5207
               type=unicode),
4643
5208
        'revision',
4644
5209
        'message',
4645
 
        RegistryOption.from_kwargs('format',
4646
 
        'Use the specified output format.',
4647
 
        **{'4': 'Bundle format 4, Merge Directive 2 (default)',
4648
 
           '0.9': 'Bundle format 0.9, Merge Directive 1',})
 
5210
        Option('body', help='Body for the email.', type=unicode),
 
5211
        RegistryOption('format',
 
5212
                       help='Use the specified output format.',
 
5213
                       lazy_registry=('bzrlib.send', 'format_registry')),
4649
5214
        ]
4650
5215
 
4651
5216
    def run(self, submit_branch=None, public_branch=None, no_bundle=False,
4652
5217
            no_patch=False, revision=None, remember=False, output=None,
4653
 
            format='4', mail_to=None, message=None, **kwargs):
4654
 
        return self._run(submit_branch, revision, public_branch, remember,
4655
 
                         format, no_bundle, no_patch, output,
4656
 
                         kwargs.get('from', '.'), mail_to, message)
4657
 
 
4658
 
    def _run(self, submit_branch, revision, public_branch, remember, format,
4659
 
             no_bundle, no_patch, output, from_, mail_to, message):
4660
 
        from bzrlib.revision import NULL_REVISION
4661
 
        branch = Branch.open_containing(from_)[0]
4662
 
        if output is None:
4663
 
            outfile = cStringIO.StringIO()
4664
 
        elif output == '-':
4665
 
            outfile = self.outf
4666
 
        else:
4667
 
            outfile = open(output, 'wb')
4668
 
        # we may need to write data into branch's repository to calculate
4669
 
        # the data to send.
4670
 
        branch.lock_write()
4671
 
        try:
4672
 
            if output is None:
4673
 
                config = branch.get_config()
4674
 
                if mail_to is None:
4675
 
                    mail_to = config.get_user_option('submit_to')
4676
 
                mail_client = config.get_mail_client()
4677
 
            if remember and submit_branch is None:
4678
 
                raise errors.BzrCommandError(
4679
 
                    '--remember requires a branch to be specified.')
4680
 
            stored_submit_branch = branch.get_submit_branch()
4681
 
            remembered_submit_branch = None
4682
 
            if submit_branch is None:
4683
 
                submit_branch = stored_submit_branch
4684
 
                remembered_submit_branch = "submit"
4685
 
            else:
4686
 
                if stored_submit_branch is None or remember:
4687
 
                    branch.set_submit_branch(submit_branch)
4688
 
            if submit_branch is None:
4689
 
                submit_branch = branch.get_parent()
4690
 
                remembered_submit_branch = "parent"
4691
 
            if submit_branch is None:
4692
 
                raise errors.BzrCommandError('No submit branch known or'
4693
 
                                             ' specified')
4694
 
            if remembered_submit_branch is not None:
4695
 
                note('Using saved %s location "%s" to determine what '
4696
 
                        'changes to submit.', remembered_submit_branch,
4697
 
                        submit_branch)
4698
 
 
4699
 
            if mail_to is None:
4700
 
                submit_config = Branch.open(submit_branch).get_config()
4701
 
                mail_to = submit_config.get_user_option("child_submit_to")
4702
 
 
4703
 
            stored_public_branch = branch.get_public_branch()
4704
 
            if public_branch is None:
4705
 
                public_branch = stored_public_branch
4706
 
            elif stored_public_branch is None or remember:
4707
 
                branch.set_public_branch(public_branch)
4708
 
            if no_bundle and public_branch is None:
4709
 
                raise errors.BzrCommandError('No public branch specified or'
4710
 
                                             ' known')
4711
 
            base_revision_id = None
4712
 
            revision_id = None
4713
 
            if revision is not None:
4714
 
                if len(revision) > 2:
4715
 
                    raise errors.BzrCommandError('bzr send takes '
4716
 
                        'at most two one revision identifiers')
4717
 
                revision_id = revision[-1].as_revision_id(branch)
4718
 
                if len(revision) == 2:
4719
 
                    base_revision_id = revision[0].as_revision_id(branch)
4720
 
            if revision_id is None:
4721
 
                revision_id = branch.last_revision()
4722
 
            if revision_id == NULL_REVISION:
4723
 
                raise errors.BzrCommandError('No revisions to submit.')
4724
 
            if format == '4':
4725
 
                directive = merge_directive.MergeDirective2.from_objects(
4726
 
                    branch.repository, revision_id, time.time(),
4727
 
                    osutils.local_time_offset(), submit_branch,
4728
 
                    public_branch=public_branch, include_patch=not no_patch,
4729
 
                    include_bundle=not no_bundle, message=message,
4730
 
                    base_revision_id=base_revision_id)
4731
 
            elif format == '0.9':
4732
 
                if not no_bundle:
4733
 
                    if not no_patch:
4734
 
                        patch_type = 'bundle'
4735
 
                    else:
4736
 
                        raise errors.BzrCommandError('Format 0.9 does not'
4737
 
                            ' permit bundle with no patch')
4738
 
                else:
4739
 
                    if not no_patch:
4740
 
                        patch_type = 'diff'
4741
 
                    else:
4742
 
                        patch_type = None
4743
 
                directive = merge_directive.MergeDirective.from_objects(
4744
 
                    branch.repository, revision_id, time.time(),
4745
 
                    osutils.local_time_offset(), submit_branch,
4746
 
                    public_branch=public_branch, patch_type=patch_type,
4747
 
                    message=message)
4748
 
 
4749
 
            outfile.writelines(directive.to_lines())
4750
 
            if output is None:
4751
 
                subject = '[MERGE] '
4752
 
                if message is not None:
4753
 
                    subject += message
4754
 
                else:
4755
 
                    revision = branch.repository.get_revision(revision_id)
4756
 
                    subject += revision.get_summary()
4757
 
                basename = directive.get_disk_name(branch)
4758
 
                mail_client.compose_merge_request(mail_to, subject,
4759
 
                                                  outfile.getvalue(), basename)
4760
 
        finally:
4761
 
            if output != '-':
4762
 
                outfile.close()
4763
 
            branch.unlock()
 
5218
            format=None, mail_to=None, message=None, body=None,
 
5219
            strict=None, **kwargs):
 
5220
        from bzrlib.send import send
 
5221
        return send(submit_branch, revision, public_branch, remember,
 
5222
                    format, no_bundle, no_patch, output,
 
5223
                    kwargs.get('from', '.'), mail_to, message, body,
 
5224
                    self.outf,
 
5225
                    strict=strict)
4764
5226
 
4765
5227
 
4766
5228
class cmd_bundle_revisions(cmd_send):
4767
 
 
4768
 
    """Create a merge-directive for submitting changes.
 
5229
    __doc__ = """Create a merge-directive for submitting changes.
4769
5230
 
4770
5231
    A merge directive provides many things needed for requesting merges:
4771
5232
 
4811
5272
               type=unicode),
4812
5273
        Option('output', short_name='o', help='Write directive to this file.',
4813
5274
               type=unicode),
 
5275
        Option('strict',
 
5276
               help='Refuse to bundle revisions if there are uncommitted'
 
5277
               ' changes in the working tree, --no-strict disables the check.'),
4814
5278
        'revision',
4815
 
        RegistryOption.from_kwargs('format',
4816
 
        'Use the specified output format.',
4817
 
        **{'4': 'Bundle format 4, Merge Directive 2 (default)',
4818
 
           '0.9': 'Bundle format 0.9, Merge Directive 1',})
 
5279
        RegistryOption('format',
 
5280
                       help='Use the specified output format.',
 
5281
                       lazy_registry=('bzrlib.send', 'format_registry')),
4819
5282
        ]
4820
5283
    aliases = ['bundle']
4821
5284
 
4825
5288
 
4826
5289
    def run(self, submit_branch=None, public_branch=None, no_bundle=False,
4827
5290
            no_patch=False, revision=None, remember=False, output=None,
4828
 
            format='4', **kwargs):
 
5291
            format=None, strict=None, **kwargs):
4829
5292
        if output is None:
4830
5293
            output = '-'
4831
 
        return self._run(submit_branch, revision, public_branch, remember,
 
5294
        from bzrlib.send import send
 
5295
        return send(submit_branch, revision, public_branch, remember,
4832
5296
                         format, no_bundle, no_patch, output,
4833
 
                         kwargs.get('from', '.'), None, None)
 
5297
                         kwargs.get('from', '.'), None, None, None,
 
5298
                         self.outf, strict=strict)
4834
5299
 
4835
5300
 
4836
5301
class cmd_tag(Command):
4837
 
    """Create, remove or modify a tag naming a revision.
4838
 
    
 
5302
    __doc__ = """Create, remove or modify a tag naming a revision.
 
5303
 
4839
5304
    Tags give human-meaningful names to revisions.  Commands that take a -r
4840
5305
    (--revision) option can be given -rtag:X, where X is any previously
4841
5306
    created tag.
4843
5308
    Tags are stored in the branch.  Tags are copied from one branch to another
4844
5309
    along when you branch, push, pull or merge.
4845
5310
 
4846
 
    It is an error to give a tag name that already exists unless you pass 
 
5311
    It is an error to give a tag name that already exists unless you pass
4847
5312
    --force, in which case the tag is moved to point to the new revision.
4848
5313
 
4849
5314
    To rename a tag (change the name but keep it on the same revsion), run ``bzr
4850
5315
    tag new-name -r tag:old-name`` and then ``bzr tag --delete oldname``.
 
5316
 
 
5317
    If no tag name is specified it will be determined through the 
 
5318
    'automatic_tag_name' hook. This can e.g. be used to automatically tag
 
5319
    upstream releases by reading configure.ac. See ``bzr help hooks`` for
 
5320
    details.
4851
5321
    """
4852
5322
 
4853
5323
    _see_also = ['commit', 'tags']
4854
 
    takes_args = ['tag_name']
 
5324
    takes_args = ['tag_name?']
4855
5325
    takes_options = [
4856
5326
        Option('delete',
4857
5327
            help='Delete this tag rather than placing it.',
4858
5328
            ),
4859
 
        Option('directory',
4860
 
            help='Branch in which to place the tag.',
4861
 
            short_name='d',
4862
 
            type=unicode,
4863
 
            ),
 
5329
        custom_help('directory',
 
5330
            help='Branch in which to place the tag.'),
4864
5331
        Option('force',
4865
5332
            help='Replace existing tags.',
4866
5333
            ),
4867
5334
        'revision',
4868
5335
        ]
4869
5336
 
4870
 
    def run(self, tag_name,
 
5337
    def run(self, tag_name=None,
4871
5338
            delete=None,
4872
5339
            directory='.',
4873
5340
            force=None,
4874
5341
            revision=None,
4875
5342
            ):
4876
5343
        branch, relpath = Branch.open_containing(directory)
4877
 
        branch.lock_write()
4878
 
        try:
4879
 
            if delete:
4880
 
                branch.tags.delete_tag(tag_name)
4881
 
                self.outf.write('Deleted tag %s.\n' % tag_name)
 
5344
        self.add_cleanup(branch.lock_write().unlock)
 
5345
        if delete:
 
5346
            if tag_name is None:
 
5347
                raise errors.BzrCommandError("No tag specified to delete.")
 
5348
            branch.tags.delete_tag(tag_name)
 
5349
            self.outf.write('Deleted tag %s.\n' % tag_name)
 
5350
        else:
 
5351
            if revision:
 
5352
                if len(revision) != 1:
 
5353
                    raise errors.BzrCommandError(
 
5354
                        "Tags can only be placed on a single revision, "
 
5355
                        "not on a range")
 
5356
                revision_id = revision[0].as_revision_id(branch)
4882
5357
            else:
4883
 
                if revision:
4884
 
                    if len(revision) != 1:
4885
 
                        raise errors.BzrCommandError(
4886
 
                            "Tags can only be placed on a single revision, "
4887
 
                            "not on a range")
4888
 
                    revision_id = revision[0].as_revision_id(branch)
4889
 
                else:
4890
 
                    revision_id = branch.last_revision()
4891
 
                if (not force) and branch.tags.has_tag(tag_name):
4892
 
                    raise errors.TagAlreadyExists(tag_name)
4893
 
                branch.tags.set_tag(tag_name, revision_id)
4894
 
                self.outf.write('Created tag %s.\n' % tag_name)
4895
 
        finally:
4896
 
            branch.unlock()
 
5358
                revision_id = branch.last_revision()
 
5359
            if tag_name is None:
 
5360
                tag_name = branch.automatic_tag_name(revision_id)
 
5361
                if tag_name is None:
 
5362
                    raise errors.BzrCommandError(
 
5363
                        "Please specify a tag name.")
 
5364
            if (not force) and branch.tags.has_tag(tag_name):
 
5365
                raise errors.TagAlreadyExists(tag_name)
 
5366
            branch.tags.set_tag(tag_name, revision_id)
 
5367
            self.outf.write('Created tag %s.\n' % tag_name)
4897
5368
 
4898
5369
 
4899
5370
class cmd_tags(Command):
4900
 
    """List tags.
 
5371
    __doc__ = """List tags.
4901
5372
 
4902
5373
    This command shows a table of tag names and the revisions they reference.
4903
5374
    """
4904
5375
 
4905
5376
    _see_also = ['tag']
4906
5377
    takes_options = [
4907
 
        Option('directory',
4908
 
            help='Branch whose tags should be displayed.',
4909
 
            short_name='d',
4910
 
            type=unicode,
4911
 
            ),
 
5378
        custom_help('directory',
 
5379
            help='Branch whose tags should be displayed.'),
4912
5380
        RegistryOption.from_kwargs('sort',
4913
5381
            'Sort tags by different criteria.', title='Sorting',
4914
5382
            alpha='Sort tags lexicographically (default).',
4931
5399
        if not tags:
4932
5400
            return
4933
5401
 
 
5402
        self.add_cleanup(branch.lock_read().unlock)
4934
5403
        if revision:
4935
 
            branch.lock_read()
4936
 
            try:
4937
 
                graph = branch.repository.get_graph()
4938
 
                rev1, rev2 = _get_revision_range(revision, branch, self.name())
4939
 
                revid1, revid2 = rev1.rev_id, rev2.rev_id
4940
 
                # only show revisions between revid1 and revid2 (inclusive)
4941
 
                tags = [(tag, revid) for tag, revid in tags if
4942
 
                    graph.is_between(revid, revid1, revid2)]
4943
 
            finally:
4944
 
                branch.unlock()
 
5404
            graph = branch.repository.get_graph()
 
5405
            rev1, rev2 = _get_revision_range(revision, branch, self.name())
 
5406
            revid1, revid2 = rev1.rev_id, rev2.rev_id
 
5407
            # only show revisions between revid1 and revid2 (inclusive)
 
5408
            tags = [(tag, revid) for tag, revid in tags if
 
5409
                graph.is_between(revid, revid1, revid2)]
4945
5410
        if sort == 'alpha':
4946
5411
            tags.sort()
4947
5412
        elif sort == 'time':
4957
5422
            tags.sort(key=lambda x: timestamps[x[1]])
4958
5423
        if not show_ids:
4959
5424
            # [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
4960
 
            revno_map = branch.get_revision_id_to_revno_map()
4961
 
            tags = [ (tag, '.'.join(map(str, revno_map.get(revid, ('?',)))))
4962
 
                        for tag, revid in tags ]
 
5425
            for index, (tag, revid) in enumerate(tags):
 
5426
                try:
 
5427
                    revno = branch.revision_id_to_dotted_revno(revid)
 
5428
                    if isinstance(revno, tuple):
 
5429
                        revno = '.'.join(map(str, revno))
 
5430
                except errors.NoSuchRevision:
 
5431
                    # Bad tag data/merges can lead to tagged revisions
 
5432
                    # which are not in this branch. Fail gracefully ...
 
5433
                    revno = '?'
 
5434
                tags[index] = (tag, revno)
 
5435
        self.cleanup_now()
4963
5436
        for tag, revspec in tags:
4964
5437
            self.outf.write('%-20s %s\n' % (tag, revspec))
4965
5438
 
4966
5439
 
4967
5440
class cmd_reconfigure(Command):
4968
 
    """Reconfigure the type of a bzr directory.
 
5441
    __doc__ = """Reconfigure the type of a bzr directory.
4969
5442
 
4970
5443
    A target configuration must be specified.
4971
5444
 
5001
5474
            ),
5002
5475
        Option('bind-to', help='Branch to bind checkout to.', type=str),
5003
5476
        Option('force',
5004
 
               help='Perform reconfiguration even if local changes'
5005
 
               ' will be lost.')
 
5477
            help='Perform reconfiguration even if local changes'
 
5478
            ' will be lost.'),
 
5479
        Option('stacked-on',
 
5480
            help='Reconfigure a branch to be stacked on another branch.',
 
5481
            type=unicode,
 
5482
            ),
 
5483
        Option('unstacked',
 
5484
            help='Reconfigure a branch to be unstacked.  This '
 
5485
                'may require copying substantial data into it.',
 
5486
            ),
5006
5487
        ]
5007
5488
 
5008
 
    def run(self, location=None, target_type=None, bind_to=None, force=False):
 
5489
    def run(self, location=None, target_type=None, bind_to=None, force=False,
 
5490
            stacked_on=None,
 
5491
            unstacked=None):
5009
5492
        directory = bzrdir.BzrDir.open(location)
 
5493
        if stacked_on and unstacked:
 
5494
            raise BzrCommandError("Can't use both --stacked-on and --unstacked")
 
5495
        elif stacked_on is not None:
 
5496
            reconfigure.ReconfigureStackedOn().apply(directory, stacked_on)
 
5497
        elif unstacked:
 
5498
            reconfigure.ReconfigureUnstacked().apply(directory)
 
5499
        # At the moment you can use --stacked-on and a different
 
5500
        # reconfiguration shape at the same time; there seems no good reason
 
5501
        # to ban it.
5010
5502
        if target_type is None:
5011
 
            raise errors.BzrCommandError('No target configuration specified')
 
5503
            if stacked_on or unstacked:
 
5504
                return
 
5505
            else:
 
5506
                raise errors.BzrCommandError('No target configuration '
 
5507
                    'specified')
5012
5508
        elif target_type == 'branch':
5013
5509
            reconfiguration = reconfigure.Reconfigure.to_branch(directory)
5014
5510
        elif target_type == 'tree':
5033
5529
 
5034
5530
 
5035
5531
class cmd_switch(Command):
5036
 
    """Set the branch of a checkout and update.
5037
 
    
 
5532
    __doc__ = """Set the branch of a checkout and update.
 
5533
 
5038
5534
    For lightweight checkouts, this changes the branch being referenced.
5039
5535
    For heavyweight checkouts, this checks that there are no local commits
5040
5536
    versus the current bound branch, then it makes the local branch a mirror
5051
5547
    /path/to/newbranch.
5052
5548
 
5053
5549
    Bound branches use the nickname of its master branch unless it is set
5054
 
    locally, in which case switching will update the the local nickname to be
 
5550
    locally, in which case switching will update the local nickname to be
5055
5551
    that of the master.
5056
5552
    """
5057
5553
 
5058
 
    takes_args = ['to_location']
5059
 
    takes_options = [Option('force',
5060
 
                        help='Switch even if local commits will be lost.')
5061
 
                     ]
 
5554
    takes_args = ['to_location?']
 
5555
    takes_options = ['directory',
 
5556
                     Option('force',
 
5557
                        help='Switch even if local commits will be lost.'),
 
5558
                     'revision',
 
5559
                     Option('create-branch', short_name='b',
 
5560
                        help='Create the target branch from this one before'
 
5561
                             ' switching to it.'),
 
5562
                    ]
5062
5563
 
5063
 
    def run(self, to_location, force=False):
 
5564
    def run(self, to_location=None, force=False, create_branch=False,
 
5565
            revision=None, directory=u'.'):
5064
5566
        from bzrlib import switch
5065
 
        tree_location = '.'
 
5567
        tree_location = directory
 
5568
        revision = _get_one_revision('switch', revision)
5066
5569
        control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
5067
 
        branch = control_dir.open_branch()
 
5570
        if to_location is None:
 
5571
            if revision is None:
 
5572
                raise errors.BzrCommandError('You must supply either a'
 
5573
                                             ' revision or a location')
 
5574
            to_location = tree_location
5068
5575
        try:
5069
 
            to_branch = Branch.open(to_location)
 
5576
            branch = control_dir.open_branch()
 
5577
            had_explicit_nick = branch.get_config().has_explicit_nickname()
5070
5578
        except errors.NotBranchError:
5071
 
            this_branch = control_dir.open_branch()
5072
 
            # This may be a heavy checkout, where we want the master branch
5073
 
            this_url = this_branch.get_bound_location()
5074
 
            # If not, use a local sibling
5075
 
            if this_url is None:
5076
 
                this_url = this_branch.base
5077
 
            to_branch = Branch.open(
5078
 
                urlutils.join(this_url, '..', to_location))
5079
 
        switch.switch(control_dir, to_branch, force)
5080
 
        if branch.get_config().has_explicit_nickname():
 
5579
            branch = None
 
5580
            had_explicit_nick = False
 
5581
        if create_branch:
 
5582
            if branch is None:
 
5583
                raise errors.BzrCommandError('cannot create branch without'
 
5584
                                             ' source branch')
 
5585
            to_location = directory_service.directories.dereference(
 
5586
                              to_location)
 
5587
            if '/' not in to_location and '\\' not in to_location:
 
5588
                # This path is meant to be relative to the existing branch
 
5589
                this_url = self._get_branch_location(control_dir)
 
5590
                to_location = urlutils.join(this_url, '..', to_location)
 
5591
            to_branch = branch.bzrdir.sprout(to_location,
 
5592
                                 possible_transports=[branch.bzrdir.root_transport],
 
5593
                                 source_branch=branch).open_branch()
 
5594
        else:
 
5595
            try:
 
5596
                to_branch = Branch.open(to_location)
 
5597
            except errors.NotBranchError:
 
5598
                this_url = self._get_branch_location(control_dir)
 
5599
                to_branch = Branch.open(
 
5600
                    urlutils.join(this_url, '..', to_location))
 
5601
        if revision is not None:
 
5602
            revision = revision.as_revision_id(to_branch)
 
5603
        switch.switch(control_dir, to_branch, force, revision_id=revision)
 
5604
        if had_explicit_nick:
5081
5605
            branch = control_dir.open_branch() #get the new branch!
5082
5606
            branch.nick = to_branch.nick
5083
5607
        note('Switched to branch: %s',
5084
5608
            urlutils.unescape_for_display(to_branch.base, 'utf-8'))
5085
5609
 
 
5610
    def _get_branch_location(self, control_dir):
 
5611
        """Return location of branch for this control dir."""
 
5612
        try:
 
5613
            this_branch = control_dir.open_branch()
 
5614
            # This may be a heavy checkout, where we want the master branch
 
5615
            master_location = this_branch.get_bound_location()
 
5616
            if master_location is not None:
 
5617
                return master_location
 
5618
            # If not, use a local sibling
 
5619
            return this_branch.base
 
5620
        except errors.NotBranchError:
 
5621
            format = control_dir.find_branch_format()
 
5622
            if getattr(format, 'get_reference', None) is not None:
 
5623
                return format.get_reference(control_dir)
 
5624
            else:
 
5625
                return control_dir.root_transport.base
 
5626
 
 
5627
 
 
5628
class cmd_view(Command):
 
5629
    __doc__ = """Manage filtered views.
 
5630
 
 
5631
    Views provide a mask over the tree so that users can focus on
 
5632
    a subset of a tree when doing their work. After creating a view,
 
5633
    commands that support a list of files - status, diff, commit, etc -
 
5634
    effectively have that list of files implicitly given each time.
 
5635
    An explicit list of files can still be given but those files
 
5636
    must be within the current view.
 
5637
 
 
5638
    In most cases, a view has a short life-span: it is created to make
 
5639
    a selected change and is deleted once that change is committed.
 
5640
    At other times, you may wish to create one or more named views
 
5641
    and switch between them.
 
5642
 
 
5643
    To disable the current view without deleting it, you can switch to
 
5644
    the pseudo view called ``off``. This can be useful when you need
 
5645
    to see the whole tree for an operation or two (e.g. merge) but
 
5646
    want to switch back to your view after that.
 
5647
 
 
5648
    :Examples:
 
5649
      To define the current view::
 
5650
 
 
5651
        bzr view file1 dir1 ...
 
5652
 
 
5653
      To list the current view::
 
5654
 
 
5655
        bzr view
 
5656
 
 
5657
      To delete the current view::
 
5658
 
 
5659
        bzr view --delete
 
5660
 
 
5661
      To disable the current view without deleting it::
 
5662
 
 
5663
        bzr view --switch off
 
5664
 
 
5665
      To define a named view and switch to it::
 
5666
 
 
5667
        bzr view --name view-name file1 dir1 ...
 
5668
 
 
5669
      To list a named view::
 
5670
 
 
5671
        bzr view --name view-name
 
5672
 
 
5673
      To delete a named view::
 
5674
 
 
5675
        bzr view --name view-name --delete
 
5676
 
 
5677
      To switch to a named view::
 
5678
 
 
5679
        bzr view --switch view-name
 
5680
 
 
5681
      To list all views defined::
 
5682
 
 
5683
        bzr view --all
 
5684
 
 
5685
      To delete all views::
 
5686
 
 
5687
        bzr view --delete --all
 
5688
    """
 
5689
 
 
5690
    _see_also = []
 
5691
    takes_args = ['file*']
 
5692
    takes_options = [
 
5693
        Option('all',
 
5694
            help='Apply list or delete action to all views.',
 
5695
            ),
 
5696
        Option('delete',
 
5697
            help='Delete the view.',
 
5698
            ),
 
5699
        Option('name',
 
5700
            help='Name of the view to define, list or delete.',
 
5701
            type=unicode,
 
5702
            ),
 
5703
        Option('switch',
 
5704
            help='Name of the view to switch to.',
 
5705
            type=unicode,
 
5706
            ),
 
5707
        ]
 
5708
 
 
5709
    def run(self, file_list,
 
5710
            all=False,
 
5711
            delete=False,
 
5712
            name=None,
 
5713
            switch=None,
 
5714
            ):
 
5715
        tree, file_list = tree_files(file_list, apply_view=False)
 
5716
        current_view, view_dict = tree.views.get_view_info()
 
5717
        if name is None:
 
5718
            name = current_view
 
5719
        if delete:
 
5720
            if file_list:
 
5721
                raise errors.BzrCommandError(
 
5722
                    "Both --delete and a file list specified")
 
5723
            elif switch:
 
5724
                raise errors.BzrCommandError(
 
5725
                    "Both --delete and --switch specified")
 
5726
            elif all:
 
5727
                tree.views.set_view_info(None, {})
 
5728
                self.outf.write("Deleted all views.\n")
 
5729
            elif name is None:
 
5730
                raise errors.BzrCommandError("No current view to delete")
 
5731
            else:
 
5732
                tree.views.delete_view(name)
 
5733
                self.outf.write("Deleted '%s' view.\n" % name)
 
5734
        elif switch:
 
5735
            if file_list:
 
5736
                raise errors.BzrCommandError(
 
5737
                    "Both --switch and a file list specified")
 
5738
            elif all:
 
5739
                raise errors.BzrCommandError(
 
5740
                    "Both --switch and --all specified")
 
5741
            elif switch == 'off':
 
5742
                if current_view is None:
 
5743
                    raise errors.BzrCommandError("No current view to disable")
 
5744
                tree.views.set_view_info(None, view_dict)
 
5745
                self.outf.write("Disabled '%s' view.\n" % (current_view))
 
5746
            else:
 
5747
                tree.views.set_view_info(switch, view_dict)
 
5748
                view_str = views.view_display_str(tree.views.lookup_view())
 
5749
                self.outf.write("Using '%s' view: %s\n" % (switch, view_str))
 
5750
        elif all:
 
5751
            if view_dict:
 
5752
                self.outf.write('Views defined:\n')
 
5753
                for view in sorted(view_dict):
 
5754
                    if view == current_view:
 
5755
                        active = "=>"
 
5756
                    else:
 
5757
                        active = "  "
 
5758
                    view_str = views.view_display_str(view_dict[view])
 
5759
                    self.outf.write('%s %-20s %s\n' % (active, view, view_str))
 
5760
            else:
 
5761
                self.outf.write('No views defined.\n')
 
5762
        elif file_list:
 
5763
            if name is None:
 
5764
                # No name given and no current view set
 
5765
                name = 'my'
 
5766
            elif name == 'off':
 
5767
                raise errors.BzrCommandError(
 
5768
                    "Cannot change the 'off' pseudo view")
 
5769
            tree.views.set_view(name, sorted(file_list))
 
5770
            view_str = views.view_display_str(tree.views.lookup_view())
 
5771
            self.outf.write("Using '%s' view: %s\n" % (name, view_str))
 
5772
        else:
 
5773
            # list the files
 
5774
            if name is None:
 
5775
                # No name given and no current view set
 
5776
                self.outf.write('No current view.\n')
 
5777
            else:
 
5778
                view_str = views.view_display_str(tree.views.lookup_view(name))
 
5779
                self.outf.write("'%s' view is: %s\n" % (name, view_str))
 
5780
 
5086
5781
 
5087
5782
class cmd_hooks(Command):
5088
 
    """Show a branch's currently registered hooks.
 
5783
    __doc__ = """Show hooks."""
 
5784
 
 
5785
    hidden = True
 
5786
 
 
5787
    def run(self):
 
5788
        for hook_key in sorted(hooks.known_hooks.keys()):
 
5789
            some_hooks = hooks.known_hooks_key_to_object(hook_key)
 
5790
            self.outf.write("%s:\n" % type(some_hooks).__name__)
 
5791
            for hook_name, hook_point in sorted(some_hooks.items()):
 
5792
                self.outf.write("  %s:\n" % (hook_name,))
 
5793
                found_hooks = list(hook_point)
 
5794
                if found_hooks:
 
5795
                    for hook in found_hooks:
 
5796
                        self.outf.write("    %s\n" %
 
5797
                                        (some_hooks.get_hook_name(hook),))
 
5798
                else:
 
5799
                    self.outf.write("    <no hooks installed>\n")
 
5800
 
 
5801
 
 
5802
class cmd_remove_branch(Command):
 
5803
    __doc__ = """Remove a branch.
 
5804
 
 
5805
    This will remove the branch from the specified location but 
 
5806
    will keep any working tree or repository in place.
 
5807
 
 
5808
    :Examples:
 
5809
 
 
5810
      Remove the branch at repo/trunk::
 
5811
 
 
5812
        bzr remove-branch repo/trunk
 
5813
 
5089
5814
    """
5090
5815
 
5091
 
    hidden = True
5092
 
    takes_args = ['path?']
5093
 
 
5094
 
    def run(self, path=None):
5095
 
        if path is None:
5096
 
            path = '.'
5097
 
        branch_hooks = Branch.open(path).hooks
5098
 
        for hook_type in branch_hooks:
5099
 
            hooks = branch_hooks[hook_type]
5100
 
            self.outf.write("%s:\n" % (hook_type,))
5101
 
            if hooks:
5102
 
                for hook in hooks:
5103
 
                    self.outf.write("  %s\n" %
5104
 
                                    (branch_hooks.get_hook_name(hook),))
5105
 
            else:
5106
 
                self.outf.write("  <no hooks installed>\n")
5107
 
 
 
5816
    takes_args = ["location?"]
 
5817
 
 
5818
    aliases = ["rmbranch"]
 
5819
 
 
5820
    def run(self, location=None):
 
5821
        if location is None:
 
5822
            location = "."
 
5823
        branch = Branch.open_containing(location)[0]
 
5824
        branch.bzrdir.destroy_branch()
 
5825
        
5108
5826
 
5109
5827
class cmd_shelve(Command):
5110
 
    """Temporarily set aside some changes from the current tree.
 
5828
    __doc__ = """Temporarily set aside some changes from the current tree.
5111
5829
 
5112
5830
    Shelve allows you to temporarily put changes you've made "on the shelf",
5113
5831
    ie. out of the way, until a later time when you can bring them back from
5134
5852
    takes_args = ['file*']
5135
5853
 
5136
5854
    takes_options = [
 
5855
        'directory',
5137
5856
        'revision',
5138
5857
        Option('all', help='Shelve all changes.'),
5139
5858
        'message',
5142
5861
                       value_switches=True, enum_switch=False),
5143
5862
 
5144
5863
        Option('list', help='List shelved changes.'),
 
5864
        Option('destroy',
 
5865
               help='Destroy removed changes instead of shelving them.'),
5145
5866
    ]
5146
5867
    _see_also = ['unshelve']
5147
5868
 
5148
5869
    def run(self, revision=None, all=False, file_list=None, message=None,
5149
 
            writer=None, list=False):
 
5870
            writer=None, list=False, destroy=False, directory=u'.'):
5150
5871
        if list:
5151
5872
            return self.run_for_list()
5152
5873
        from bzrlib.shelf_ui import Shelver
5153
5874
        if writer is None:
5154
5875
            writer = bzrlib.option.diff_writer_registry.get()
5155
5876
        try:
5156
 
            Shelver.from_args(writer(sys.stdout), revision, all, file_list,
5157
 
                              message).run()
 
5877
            shelver = Shelver.from_args(writer(sys.stdout), revision, all,
 
5878
                file_list, message, destroy=destroy, directory=directory)
 
5879
            try:
 
5880
                shelver.run()
 
5881
            finally:
 
5882
                shelver.finalize()
5158
5883
        except errors.UserAbort:
5159
5884
            return 0
5160
5885
 
5161
5886
    def run_for_list(self):
5162
5887
        tree = WorkingTree.open_containing('.')[0]
5163
 
        tree.lock_read()
5164
 
        try:
5165
 
            manager = tree.get_shelf_manager()
5166
 
            shelves = manager.active_shelves()
5167
 
            if len(shelves) == 0:
5168
 
                note('No shelved changes.')
5169
 
                return 0
5170
 
            for shelf_id in reversed(shelves):
5171
 
                message = manager.get_metadata(shelf_id).get('message')
5172
 
                if message is None:
5173
 
                    message = '<no message>'
5174
 
                self.outf.write('%3d: %s\n' % (shelf_id, message))
5175
 
            return 1
5176
 
        finally:
5177
 
            tree.unlock()
 
5888
        self.add_cleanup(tree.lock_read().unlock)
 
5889
        manager = tree.get_shelf_manager()
 
5890
        shelves = manager.active_shelves()
 
5891
        if len(shelves) == 0:
 
5892
            note('No shelved changes.')
 
5893
            return 0
 
5894
        for shelf_id in reversed(shelves):
 
5895
            message = manager.get_metadata(shelf_id).get('message')
 
5896
            if message is None:
 
5897
                message = '<no message>'
 
5898
            self.outf.write('%3d: %s\n' % (shelf_id, message))
 
5899
        return 1
5178
5900
 
5179
5901
 
5180
5902
class cmd_unshelve(Command):
5181
 
    """Restore shelved changes.
 
5903
    __doc__ = """Restore shelved changes.
5182
5904
 
5183
5905
    By default, the most recently shelved changes are restored. However if you
5184
5906
    specify a shelf by id those changes will be restored instead.  This works
5187
5909
 
5188
5910
    takes_args = ['shelf_id?']
5189
5911
    takes_options = [
 
5912
        'directory',
5190
5913
        RegistryOption.from_kwargs(
5191
5914
            'action', help="The action to perform.",
5192
5915
            enum_switch=False, value_switches=True,
5193
5916
            apply="Apply changes and remove from the shelf.",
5194
5917
            dry_run="Show changes, but do not apply or remove them.",
5195
 
            delete_only="Delete changes without applying them."
 
5918
            preview="Instead of unshelving the changes, show the diff that "
 
5919
                    "would result from unshelving.",
 
5920
            delete_only="Delete changes without applying them.",
 
5921
            keep="Apply changes but don't delete them.",
5196
5922
        )
5197
5923
    ]
5198
5924
    _see_also = ['shelve']
5199
5925
 
5200
 
    def run(self, shelf_id=None, action='apply'):
 
5926
    def run(self, shelf_id=None, action='apply', directory=u'.'):
5201
5927
        from bzrlib.shelf_ui import Unshelver
5202
 
        Unshelver.from_args(shelf_id, action).run()
5203
 
 
5204
 
 
5205
 
def _create_prefix(cur_transport):
5206
 
    needed = [cur_transport]
5207
 
    # Recurse upwards until we can create a directory successfully
5208
 
    while True:
5209
 
        new_transport = cur_transport.clone('..')
5210
 
        if new_transport.base == cur_transport.base:
5211
 
            raise errors.BzrCommandError(
5212
 
                "Failed to create path prefix for %s."
5213
 
                % cur_transport.base)
 
5928
        unshelver = Unshelver.from_args(shelf_id, action, directory=directory)
5214
5929
        try:
5215
 
            new_transport.mkdir('.')
5216
 
        except errors.NoSuchFile:
5217
 
            needed.append(new_transport)
5218
 
            cur_transport = new_transport
 
5930
            unshelver.run()
 
5931
        finally:
 
5932
            unshelver.tree.unlock()
 
5933
 
 
5934
 
 
5935
class cmd_clean_tree(Command):
 
5936
    __doc__ = """Remove unwanted files from working tree.
 
5937
 
 
5938
    By default, only unknown files, not ignored files, are deleted.  Versioned
 
5939
    files are never deleted.
 
5940
 
 
5941
    Another class is 'detritus', which includes files emitted by bzr during
 
5942
    normal operations and selftests.  (The value of these files decreases with
 
5943
    time.)
 
5944
 
 
5945
    If no options are specified, unknown files are deleted.  Otherwise, option
 
5946
    flags are respected, and may be combined.
 
5947
 
 
5948
    To check what clean-tree will do, use --dry-run.
 
5949
    """
 
5950
    takes_options = ['directory',
 
5951
                     Option('ignored', help='Delete all ignored files.'),
 
5952
                     Option('detritus', help='Delete conflict files, merge'
 
5953
                            ' backups, and failed selftest dirs.'),
 
5954
                     Option('unknown',
 
5955
                            help='Delete files unknown to bzr (default).'),
 
5956
                     Option('dry-run', help='Show files to delete instead of'
 
5957
                            ' deleting them.'),
 
5958
                     Option('force', help='Do not prompt before deleting.')]
 
5959
    def run(self, unknown=False, ignored=False, detritus=False, dry_run=False,
 
5960
            force=False, directory=u'.'):
 
5961
        from bzrlib.clean_tree import clean_tree
 
5962
        if not (unknown or ignored or detritus):
 
5963
            unknown = True
 
5964
        if dry_run:
 
5965
            force = True
 
5966
        clean_tree(directory, unknown=unknown, ignored=ignored,
 
5967
                   detritus=detritus, dry_run=dry_run, no_prompt=force)
 
5968
 
 
5969
 
 
5970
class cmd_reference(Command):
 
5971
    __doc__ = """list, view and set branch locations for nested trees.
 
5972
 
 
5973
    If no arguments are provided, lists the branch locations for nested trees.
 
5974
    If one argument is provided, display the branch location for that tree.
 
5975
    If two arguments are provided, set the branch location for that tree.
 
5976
    """
 
5977
 
 
5978
    hidden = True
 
5979
 
 
5980
    takes_args = ['path?', 'location?']
 
5981
 
 
5982
    def run(self, path=None, location=None):
 
5983
        branchdir = '.'
 
5984
        if path is not None:
 
5985
            branchdir = path
 
5986
        tree, branch, relpath =(
 
5987
            bzrdir.BzrDir.open_containing_tree_or_branch(branchdir))
 
5988
        if path is not None:
 
5989
            path = relpath
 
5990
        if tree is None:
 
5991
            tree = branch.basis_tree()
 
5992
        if path is None:
 
5993
            info = branch._get_all_reference_info().iteritems()
 
5994
            self._display_reference_info(tree, branch, info)
5219
5995
        else:
5220
 
            break
5221
 
    # Now we only need to create child directories
5222
 
    while needed:
5223
 
        cur_transport = needed.pop()
5224
 
        cur_transport.ensure_base()
5225
 
 
5226
 
 
5227
 
# these get imported and then picked up by the scan for cmd_*
5228
 
# TODO: Some more consistent way to split command definitions across files;
5229
 
# we do need to load at least some information about them to know of 
5230
 
# aliases.  ideally we would avoid loading the implementation until the
5231
 
# details were needed.
5232
 
from bzrlib.cmd_version_info import cmd_version_info
5233
 
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore
5234
 
from bzrlib.bundle.commands import (
5235
 
    cmd_bundle_info,
5236
 
    )
5237
 
from bzrlib.sign_my_commits import cmd_sign_my_commits
5238
 
from bzrlib.weave_commands import cmd_versionedfile_list, \
5239
 
        cmd_weave_plan_merge, cmd_weave_merge_text
 
5996
            file_id = tree.path2id(path)
 
5997
            if file_id is None:
 
5998
                raise errors.NotVersionedError(path)
 
5999
            if location is None:
 
6000
                info = [(file_id, branch.get_reference_info(file_id))]
 
6001
                self._display_reference_info(tree, branch, info)
 
6002
            else:
 
6003
                branch.set_reference_info(file_id, path, location)
 
6004
 
 
6005
    def _display_reference_info(self, tree, branch, info):
 
6006
        ref_list = []
 
6007
        for file_id, (path, location) in info:
 
6008
            try:
 
6009
                path = tree.id2path(file_id)
 
6010
            except errors.NoSuchId:
 
6011
                pass
 
6012
            ref_list.append((path, location))
 
6013
        for path, location in sorted(ref_list):
 
6014
            self.outf.write('%s %s\n' % (path, location))
 
6015
 
 
6016
 
 
6017
def _register_lazy_builtins():
 
6018
    # register lazy builtins from other modules; called at startup and should
 
6019
    # be only called once.
 
6020
    for (name, aliases, module_name) in [
 
6021
        ('cmd_bundle_info', [], 'bzrlib.bundle.commands'),
 
6022
        ('cmd_dpush', [], 'bzrlib.foreign'),
 
6023
        ('cmd_version_info', [], 'bzrlib.cmd_version_info'),
 
6024
        ('cmd_resolve', ['resolved'], 'bzrlib.conflicts'),
 
6025
        ('cmd_conflicts', [], 'bzrlib.conflicts'),
 
6026
        ('cmd_sign_my_commits', [], 'bzrlib.sign_my_commits'),
 
6027
        ]:
 
6028
        builtin_command_registry.register_lazy(name, aliases, module_name)