/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: Mark Hammond
  • Date: 2008-12-21 07:42:20 UTC
  • mfrom: (3915 +trunk)
  • mto: (3932.3.1 cicp-1.11)
  • mto: This revision was merged to the branch mainline in revision 3937.
  • Revision ID: mhammond@skippinet.com.au-20081221074220-7dr5oydglxyyvic3
Merge trunk.

Show diffs side-by-side

added added

removed removed

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