/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: 2009-01-12 01:55:34 UTC
  • mto: (3995.8.2 prepare-1.12)
  • mto: This revision was merged to the branch mainline in revision 4007.
  • Revision ID: mhammond@skippinet.com.au-20090112015534-yfxg50p7mpds9j4v
Include all .html files from the tortoise doc directory.

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