/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: Marius Kruger
  • Date: 2009-01-02 09:47:53 UTC
  • mto: (3969.1.1 ianc-integration)
  • mto: This revision was merged to the branch mainline in revision 3970.
  • Revision ID: amanic@gmail.com-20090102094753-8h0o3sxfvwz5wv9c
* add some blackbox tests and another whitebox test
* don't import _parse_revision_str lazily
* remove some unneeded todos I added

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