/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-01 22:08:22 UTC
  • mto: (3969.1.1 ianc-integration)
  • mto: This revision was merged to the branch mainline in revision 3970.
  • Revision ID: amanic@gmail.com-20090101220822-iopb8ag69ie4auno
* fix some indentation anomalies in cmd_missing
* note that the `missing` revision filters are inclusive
* some minor white space cleanups
* add some param docstrings for missing.find_unmerged

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