/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/builtins.py

  • Committer: John Arbash Meinel
  • Date: 2008-10-08 20:40:23 UTC
  • mto: This revision was merged to the branch mainline in revision 3773.
  • Revision ID: john@arbash-meinel.com-20081008204023-z1u32sjby509wl12
First draft of a basic dump-btree command.

Does enough for what I need with pack-names files, but I'd like it to be a
bit more 'raw'.

Show diffs side-by-side

added added

removed removed

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