/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: Daniel Watkins
  • Date: 2009-02-07 23:54:41 UTC
  • mto: (3993.1.1 ianc-integration)
  • mto: This revision was merged to the branch mainline in revision 3994.
  • Revision ID: daniel@daniel-watkins.co.uk-20090207235441-igbvmxlrs7nz966p
Changed from option type to helper function.

Show diffs side-by-side

added added

removed removed

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