/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: Robert Collins
  • Date: 2007-04-23 03:41:48 UTC
  • mfrom: (2387.2.1 cleanassertions)
  • mto: This revision was merged to the branch mainline in revision 2444.
  • Revision ID: robertc@robertcollins.net-20070423034148-b4m9c1iwl7528prf
Review feedback.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2004, 2005, 2006, 2007 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
from StringIO import StringIO
 
21
 
 
22
from bzrlib.lazy_import import lazy_import
 
23
lazy_import(globals(), """
 
24
import codecs
 
25
import errno
 
26
import smtplib
 
27
import sys
 
28
import tempfile
 
29
import time
 
30
 
 
31
import bzrlib
 
32
from bzrlib import (
 
33
    branch,
 
34
    bundle,
 
35
    bzrdir,
 
36
    delta,
 
37
    config,
 
38
    errors,
 
39
    globbing,
 
40
    ignores,
 
41
    log,
 
42
    merge as _mod_merge,
 
43
    merge_directive,
 
44
    osutils,
 
45
    registry,
 
46
    repository,
 
47
    symbol_versioning,
 
48
    transport,
 
49
    tree as _mod_tree,
 
50
    ui,
 
51
    urlutils,
 
52
    )
 
53
from bzrlib.branch import Branch
 
54
from bzrlib.bundle.apply_bundle import install_bundle, merge_bundle
 
55
from bzrlib.conflicts import ConflictList
 
56
from bzrlib.revision import common_ancestor
 
57
from bzrlib.revisionspec import RevisionSpec
 
58
from bzrlib.workingtree import WorkingTree
 
59
""")
 
60
 
 
61
from bzrlib.commands import Command, display_command
 
62
from bzrlib.option import Option, RegistryOption
 
63
from bzrlib.progress import DummyProgress, ProgressPhase
 
64
from bzrlib.trace import mutter, note, log_error, warning, is_quiet, info
 
65
 
 
66
 
 
67
def tree_files(file_list, default_branch=u'.'):
 
68
    try:
 
69
        return internal_tree_files(file_list, default_branch)
 
70
    except errors.FileInWrongBranch, e:
 
71
        raise errors.BzrCommandError("%s is not in the same branch as %s" %
 
72
                                     (e.path, file_list[0]))
 
73
 
 
74
 
 
75
# XXX: Bad function name; should possibly also be a class method of
 
76
# WorkingTree rather than a function.
 
77
def internal_tree_files(file_list, default_branch=u'.'):
 
78
    """Convert command-line paths to a WorkingTree and relative paths.
 
79
 
 
80
    This is typically used for command-line processors that take one or
 
81
    more filenames, and infer the workingtree that contains them.
 
82
 
 
83
    The filenames given are not required to exist.
 
84
 
 
85
    :param file_list: Filenames to convert.  
 
86
 
 
87
    :param default_branch: Fallback tree path to use if file_list is empty or
 
88
        None.
 
89
 
 
90
    :return: workingtree, [relative_paths]
 
91
    """
 
92
    if file_list is None or len(file_list) == 0:
 
93
        return WorkingTree.open_containing(default_branch)[0], file_list
 
94
    tree = WorkingTree.open_containing(osutils.realpath(file_list[0]))[0]
 
95
    new_list = []
 
96
    for filename in file_list:
 
97
        try:
 
98
            new_list.append(tree.relpath(osutils.dereference_path(filename)))
 
99
        except errors.PathNotChild:
 
100
            raise errors.FileInWrongBranch(tree.branch, filename)
 
101
    return tree, new_list
 
102
 
 
103
 
 
104
@symbol_versioning.deprecated_function(symbol_versioning.zero_fifteen)
 
105
def get_format_type(typestring):
 
106
    """Parse and return a format specifier."""
 
107
    # Have to use BzrDirMetaFormat1 directly, so that
 
108
    # RepositoryFormat.set_default_format works
 
109
    if typestring == "default":
 
110
        return bzrdir.BzrDirMetaFormat1()
 
111
    try:
 
112
        return bzrdir.format_registry.make_bzrdir(typestring)
 
113
    except KeyError:
 
114
        msg = 'Unknown bzr format "%s". See "bzr help formats".' % typestring
 
115
        raise errors.BzrCommandError(msg)
 
116
 
 
117
 
 
118
# TODO: Make sure no commands unconditionally use the working directory as a
 
119
# branch.  If a filename argument is used, the first of them should be used to
 
120
# specify the branch.  (Perhaps this can be factored out into some kind of
 
121
# Argument class, representing a file in a branch, where the first occurrence
 
122
# opens the branch?)
 
123
 
 
124
class cmd_status(Command):
 
125
    """Display status summary.
 
126
 
 
127
    This reports on versioned and unknown files, reporting them
 
128
    grouped by state.  Possible states are:
 
129
 
 
130
    added
 
131
        Versioned in the working copy but not in the previous revision.
 
132
 
 
133
    removed
 
134
        Versioned in the previous revision but removed or deleted
 
135
        in the working copy.
 
136
 
 
137
    renamed
 
138
        Path of this file changed from the previous revision;
 
139
        the text may also have changed.  This includes files whose
 
140
        parent directory was renamed.
 
141
 
 
142
    modified
 
143
        Text has changed since the previous revision.
 
144
 
 
145
    kind changed
 
146
        File kind has been changed (e.g. from file to directory).
 
147
 
 
148
    unknown
 
149
        Not versioned and not matching an ignore pattern.
 
150
 
 
151
    To see ignored files use 'bzr ignored'.  For details on the
 
152
    changes to file texts, use 'bzr diff'.
 
153
    
 
154
    --short gives a status flags for each item, similar to the SVN's status
 
155
    command.
 
156
 
 
157
    Column 1: versioning / renames
 
158
      + File versioned
 
159
      - File unversioned
 
160
      R File renamed
 
161
      ? File unknown
 
162
      C File has conflicts
 
163
      P Entry for a pending merge (not a file)
 
164
 
 
165
    Column 2: Contents
 
166
      N File created
 
167
      D File deleted
 
168
      K File kind changed
 
169
      M File modified
 
170
 
 
171
    Column 3: Execute
 
172
      * The execute bit was changed
 
173
 
 
174
    If no arguments are specified, the status of the entire working
 
175
    directory is shown.  Otherwise, only the status of the specified
 
176
    files or directories is reported.  If a directory is given, status
 
177
    is reported for everything inside that directory.
 
178
 
 
179
    If a revision argument is given, the status is calculated against
 
180
    that revision, or between two revisions if two are provided.
 
181
    """
 
182
    
 
183
    # TODO: --no-recurse, --recurse options
 
184
    
 
185
    takes_args = ['file*']
 
186
    takes_options = ['show-ids', 'revision',
 
187
                     Option('short', help='Give short SVN-style status lines'),
 
188
                     Option('versioned', help='Only show versioned files')]
 
189
    aliases = ['st', 'stat']
 
190
 
 
191
    encoding_type = 'replace'
 
192
    _see_also = ['diff', 'revert']
 
193
    
 
194
    @display_command
 
195
    def run(self, show_ids=False, file_list=None, revision=None, short=False,
 
196
            versioned=False):
 
197
        from bzrlib.status import show_tree_status
 
198
 
 
199
        tree, file_list = tree_files(file_list)
 
200
            
 
201
        show_tree_status(tree, show_ids=show_ids,
 
202
                         specific_files=file_list, revision=revision,
 
203
                         to_file=self.outf, short=short, versioned=versioned)
 
204
 
 
205
 
 
206
class cmd_cat_revision(Command):
 
207
    """Write out metadata for a revision.
 
208
    
 
209
    The revision to print can either be specified by a specific
 
210
    revision identifier, or you can use --revision.
 
211
    """
 
212
 
 
213
    hidden = True
 
214
    takes_args = ['revision_id?']
 
215
    takes_options = ['revision']
 
216
    # cat-revision is more for frontends so should be exact
 
217
    encoding = 'strict'
 
218
    
 
219
    @display_command
 
220
    def run(self, revision_id=None, revision=None):
 
221
 
 
222
        revision_id = osutils.safe_revision_id(revision_id, warn=False)
 
223
        if revision_id is not None and revision is not None:
 
224
            raise errors.BzrCommandError('You can only supply one of'
 
225
                                         ' revision_id or --revision')
 
226
        if revision_id is None and revision is None:
 
227
            raise errors.BzrCommandError('You must supply either'
 
228
                                         ' --revision or a revision_id')
 
229
        b = WorkingTree.open_containing(u'.')[0].branch
 
230
 
 
231
        # TODO: jam 20060112 should cat-revision always output utf-8?
 
232
        if revision_id is not None:
 
233
            self.outf.write(b.repository.get_revision_xml(revision_id).decode('utf-8'))
 
234
        elif revision is not None:
 
235
            for rev in revision:
 
236
                if rev is None:
 
237
                    raise errors.BzrCommandError('You cannot specify a NULL'
 
238
                                                 ' revision.')
 
239
                revno, rev_id = rev.in_history(b)
 
240
                self.outf.write(b.repository.get_revision_xml(rev_id).decode('utf-8'))
 
241
    
 
242
 
 
243
class cmd_remove_tree(Command):
 
244
    """Remove the working tree from a given branch/checkout.
 
245
 
 
246
    Since a lightweight checkout is little more than a working tree
 
247
    this will refuse to run against one.
 
248
 
 
249
    To re-create the working tree, use "bzr checkout".
 
250
    """
 
251
    _see_also = ['checkout']
 
252
 
 
253
    takes_args = ['location?']
 
254
 
 
255
    def run(self, location='.'):
 
256
        d = bzrdir.BzrDir.open(location)
 
257
        
 
258
        try:
 
259
            working = d.open_workingtree()
 
260
        except errors.NoWorkingTree:
 
261
            raise errors.BzrCommandError("No working tree to remove")
 
262
        except errors.NotLocalUrl:
 
263
            raise errors.BzrCommandError("You cannot remove the working tree of a "
 
264
                                         "remote path")
 
265
        
 
266
        working_path = working.bzrdir.root_transport.base
 
267
        branch_path = working.branch.bzrdir.root_transport.base
 
268
        if working_path != branch_path:
 
269
            raise errors.BzrCommandError("You cannot remove the working tree from "
 
270
                                         "a lightweight checkout")
 
271
        
 
272
        d.destroy_workingtree()
 
273
        
 
274
 
 
275
class cmd_revno(Command):
 
276
    """Show current revision number.
 
277
 
 
278
    This is equal to the number of revisions on this branch.
 
279
    """
 
280
 
 
281
    _see_also = ['info']
 
282
    takes_args = ['location?']
 
283
 
 
284
    @display_command
 
285
    def run(self, location=u'.'):
 
286
        self.outf.write(str(Branch.open_containing(location)[0].revno()))
 
287
        self.outf.write('\n')
 
288
 
 
289
 
 
290
class cmd_revision_info(Command):
 
291
    """Show revision number and revision id for a given revision identifier.
 
292
    """
 
293
    hidden = True
 
294
    takes_args = ['revision_info*']
 
295
    takes_options = ['revision']
 
296
 
 
297
    @display_command
 
298
    def run(self, revision=None, revision_info_list=[]):
 
299
 
 
300
        revs = []
 
301
        if revision is not None:
 
302
            revs.extend(revision)
 
303
        if revision_info_list is not None:
 
304
            for rev in revision_info_list:
 
305
                revs.append(RevisionSpec.from_string(rev))
 
306
        if len(revs) == 0:
 
307
            raise errors.BzrCommandError('You must supply a revision identifier')
 
308
 
 
309
        b = WorkingTree.open_containing(u'.')[0].branch
 
310
 
 
311
        for rev in revs:
 
312
            revinfo = rev.in_history(b)
 
313
            if revinfo.revno is None:
 
314
                print '     %s' % revinfo.rev_id
 
315
            else:
 
316
                print '%4d %s' % (revinfo.revno, revinfo.rev_id)
 
317
 
 
318
    
 
319
class cmd_add(Command):
 
320
    """Add specified files or directories.
 
321
 
 
322
    In non-recursive mode, all the named items are added, regardless
 
323
    of whether they were previously ignored.  A warning is given if
 
324
    any of the named files are already versioned.
 
325
 
 
326
    In recursive mode (the default), files are treated the same way
 
327
    but the behaviour for directories is different.  Directories that
 
328
    are already versioned do not give a warning.  All directories,
 
329
    whether already versioned or not, are searched for files or
 
330
    subdirectories that are neither versioned or ignored, and these
 
331
    are added.  This search proceeds recursively into versioned
 
332
    directories.  If no names are given '.' is assumed.
 
333
 
 
334
    Therefore simply saying 'bzr add' will version all files that
 
335
    are currently unknown.
 
336
 
 
337
    Adding a file whose parent directory is not versioned will
 
338
    implicitly add the parent, and so on up to the root. This means
 
339
    you should never need to explicitly add a directory, they'll just
 
340
    get added when you add a file in the directory.
 
341
 
 
342
    --dry-run will show which files would be added, but not actually 
 
343
    add them.
 
344
 
 
345
    --file-ids-from will try to use the file ids from the supplied path.
 
346
    It looks up ids trying to find a matching parent directory with the
 
347
    same filename, and then by pure path. This option is rarely needed
 
348
    but can be useful when adding the same logical file into two
 
349
    branches that will be merged later (without showing the two different
 
350
    adds as a conflict). It is also useful when merging another project
 
351
    into a subdirectory of this one.
 
352
    """
 
353
    takes_args = ['file*']
 
354
    takes_options = ['no-recurse', 'dry-run', 'verbose',
 
355
                     Option('file-ids-from', type=unicode,
 
356
                            help='Lookup file ids from here')]
 
357
    encoding_type = 'replace'
 
358
    _see_also = ['remove']
 
359
 
 
360
    def run(self, file_list, no_recurse=False, dry_run=False, verbose=False,
 
361
            file_ids_from=None):
 
362
        import bzrlib.add
 
363
 
 
364
        base_tree = None
 
365
        if file_ids_from is not None:
 
366
            try:
 
367
                base_tree, base_path = WorkingTree.open_containing(
 
368
                                            file_ids_from)
 
369
            except errors.NoWorkingTree:
 
370
                base_branch, base_path = Branch.open_containing(
 
371
                                            file_ids_from)
 
372
                base_tree = base_branch.basis_tree()
 
373
 
 
374
            action = bzrlib.add.AddFromBaseAction(base_tree, base_path,
 
375
                          to_file=self.outf, should_print=(not is_quiet()))
 
376
        else:
 
377
            action = bzrlib.add.AddAction(to_file=self.outf,
 
378
                should_print=(not is_quiet()))
 
379
 
 
380
        if base_tree:
 
381
            base_tree.lock_read()
 
382
        try:
 
383
            added, ignored = bzrlib.add.smart_add(file_list, not no_recurse,
 
384
                action=action, save=not dry_run)
 
385
        finally:
 
386
            if base_tree is not None:
 
387
                base_tree.unlock()
 
388
        if len(ignored) > 0:
 
389
            if verbose:
 
390
                for glob in sorted(ignored.keys()):
 
391
                    for path in ignored[glob]:
 
392
                        self.outf.write("ignored %s matching \"%s\"\n" 
 
393
                                        % (path, glob))
 
394
            else:
 
395
                match_len = 0
 
396
                for glob, paths in ignored.items():
 
397
                    match_len += len(paths)
 
398
                self.outf.write("ignored %d file(s).\n" % match_len)
 
399
            self.outf.write("If you wish to add some of these files,"
 
400
                            " please add them by name.\n")
 
401
 
 
402
 
 
403
class cmd_mkdir(Command):
 
404
    """Create a new versioned directory.
 
405
 
 
406
    This is equivalent to creating the directory and then adding it.
 
407
    """
 
408
 
 
409
    takes_args = ['dir+']
 
410
    encoding_type = 'replace'
 
411
 
 
412
    def run(self, dir_list):
 
413
        for d in dir_list:
 
414
            os.mkdir(d)
 
415
            wt, dd = WorkingTree.open_containing(d)
 
416
            wt.add([dd])
 
417
            self.outf.write('added %s\n' % d)
 
418
 
 
419
 
 
420
class cmd_relpath(Command):
 
421
    """Show path of a file relative to root"""
 
422
 
 
423
    takes_args = ['filename']
 
424
    hidden = True
 
425
    
 
426
    @display_command
 
427
    def run(self, filename):
 
428
        # TODO: jam 20050106 Can relpath return a munged path if
 
429
        #       sys.stdout encoding cannot represent it?
 
430
        tree, relpath = WorkingTree.open_containing(filename)
 
431
        self.outf.write(relpath)
 
432
        self.outf.write('\n')
 
433
 
 
434
 
 
435
class cmd_inventory(Command):
 
436
    """Show inventory of the current working copy or a revision.
 
437
 
 
438
    It is possible to limit the output to a particular entry
 
439
    type using the --kind option.  For example: --kind file.
 
440
 
 
441
    It is also possible to restrict the list of files to a specific
 
442
    set. For example: bzr inventory --show-ids this/file
 
443
    """
 
444
 
 
445
    hidden = True
 
446
    _see_also = ['ls']
 
447
    takes_options = ['revision', 'show-ids', 'kind']
 
448
    takes_args = ['file*']
 
449
 
 
450
    @display_command
 
451
    def run(self, revision=None, show_ids=False, kind=None, file_list=None):
 
452
        if kind and kind not in ['file', 'directory', 'symlink']:
 
453
            raise errors.BzrCommandError('invalid kind specified')
 
454
 
 
455
        work_tree, file_list = tree_files(file_list)
 
456
        work_tree.lock_read()
 
457
        try:
 
458
            if revision is not None:
 
459
                if len(revision) > 1:
 
460
                    raise errors.BzrCommandError(
 
461
                        'bzr inventory --revision takes exactly one revision'
 
462
                        ' identifier')
 
463
                revision_id = revision[0].in_history(work_tree.branch).rev_id
 
464
                tree = work_tree.branch.repository.revision_tree(revision_id)
 
465
 
 
466
                extra_trees = [work_tree]
 
467
                tree.lock_read()
 
468
            else:
 
469
                tree = work_tree
 
470
                extra_trees = []
 
471
 
 
472
            if file_list is not None:
 
473
                file_ids = tree.paths2ids(file_list, trees=extra_trees,
 
474
                                          require_versioned=True)
 
475
                # find_ids_across_trees may include some paths that don't
 
476
                # exist in 'tree'.
 
477
                entries = sorted((tree.id2path(file_id), tree.inventory[file_id])
 
478
                                 for file_id in file_ids if file_id in tree)
 
479
            else:
 
480
                entries = tree.inventory.entries()
 
481
        finally:
 
482
            tree.unlock()
 
483
            if tree is not work_tree:
 
484
                work_tree.unlock()
 
485
 
 
486
        for path, entry in entries:
 
487
            if kind and kind != entry.kind:
 
488
                continue
 
489
            if show_ids:
 
490
                self.outf.write('%-50s %s\n' % (path, entry.file_id))
 
491
            else:
 
492
                self.outf.write(path)
 
493
                self.outf.write('\n')
 
494
 
 
495
 
 
496
class cmd_mv(Command):
 
497
    """Move or rename a file.
 
498
 
 
499
    usage:
 
500
        bzr mv OLDNAME NEWNAME
 
501
        bzr mv SOURCE... DESTINATION
 
502
 
 
503
    If the last argument is a versioned directory, all the other names
 
504
    are moved into it.  Otherwise, there must be exactly two arguments
 
505
    and the file is changed to a new name.
 
506
 
 
507
    If OLDNAME does not exist on the filesystem but is versioned and
 
508
    NEWNAME does exist on the filesystem but is not versioned, mv
 
509
    assumes that the file has been manually moved and only updates
 
510
    its internal inventory to reflect that change.
 
511
    The same is valid when moving many SOURCE files to a DESTINATION.
 
512
 
 
513
    Files cannot be moved between branches.
 
514
    """
 
515
 
 
516
    takes_args = ['names*']
 
517
    takes_options = [Option("after", help="move only the bzr identifier"
 
518
        " of the file (file has already been moved). Use this flag if"
 
519
        " bzr is not able to detect this itself.")]
 
520
    aliases = ['move', 'rename']
 
521
    encoding_type = 'replace'
 
522
 
 
523
    def run(self, names_list, after=False):
 
524
        if names_list is None:
 
525
            names_list = []
 
526
 
 
527
        if len(names_list) < 2:
 
528
            raise errors.BzrCommandError("missing file argument")
 
529
        tree, rel_names = tree_files(names_list)
 
530
        
 
531
        if os.path.isdir(names_list[-1]):
 
532
            # move into existing directory
 
533
            for pair in tree.move(rel_names[:-1], rel_names[-1], after=after):
 
534
                self.outf.write("%s => %s\n" % pair)
 
535
        else:
 
536
            if len(names_list) != 2:
 
537
                raise errors.BzrCommandError('to mv multiple files the'
 
538
                                             ' destination must be a versioned'
 
539
                                             ' directory')
 
540
            tree.rename_one(rel_names[0], rel_names[1], after=after)
 
541
            self.outf.write("%s => %s\n" % (rel_names[0], rel_names[1]))
 
542
            
 
543
    
 
544
class cmd_pull(Command):
 
545
    """Turn this branch into a mirror of another branch.
 
546
 
 
547
    This command only works on branches that have not diverged.  Branches are
 
548
    considered diverged if the destination branch's most recent commit is one
 
549
    that has not been merged (directly or indirectly) into the parent.
 
550
 
 
551
    If branches have diverged, you can use 'bzr merge' to integrate the changes
 
552
    from one into the other.  Once one branch has merged, the other should
 
553
    be able to pull it again.
 
554
 
 
555
    If you want to forget your local changes and just update your branch to
 
556
    match the remote one, use pull --overwrite.
 
557
 
 
558
    If there is no default location set, the first pull will set it.  After
 
559
    that, you can omit the location to use the default.  To change the
 
560
    default, use --remember. The value will only be saved if the remote
 
561
    location can be accessed.
 
562
    """
 
563
 
 
564
    _see_also = ['push', 'update']
 
565
    takes_options = ['remember', 'overwrite', 'revision', 'verbose',
 
566
        Option('directory',
 
567
            help='branch to pull into, '
 
568
                 'rather than the one containing the working directory',
 
569
            short_name='d',
 
570
            type=unicode,
 
571
            ),
 
572
        ]
 
573
    takes_args = ['location?']
 
574
    encoding_type = 'replace'
 
575
 
 
576
    def run(self, location=None, remember=False, overwrite=False,
 
577
            revision=None, verbose=False,
 
578
            directory=None):
 
579
        from bzrlib.tag import _merge_tags_if_possible
 
580
        # FIXME: too much stuff is in the command class
 
581
        revision_id = None
 
582
        mergeable = None
 
583
        if directory is None:
 
584
            directory = u'.'
 
585
        try:
 
586
            tree_to = WorkingTree.open_containing(directory)[0]
 
587
            branch_to = tree_to.branch
 
588
        except errors.NoWorkingTree:
 
589
            tree_to = None
 
590
            branch_to = Branch.open_containing(directory)[0]
 
591
 
 
592
        reader = None
 
593
        if location is not None:
 
594
            try:
 
595
                mergeable = bundle.read_mergeable_from_url(
 
596
                    location)
 
597
            except errors.NotABundle:
 
598
                pass # Continue on considering this url a Branch
 
599
 
 
600
        stored_loc = branch_to.get_parent()
 
601
        if location is None:
 
602
            if stored_loc is None:
 
603
                raise errors.BzrCommandError("No pull location known or"
 
604
                                             " specified.")
 
605
            else:
 
606
                display_url = urlutils.unescape_for_display(stored_loc,
 
607
                        self.outf.encoding)
 
608
                self.outf.write("Using saved location: %s\n" % display_url)
 
609
                location = stored_loc
 
610
 
 
611
        if mergeable is not None:
 
612
            if revision is not None:
 
613
                raise errors.BzrCommandError(
 
614
                    'Cannot use -r with merge directives or bundles')
 
615
            revision_id = mergeable.install_revisions(branch_to.repository)
 
616
            branch_from = branch_to
 
617
        else:
 
618
            branch_from = Branch.open(location)
 
619
 
 
620
            if branch_to.get_parent() is None or remember:
 
621
                branch_to.set_parent(branch_from.base)
 
622
 
 
623
        if revision is not None:
 
624
            if len(revision) == 1:
 
625
                revision_id = revision[0].in_history(branch_from).rev_id
 
626
            else:
 
627
                raise errors.BzrCommandError(
 
628
                    'bzr pull --revision takes one value.')
 
629
 
 
630
        old_rh = branch_to.revision_history()
 
631
        if tree_to is not None:
 
632
            result = tree_to.pull(branch_from, overwrite, revision_id,
 
633
                delta._ChangeReporter(unversioned_filter=tree_to.is_ignored))
 
634
        else:
 
635
            result = branch_to.pull(branch_from, overwrite, revision_id)
 
636
 
 
637
        result.report(self.outf)
 
638
        if verbose:
 
639
            from bzrlib.log import show_changed_revisions
 
640
            new_rh = branch_to.revision_history()
 
641
            show_changed_revisions(branch_to, old_rh, new_rh,
 
642
                                   to_file=self.outf)
 
643
 
 
644
 
 
645
class cmd_push(Command):
 
646
    """Update a mirror of this branch.
 
647
    
 
648
    The target branch will not have its working tree populated because this
 
649
    is both expensive, and is not supported on remote file systems.
 
650
    
 
651
    Some smart servers or protocols *may* put the working tree in place in
 
652
    the future.
 
653
 
 
654
    This command only works on branches that have not diverged.  Branches are
 
655
    considered diverged if the destination branch's most recent commit is one
 
656
    that has not been merged (directly or indirectly) by the source branch.
 
657
 
 
658
    If branches have diverged, you can use 'bzr push --overwrite' to replace
 
659
    the other branch completely, discarding its unmerged changes.
 
660
    
 
661
    If you want to ensure you have the different changes in the other branch,
 
662
    do a merge (see bzr help merge) from the other branch, and commit that.
 
663
    After that you will be able to do a push without '--overwrite'.
 
664
 
 
665
    If there is no default push location set, the first push will set it.
 
666
    After that, you can omit the location to use the default.  To change the
 
667
    default, use --remember. The value will only be saved if the remote
 
668
    location can be accessed.
 
669
    """
 
670
 
 
671
    _see_also = ['pull', 'update']
 
672
    takes_options = ['remember', 'overwrite', 'verbose',
 
673
        Option('create-prefix',
 
674
               help='Create the path leading up to the branch '
 
675
                    'if it does not already exist'),
 
676
        Option('directory',
 
677
            help='branch to push from, '
 
678
                 'rather than the one containing the working directory',
 
679
            short_name='d',
 
680
            type=unicode,
 
681
            ),
 
682
        Option('use-existing-dir',
 
683
               help='By default push will fail if the target'
 
684
                    ' directory exists, but does not already'
 
685
                    ' have a control directory. This flag will'
 
686
                    ' allow push to proceed.'),
 
687
        ]
 
688
    takes_args = ['location?']
 
689
    encoding_type = 'replace'
 
690
 
 
691
    def run(self, location=None, remember=False, overwrite=False,
 
692
            create_prefix=False, verbose=False,
 
693
            use_existing_dir=False,
 
694
            directory=None):
 
695
        # FIXME: Way too big!  Put this into a function called from the
 
696
        # command.
 
697
        if directory is None:
 
698
            directory = '.'
 
699
        br_from = Branch.open_containing(directory)[0]
 
700
        stored_loc = br_from.get_push_location()
 
701
        if location is None:
 
702
            if stored_loc is None:
 
703
                raise errors.BzrCommandError("No push location known or specified.")
 
704
            else:
 
705
                display_url = urlutils.unescape_for_display(stored_loc,
 
706
                        self.outf.encoding)
 
707
                self.outf.write("Using saved location: %s\n" % display_url)
 
708
                location = stored_loc
 
709
 
 
710
        to_transport = transport.get_transport(location)
 
711
        location_url = to_transport.base
 
712
 
 
713
        br_to = repository_to = dir_to = None
 
714
        try:
 
715
            dir_to = bzrdir.BzrDir.open_from_transport(to_transport)
 
716
        except errors.NotBranchError:
 
717
            pass # Didn't find anything
 
718
        else:
 
719
            # If we can open a branch, use its direct repository, otherwise see
 
720
            # if there is a repository without a branch.
 
721
            try:
 
722
                br_to = dir_to.open_branch()
 
723
            except errors.NotBranchError:
 
724
                # Didn't find a branch, can we find a repository?
 
725
                try:
 
726
                    repository_to = dir_to.find_repository()
 
727
                except errors.NoRepositoryPresent:
 
728
                    pass
 
729
            else:
 
730
                # Found a branch, so we must have found a repository
 
731
                repository_to = br_to.repository
 
732
        push_result = None
 
733
        old_rh = []
 
734
        if dir_to is None:
 
735
            # The destination doesn't exist; create it.
 
736
            # XXX: Refactor the create_prefix/no_create_prefix code into a
 
737
            #      common helper function
 
738
            try:
 
739
                to_transport.mkdir('.')
 
740
            except errors.FileExists:
 
741
                if not use_existing_dir:
 
742
                    raise errors.BzrCommandError("Target directory %s"
 
743
                         " already exists, but does not have a valid .bzr"
 
744
                         " directory. Supply --use-existing-dir to push"
 
745
                         " there anyway." % location)
 
746
            except errors.NoSuchFile:
 
747
                if not create_prefix:
 
748
                    raise errors.BzrCommandError("Parent directory of %s"
 
749
                        " does not exist."
 
750
                        "\nYou may supply --create-prefix to create all"
 
751
                        " leading parent directories."
 
752
                        % location)
 
753
 
 
754
                cur_transport = to_transport
 
755
                needed = [cur_transport]
 
756
                # Recurse upwards until we can create a directory successfully
 
757
                while True:
 
758
                    new_transport = cur_transport.clone('..')
 
759
                    if new_transport.base == cur_transport.base:
 
760
                        raise errors.BzrCommandError("Failed to create path"
 
761
                                                     " prefix for %s."
 
762
                                                     % location)
 
763
                    try:
 
764
                        new_transport.mkdir('.')
 
765
                    except errors.NoSuchFile:
 
766
                        needed.append(new_transport)
 
767
                        cur_transport = new_transport
 
768
                    else:
 
769
                        break
 
770
 
 
771
                # Now we only need to create child directories
 
772
                while needed:
 
773
                    cur_transport = needed.pop()
 
774
                    cur_transport.mkdir('.')
 
775
            
 
776
            # Now the target directory exists, but doesn't have a .bzr
 
777
            # directory. So we need to create it, along with any work to create
 
778
            # all of the dependent branches, etc.
 
779
            dir_to = br_from.bzrdir.clone(location_url,
 
780
                revision_id=br_from.last_revision())
 
781
            br_to = dir_to.open_branch()
 
782
            # TODO: Some more useful message about what was copied
 
783
            note('Created new branch.')
 
784
            # We successfully created the target, remember it
 
785
            if br_from.get_push_location() is None or remember:
 
786
                br_from.set_push_location(br_to.base)
 
787
        elif repository_to is None:
 
788
            # we have a bzrdir but no branch or repository
 
789
            # XXX: Figure out what to do other than complain.
 
790
            raise errors.BzrCommandError("At %s you have a valid .bzr control"
 
791
                " directory, but not a branch or repository. This is an"
 
792
                " unsupported configuration. Please move the target directory"
 
793
                " out of the way and try again."
 
794
                % location)
 
795
        elif br_to is None:
 
796
            # We have a repository but no branch, copy the revisions, and then
 
797
            # create a branch.
 
798
            last_revision_id = br_from.last_revision()
 
799
            repository_to.fetch(br_from.repository,
 
800
                                revision_id=last_revision_id)
 
801
            br_to = br_from.clone(dir_to, revision_id=last_revision_id)
 
802
            note('Created new branch.')
 
803
            if br_from.get_push_location() is None or remember:
 
804
                br_from.set_push_location(br_to.base)
 
805
        else: # We have a valid to branch
 
806
            # We were able to connect to the remote location, so remember it
 
807
            # we don't need to successfully push because of possible divergence.
 
808
            if br_from.get_push_location() is None or remember:
 
809
                br_from.set_push_location(br_to.base)
 
810
            old_rh = br_to.revision_history()
 
811
            try:
 
812
                try:
 
813
                    tree_to = dir_to.open_workingtree()
 
814
                except errors.NotLocalUrl:
 
815
                    warning('This transport does not update the working '
 
816
                            'tree of: %s' % (br_to.base,))
 
817
                    push_result = br_from.push(br_to, overwrite)
 
818
                except errors.NoWorkingTree:
 
819
                    push_result = br_from.push(br_to, overwrite)
 
820
                else:
 
821
                    tree_to.lock_write()
 
822
                    try:
 
823
                        push_result = br_from.push(tree_to.branch, overwrite)
 
824
                        tree_to.update()
 
825
                    finally:
 
826
                        tree_to.unlock()
 
827
            except errors.DivergedBranches:
 
828
                raise errors.BzrCommandError('These branches have diverged.'
 
829
                                        '  Try using "merge" and then "push".')
 
830
        if push_result is not None:
 
831
            push_result.report(self.outf)
 
832
        elif verbose:
 
833
            new_rh = br_to.revision_history()
 
834
            if old_rh != new_rh:
 
835
                # Something changed
 
836
                from bzrlib.log import show_changed_revisions
 
837
                show_changed_revisions(br_to, old_rh, new_rh,
 
838
                                       to_file=self.outf)
 
839
        else:
 
840
            # we probably did a clone rather than a push, so a message was
 
841
            # emitted above
 
842
            pass
 
843
 
 
844
 
 
845
class cmd_branch(Command):
 
846
    """Create a new copy of a branch.
 
847
 
 
848
    If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
 
849
    be used.  In other words, "branch ../foo/bar" will attempt to create ./bar.
 
850
 
 
851
    To retrieve the branch as of a particular revision, supply the --revision
 
852
    parameter, as in "branch foo/bar -r 5".
 
853
    """
 
854
 
 
855
    _see_also = ['checkout']
 
856
    takes_args = ['from_location', 'to_location?']
 
857
    takes_options = ['revision']
 
858
    aliases = ['get', 'clone']
 
859
 
 
860
    def run(self, from_location, to_location=None, revision=None):
 
861
        from bzrlib.tag import _merge_tags_if_possible
 
862
        if revision is None:
 
863
            revision = [None]
 
864
        elif len(revision) > 1:
 
865
            raise errors.BzrCommandError(
 
866
                'bzr branch --revision takes exactly 1 revision value')
 
867
 
 
868
        br_from = Branch.open(from_location)
 
869
        br_from.lock_read()
 
870
        try:
 
871
            if len(revision) == 1 and revision[0] is not None:
 
872
                revision_id = revision[0].in_history(br_from)[1]
 
873
            else:
 
874
                # FIXME - wt.last_revision, fallback to branch, fall back to
 
875
                # None or perhaps NULL_REVISION to mean copy nothing
 
876
                # RBC 20060209
 
877
                revision_id = br_from.last_revision()
 
878
            if to_location is None:
 
879
                to_location = os.path.basename(from_location.rstrip("/\\"))
 
880
                name = None
 
881
            else:
 
882
                name = os.path.basename(to_location) + '\n'
 
883
 
 
884
            to_transport = transport.get_transport(to_location)
 
885
            try:
 
886
                to_transport.mkdir('.')
 
887
            except errors.FileExists:
 
888
                raise errors.BzrCommandError('Target directory "%s" already'
 
889
                                             ' exists.' % to_location)
 
890
            except errors.NoSuchFile:
 
891
                raise errors.BzrCommandError('Parent of "%s" does not exist.'
 
892
                                             % to_location)
 
893
            try:
 
894
                # preserve whatever source format we have.
 
895
                dir = br_from.bzrdir.sprout(to_transport.base, revision_id)
 
896
                branch = dir.open_branch()
 
897
            except errors.NoSuchRevision:
 
898
                to_transport.delete_tree('.')
 
899
                msg = "The branch %s has no revision %s." % (from_location, revision[0])
 
900
                raise errors.BzrCommandError(msg)
 
901
            if name:
 
902
                branch.control_files.put_utf8('branch-name', name)
 
903
            _merge_tags_if_possible(br_from, branch)
 
904
            note('Branched %d revision(s).' % branch.revno())
 
905
        finally:
 
906
            br_from.unlock()
 
907
 
 
908
 
 
909
class cmd_checkout(Command):
 
910
    """Create a new checkout of an existing branch.
 
911
 
 
912
    If BRANCH_LOCATION is omitted, checkout will reconstitute a working tree for
 
913
    the branch found in '.'. This is useful if you have removed the working tree
 
914
    or if it was never created - i.e. if you pushed the branch to its current
 
915
    location using SFTP.
 
916
    
 
917
    If the TO_LOCATION is omitted, the last component of the BRANCH_LOCATION will
 
918
    be used.  In other words, "checkout ../foo/bar" will attempt to create ./bar.
 
919
 
 
920
    To retrieve the branch as of a particular revision, supply the --revision
 
921
    parameter, as in "checkout foo/bar -r 5". Note that this will be immediately
 
922
    out of date [so you cannot commit] but it may be useful (i.e. to examine old
 
923
    code.)
 
924
    """
 
925
 
 
926
    _see_also = ['checkouts', 'branch']
 
927
    takes_args = ['branch_location?', 'to_location?']
 
928
    takes_options = ['revision',
 
929
                     Option('lightweight',
 
930
                            help="perform a lightweight checkout. Lightweight "
 
931
                                 "checkouts depend on access to the branch for "
 
932
                                 "every operation. Normal checkouts can perform "
 
933
                                 "common operations like diff and status without "
 
934
                                 "such access, and also support local commits."
 
935
                            ),
 
936
                     ]
 
937
    aliases = ['co']
 
938
 
 
939
    def run(self, branch_location=None, to_location=None, revision=None,
 
940
            lightweight=False):
 
941
        if revision is None:
 
942
            revision = [None]
 
943
        elif len(revision) > 1:
 
944
            raise errors.BzrCommandError(
 
945
                'bzr checkout --revision takes exactly 1 revision value')
 
946
        if branch_location is None:
 
947
            branch_location = osutils.getcwd()
 
948
            to_location = branch_location
 
949
        source = Branch.open(branch_location)
 
950
        if len(revision) == 1 and revision[0] is not None:
 
951
            revision_id = revision[0].in_history(source)[1]
 
952
        else:
 
953
            revision_id = None
 
954
        if to_location is None:
 
955
            to_location = os.path.basename(branch_location.rstrip("/\\"))
 
956
        # if the source and to_location are the same, 
 
957
        # and there is no working tree,
 
958
        # then reconstitute a branch
 
959
        if (osutils.abspath(to_location) ==
 
960
            osutils.abspath(branch_location)):
 
961
            try:
 
962
                source.bzrdir.open_workingtree()
 
963
            except errors.NoWorkingTree:
 
964
                source.bzrdir.create_workingtree()
 
965
                return
 
966
        try:
 
967
            os.mkdir(to_location)
 
968
        except OSError, e:
 
969
            if e.errno == errno.EEXIST:
 
970
                raise errors.BzrCommandError('Target directory "%s" already'
 
971
                                             ' exists.' % to_location)
 
972
            if e.errno == errno.ENOENT:
 
973
                raise errors.BzrCommandError('Parent of "%s" does not exist.'
 
974
                                             % to_location)
 
975
            else:
 
976
                raise
 
977
        source.create_checkout(to_location, revision_id, lightweight)
 
978
 
 
979
 
 
980
class cmd_renames(Command):
 
981
    """Show list of renamed files.
 
982
    """
 
983
    # TODO: Option to show renames between two historical versions.
 
984
 
 
985
    # TODO: Only show renames under dir, rather than in the whole branch.
 
986
    _see_also = ['status']
 
987
    takes_args = ['dir?']
 
988
 
 
989
    @display_command
 
990
    def run(self, dir=u'.'):
 
991
        tree = WorkingTree.open_containing(dir)[0]
 
992
        tree.lock_read()
 
993
        try:
 
994
            new_inv = tree.inventory
 
995
            old_tree = tree.basis_tree()
 
996
            old_tree.lock_read()
 
997
            try:
 
998
                old_inv = old_tree.inventory
 
999
                renames = list(_mod_tree.find_renames(old_inv, new_inv))
 
1000
                renames.sort()
 
1001
                for old_name, new_name in renames:
 
1002
                    self.outf.write("%s => %s\n" % (old_name, new_name))
 
1003
            finally:
 
1004
                old_tree.unlock()
 
1005
        finally:
 
1006
            tree.unlock()
 
1007
 
 
1008
 
 
1009
class cmd_update(Command):
 
1010
    """Update a tree to have the latest code committed to its branch.
 
1011
    
 
1012
    This will perform a merge into the working tree, and may generate
 
1013
    conflicts. If you have any local changes, you will still 
 
1014
    need to commit them after the update for the update to be complete.
 
1015
    
 
1016
    If you want to discard your local changes, you can just do a 
 
1017
    'bzr revert' instead of 'bzr commit' after the update.
 
1018
    """
 
1019
 
 
1020
    _see_also = ['pull']
 
1021
    takes_args = ['dir?']
 
1022
    aliases = ['up']
 
1023
 
 
1024
    def run(self, dir='.'):
 
1025
        tree = WorkingTree.open_containing(dir)[0]
 
1026
        master = tree.branch.get_master_branch()
 
1027
        if master is not None:
 
1028
            tree.lock_write()
 
1029
        else:
 
1030
            tree.lock_tree_write()
 
1031
        try:
 
1032
            existing_pending_merges = tree.get_parent_ids()[1:]
 
1033
            last_rev = tree.last_revision()
 
1034
            if last_rev == tree.branch.last_revision():
 
1035
                # may be up to date, check master too.
 
1036
                master = tree.branch.get_master_branch()
 
1037
                if master is None or last_rev == master.last_revision():
 
1038
                    revno = tree.branch.revision_id_to_revno(last_rev)
 
1039
                    note("Tree is up to date at revision %d." % (revno,))
 
1040
                    return 0
 
1041
            conflicts = tree.update()
 
1042
            revno = tree.branch.revision_id_to_revno(tree.last_revision())
 
1043
            note('Updated to revision %d.' % (revno,))
 
1044
            if tree.get_parent_ids()[1:] != existing_pending_merges:
 
1045
                note('Your local commits will now show as pending merges with '
 
1046
                     "'bzr status', and can be committed with 'bzr commit'.")
 
1047
            if conflicts != 0:
 
1048
                return 1
 
1049
            else:
 
1050
                return 0
 
1051
        finally:
 
1052
            tree.unlock()
 
1053
 
 
1054
 
 
1055
class cmd_info(Command):
 
1056
    """Show information about a working tree, branch or repository.
 
1057
 
 
1058
    This command will show all known locations and formats associated to the
 
1059
    tree, branch or repository.  Statistical information is included with
 
1060
    each report.
 
1061
 
 
1062
    Branches and working trees will also report any missing revisions.
 
1063
    """
 
1064
    _see_also = ['revno']
 
1065
    takes_args = ['location?']
 
1066
    takes_options = ['verbose']
 
1067
 
 
1068
    @display_command
 
1069
    def run(self, location=None, verbose=False):
 
1070
        from bzrlib.info import show_bzrdir_info
 
1071
        show_bzrdir_info(bzrdir.BzrDir.open_containing(location)[0],
 
1072
                         verbose=verbose)
 
1073
 
 
1074
 
 
1075
class cmd_remove(Command):
 
1076
    """Make a file unversioned.
 
1077
 
 
1078
    This makes bzr stop tracking changes to a versioned file.  It does
 
1079
    not delete the working copy.
 
1080
 
 
1081
    You can specify one or more files, and/or --new.  If you specify --new,
 
1082
    only 'added' files will be removed.  If you specify both, then new files
 
1083
    in the specified directories will be removed.  If the directories are
 
1084
    also new, they will also be removed.
 
1085
    """
 
1086
    takes_args = ['file*']
 
1087
    takes_options = ['verbose', Option('new', help='remove newly-added files')]
 
1088
    aliases = ['rm']
 
1089
    encoding_type = 'replace'
 
1090
    
 
1091
    def run(self, file_list, verbose=False, new=False):
 
1092
        tree, file_list = tree_files(file_list)
 
1093
        if new is False:
 
1094
            if file_list is None:
 
1095
                raise errors.BzrCommandError('Specify one or more files to'
 
1096
                                             ' remove, or use --new.')
 
1097
        else:
 
1098
            added = tree.changes_from(tree.basis_tree(),
 
1099
                specific_files=file_list).added
 
1100
            file_list = sorted([f[0] for f in added], reverse=True)
 
1101
            if len(file_list) == 0:
 
1102
                raise errors.BzrCommandError('No matching files.')
 
1103
        tree.remove(file_list, verbose=verbose, to_file=self.outf)
 
1104
 
 
1105
 
 
1106
class cmd_file_id(Command):
 
1107
    """Print file_id of a particular file or directory.
 
1108
 
 
1109
    The file_id is assigned when the file is first added and remains the
 
1110
    same through all revisions where the file exists, even when it is
 
1111
    moved or renamed.
 
1112
    """
 
1113
 
 
1114
    hidden = True
 
1115
    _see_also = ['inventory', 'ls']
 
1116
    takes_args = ['filename']
 
1117
 
 
1118
    @display_command
 
1119
    def run(self, filename):
 
1120
        tree, relpath = WorkingTree.open_containing(filename)
 
1121
        i = tree.path2id(relpath)
 
1122
        if i is None:
 
1123
            raise errors.NotVersionedError(filename)
 
1124
        else:
 
1125
            self.outf.write(i + '\n')
 
1126
 
 
1127
 
 
1128
class cmd_file_path(Command):
 
1129
    """Print path of file_ids to a file or directory.
 
1130
 
 
1131
    This prints one line for each directory down to the target,
 
1132
    starting at the branch root.
 
1133
    """
 
1134
 
 
1135
    hidden = True
 
1136
    takes_args = ['filename']
 
1137
 
 
1138
    @display_command
 
1139
    def run(self, filename):
 
1140
        tree, relpath = WorkingTree.open_containing(filename)
 
1141
        fid = tree.path2id(relpath)
 
1142
        if fid is None:
 
1143
            raise errors.NotVersionedError(filename)
 
1144
        segments = osutils.splitpath(relpath)
 
1145
        for pos in range(1, len(segments) + 1):
 
1146
            path = osutils.joinpath(segments[:pos])
 
1147
            self.outf.write("%s\n" % tree.path2id(path))
 
1148
 
 
1149
 
 
1150
class cmd_reconcile(Command):
 
1151
    """Reconcile bzr metadata in a branch.
 
1152
 
 
1153
    This can correct data mismatches that may have been caused by
 
1154
    previous ghost operations or bzr upgrades. You should only
 
1155
    need to run this command if 'bzr check' or a bzr developer 
 
1156
    advises you to run it.
 
1157
 
 
1158
    If a second branch is provided, cross-branch reconciliation is
 
1159
    also attempted, which will check that data like the tree root
 
1160
    id which was not present in very early bzr versions is represented
 
1161
    correctly in both branches.
 
1162
 
 
1163
    At the same time it is run it may recompress data resulting in 
 
1164
    a potential saving in disk space or performance gain.
 
1165
 
 
1166
    The branch *MUST* be on a listable system such as local disk or sftp.
 
1167
    """
 
1168
 
 
1169
    _see_also = ['check']
 
1170
    takes_args = ['branch?']
 
1171
 
 
1172
    def run(self, branch="."):
 
1173
        from bzrlib.reconcile import reconcile
 
1174
        dir = bzrdir.BzrDir.open(branch)
 
1175
        reconcile(dir)
 
1176
 
 
1177
 
 
1178
class cmd_revision_history(Command):
 
1179
    """Display the list of revision ids on a branch."""
 
1180
 
 
1181
    _see_also = ['log']
 
1182
    takes_args = ['location?']
 
1183
 
 
1184
    hidden = True
 
1185
 
 
1186
    @display_command
 
1187
    def run(self, location="."):
 
1188
        branch = Branch.open_containing(location)[0]
 
1189
        for revid in branch.revision_history():
 
1190
            self.outf.write(revid)
 
1191
            self.outf.write('\n')
 
1192
 
 
1193
 
 
1194
class cmd_ancestry(Command):
 
1195
    """List all revisions merged into this branch."""
 
1196
 
 
1197
    _see_also = ['log', 'revision-history']
 
1198
    takes_args = ['location?']
 
1199
 
 
1200
    hidden = True
 
1201
 
 
1202
    @display_command
 
1203
    def run(self, location="."):
 
1204
        try:
 
1205
            wt = WorkingTree.open_containing(location)[0]
 
1206
        except errors.NoWorkingTree:
 
1207
            b = Branch.open(location)
 
1208
            last_revision = b.last_revision()
 
1209
        else:
 
1210
            b = wt.branch
 
1211
            last_revision = wt.last_revision()
 
1212
 
 
1213
        revision_ids = b.repository.get_ancestry(last_revision)
 
1214
        assert revision_ids[0] is None
 
1215
        revision_ids.pop(0)
 
1216
        for revision_id in revision_ids:
 
1217
            self.outf.write(revision_id + '\n')
 
1218
 
 
1219
 
 
1220
class cmd_init(Command):
 
1221
    """Make a directory into a versioned branch.
 
1222
 
 
1223
    Use this to create an empty branch, or before importing an
 
1224
    existing project.
 
1225
 
 
1226
    If there is a repository in a parent directory of the location, then 
 
1227
    the history of the branch will be stored in the repository.  Otherwise
 
1228
    init creates a standalone branch which carries its own history
 
1229
    in the .bzr directory.
 
1230
 
 
1231
    If there is already a branch at the location but it has no working tree,
 
1232
    the tree can be populated with 'bzr checkout'.
 
1233
 
 
1234
    Recipe for importing a tree of files:
 
1235
        cd ~/project
 
1236
        bzr init
 
1237
        bzr add .
 
1238
        bzr status
 
1239
        bzr commit -m 'imported project'
 
1240
    """
 
1241
 
 
1242
    _see_also = ['init-repo', 'branch', 'checkout']
 
1243
    takes_args = ['location?']
 
1244
    takes_options = [
 
1245
         RegistryOption('format',
 
1246
                help='Specify a format for this branch. '
 
1247
                'See "help formats".',
 
1248
                registry=bzrdir.format_registry,
 
1249
                converter=bzrdir.format_registry.make_bzrdir,
 
1250
                value_switches=True,
 
1251
                title="Branch Format",
 
1252
                ),
 
1253
         Option('append-revisions-only',
 
1254
                help='Never change revnos or the existing log.'
 
1255
                '  Append revisions to it only.')
 
1256
         ]
 
1257
    def run(self, location=None, format=None, append_revisions_only=False):
 
1258
        if format is None:
 
1259
            format = bzrdir.format_registry.make_bzrdir('default')
 
1260
        if location is None:
 
1261
            location = u'.'
 
1262
 
 
1263
        to_transport = transport.get_transport(location)
 
1264
 
 
1265
        # The path has to exist to initialize a
 
1266
        # branch inside of it.
 
1267
        # Just using os.mkdir, since I don't
 
1268
        # believe that we want to create a bunch of
 
1269
        # locations if the user supplies an extended path
 
1270
        # TODO: create-prefix
 
1271
        try:
 
1272
            to_transport.mkdir('.')
 
1273
        except errors.FileExists:
 
1274
            pass
 
1275
                    
 
1276
        try:
 
1277
            existing_bzrdir = bzrdir.BzrDir.open(location)
 
1278
        except errors.NotBranchError:
 
1279
            # really a NotBzrDir error...
 
1280
            branch = bzrdir.BzrDir.create_branch_convenience(to_transport.base,
 
1281
                                                             format=format)
 
1282
        else:
 
1283
            from bzrlib.transport.local import LocalTransport
 
1284
            if existing_bzrdir.has_branch():
 
1285
                if (isinstance(to_transport, LocalTransport)
 
1286
                    and not existing_bzrdir.has_workingtree()):
 
1287
                        raise errors.BranchExistsWithoutWorkingTree(location)
 
1288
                raise errors.AlreadyBranchError(location)
 
1289
            else:
 
1290
                branch = existing_bzrdir.create_branch()
 
1291
                existing_bzrdir.create_workingtree()
 
1292
        if append_revisions_only:
 
1293
            try:
 
1294
                branch.set_append_revisions_only(True)
 
1295
            except errors.UpgradeRequired:
 
1296
                raise errors.BzrCommandError('This branch format cannot be set'
 
1297
                    ' to append-revisions-only.  Try --experimental-branch6')
 
1298
 
 
1299
 
 
1300
class cmd_init_repository(Command):
 
1301
    """Create a shared repository to hold branches.
 
1302
 
 
1303
    New branches created under the repository directory will store their revisions
 
1304
    in the repository, not in the branch directory.
 
1305
 
 
1306
    example:
 
1307
        bzr init-repo --no-trees repo
 
1308
        bzr init repo/trunk
 
1309
        bzr checkout --lightweight repo/trunk trunk-checkout
 
1310
        cd trunk-checkout
 
1311
        (add files here)
 
1312
    """
 
1313
 
 
1314
    _see_also = ['init', 'branch', 'checkout']
 
1315
    takes_args = ["location"]
 
1316
    takes_options = [RegistryOption('format',
 
1317
                            help='Specify a format for this repository. See'
 
1318
                                 ' "bzr help formats" for details',
 
1319
                            registry=bzrdir.format_registry,
 
1320
                            converter=bzrdir.format_registry.make_bzrdir,
 
1321
                            value_switches=True, title='Repository format'),
 
1322
                     Option('no-trees',
 
1323
                             help='Branches in the repository will default to'
 
1324
                                  ' not having a working tree'),
 
1325
                    ]
 
1326
    aliases = ["init-repo"]
 
1327
 
 
1328
    def run(self, location, format=None, no_trees=False):
 
1329
        if format is None:
 
1330
            format = bzrdir.format_registry.make_bzrdir('default')
 
1331
 
 
1332
        if location is None:
 
1333
            location = '.'
 
1334
 
 
1335
        to_transport = transport.get_transport(location)
 
1336
        try:
 
1337
            to_transport.mkdir('.')
 
1338
        except errors.FileExists:
 
1339
            pass
 
1340
 
 
1341
        newdir = format.initialize_on_transport(to_transport)
 
1342
        repo = newdir.create_repository(shared=True)
 
1343
        repo.set_make_working_trees(not no_trees)
 
1344
 
 
1345
 
 
1346
class cmd_diff(Command):
 
1347
    """Show differences in the working tree or between revisions.
 
1348
    
 
1349
    If files are listed, only the changes in those files are listed.
 
1350
    Otherwise, all changes for the tree are listed.
 
1351
 
 
1352
    "bzr diff -p1" is equivalent to "bzr diff --prefix old/:new/", and
 
1353
    produces patches suitable for "patch -p1".
 
1354
 
 
1355
    examples:
 
1356
        bzr diff
 
1357
            Shows the difference in the working tree versus the last commit
 
1358
        bzr diff -r1
 
1359
            Difference between the working tree and revision 1
 
1360
        bzr diff -r1..2
 
1361
            Difference between revision 2 and revision 1
 
1362
        bzr diff --prefix old/:new/
 
1363
            Same as 'bzr diff' but prefix paths with old/ and new/
 
1364
        bzr diff bzr.mine bzr.dev
 
1365
            Show the differences between the two working trees
 
1366
        bzr diff foo.c
 
1367
            Show just the differences for 'foo.c'
 
1368
    """
 
1369
    # TODO: Option to use external diff command; could be GNU diff, wdiff,
 
1370
    #       or a graphical diff.
 
1371
 
 
1372
    # TODO: Python difflib is not exactly the same as unidiff; should
 
1373
    #       either fix it up or prefer to use an external diff.
 
1374
 
 
1375
    # TODO: Selected-file diff is inefficient and doesn't show you
 
1376
    #       deleted files.
 
1377
 
 
1378
    # TODO: This probably handles non-Unix newlines poorly.
 
1379
 
 
1380
    _see_also = ['status']
 
1381
    takes_args = ['file*']
 
1382
    takes_options = ['revision', 'diff-options',
 
1383
        Option('prefix', type=str,
 
1384
               short_name='p',
 
1385
               help='Set prefixes to added to old and new filenames, as '
 
1386
                    'two values separated by a colon. (eg "old/:new/")'),
 
1387
        ]
 
1388
    aliases = ['di', 'dif']
 
1389
    encoding_type = 'exact'
 
1390
 
 
1391
    @display_command
 
1392
    def run(self, revision=None, file_list=None, diff_options=None,
 
1393
            prefix=None):
 
1394
        from bzrlib.diff import diff_cmd_helper, show_diff_trees
 
1395
 
 
1396
        if (prefix is None) or (prefix == '0'):
 
1397
            # diff -p0 format
 
1398
            old_label = ''
 
1399
            new_label = ''
 
1400
        elif prefix == '1':
 
1401
            old_label = 'old/'
 
1402
            new_label = 'new/'
 
1403
        elif ':' in prefix:
 
1404
            old_label, new_label = prefix.split(":")
 
1405
        else:
 
1406
            raise errors.BzrCommandError(
 
1407
                '--prefix expects two values separated by a colon'
 
1408
                ' (eg "old/:new/")')
 
1409
 
 
1410
        if revision and len(revision) > 2:
 
1411
            raise errors.BzrCommandError('bzr diff --revision takes exactly'
 
1412
                                         ' one or two revision specifiers')
 
1413
 
 
1414
        try:
 
1415
            tree1, file_list = internal_tree_files(file_list)
 
1416
            tree2 = None
 
1417
            b = None
 
1418
            b2 = None
 
1419
        except errors.FileInWrongBranch:
 
1420
            if len(file_list) != 2:
 
1421
                raise errors.BzrCommandError("Files are in different branches")
 
1422
 
 
1423
            tree1, file1 = WorkingTree.open_containing(file_list[0])
 
1424
            tree2, file2 = WorkingTree.open_containing(file_list[1])
 
1425
            if file1 != "" or file2 != "":
 
1426
                # FIXME diff those two files. rbc 20051123
 
1427
                raise errors.BzrCommandError("Files are in different branches")
 
1428
            file_list = None
 
1429
        except errors.NotBranchError:
 
1430
            if (revision is not None and len(revision) == 2
 
1431
                and not revision[0].needs_branch()
 
1432
                and not revision[1].needs_branch()):
 
1433
                # If both revision specs include a branch, we can
 
1434
                # diff them without needing a local working tree
 
1435
                tree1, tree2 = None, None
 
1436
            else:
 
1437
                raise
 
1438
 
 
1439
        if tree2 is not None:
 
1440
            if revision is not None:
 
1441
                # FIXME: but there should be a clean way to diff between
 
1442
                # non-default versions of two trees, it's not hard to do
 
1443
                # internally...
 
1444
                raise errors.BzrCommandError(
 
1445
                        "Sorry, diffing arbitrary revisions across branches "
 
1446
                        "is not implemented yet")
 
1447
            return show_diff_trees(tree1, tree2, sys.stdout, 
 
1448
                                   specific_files=file_list,
 
1449
                                   external_diff_options=diff_options,
 
1450
                                   old_label=old_label, new_label=new_label)
 
1451
 
 
1452
        return diff_cmd_helper(tree1, file_list, diff_options,
 
1453
                               revision_specs=revision,
 
1454
                               old_label=old_label, new_label=new_label)
 
1455
 
 
1456
 
 
1457
class cmd_deleted(Command):
 
1458
    """List files deleted in the working tree.
 
1459
    """
 
1460
    # TODO: Show files deleted since a previous revision, or
 
1461
    # between two revisions.
 
1462
    # TODO: Much more efficient way to do this: read in new
 
1463
    # directories with readdir, rather than stating each one.  Same
 
1464
    # level of effort but possibly much less IO.  (Or possibly not,
 
1465
    # if the directories are very large...)
 
1466
    _see_also = ['status', 'ls']
 
1467
    takes_options = ['show-ids']
 
1468
 
 
1469
    @display_command
 
1470
    def run(self, show_ids=False):
 
1471
        tree = WorkingTree.open_containing(u'.')[0]
 
1472
        tree.lock_read()
 
1473
        try:
 
1474
            old = tree.basis_tree()
 
1475
            old.lock_read()
 
1476
            try:
 
1477
                for path, ie in old.inventory.iter_entries():
 
1478
                    if not tree.has_id(ie.file_id):
 
1479
                        self.outf.write(path)
 
1480
                        if show_ids:
 
1481
                            self.outf.write(' ')
 
1482
                            self.outf.write(ie.file_id)
 
1483
                        self.outf.write('\n')
 
1484
            finally:
 
1485
                old.unlock()
 
1486
        finally:
 
1487
            tree.unlock()
 
1488
 
 
1489
 
 
1490
class cmd_modified(Command):
 
1491
    """List files modified in working tree.
 
1492
    """
 
1493
 
 
1494
    hidden = True
 
1495
    _see_also = ['status', 'ls']
 
1496
 
 
1497
    @display_command
 
1498
    def run(self):
 
1499
        tree = WorkingTree.open_containing(u'.')[0]
 
1500
        td = tree.changes_from(tree.basis_tree())
 
1501
        for path, id, kind, text_modified, meta_modified in td.modified:
 
1502
            self.outf.write(path + '\n')
 
1503
 
 
1504
 
 
1505
class cmd_added(Command):
 
1506
    """List files added in working tree.
 
1507
    """
 
1508
 
 
1509
    hidden = True
 
1510
    _see_also = ['status', 'ls']
 
1511
 
 
1512
    @display_command
 
1513
    def run(self):
 
1514
        wt = WorkingTree.open_containing(u'.')[0]
 
1515
        wt.lock_read()
 
1516
        try:
 
1517
            basis = wt.basis_tree()
 
1518
            basis.lock_read()
 
1519
            try:
 
1520
                basis_inv = basis.inventory
 
1521
                inv = wt.inventory
 
1522
                for file_id in inv:
 
1523
                    if file_id in basis_inv:
 
1524
                        continue
 
1525
                    if inv.is_root(file_id) and len(basis_inv) == 0:
 
1526
                        continue
 
1527
                    path = inv.id2path(file_id)
 
1528
                    if not os.access(osutils.abspath(path), os.F_OK):
 
1529
                        continue
 
1530
                    self.outf.write(path + '\n')
 
1531
            finally:
 
1532
                basis.unlock()
 
1533
        finally:
 
1534
            wt.unlock()
 
1535
 
 
1536
 
 
1537
class cmd_root(Command):
 
1538
    """Show the tree root directory.
 
1539
 
 
1540
    The root is the nearest enclosing directory with a .bzr control
 
1541
    directory."""
 
1542
 
 
1543
    takes_args = ['filename?']
 
1544
    @display_command
 
1545
    def run(self, filename=None):
 
1546
        """Print the branch root."""
 
1547
        tree = WorkingTree.open_containing(filename)[0]
 
1548
        self.outf.write(tree.basedir + '\n')
 
1549
 
 
1550
 
 
1551
class cmd_log(Command):
 
1552
    """Show log of a branch, file, or directory.
 
1553
 
 
1554
    By default show the log of the branch containing the working directory.
 
1555
 
 
1556
    To request a range of logs, you can use the command -r begin..end
 
1557
    -r revision requests a specific revision, -r ..end or -r begin.. are
 
1558
    also valid.
 
1559
 
 
1560
    examples:
 
1561
        bzr log
 
1562
        bzr log foo.c
 
1563
        bzr log -r -10.. http://server/branch
 
1564
    """
 
1565
 
 
1566
    # TODO: Make --revision support uuid: and hash: [future tag:] notation.
 
1567
 
 
1568
    takes_args = ['location?']
 
1569
    takes_options = [Option('forward', 
 
1570
                            help='show from oldest to newest'),
 
1571
                     'timezone', 
 
1572
                     Option('verbose', 
 
1573
                             short_name='v',
 
1574
                             help='show files changed in each revision'),
 
1575
                     'show-ids', 'revision',
 
1576
                     'log-format',
 
1577
                     Option('message',
 
1578
                            short_name='m',
 
1579
                            help='show revisions whose message matches this regexp',
 
1580
                            type=str),
 
1581
                     ]
 
1582
    encoding_type = 'replace'
 
1583
 
 
1584
    @display_command
 
1585
    def run(self, location=None, timezone='original',
 
1586
            verbose=False,
 
1587
            show_ids=False,
 
1588
            forward=False,
 
1589
            revision=None,
 
1590
            log_format=None,
 
1591
            message=None):
 
1592
        from bzrlib.log import show_log
 
1593
        assert message is None or isinstance(message, basestring), \
 
1594
            "invalid message argument %r" % message
 
1595
        direction = (forward and 'forward') or 'reverse'
 
1596
        
 
1597
        # log everything
 
1598
        file_id = None
 
1599
        if location:
 
1600
            # find the file id to log:
 
1601
 
 
1602
            tree, b, fp = bzrdir.BzrDir.open_containing_tree_or_branch(
 
1603
                location)
 
1604
            if fp != '':
 
1605
                if tree is None:
 
1606
                    tree = b.basis_tree()
 
1607
                file_id = tree.path2id(fp)
 
1608
                if file_id is None:
 
1609
                    raise errors.BzrCommandError(
 
1610
                        "Path does not have any revision history: %s" %
 
1611
                        location)
 
1612
        else:
 
1613
            # local dir only
 
1614
            # FIXME ? log the current subdir only RBC 20060203 
 
1615
            if revision is not None \
 
1616
                    and len(revision) > 0 and revision[0].get_branch():
 
1617
                location = revision[0].get_branch()
 
1618
            else:
 
1619
                location = '.'
 
1620
            dir, relpath = bzrdir.BzrDir.open_containing(location)
 
1621
            b = dir.open_branch()
 
1622
 
 
1623
        b.lock_read()
 
1624
        try:
 
1625
            if revision is None:
 
1626
                rev1 = None
 
1627
                rev2 = None
 
1628
            elif len(revision) == 1:
 
1629
                rev1 = rev2 = revision[0].in_history(b).revno
 
1630
            elif len(revision) == 2:
 
1631
                if revision[1].get_branch() != revision[0].get_branch():
 
1632
                    # b is taken from revision[0].get_branch(), and
 
1633
                    # show_log will use its revision_history. Having
 
1634
                    # different branches will lead to weird behaviors.
 
1635
                    raise errors.BzrCommandError(
 
1636
                        "Log doesn't accept two revisions in different"
 
1637
                        " branches.")
 
1638
                if revision[0].spec is None:
 
1639
                    # missing begin-range means first revision
 
1640
                    rev1 = 1
 
1641
                else:
 
1642
                    rev1 = revision[0].in_history(b).revno
 
1643
 
 
1644
                if revision[1].spec is None:
 
1645
                    # missing end-range means last known revision
 
1646
                    rev2 = b.revno()
 
1647
                else:
 
1648
                    rev2 = revision[1].in_history(b).revno
 
1649
            else:
 
1650
                raise errors.BzrCommandError(
 
1651
                    'bzr log --revision takes one or two values.')
 
1652
 
 
1653
            # By this point, the revision numbers are converted to the +ve
 
1654
            # form if they were supplied in the -ve form, so we can do
 
1655
            # this comparison in relative safety
 
1656
            if rev1 > rev2:
 
1657
                (rev2, rev1) = (rev1, rev2)
 
1658
 
 
1659
            if log_format is None:
 
1660
                log_format = log.log_formatter_registry.get_default(b)
 
1661
 
 
1662
            lf = log_format(show_ids=show_ids, to_file=self.outf,
 
1663
                            show_timezone=timezone)
 
1664
 
 
1665
            show_log(b,
 
1666
                     lf,
 
1667
                     file_id,
 
1668
                     verbose=verbose,
 
1669
                     direction=direction,
 
1670
                     start_revision=rev1,
 
1671
                     end_revision=rev2,
 
1672
                     search=message)
 
1673
        finally:
 
1674
            b.unlock()
 
1675
 
 
1676
 
 
1677
def get_log_format(long=False, short=False, line=False, default='long'):
 
1678
    log_format = default
 
1679
    if long:
 
1680
        log_format = 'long'
 
1681
    if short:
 
1682
        log_format = 'short'
 
1683
    if line:
 
1684
        log_format = 'line'
 
1685
    return log_format
 
1686
 
 
1687
 
 
1688
class cmd_touching_revisions(Command):
 
1689
    """Return revision-ids which affected a particular file.
 
1690
 
 
1691
    A more user-friendly interface is "bzr log FILE".
 
1692
    """
 
1693
 
 
1694
    hidden = True
 
1695
    takes_args = ["filename"]
 
1696
 
 
1697
    @display_command
 
1698
    def run(self, filename):
 
1699
        tree, relpath = WorkingTree.open_containing(filename)
 
1700
        b = tree.branch
 
1701
        file_id = tree.path2id(relpath)
 
1702
        for revno, revision_id, what in log.find_touching_revisions(b, file_id):
 
1703
            self.outf.write("%6d %s\n" % (revno, what))
 
1704
 
 
1705
 
 
1706
class cmd_ls(Command):
 
1707
    """List files in a tree.
 
1708
    """
 
1709
 
 
1710
    _see_also = ['status', 'cat']
 
1711
    takes_args = ['path?']
 
1712
    # TODO: Take a revision or remote path and list that tree instead.
 
1713
    takes_options = ['verbose', 'revision',
 
1714
                     Option('non-recursive',
 
1715
                            help='don\'t recurse into sub-directories'),
 
1716
                     Option('from-root',
 
1717
                            help='Print all paths from the root of the branch.'),
 
1718
                     Option('unknown', help='Print unknown files'),
 
1719
                     Option('versioned', help='Print versioned files'),
 
1720
                     Option('ignored', help='Print ignored files'),
 
1721
 
 
1722
                     Option('null', help='Null separate the files'),
 
1723
                     'kind', 'show-ids'
 
1724
                    ]
 
1725
    @display_command
 
1726
    def run(self, revision=None, verbose=False, 
 
1727
            non_recursive=False, from_root=False,
 
1728
            unknown=False, versioned=False, ignored=False,
 
1729
            null=False, kind=None, show_ids=False, path=None):
 
1730
 
 
1731
        if kind and kind not in ('file', 'directory', 'symlink'):
 
1732
            raise errors.BzrCommandError('invalid kind specified')
 
1733
 
 
1734
        if verbose and null:
 
1735
            raise errors.BzrCommandError('Cannot set both --verbose and --null')
 
1736
        all = not (unknown or versioned or ignored)
 
1737
 
 
1738
        selection = {'I':ignored, '?':unknown, 'V':versioned}
 
1739
 
 
1740
        if path is None:
 
1741
            fs_path = '.'
 
1742
            prefix = ''
 
1743
        else:
 
1744
            if from_root:
 
1745
                raise errors.BzrCommandError('cannot specify both --from-root'
 
1746
                                             ' and PATH')
 
1747
            fs_path = path
 
1748
            prefix = path
 
1749
        tree, branch, relpath = bzrdir.BzrDir.open_containing_tree_or_branch(
 
1750
            fs_path)
 
1751
        if from_root:
 
1752
            relpath = u''
 
1753
        elif relpath:
 
1754
            relpath += '/'
 
1755
        if revision is not None:
 
1756
            tree = branch.repository.revision_tree(
 
1757
                revision[0].in_history(branch).rev_id)
 
1758
        elif tree is None:
 
1759
            tree = branch.basis_tree()
 
1760
 
 
1761
        tree.lock_read()
 
1762
        try:
 
1763
            for fp, fc, fkind, fid, entry in tree.list_files(include_root=False):
 
1764
                if fp.startswith(relpath):
 
1765
                    fp = osutils.pathjoin(prefix, fp[len(relpath):])
 
1766
                    if non_recursive and '/' in fp:
 
1767
                        continue
 
1768
                    if not all and not selection[fc]:
 
1769
                        continue
 
1770
                    if kind is not None and fkind != kind:
 
1771
                        continue
 
1772
                    if verbose:
 
1773
                        kindch = entry.kind_character()
 
1774
                        outstring = '%-8s %s%s' % (fc, fp, kindch)
 
1775
                        if show_ids and fid is not None:
 
1776
                            outstring = "%-50s %s" % (outstring, fid)
 
1777
                        self.outf.write(outstring + '\n')
 
1778
                    elif null:
 
1779
                        self.outf.write(fp + '\0')
 
1780
                        if show_ids:
 
1781
                            if fid is not None:
 
1782
                                self.outf.write(fid)
 
1783
                            self.outf.write('\0')
 
1784
                        self.outf.flush()
 
1785
                    else:
 
1786
                        if fid is not None:
 
1787
                            my_id = fid
 
1788
                        else:
 
1789
                            my_id = ''
 
1790
                        if show_ids:
 
1791
                            self.outf.write('%-50s %s\n' % (fp, my_id))
 
1792
                        else:
 
1793
                            self.outf.write(fp + '\n')
 
1794
        finally:
 
1795
            tree.unlock()
 
1796
 
 
1797
 
 
1798
class cmd_unknowns(Command):
 
1799
    """List unknown files.
 
1800
    """
 
1801
 
 
1802
    hidden = True
 
1803
    _see_also = ['ls']
 
1804
 
 
1805
    @display_command
 
1806
    def run(self):
 
1807
        for f in WorkingTree.open_containing(u'.')[0].unknowns():
 
1808
            self.outf.write(osutils.quotefn(f) + '\n')
 
1809
 
 
1810
 
 
1811
class cmd_ignore(Command):
 
1812
    """Ignore specified files or patterns.
 
1813
 
 
1814
    To remove patterns from the ignore list, edit the .bzrignore file.
 
1815
 
 
1816
    Trailing slashes on patterns are ignored. 
 
1817
    If the pattern contains a slash or is a regular expression, it is compared 
 
1818
    to the whole path from the branch root.  Otherwise, it is compared to only
 
1819
    the last component of the path.  To match a file only in the root 
 
1820
    directory, prepend './'.
 
1821
 
 
1822
    Ignore patterns specifying absolute paths are not allowed.
 
1823
 
 
1824
    Ignore patterns may include globbing wildcards such as:
 
1825
      ? - Matches any single character except '/'
 
1826
      * - Matches 0 or more characters except '/'
 
1827
      /**/ - Matches 0 or more directories in a path
 
1828
      [a-z] - Matches a single character from within a group of characters
 
1829
 
 
1830
    Ignore patterns may also be Python regular expressions.  
 
1831
    Regular expression ignore patterns are identified by a 'RE:' prefix 
 
1832
    followed by the regular expression.  Regular expression ignore patterns
 
1833
    may not include named or numbered groups.
 
1834
 
 
1835
    Note: ignore patterns containing shell wildcards must be quoted from 
 
1836
    the shell on Unix.
 
1837
 
 
1838
    examples:
 
1839
        bzr ignore ./Makefile
 
1840
        bzr ignore '*.class'
 
1841
        bzr ignore 'lib/**/*.o'
 
1842
        bzr ignore 'RE:lib/.*\.o'
 
1843
    """
 
1844
 
 
1845
    _see_also = ['status', 'ignored']
 
1846
    takes_args = ['name_pattern*']
 
1847
    takes_options = [
 
1848
                     Option('old-default-rules',
 
1849
                            help='Out the ignore rules bzr < 0.9 always used.')
 
1850
                     ]
 
1851
    
 
1852
    def run(self, name_pattern_list=None, old_default_rules=None):
 
1853
        from bzrlib.atomicfile import AtomicFile
 
1854
        if old_default_rules is not None:
 
1855
            # dump the rules and exit
 
1856
            for pattern in ignores.OLD_DEFAULTS:
 
1857
                print pattern
 
1858
            return
 
1859
        if not name_pattern_list:
 
1860
            raise errors.BzrCommandError("ignore requires at least one "
 
1861
                                  "NAME_PATTERN or --old-default-rules")
 
1862
        name_pattern_list = [globbing.normalize_pattern(p) 
 
1863
                             for p in name_pattern_list]
 
1864
        for name_pattern in name_pattern_list:
 
1865
            if (name_pattern[0] == '/' or 
 
1866
                (len(name_pattern) > 1 and name_pattern[1] == ':')):
 
1867
                raise errors.BzrCommandError(
 
1868
                    "NAME_PATTERN should not be an absolute path")
 
1869
        tree, relpath = WorkingTree.open_containing(u'.')
 
1870
        ifn = tree.abspath('.bzrignore')
 
1871
        if os.path.exists(ifn):
 
1872
            f = open(ifn, 'rt')
 
1873
            try:
 
1874
                igns = f.read().decode('utf-8')
 
1875
            finally:
 
1876
                f.close()
 
1877
        else:
 
1878
            igns = ''
 
1879
 
 
1880
        # TODO: If the file already uses crlf-style termination, maybe
 
1881
        # we should use that for the newly added lines?
 
1882
 
 
1883
        if igns and igns[-1] != '\n':
 
1884
            igns += '\n'
 
1885
        for name_pattern in name_pattern_list:
 
1886
            igns += name_pattern + '\n'
 
1887
 
 
1888
        f = AtomicFile(ifn, 'wb')
 
1889
        try:
 
1890
            f.write(igns.encode('utf-8'))
 
1891
            f.commit()
 
1892
        finally:
 
1893
            f.close()
 
1894
 
 
1895
        if not tree.path2id('.bzrignore'):
 
1896
            tree.add(['.bzrignore'])
 
1897
 
 
1898
 
 
1899
class cmd_ignored(Command):
 
1900
    """List ignored files and the patterns that matched them.
 
1901
    """
 
1902
 
 
1903
    _see_also = ['ignore']
 
1904
    @display_command
 
1905
    def run(self):
 
1906
        tree = WorkingTree.open_containing(u'.')[0]
 
1907
        tree.lock_read()
 
1908
        try:
 
1909
            for path, file_class, kind, file_id, entry in tree.list_files():
 
1910
                if file_class != 'I':
 
1911
                    continue
 
1912
                ## XXX: Slightly inefficient since this was already calculated
 
1913
                pat = tree.is_ignored(path)
 
1914
                print '%-50s %s' % (path, pat)
 
1915
        finally:
 
1916
            tree.unlock()
 
1917
 
 
1918
 
 
1919
class cmd_lookup_revision(Command):
 
1920
    """Lookup the revision-id from a revision-number
 
1921
 
 
1922
    example:
 
1923
        bzr lookup-revision 33
 
1924
    """
 
1925
    hidden = True
 
1926
    takes_args = ['revno']
 
1927
    
 
1928
    @display_command
 
1929
    def run(self, revno):
 
1930
        try:
 
1931
            revno = int(revno)
 
1932
        except ValueError:
 
1933
            raise errors.BzrCommandError("not a valid revision-number: %r" % revno)
 
1934
 
 
1935
        print WorkingTree.open_containing(u'.')[0].branch.get_rev_id(revno)
 
1936
 
 
1937
 
 
1938
class cmd_export(Command):
 
1939
    """Export current or past revision to a destination directory or archive.
 
1940
 
 
1941
    If no revision is specified this exports the last committed revision.
 
1942
 
 
1943
    Format may be an "exporter" name, such as tar, tgz, tbz2.  If none is
 
1944
    given, try to find the format with the extension. If no extension
 
1945
    is found exports to a directory (equivalent to --format=dir).
 
1946
 
 
1947
    If root is supplied, it will be used as the root directory inside
 
1948
    container formats (tar, zip, etc). If it is not supplied it will default
 
1949
    to the exported filename. The root option has no effect for 'dir' format.
 
1950
 
 
1951
    If branch is omitted then the branch containing the current working
 
1952
    directory will be used.
 
1953
 
 
1954
    Note: Export of tree with non-ASCII filenames to zip is not supported.
 
1955
 
 
1956
     Supported formats       Autodetected by extension
 
1957
     -----------------       -------------------------
 
1958
         dir                            -
 
1959
         tar                          .tar
 
1960
         tbz2                    .tar.bz2, .tbz2
 
1961
         tgz                      .tar.gz, .tgz
 
1962
         zip                          .zip
 
1963
    """
 
1964
    takes_args = ['dest', 'branch?']
 
1965
    takes_options = ['revision', 'format', 'root']
 
1966
    def run(self, dest, branch=None, revision=None, format=None, root=None):
 
1967
        from bzrlib.export import export
 
1968
 
 
1969
        if branch is None:
 
1970
            tree = WorkingTree.open_containing(u'.')[0]
 
1971
            b = tree.branch
 
1972
        else:
 
1973
            b = Branch.open(branch)
 
1974
            
 
1975
        if revision is None:
 
1976
            # should be tree.last_revision  FIXME
 
1977
            rev_id = b.last_revision()
 
1978
        else:
 
1979
            if len(revision) != 1:
 
1980
                raise errors.BzrCommandError('bzr export --revision takes exactly 1 argument')
 
1981
            rev_id = revision[0].in_history(b).rev_id
 
1982
        t = b.repository.revision_tree(rev_id)
 
1983
        try:
 
1984
            export(t, dest, format, root)
 
1985
        except errors.NoSuchExportFormat, e:
 
1986
            raise errors.BzrCommandError('Unsupported export format: %s' % e.format)
 
1987
 
 
1988
 
 
1989
class cmd_cat(Command):
 
1990
    """Write the contents of a file as of a given revision to standard output.
 
1991
 
 
1992
    If no revision is nominated, the last revision is used.
 
1993
 
 
1994
    Note: Take care to redirect standard output when using this command on a
 
1995
    binary file. 
 
1996
    """
 
1997
 
 
1998
    _see_also = ['ls']
 
1999
    takes_options = ['revision', 'name-from-revision']
 
2000
    takes_args = ['filename']
 
2001
    encoding_type = 'exact'
 
2002
 
 
2003
    @display_command
 
2004
    def run(self, filename, revision=None, name_from_revision=False):
 
2005
        if revision is not None and len(revision) != 1:
 
2006
            raise errors.BzrCommandError("bzr cat --revision takes exactly"
 
2007
                                        " one number")
 
2008
 
 
2009
        tree = None
 
2010
        try:
 
2011
            tree, b, relpath = \
 
2012
                    bzrdir.BzrDir.open_containing_tree_or_branch(filename)
 
2013
        except errors.NotBranchError:
 
2014
            pass
 
2015
 
 
2016
        if revision is not None and revision[0].get_branch() is not None:
 
2017
            b = Branch.open(revision[0].get_branch())
 
2018
        if tree is None:
 
2019
            tree = b.basis_tree()
 
2020
        if revision is None:
 
2021
            revision_id = b.last_revision()
 
2022
        else:
 
2023
            revision_id = revision[0].in_history(b).rev_id
 
2024
 
 
2025
        cur_file_id = tree.path2id(relpath)
 
2026
        rev_tree = b.repository.revision_tree(revision_id)
 
2027
        old_file_id = rev_tree.path2id(relpath)
 
2028
        
 
2029
        if name_from_revision:
 
2030
            if old_file_id is None:
 
2031
                raise errors.BzrCommandError("%r is not present in revision %s"
 
2032
                                                % (filename, revision_id))
 
2033
            else:
 
2034
                rev_tree.print_file(old_file_id)
 
2035
        elif cur_file_id is not None:
 
2036
            rev_tree.print_file(cur_file_id)
 
2037
        elif old_file_id is not None:
 
2038
            rev_tree.print_file(old_file_id)
 
2039
        else:
 
2040
            raise errors.BzrCommandError("%r is not present in revision %s" %
 
2041
                                         (filename, revision_id))
 
2042
 
 
2043
 
 
2044
class cmd_local_time_offset(Command):
 
2045
    """Show the offset in seconds from GMT to local time."""
 
2046
    hidden = True    
 
2047
    @display_command
 
2048
    def run(self):
 
2049
        print osutils.local_time_offset()
 
2050
 
 
2051
 
 
2052
 
 
2053
class cmd_commit(Command):
 
2054
    """Commit changes into a new revision.
 
2055
    
 
2056
    If no arguments are given, the entire tree is committed.
 
2057
 
 
2058
    If selected files are specified, only changes to those files are
 
2059
    committed.  If a directory is specified then the directory and everything 
 
2060
    within it is committed.
 
2061
 
 
2062
    A selected-file commit may fail in some cases where the committed
 
2063
    tree would be invalid. Consider::
 
2064
 
 
2065
      bzr init foo
 
2066
      mkdir foo/bar
 
2067
      bzr add foo/bar
 
2068
      bzr commit foo -m "committing foo"
 
2069
      bzr mv foo/bar foo/baz
 
2070
      mkdir foo/bar
 
2071
      bzr add foo/bar
 
2072
      bzr commit foo/bar -m "committing bar but not baz"
 
2073
 
 
2074
    In the example above, the last commit will fail by design. This gives
 
2075
    the user the opportunity to decide whether they want to commit the
 
2076
    rename at the same time, separately first, or not at all. (As a general
 
2077
    rule, when in doubt, Bazaar has a policy of Doing the Safe Thing.)
 
2078
 
 
2079
    Note: A selected-file commit after a merge is not yet supported.
 
2080
    """
 
2081
    # TODO: Run hooks on tree to-be-committed, and after commit.
 
2082
 
 
2083
    # TODO: Strict commit that fails if there are deleted files.
 
2084
    #       (what does "deleted files" mean ??)
 
2085
 
 
2086
    # TODO: Give better message for -s, --summary, used by tla people
 
2087
 
 
2088
    # XXX: verbose currently does nothing
 
2089
 
 
2090
    _see_also = ['uncommit']
 
2091
    takes_args = ['selected*']
 
2092
    takes_options = ['message', 'verbose', 
 
2093
                     Option('unchanged',
 
2094
                            help='commit even if nothing has changed'),
 
2095
                     Option('file', type=str, 
 
2096
                            short_name='F',
 
2097
                            argname='msgfile',
 
2098
                            help='file containing commit message'),
 
2099
                     Option('strict',
 
2100
                            help="refuse to commit if there are unknown "
 
2101
                            "files in the working tree."),
 
2102
                     Option('local',
 
2103
                            help="perform a local only commit in a bound "
 
2104
                                 "branch. Such commits are not pushed to "
 
2105
                                 "the master branch until a normal commit "
 
2106
                                 "is performed."
 
2107
                            ),
 
2108
                     ]
 
2109
    aliases = ['ci', 'checkin']
 
2110
 
 
2111
    def run(self, message=None, file=None, verbose=True, selected_list=None,
 
2112
            unchanged=False, strict=False, local=False):
 
2113
        from bzrlib.commit import (NullCommitReporter, ReportCommitToLog)
 
2114
        from bzrlib.errors import (PointlessCommit, ConflictsInTree,
 
2115
                StrictCommitFailed)
 
2116
        from bzrlib.msgeditor import edit_commit_message, \
 
2117
                make_commit_message_template
 
2118
 
 
2119
        # TODO: Need a blackbox test for invoking the external editor; may be
 
2120
        # slightly problematic to run this cross-platform.
 
2121
 
 
2122
        # TODO: do more checks that the commit will succeed before 
 
2123
        # spending the user's valuable time typing a commit message.
 
2124
        tree, selected_list = tree_files(selected_list)
 
2125
        if selected_list == ['']:
 
2126
            # workaround - commit of root of tree should be exactly the same
 
2127
            # as just default commit in that tree, and succeed even though
 
2128
            # selected-file merge commit is not done yet
 
2129
            selected_list = []
 
2130
 
 
2131
        if local and not tree.branch.get_bound_location():
 
2132
            raise errors.LocalRequiresBoundBranch()
 
2133
 
 
2134
        def get_message(commit_obj):
 
2135
            """Callback to get commit message"""
 
2136
            my_message = message
 
2137
            if my_message is None and not file:
 
2138
                template = make_commit_message_template(tree, selected_list)
 
2139
                my_message = edit_commit_message(template)
 
2140
                if my_message is None:
 
2141
                    raise errors.BzrCommandError("please specify a commit"
 
2142
                        " message with either --message or --file")
 
2143
            elif my_message and file:
 
2144
                raise errors.BzrCommandError(
 
2145
                    "please specify either --message or --file")
 
2146
            if file:
 
2147
                my_message = codecs.open(file, 'rt', 
 
2148
                                         bzrlib.user_encoding).read()
 
2149
            if my_message == "":
 
2150
                raise errors.BzrCommandError("empty commit message specified")
 
2151
            return my_message
 
2152
        
 
2153
        if verbose:
 
2154
            reporter = ReportCommitToLog()
 
2155
        else:
 
2156
            reporter = NullCommitReporter()
 
2157
 
 
2158
        try:
 
2159
            tree.commit(message_callback=get_message,
 
2160
                        specific_files=selected_list,
 
2161
                        allow_pointless=unchanged, strict=strict, local=local,
 
2162
                        reporter=reporter)
 
2163
        except PointlessCommit:
 
2164
            # FIXME: This should really happen before the file is read in;
 
2165
            # perhaps prepare the commit; get the message; then actually commit
 
2166
            raise errors.BzrCommandError("no changes to commit."
 
2167
                              " use --unchanged to commit anyhow")
 
2168
        except ConflictsInTree:
 
2169
            raise errors.BzrCommandError('Conflicts detected in working '
 
2170
                'tree.  Use "bzr conflicts" to list, "bzr resolve FILE" to'
 
2171
                ' resolve.')
 
2172
        except StrictCommitFailed:
 
2173
            raise errors.BzrCommandError("Commit refused because there are"
 
2174
                              " unknown files in the working tree.")
 
2175
        except errors.BoundBranchOutOfDate, e:
 
2176
            raise errors.BzrCommandError(str(e) + "\n"
 
2177
            'To commit to master branch, run update and then commit.\n'
 
2178
            'You can also pass --local to commit to continue working '
 
2179
            'disconnected.')
 
2180
 
 
2181
 
 
2182
class cmd_check(Command):
 
2183
    """Validate consistency of branch history.
 
2184
 
 
2185
    This command checks various invariants about the branch storage to
 
2186
    detect data corruption or bzr bugs.
 
2187
    """
 
2188
 
 
2189
    _see_also = ['reconcile']
 
2190
    takes_args = ['branch?']
 
2191
    takes_options = ['verbose']
 
2192
 
 
2193
    def run(self, branch=None, verbose=False):
 
2194
        from bzrlib.check import check
 
2195
        if branch is None:
 
2196
            tree = WorkingTree.open_containing()[0]
 
2197
            branch = tree.branch
 
2198
        else:
 
2199
            branch = Branch.open(branch)
 
2200
        check(branch, verbose)
 
2201
 
 
2202
 
 
2203
class cmd_upgrade(Command):
 
2204
    """Upgrade branch storage to current format.
 
2205
 
 
2206
    The check command or bzr developers may sometimes advise you to run
 
2207
    this command. When the default format has changed you may also be warned
 
2208
    during other operations to upgrade.
 
2209
    """
 
2210
 
 
2211
    _see_also = ['check']
 
2212
    takes_args = ['url?']
 
2213
    takes_options = [
 
2214
                    RegistryOption('format',
 
2215
                        help='Upgrade to a specific format.  See "bzr help'
 
2216
                             ' formats" for details',
 
2217
                        registry=bzrdir.format_registry,
 
2218
                        converter=bzrdir.format_registry.make_bzrdir,
 
2219
                        value_switches=True, title='Branch format'),
 
2220
                    ]
 
2221
 
 
2222
    def run(self, url='.', format=None):
 
2223
        from bzrlib.upgrade import upgrade
 
2224
        if format is None:
 
2225
            format = bzrdir.format_registry.make_bzrdir('default')
 
2226
        upgrade(url, format)
 
2227
 
 
2228
 
 
2229
class cmd_whoami(Command):
 
2230
    """Show or set bzr user id.
 
2231
    
 
2232
    examples:
 
2233
        bzr whoami --email
 
2234
        bzr whoami 'Frank Chu <fchu@example.com>'
 
2235
    """
 
2236
    takes_options = [ Option('email',
 
2237
                             help='display email address only'),
 
2238
                      Option('branch',
 
2239
                             help='set identity for the current branch instead of '
 
2240
                                  'globally'),
 
2241
                    ]
 
2242
    takes_args = ['name?']
 
2243
    encoding_type = 'replace'
 
2244
    
 
2245
    @display_command
 
2246
    def run(self, email=False, branch=False, name=None):
 
2247
        if name is None:
 
2248
            # use branch if we're inside one; otherwise global config
 
2249
            try:
 
2250
                c = Branch.open_containing('.')[0].get_config()
 
2251
            except errors.NotBranchError:
 
2252
                c = config.GlobalConfig()
 
2253
            if email:
 
2254
                self.outf.write(c.user_email() + '\n')
 
2255
            else:
 
2256
                self.outf.write(c.username() + '\n')
 
2257
            return
 
2258
 
 
2259
        # display a warning if an email address isn't included in the given name.
 
2260
        try:
 
2261
            config.extract_email_address(name)
 
2262
        except errors.NoEmailInUsername, e:
 
2263
            warning('"%s" does not seem to contain an email address.  '
 
2264
                    'This is allowed, but not recommended.', name)
 
2265
        
 
2266
        # use global config unless --branch given
 
2267
        if branch:
 
2268
            c = Branch.open_containing('.')[0].get_config()
 
2269
        else:
 
2270
            c = config.GlobalConfig()
 
2271
        c.set_user_option('email', name)
 
2272
 
 
2273
 
 
2274
class cmd_nick(Command):
 
2275
    """Print or set the branch nickname.  
 
2276
 
 
2277
    If unset, the tree root directory name is used as the nickname
 
2278
    To print the current nickname, execute with no argument.  
 
2279
    """
 
2280
 
 
2281
    _see_also = ['info']
 
2282
    takes_args = ['nickname?']
 
2283
    def run(self, nickname=None):
 
2284
        branch = Branch.open_containing(u'.')[0]
 
2285
        if nickname is None:
 
2286
            self.printme(branch)
 
2287
        else:
 
2288
            branch.nick = nickname
 
2289
 
 
2290
    @display_command
 
2291
    def printme(self, branch):
 
2292
        print branch.nick
 
2293
 
 
2294
 
 
2295
class cmd_selftest(Command):
 
2296
    """Run internal test suite.
 
2297
    
 
2298
    This creates temporary test directories in the working directory, but not
 
2299
    existing data is affected.  These directories are deleted if the tests
 
2300
    pass, or left behind to help in debugging if they fail and --keep-output
 
2301
    is specified.
 
2302
    
 
2303
    If arguments are given, they are regular expressions that say which tests
 
2304
    should run.  Tests matching any expression are run, and other tests are
 
2305
    not run.
 
2306
 
 
2307
    Alternatively if --first is given, matching tests are run first and then
 
2308
    all other tests are run.  This is useful if you have been working in a
 
2309
    particular area, but want to make sure nothing else was broken.
 
2310
 
 
2311
    If the global option '--no-plugins' is given, plugins are not loaded
 
2312
    before running the selftests.  This has two effects: features provided or
 
2313
    modified by plugins will not be tested, and tests provided by plugins will
 
2314
    not be run.
 
2315
 
 
2316
    examples::
 
2317
        bzr selftest ignore
 
2318
            run only tests relating to 'ignore'
 
2319
        bzr --no-plugins selftest -v
 
2320
            disable plugins and list tests as they're run
 
2321
 
 
2322
    For each test, that needs actual disk access, bzr create their own
 
2323
    subdirectory in the temporary testing directory (testXXXX.tmp).
 
2324
    By default the name of such subdirectory is based on the name of the test.
 
2325
    If option '--numbered-dirs' is given, bzr will use sequent numbers
 
2326
    of running tests to create such subdirectories. This is default behavior
 
2327
    on Windows because of path length limitation.
 
2328
    """
 
2329
    # TODO: --list should give a list of all available tests
 
2330
 
 
2331
    # NB: this is used from the class without creating an instance, which is
 
2332
    # why it does not have a self parameter.
 
2333
    def get_transport_type(typestring):
 
2334
        """Parse and return a transport specifier."""
 
2335
        if typestring == "sftp":
 
2336
            from bzrlib.transport.sftp import SFTPAbsoluteServer
 
2337
            return SFTPAbsoluteServer
 
2338
        if typestring == "memory":
 
2339
            from bzrlib.transport.memory import MemoryServer
 
2340
            return MemoryServer
 
2341
        if typestring == "fakenfs":
 
2342
            from bzrlib.transport.fakenfs import FakeNFSServer
 
2343
            return FakeNFSServer
 
2344
        msg = "No known transport type %s. Supported types are: sftp\n" %\
 
2345
            (typestring)
 
2346
        raise errors.BzrCommandError(msg)
 
2347
 
 
2348
    hidden = True
 
2349
    takes_args = ['testspecs*']
 
2350
    takes_options = ['verbose',
 
2351
                     Option('one',
 
2352
                             help='stop when one test fails',
 
2353
                             short_name='1',
 
2354
                             ),
 
2355
                     Option('keep-output',
 
2356
                            help='keep output directories when tests fail'),
 
2357
                     Option('transport',
 
2358
                            help='Use a different transport by default '
 
2359
                                 'throughout the test suite.',
 
2360
                            type=get_transport_type),
 
2361
                     Option('benchmark', help='run the bzr benchmarks.'),
 
2362
                     Option('lsprof-timed',
 
2363
                            help='generate lsprof output for benchmarked'
 
2364
                                 ' sections of code.'),
 
2365
                     Option('cache-dir', type=str,
 
2366
                            help='a directory to cache intermediate'
 
2367
                                 ' benchmark steps'),
 
2368
                     Option('clean-output',
 
2369
                            help='clean temporary tests directories'
 
2370
                                 ' without running tests'),
 
2371
                     Option('first',
 
2372
                            help='run all tests, but run specified tests first',
 
2373
                            short_name='f',
 
2374
                            ),
 
2375
                     Option('numbered-dirs',
 
2376
                            help='use numbered dirs for TestCaseInTempDir'),
 
2377
                     ]
 
2378
    encoding_type = 'replace'
 
2379
 
 
2380
    def run(self, testspecs_list=None, verbose=None, one=False,
 
2381
            keep_output=False, transport=None, benchmark=None,
 
2382
            lsprof_timed=None, cache_dir=None, clean_output=False,
 
2383
            first=False, numbered_dirs=None):
 
2384
        import bzrlib.ui
 
2385
        from bzrlib.tests import selftest
 
2386
        import bzrlib.benchmarks as benchmarks
 
2387
        from bzrlib.benchmarks import tree_creator
 
2388
 
 
2389
        if clean_output:
 
2390
            from bzrlib.tests import clean_selftest_output
 
2391
            clean_selftest_output()
 
2392
            return 0
 
2393
 
 
2394
        if numbered_dirs is None and sys.platform == 'win32':
 
2395
            numbered_dirs = True
 
2396
 
 
2397
        if cache_dir is not None:
 
2398
            tree_creator.TreeCreator.CACHE_ROOT = osutils.abspath(cache_dir)
 
2399
        print '%10s: %s' % ('bzr', osutils.realpath(sys.argv[0]))
 
2400
        print '%10s: %s' % ('bzrlib', bzrlib.__path__[0])
 
2401
        print
 
2402
        if testspecs_list is not None:
 
2403
            pattern = '|'.join(testspecs_list)
 
2404
        else:
 
2405
            pattern = ".*"
 
2406
        if benchmark:
 
2407
            test_suite_factory = benchmarks.test_suite
 
2408
            if verbose is None:
 
2409
                verbose = True
 
2410
            # TODO: should possibly lock the history file...
 
2411
            benchfile = open(".perf_history", "at", buffering=1)
 
2412
        else:
 
2413
            test_suite_factory = None
 
2414
            if verbose is None:
 
2415
                verbose = False
 
2416
            benchfile = None
 
2417
        try:
 
2418
            result = selftest(verbose=verbose, 
 
2419
                              pattern=pattern,
 
2420
                              stop_on_failure=one, 
 
2421
                              keep_output=keep_output,
 
2422
                              transport=transport,
 
2423
                              test_suite_factory=test_suite_factory,
 
2424
                              lsprof_timed=lsprof_timed,
 
2425
                              bench_history=benchfile,
 
2426
                              matching_tests_first=first,
 
2427
                              numbered_dirs=numbered_dirs,
 
2428
                              )
 
2429
        finally:
 
2430
            if benchfile is not None:
 
2431
                benchfile.close()
 
2432
        if result:
 
2433
            info('tests passed')
 
2434
        else:
 
2435
            info('tests failed')
 
2436
        return int(not result)
 
2437
 
 
2438
 
 
2439
class cmd_version(Command):
 
2440
    """Show version of bzr."""
 
2441
 
 
2442
    @display_command
 
2443
    def run(self):
 
2444
        from bzrlib.version import show_version
 
2445
        show_version()
 
2446
 
 
2447
 
 
2448
class cmd_rocks(Command):
 
2449
    """Statement of optimism."""
 
2450
 
 
2451
    hidden = True
 
2452
 
 
2453
    @display_command
 
2454
    def run(self):
 
2455
        print "It sure does!"
 
2456
 
 
2457
 
 
2458
class cmd_find_merge_base(Command):
 
2459
    """Find and print a base revision for merging two branches."""
 
2460
    # TODO: Options to specify revisions on either side, as if
 
2461
    #       merging only part of the history.
 
2462
    takes_args = ['branch', 'other']
 
2463
    hidden = True
 
2464
    
 
2465
    @display_command
 
2466
    def run(self, branch, other):
 
2467
        from bzrlib.revision import MultipleRevisionSources
 
2468
        
 
2469
        branch1 = Branch.open_containing(branch)[0]
 
2470
        branch2 = Branch.open_containing(other)[0]
 
2471
 
 
2472
        last1 = branch1.last_revision()
 
2473
        last2 = branch2.last_revision()
 
2474
 
 
2475
        source = MultipleRevisionSources(branch1.repository, 
 
2476
                                         branch2.repository)
 
2477
        
 
2478
        base_rev_id = common_ancestor(last1, last2, source)
 
2479
 
 
2480
        print 'merge base is revision %s' % base_rev_id
 
2481
 
 
2482
 
 
2483
class cmd_merge(Command):
 
2484
    """Perform a three-way merge.
 
2485
    
 
2486
    The branch is the branch you will merge from.  By default, it will merge
 
2487
    the latest revision.  If you specify a revision, that revision will be
 
2488
    merged.  If you specify two revisions, the first will be used as a BASE,
 
2489
    and the second one as OTHER.  Revision numbers are always relative to the
 
2490
    specified branch.
 
2491
 
 
2492
    By default, bzr will try to merge in all new work from the other
 
2493
    branch, automatically determining an appropriate base.  If this
 
2494
    fails, you may need to give an explicit base.
 
2495
    
 
2496
    Merge will do its best to combine the changes in two branches, but there
 
2497
    are some kinds of problems only a human can fix.  When it encounters those,
 
2498
    it will mark a conflict.  A conflict means that you need to fix something,
 
2499
    before you should commit.
 
2500
 
 
2501
    Use bzr resolve when you have fixed a problem.  See also bzr conflicts.
 
2502
 
 
2503
    If there is no default branch set, the first merge will set it. After
 
2504
    that, you can omit the branch to use the default.  To change the
 
2505
    default, use --remember. The value will only be saved if the remote
 
2506
    location can be accessed.
 
2507
 
 
2508
    The results of the merge are placed into the destination working
 
2509
    directory, where they can be reviewed (with bzr diff), tested, and then
 
2510
    committed to record the result of the merge.
 
2511
 
 
2512
    Examples:
 
2513
 
 
2514
    To merge the latest revision from bzr.dev:
 
2515
        bzr merge ../bzr.dev
 
2516
 
 
2517
    To merge changes up to and including revision 82 from bzr.dev:
 
2518
        bzr merge -r 82 ../bzr.dev
 
2519
 
 
2520
    To merge the changes introduced by 82, without previous changes:
 
2521
        bzr merge -r 81..82 ../bzr.dev
 
2522
    
 
2523
    merge refuses to run if there are any uncommitted changes, unless
 
2524
    --force is given.
 
2525
    """
 
2526
 
 
2527
    _see_also = ['update', 'remerge']
 
2528
    takes_args = ['branch?']
 
2529
    takes_options = ['revision', 'force', 'merge-type', 'reprocess', 'remember',
 
2530
        Option('show-base', help="Show base revision text in "
 
2531
               "conflicts"),
 
2532
        Option('uncommitted', help='Apply uncommitted changes'
 
2533
               ' from a working copy, instead of branch changes'),
 
2534
        Option('pull', help='If the destination is already'
 
2535
                ' completely merged into the source, pull from the'
 
2536
                ' source rather than merging. When this happens,'
 
2537
                ' you do not need to commit the result.'),
 
2538
        Option('directory',
 
2539
            help='Branch to merge into, '
 
2540
                 'rather than the one containing the working directory',
 
2541
            short_name='d',
 
2542
            type=unicode,
 
2543
            ),
 
2544
    ]
 
2545
 
 
2546
    def run(self, branch=None, revision=None, force=False, merge_type=None,
 
2547
            show_base=False, reprocess=False, remember=False,
 
2548
            uncommitted=False, pull=False,
 
2549
            directory=None,
 
2550
            ):
 
2551
        from bzrlib.tag import _merge_tags_if_possible
 
2552
        other_revision_id = None
 
2553
        if merge_type is None:
 
2554
            merge_type = _mod_merge.Merge3Merger
 
2555
 
 
2556
        if directory is None: directory = u'.'
 
2557
        # XXX: jam 20070225 WorkingTree should be locked before you extract its
 
2558
        #      inventory. Because merge is a mutating operation, it really
 
2559
        #      should be a lock_write() for the whole cmd_merge operation.
 
2560
        #      However, cmd_merge open's its own tree in _merge_helper, which
 
2561
        #      means if we lock here, the later lock_write() will always block.
 
2562
        #      Either the merge helper code should be updated to take a tree,
 
2563
        #      (What about tree.merge_from_branch?)
 
2564
        tree = WorkingTree.open_containing(directory)[0]
 
2565
        change_reporter = delta._ChangeReporter(
 
2566
            unversioned_filter=tree.is_ignored)
 
2567
 
 
2568
        if branch is not None:
 
2569
            try:
 
2570
                mergeable = bundle.read_mergeable_from_url(
 
2571
                    branch)
 
2572
            except errors.NotABundle:
 
2573
                pass # Continue on considering this url a Branch
 
2574
            else:
 
2575
                if revision is not None:
 
2576
                    raise errors.BzrCommandError(
 
2577
                        'Cannot use -r with merge directives or bundles')
 
2578
                other_revision_id = mergeable.install_revisions(
 
2579
                    tree.branch.repository)
 
2580
                revision = [RevisionSpec.from_string(
 
2581
                    'revid:' + other_revision_id)]
 
2582
 
 
2583
        if revision is None \
 
2584
                or len(revision) < 1 or revision[0].needs_branch():
 
2585
            branch = self._get_remembered_parent(tree, branch, 'Merging from')
 
2586
 
 
2587
        if revision is None or len(revision) < 1:
 
2588
            if uncommitted:
 
2589
                base = [branch, -1]
 
2590
                other = [branch, None]
 
2591
            else:
 
2592
                base = [None, None]
 
2593
                other = [branch, -1]
 
2594
            other_branch, path = Branch.open_containing(branch)
 
2595
        else:
 
2596
            if uncommitted:
 
2597
                raise errors.BzrCommandError('Cannot use --uncommitted and'
 
2598
                                             ' --revision at the same time.')
 
2599
            branch = revision[0].get_branch() or branch
 
2600
            if len(revision) == 1:
 
2601
                base = [None, None]
 
2602
                if other_revision_id is not None:
 
2603
                    other_branch = None
 
2604
                    path = ""
 
2605
                    other = None
 
2606
                else:
 
2607
                    other_branch, path = Branch.open_containing(branch)
 
2608
                    revno = revision[0].in_history(other_branch).revno
 
2609
                    other = [branch, revno]
 
2610
            else:
 
2611
                assert len(revision) == 2
 
2612
                if None in revision:
 
2613
                    raise errors.BzrCommandError(
 
2614
                        "Merge doesn't permit empty revision specifier.")
 
2615
                base_branch, path = Branch.open_containing(branch)
 
2616
                branch1 = revision[1].get_branch() or branch
 
2617
                other_branch, path1 = Branch.open_containing(branch1)
 
2618
                if revision[0].get_branch() is not None:
 
2619
                    # then path was obtained from it, and is None.
 
2620
                    path = path1
 
2621
 
 
2622
                base = [branch, revision[0].in_history(base_branch).revno]
 
2623
                other = [branch1, revision[1].in_history(other_branch).revno]
 
2624
 
 
2625
        if ((tree.branch.get_parent() is None or remember) and
 
2626
            other_branch is not None):
 
2627
            tree.branch.set_parent(other_branch.base)
 
2628
 
 
2629
        # pull tags now... it's a bit inconsistent to do it ahead of copying
 
2630
        # the history but that's done inside the merge code
 
2631
        if other_branch is not None:
 
2632
            _merge_tags_if_possible(other_branch, tree.branch)
 
2633
 
 
2634
        if path != "":
 
2635
            interesting_files = [path]
 
2636
        else:
 
2637
            interesting_files = None
 
2638
        pb = ui.ui_factory.nested_progress_bar()
 
2639
        try:
 
2640
            try:
 
2641
                conflict_count = _merge_helper(
 
2642
                    other, base, other_rev_id=other_revision_id,
 
2643
                    check_clean=(not force),
 
2644
                    merge_type=merge_type,
 
2645
                    reprocess=reprocess,
 
2646
                    show_base=show_base,
 
2647
                    pull=pull,
 
2648
                    this_dir=directory,
 
2649
                    pb=pb, file_list=interesting_files,
 
2650
                    change_reporter=change_reporter)
 
2651
            finally:
 
2652
                pb.finished()
 
2653
            if conflict_count != 0:
 
2654
                return 1
 
2655
            else:
 
2656
                return 0
 
2657
        except errors.AmbiguousBase, e:
 
2658
            m = ("sorry, bzr can't determine the right merge base yet\n"
 
2659
                 "candidates are:\n  "
 
2660
                 + "\n  ".join(e.bases)
 
2661
                 + "\n"
 
2662
                 "please specify an explicit base with -r,\n"
 
2663
                 "and (if you want) report this to the bzr developers\n")
 
2664
            log_error(m)
 
2665
 
 
2666
    # TODO: move up to common parent; this isn't merge-specific anymore. 
 
2667
    def _get_remembered_parent(self, tree, supplied_location, verb_string):
 
2668
        """Use tree.branch's parent if none was supplied.
 
2669
 
 
2670
        Report if the remembered location was used.
 
2671
        """
 
2672
        if supplied_location is not None:
 
2673
            return supplied_location
 
2674
        stored_location = tree.branch.get_parent()
 
2675
        mutter("%s", stored_location)
 
2676
        if stored_location is None:
 
2677
            raise errors.BzrCommandError("No location specified or remembered")
 
2678
        display_url = urlutils.unescape_for_display(stored_location, self.outf.encoding)
 
2679
        self.outf.write("%s remembered location %s\n" % (verb_string, display_url))
 
2680
        return stored_location
 
2681
 
 
2682
 
 
2683
class cmd_remerge(Command):
 
2684
    """Redo a merge.
 
2685
 
 
2686
    Use this if you want to try a different merge technique while resolving
 
2687
    conflicts.  Some merge techniques are better than others, and remerge 
 
2688
    lets you try different ones on different files.
 
2689
 
 
2690
    The options for remerge have the same meaning and defaults as the ones for
 
2691
    merge.  The difference is that remerge can (only) be run when there is a
 
2692
    pending merge, and it lets you specify particular files.
 
2693
 
 
2694
    Examples:
 
2695
 
 
2696
    $ bzr remerge --show-base
 
2697
        Re-do the merge of all conflicted files, and show the base text in
 
2698
        conflict regions, in addition to the usual THIS and OTHER texts.
 
2699
 
 
2700
    $ bzr remerge --merge-type weave --reprocess foobar
 
2701
        Re-do the merge of "foobar", using the weave merge algorithm, with
 
2702
        additional processing to reduce the size of conflict regions.
 
2703
    """
 
2704
    takes_args = ['file*']
 
2705
    takes_options = ['merge-type', 'reprocess',
 
2706
                     Option('show-base', help="Show base revision text in "
 
2707
                            "conflicts")]
 
2708
 
 
2709
    def run(self, file_list=None, merge_type=None, show_base=False,
 
2710
            reprocess=False):
 
2711
        if merge_type is None:
 
2712
            merge_type = _mod_merge.Merge3Merger
 
2713
        tree, file_list = tree_files(file_list)
 
2714
        tree.lock_write()
 
2715
        try:
 
2716
            parents = tree.get_parent_ids()
 
2717
            if len(parents) != 2:
 
2718
                raise errors.BzrCommandError("Sorry, remerge only works after normal"
 
2719
                                             " merges.  Not cherrypicking or"
 
2720
                                             " multi-merges.")
 
2721
            repository = tree.branch.repository
 
2722
            base_revision = common_ancestor(parents[0],
 
2723
                                            parents[1], repository)
 
2724
            base_tree = repository.revision_tree(base_revision)
 
2725
            other_tree = repository.revision_tree(parents[1])
 
2726
            interesting_ids = None
 
2727
            new_conflicts = []
 
2728
            conflicts = tree.conflicts()
 
2729
            if file_list is not None:
 
2730
                interesting_ids = set()
 
2731
                for filename in file_list:
 
2732
                    file_id = tree.path2id(filename)
 
2733
                    if file_id is None:
 
2734
                        raise errors.NotVersionedError(filename)
 
2735
                    interesting_ids.add(file_id)
 
2736
                    if tree.kind(file_id) != "directory":
 
2737
                        continue
 
2738
                    
 
2739
                    for name, ie in tree.inventory.iter_entries(file_id):
 
2740
                        interesting_ids.add(ie.file_id)
 
2741
                new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
 
2742
            else:
 
2743
                # Remerge only supports resolving contents conflicts
 
2744
                allowed_conflicts = ('text conflict', 'contents conflict')
 
2745
                restore_files = [c.path for c in conflicts
 
2746
                                 if c.typestring in allowed_conflicts]
 
2747
            _mod_merge.transform_tree(tree, tree.basis_tree(), interesting_ids)
 
2748
            tree.set_conflicts(ConflictList(new_conflicts))
 
2749
            if file_list is not None:
 
2750
                restore_files = file_list
 
2751
            for filename in restore_files:
 
2752
                try:
 
2753
                    restore(tree.abspath(filename))
 
2754
                except errors.NotConflicted:
 
2755
                    pass
 
2756
            conflicts = _mod_merge.merge_inner(
 
2757
                                      tree.branch, other_tree, base_tree,
 
2758
                                      this_tree=tree,
 
2759
                                      interesting_ids=interesting_ids,
 
2760
                                      other_rev_id=parents[1],
 
2761
                                      merge_type=merge_type,
 
2762
                                      show_base=show_base,
 
2763
                                      reprocess=reprocess)
 
2764
        finally:
 
2765
            tree.unlock()
 
2766
        if conflicts > 0:
 
2767
            return 1
 
2768
        else:
 
2769
            return 0
 
2770
 
 
2771
 
 
2772
class cmd_revert(Command):
 
2773
    """Revert files to a previous revision.
 
2774
 
 
2775
    Giving a list of files will revert only those files.  Otherwise, all files
 
2776
    will be reverted.  If the revision is not specified with '--revision', the
 
2777
    last committed revision is used.
 
2778
 
 
2779
    To remove only some changes, without reverting to a prior version, use
 
2780
    merge instead.  For example, "merge . --r-2..-3" will remove the changes
 
2781
    introduced by -2, without affecting the changes introduced by -1.  Or
 
2782
    to remove certain changes on a hunk-by-hunk basis, see the Shelf plugin.
 
2783
    
 
2784
    By default, any files that have been manually changed will be backed up
 
2785
    first.  (Files changed only by merge are not backed up.)  Backup files have
 
2786
    '.~#~' appended to their name, where # is a number.
 
2787
 
 
2788
    When you provide files, you can use their current pathname or the pathname
 
2789
    from the target revision.  So you can use revert to "undelete" a file by
 
2790
    name.  If you name a directory, all the contents of that directory will be
 
2791
    reverted.
 
2792
    """
 
2793
 
 
2794
    _see_also = ['cat', 'export']
 
2795
    takes_options = ['revision', 'no-backup']
 
2796
    takes_args = ['file*']
 
2797
 
 
2798
    def run(self, revision=None, no_backup=False, file_list=None):
 
2799
        if file_list is not None:
 
2800
            if len(file_list) == 0:
 
2801
                raise errors.BzrCommandError("No files specified")
 
2802
        else:
 
2803
            file_list = []
 
2804
        
 
2805
        tree, file_list = tree_files(file_list)
 
2806
        if revision is None:
 
2807
            # FIXME should be tree.last_revision
 
2808
            rev_id = tree.last_revision()
 
2809
        elif len(revision) != 1:
 
2810
            raise errors.BzrCommandError('bzr revert --revision takes exactly 1 argument')
 
2811
        else:
 
2812
            rev_id = revision[0].in_history(tree.branch).rev_id
 
2813
        pb = ui.ui_factory.nested_progress_bar()
 
2814
        try:
 
2815
            tree.revert(file_list, 
 
2816
                        tree.branch.repository.revision_tree(rev_id),
 
2817
                        not no_backup, pb, report_changes=True)
 
2818
        finally:
 
2819
            pb.finished()
 
2820
 
 
2821
 
 
2822
class cmd_assert_fail(Command):
 
2823
    """Test reporting of assertion failures"""
 
2824
    # intended just for use in testing
 
2825
 
 
2826
    hidden = True
 
2827
 
 
2828
    def run(self):
 
2829
        raise AssertionError("always fails")
 
2830
 
 
2831
 
 
2832
class cmd_help(Command):
 
2833
    """Show help on a command or other topic.
 
2834
    """
 
2835
 
 
2836
    _see_also = ['topics']
 
2837
    takes_options = [Option('long', 'show help on all commands')]
 
2838
    takes_args = ['topic?']
 
2839
    aliases = ['?', '--help', '-?', '-h']
 
2840
    
 
2841
    @display_command
 
2842
    def run(self, topic=None, long=False):
 
2843
        import bzrlib.help
 
2844
        if topic is None and long:
 
2845
            topic = "commands"
 
2846
        bzrlib.help.help(topic)
 
2847
 
 
2848
 
 
2849
class cmd_shell_complete(Command):
 
2850
    """Show appropriate completions for context.
 
2851
 
 
2852
    For a list of all available commands, say 'bzr shell-complete'.
 
2853
    """
 
2854
    takes_args = ['context?']
 
2855
    aliases = ['s-c']
 
2856
    hidden = True
 
2857
    
 
2858
    @display_command
 
2859
    def run(self, context=None):
 
2860
        import shellcomplete
 
2861
        shellcomplete.shellcomplete(context)
 
2862
 
 
2863
 
 
2864
class cmd_fetch(Command):
 
2865
    """Copy in history from another branch but don't merge it.
 
2866
 
 
2867
    This is an internal method used for pull and merge.
 
2868
    """
 
2869
    hidden = True
 
2870
    takes_args = ['from_branch', 'to_branch']
 
2871
    def run(self, from_branch, to_branch):
 
2872
        from bzrlib.fetch import Fetcher
 
2873
        from_b = Branch.open(from_branch)
 
2874
        to_b = Branch.open(to_branch)
 
2875
        Fetcher(to_b, from_b)
 
2876
 
 
2877
 
 
2878
class cmd_missing(Command):
 
2879
    """Show unmerged/unpulled revisions between two branches.
 
2880
 
 
2881
    OTHER_BRANCH may be local or remote.
 
2882
    """
 
2883
 
 
2884
    _see_also = ['merge', 'pull']
 
2885
    takes_args = ['other_branch?']
 
2886
    takes_options = [Option('reverse', 'Reverse the order of revisions'),
 
2887
                     Option('mine-only', 
 
2888
                            'Display changes in the local branch only'),
 
2889
                     Option('theirs-only', 
 
2890
                            'Display changes in the remote branch only'), 
 
2891
                     'log-format',
 
2892
                     'show-ids',
 
2893
                     'verbose'
 
2894
                     ]
 
2895
    encoding_type = 'replace'
 
2896
 
 
2897
    @display_command
 
2898
    def run(self, other_branch=None, reverse=False, mine_only=False,
 
2899
            theirs_only=False, log_format=None, long=False, short=False, line=False, 
 
2900
            show_ids=False, verbose=False):
 
2901
        from bzrlib.missing import find_unmerged, iter_log_data
 
2902
        from bzrlib.log import log_formatter
 
2903
        local_branch = Branch.open_containing(u".")[0]
 
2904
        parent = local_branch.get_parent()
 
2905
        if other_branch is None:
 
2906
            other_branch = parent
 
2907
            if other_branch is None:
 
2908
                raise errors.BzrCommandError("No peer location known or specified.")
 
2909
            display_url = urlutils.unescape_for_display(parent,
 
2910
                                                        self.outf.encoding)
 
2911
            print "Using last location: " + display_url
 
2912
 
 
2913
        remote_branch = Branch.open(other_branch)
 
2914
        if remote_branch.base == local_branch.base:
 
2915
            remote_branch = local_branch
 
2916
        local_branch.lock_read()
 
2917
        try:
 
2918
            remote_branch.lock_read()
 
2919
            try:
 
2920
                local_extra, remote_extra = find_unmerged(local_branch, remote_branch)
 
2921
                if (log_format is None):
 
2922
                    log_format = log.log_formatter_registry.get_default(
 
2923
                        local_branch)
 
2924
                lf = log_format(to_file=self.outf,
 
2925
                                show_ids=show_ids,
 
2926
                                show_timezone='original')
 
2927
                if reverse is False:
 
2928
                    local_extra.reverse()
 
2929
                    remote_extra.reverse()
 
2930
                if local_extra and not theirs_only:
 
2931
                    print "You have %d extra revision(s):" % len(local_extra)
 
2932
                    for data in iter_log_data(local_extra, local_branch.repository,
 
2933
                                              verbose):
 
2934
                        lf.show(*data)
 
2935
                    printed_local = True
 
2936
                else:
 
2937
                    printed_local = False
 
2938
                if remote_extra and not mine_only:
 
2939
                    if printed_local is True:
 
2940
                        print "\n\n"
 
2941
                    print "You are missing %d revision(s):" % len(remote_extra)
 
2942
                    for data in iter_log_data(remote_extra, remote_branch.repository, 
 
2943
                                              verbose):
 
2944
                        lf.show(*data)
 
2945
                if not remote_extra and not local_extra:
 
2946
                    status_code = 0
 
2947
                    print "Branches are up to date."
 
2948
                else:
 
2949
                    status_code = 1
 
2950
            finally:
 
2951
                remote_branch.unlock()
 
2952
        finally:
 
2953
            local_branch.unlock()
 
2954
        if not status_code and parent is None and other_branch is not None:
 
2955
            local_branch.lock_write()
 
2956
            try:
 
2957
                # handle race conditions - a parent might be set while we run.
 
2958
                if local_branch.get_parent() is None:
 
2959
                    local_branch.set_parent(remote_branch.base)
 
2960
            finally:
 
2961
                local_branch.unlock()
 
2962
        return status_code
 
2963
 
 
2964
 
 
2965
class cmd_plugins(Command):
 
2966
    """List plugins"""
 
2967
    hidden = True
 
2968
    @display_command
 
2969
    def run(self):
 
2970
        import bzrlib.plugin
 
2971
        from inspect import getdoc
 
2972
        for name, plugin in bzrlib.plugin.all_plugins().items():
 
2973
            if getattr(plugin, '__path__', None) is not None:
 
2974
                print plugin.__path__[0]
 
2975
            elif getattr(plugin, '__file__', None) is not None:
 
2976
                print plugin.__file__
 
2977
            else:
 
2978
                print repr(plugin)
 
2979
                
 
2980
            d = getdoc(plugin)
 
2981
            if d:
 
2982
                print '\t', d.split('\n')[0]
 
2983
 
 
2984
 
 
2985
class cmd_testament(Command):
 
2986
    """Show testament (signing-form) of a revision."""
 
2987
    takes_options = ['revision',
 
2988
                     Option('long', help='Produce long-format testament'), 
 
2989
                     Option('strict', help='Produce a strict-format'
 
2990
                            ' testament')]
 
2991
    takes_args = ['branch?']
 
2992
    @display_command
 
2993
    def run(self, branch=u'.', revision=None, long=False, strict=False):
 
2994
        from bzrlib.testament import Testament, StrictTestament
 
2995
        if strict is True:
 
2996
            testament_class = StrictTestament
 
2997
        else:
 
2998
            testament_class = Testament
 
2999
        b = WorkingTree.open_containing(branch)[0].branch
 
3000
        b.lock_read()
 
3001
        try:
 
3002
            if revision is None:
 
3003
                rev_id = b.last_revision()
 
3004
            else:
 
3005
                rev_id = revision[0].in_history(b).rev_id
 
3006
            t = testament_class.from_revision(b.repository, rev_id)
 
3007
            if long:
 
3008
                sys.stdout.writelines(t.as_text_lines())
 
3009
            else:
 
3010
                sys.stdout.write(t.as_short_text())
 
3011
        finally:
 
3012
            b.unlock()
 
3013
 
 
3014
 
 
3015
class cmd_annotate(Command):
 
3016
    """Show the origin of each line in a file.
 
3017
 
 
3018
    This prints out the given file with an annotation on the left side
 
3019
    indicating which revision, author and date introduced the change.
 
3020
 
 
3021
    If the origin is the same for a run of consecutive lines, it is 
 
3022
    shown only at the top, unless the --all option is given.
 
3023
    """
 
3024
    # TODO: annotate directories; showing when each file was last changed
 
3025
    # TODO: if the working copy is modified, show annotations on that 
 
3026
    #       with new uncommitted lines marked
 
3027
    aliases = ['ann', 'blame', 'praise']
 
3028
    takes_args = ['filename']
 
3029
    takes_options = [Option('all', help='show annotations on all lines'),
 
3030
                     Option('long', help='show date in annotations'),
 
3031
                     'revision',
 
3032
                     'show-ids',
 
3033
                     ]
 
3034
 
 
3035
    @display_command
 
3036
    def run(self, filename, all=False, long=False, revision=None,
 
3037
            show_ids=False):
 
3038
        from bzrlib.annotate import annotate_file
 
3039
        tree, relpath = WorkingTree.open_containing(filename)
 
3040
        branch = tree.branch
 
3041
        branch.lock_read()
 
3042
        try:
 
3043
            if revision is None:
 
3044
                revision_id = branch.last_revision()
 
3045
            elif len(revision) != 1:
 
3046
                raise errors.BzrCommandError('bzr annotate --revision takes exactly 1 argument')
 
3047
            else:
 
3048
                revision_id = revision[0].in_history(branch).rev_id
 
3049
            file_id = tree.path2id(relpath)
 
3050
            tree = branch.repository.revision_tree(revision_id)
 
3051
            file_version = tree.inventory[file_id].revision
 
3052
            annotate_file(branch, file_version, file_id, long, all, sys.stdout,
 
3053
                          show_ids=show_ids)
 
3054
        finally:
 
3055
            branch.unlock()
 
3056
 
 
3057
 
 
3058
class cmd_re_sign(Command):
 
3059
    """Create a digital signature for an existing revision."""
 
3060
    # TODO be able to replace existing ones.
 
3061
 
 
3062
    hidden = True # is this right ?
 
3063
    takes_args = ['revision_id*']
 
3064
    takes_options = ['revision']
 
3065
    
 
3066
    def run(self, revision_id_list=None, revision=None):
 
3067
        import bzrlib.gpg as gpg
 
3068
        if revision_id_list is not None and revision is not None:
 
3069
            raise errors.BzrCommandError('You can only supply one of revision_id or --revision')
 
3070
        if revision_id_list is None and revision is None:
 
3071
            raise errors.BzrCommandError('You must supply either --revision or a revision_id')
 
3072
        b = WorkingTree.open_containing(u'.')[0].branch
 
3073
        gpg_strategy = gpg.GPGStrategy(b.get_config())
 
3074
        if revision_id_list is not None:
 
3075
            for revision_id in revision_id_list:
 
3076
                b.repository.sign_revision(revision_id, gpg_strategy)
 
3077
        elif revision is not None:
 
3078
            if len(revision) == 1:
 
3079
                revno, rev_id = revision[0].in_history(b)
 
3080
                b.repository.sign_revision(rev_id, gpg_strategy)
 
3081
            elif len(revision) == 2:
 
3082
                # are they both on rh- if so we can walk between them
 
3083
                # might be nice to have a range helper for arbitrary
 
3084
                # revision paths. hmm.
 
3085
                from_revno, from_revid = revision[0].in_history(b)
 
3086
                to_revno, to_revid = revision[1].in_history(b)
 
3087
                if to_revid is None:
 
3088
                    to_revno = b.revno()
 
3089
                if from_revno is None or to_revno is None:
 
3090
                    raise errors.BzrCommandError('Cannot sign a range of non-revision-history revisions')
 
3091
                for revno in range(from_revno, to_revno + 1):
 
3092
                    b.repository.sign_revision(b.get_rev_id(revno), 
 
3093
                                               gpg_strategy)
 
3094
            else:
 
3095
                raise errors.BzrCommandError('Please supply either one revision, or a range.')
 
3096
 
 
3097
 
 
3098
class cmd_bind(Command):
 
3099
    """Convert the current branch into a checkout of the supplied branch.
 
3100
 
 
3101
    Once converted into a checkout, commits must succeed on the master branch
 
3102
    before they will be applied to the local branch.
 
3103
    """
 
3104
 
 
3105
    _see_also = ['checkouts', 'unbind']
 
3106
    takes_args = ['location?']
 
3107
    takes_options = []
 
3108
 
 
3109
    def run(self, location=None):
 
3110
        b, relpath = Branch.open_containing(u'.')
 
3111
        if location is None:
 
3112
            try:
 
3113
                location = b.get_old_bound_location()
 
3114
            except errors.UpgradeRequired:
 
3115
                raise errors.BzrCommandError('No location supplied.  '
 
3116
                    'This format does not remember old locations.')
 
3117
            else:
 
3118
                if location is None:
 
3119
                    raise errors.BzrCommandError('No location supplied and no '
 
3120
                        'previous location known')
 
3121
        b_other = Branch.open(location)
 
3122
        try:
 
3123
            b.bind(b_other)
 
3124
        except errors.DivergedBranches:
 
3125
            raise errors.BzrCommandError('These branches have diverged.'
 
3126
                                         ' Try merging, and then bind again.')
 
3127
 
 
3128
 
 
3129
class cmd_unbind(Command):
 
3130
    """Convert the current checkout into a regular branch.
 
3131
 
 
3132
    After unbinding, the local branch is considered independent and subsequent
 
3133
    commits will be local only.
 
3134
    """
 
3135
 
 
3136
    _see_also = ['checkouts', 'bind']
 
3137
    takes_args = []
 
3138
    takes_options = []
 
3139
 
 
3140
    def run(self):
 
3141
        b, relpath = Branch.open_containing(u'.')
 
3142
        if not b.unbind():
 
3143
            raise errors.BzrCommandError('Local branch is not bound')
 
3144
 
 
3145
 
 
3146
class cmd_uncommit(Command):
 
3147
    """Remove the last committed revision.
 
3148
 
 
3149
    --verbose will print out what is being removed.
 
3150
    --dry-run will go through all the motions, but not actually
 
3151
    remove anything.
 
3152
    
 
3153
    In the future, uncommit will create a revision bundle, which can then
 
3154
    be re-applied.
 
3155
    """
 
3156
 
 
3157
    # TODO: jam 20060108 Add an option to allow uncommit to remove
 
3158
    # unreferenced information in 'branch-as-repository' branches.
 
3159
    # TODO: jam 20060108 Add the ability for uncommit to remove unreferenced
 
3160
    # information in shared branches as well.
 
3161
    _see_also = ['commit']
 
3162
    takes_options = ['verbose', 'revision',
 
3163
                    Option('dry-run', help='Don\'t actually make changes'),
 
3164
                    Option('force', help='Say yes to all questions.')]
 
3165
    takes_args = ['location?']
 
3166
    aliases = []
 
3167
 
 
3168
    def run(self, location=None,
 
3169
            dry_run=False, verbose=False,
 
3170
            revision=None, force=False):
 
3171
        from bzrlib.log import log_formatter, show_log
 
3172
        import sys
 
3173
        from bzrlib.uncommit import uncommit
 
3174
 
 
3175
        if location is None:
 
3176
            location = u'.'
 
3177
        control, relpath = bzrdir.BzrDir.open_containing(location)
 
3178
        try:
 
3179
            tree = control.open_workingtree()
 
3180
            b = tree.branch
 
3181
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
3182
            tree = None
 
3183
            b = control.open_branch()
 
3184
 
 
3185
        rev_id = None
 
3186
        if revision is None:
 
3187
            revno = b.revno()
 
3188
        else:
 
3189
            # 'bzr uncommit -r 10' actually means uncommit
 
3190
            # so that the final tree is at revno 10.
 
3191
            # but bzrlib.uncommit.uncommit() actually uncommits
 
3192
            # the revisions that are supplied.
 
3193
            # So we need to offset it by one
 
3194
            revno = revision[0].in_history(b).revno+1
 
3195
 
 
3196
        if revno <= b.revno():
 
3197
            rev_id = b.get_rev_id(revno)
 
3198
        if rev_id is None:
 
3199
            self.outf.write('No revisions to uncommit.\n')
 
3200
            return 1
 
3201
 
 
3202
        lf = log_formatter('short',
 
3203
                           to_file=self.outf,
 
3204
                           show_timezone='original')
 
3205
 
 
3206
        show_log(b,
 
3207
                 lf,
 
3208
                 verbose=False,
 
3209
                 direction='forward',
 
3210
                 start_revision=revno,
 
3211
                 end_revision=b.revno())
 
3212
 
 
3213
        if dry_run:
 
3214
            print 'Dry-run, pretending to remove the above revisions.'
 
3215
            if not force:
 
3216
                val = raw_input('Press <enter> to continue')
 
3217
        else:
 
3218
            print 'The above revision(s) will be removed.'
 
3219
            if not force:
 
3220
                val = raw_input('Are you sure [y/N]? ')
 
3221
                if val.lower() not in ('y', 'yes'):
 
3222
                    print 'Canceled'
 
3223
                    return 0
 
3224
 
 
3225
        uncommit(b, tree=tree, dry_run=dry_run, verbose=verbose,
 
3226
                revno=revno)
 
3227
 
 
3228
 
 
3229
class cmd_break_lock(Command):
 
3230
    """Break a dead lock on a repository, branch or working directory.
 
3231
 
 
3232
    CAUTION: Locks should only be broken when you are sure that the process
 
3233
    holding the lock has been stopped.
 
3234
 
 
3235
    You can get information on what locks are open via the 'bzr info' command.
 
3236
    
 
3237
    example:
 
3238
        bzr break-lock
 
3239
    """
 
3240
    takes_args = ['location?']
 
3241
 
 
3242
    def run(self, location=None, show=False):
 
3243
        if location is None:
 
3244
            location = u'.'
 
3245
        control, relpath = bzrdir.BzrDir.open_containing(location)
 
3246
        try:
 
3247
            control.break_lock()
 
3248
        except NotImplementedError:
 
3249
            pass
 
3250
        
 
3251
 
 
3252
class cmd_wait_until_signalled(Command):
 
3253
    """Test helper for test_start_and_stop_bzr_subprocess_send_signal.
 
3254
 
 
3255
    This just prints a line to signal when it is ready, then blocks on stdin.
 
3256
    """
 
3257
 
 
3258
    hidden = True
 
3259
 
 
3260
    def run(self):
 
3261
        sys.stdout.write("running\n")
 
3262
        sys.stdout.flush()
 
3263
        sys.stdin.readline()
 
3264
 
 
3265
 
 
3266
class cmd_serve(Command):
 
3267
    """Run the bzr server."""
 
3268
 
 
3269
    aliases = ['server']
 
3270
 
 
3271
    takes_options = [
 
3272
        Option('inet',
 
3273
               help='serve on stdin/out for use from inetd or sshd'),
 
3274
        Option('port',
 
3275
               help='listen for connections on nominated port of the form '
 
3276
                    '[hostname:]portnumber. Passing 0 as the port number will '
 
3277
                    'result in a dynamically allocated port. Default port is '
 
3278
                    '4155.',
 
3279
               type=str),
 
3280
        Option('directory',
 
3281
               help='serve contents of directory',
 
3282
               type=unicode),
 
3283
        Option('allow-writes',
 
3284
               help='By default the server is a readonly server. Supplying '
 
3285
                    '--allow-writes enables write access to the contents of '
 
3286
                    'the served directory and below. '
 
3287
                ),
 
3288
        ]
 
3289
 
 
3290
    def run(self, port=None, inet=False, directory=None, allow_writes=False):
 
3291
        from bzrlib.smart import medium, server
 
3292
        from bzrlib.transport import get_transport
 
3293
        from bzrlib.transport.chroot import ChrootServer
 
3294
        from bzrlib.transport.remote import BZR_DEFAULT_PORT
 
3295
        if directory is None:
 
3296
            directory = os.getcwd()
 
3297
        url = urlutils.local_path_to_url(directory)
 
3298
        if not allow_writes:
 
3299
            url = 'readonly+' + url
 
3300
        chroot_server = ChrootServer(get_transport(url))
 
3301
        chroot_server.setUp()
 
3302
        t = get_transport(chroot_server.get_url())
 
3303
        if inet:
 
3304
            smart_server = medium.SmartServerPipeStreamMedium(
 
3305
                sys.stdin, sys.stdout, t)
 
3306
        else:
 
3307
            if port is None:
 
3308
                port = BZR_DEFAULT_PORT
 
3309
                host = '127.0.0.1'
 
3310
            else:
 
3311
                if ':' in port:
 
3312
                    host, port = port.split(':')
 
3313
                else:
 
3314
                    host = '127.0.0.1'
 
3315
                port = int(port)
 
3316
            smart_server = server.SmartTCPServer(t, host=host, port=port)
 
3317
            print 'listening on port: ', smart_server.port
 
3318
            sys.stdout.flush()
 
3319
        # for the duration of this server, no UI output is permitted.
 
3320
        # note that this may cause problems with blackbox tests. This should
 
3321
        # be changed with care though, as we dont want to use bandwidth sending
 
3322
        # progress over stderr to smart server clients!
 
3323
        old_factory = ui.ui_factory
 
3324
        try:
 
3325
            ui.ui_factory = ui.SilentUIFactory()
 
3326
            smart_server.serve()
 
3327
        finally:
 
3328
            ui.ui_factory = old_factory
 
3329
 
 
3330
 
 
3331
class cmd_join(Command):
 
3332
    """Combine a subtree into its containing tree.
 
3333
    
 
3334
    This command is for experimental use only.  It requires the target tree
 
3335
    to be in dirstate-with-subtree format, which cannot be converted into
 
3336
    earlier formats.
 
3337
 
 
3338
    The TREE argument should be an independent tree, inside another tree, but
 
3339
    not part of it.  (Such trees can be produced by "bzr split", but also by
 
3340
    running "bzr branch" with the target inside a tree.)
 
3341
 
 
3342
    The result is a combined tree, with the subtree no longer an independant
 
3343
    part.  This is marked as a merge of the subtree into the containing tree,
 
3344
    and all history is preserved.
 
3345
 
 
3346
    If --reference is specified, the subtree retains its independence.  It can
 
3347
    be branched by itself, and can be part of multiple projects at the same
 
3348
    time.  But operations performed in the containing tree, such as commit
 
3349
    and merge, will recurse into the subtree.
 
3350
    """
 
3351
 
 
3352
    _see_also = ['split']
 
3353
    takes_args = ['tree']
 
3354
    takes_options = [Option('reference', 'join by reference')]
 
3355
    hidden = True
 
3356
 
 
3357
    def run(self, tree, reference=False):
 
3358
        sub_tree = WorkingTree.open(tree)
 
3359
        parent_dir = osutils.dirname(sub_tree.basedir)
 
3360
        containing_tree = WorkingTree.open_containing(parent_dir)[0]
 
3361
        repo = containing_tree.branch.repository
 
3362
        if not repo.supports_rich_root():
 
3363
            raise errors.BzrCommandError(
 
3364
                "Can't join trees because %s doesn't support rich root data.\n"
 
3365
                "You can use bzr upgrade on the repository."
 
3366
                % (repo,))
 
3367
        if reference:
 
3368
            try:
 
3369
                containing_tree.add_reference(sub_tree)
 
3370
            except errors.BadReferenceTarget, e:
 
3371
                # XXX: Would be better to just raise a nicely printable
 
3372
                # exception from the real origin.  Also below.  mbp 20070306
 
3373
                raise errors.BzrCommandError("Cannot join %s.  %s" %
 
3374
                                             (tree, e.reason))
 
3375
        else:
 
3376
            try:
 
3377
                containing_tree.subsume(sub_tree)
 
3378
            except errors.BadSubsumeSource, e:
 
3379
                raise errors.BzrCommandError("Cannot join %s.  %s" % 
 
3380
                                             (tree, e.reason))
 
3381
 
 
3382
 
 
3383
class cmd_split(Command):
 
3384
    """Split a tree into two trees.
 
3385
 
 
3386
    This command is for experimental use only.  It requires the target tree
 
3387
    to be in dirstate-with-subtree format, which cannot be converted into
 
3388
    earlier formats.
 
3389
 
 
3390
    The TREE argument should be a subdirectory of a working tree.  That
 
3391
    subdirectory will be converted into an independent tree, with its own
 
3392
    branch.  Commits in the top-level tree will not apply to the new subtree.
 
3393
    If you want that behavior, do "bzr join --reference TREE".
 
3394
    """
 
3395
 
 
3396
    _see_also = ['join']
 
3397
    takes_args = ['tree']
 
3398
 
 
3399
    hidden = True
 
3400
 
 
3401
    def run(self, tree):
 
3402
        containing_tree, subdir = WorkingTree.open_containing(tree)
 
3403
        sub_id = containing_tree.path2id(subdir)
 
3404
        if sub_id is None:
 
3405
            raise errors.NotVersionedError(subdir)
 
3406
        try:
 
3407
            containing_tree.extract(sub_id)
 
3408
        except errors.RootNotRich:
 
3409
            raise errors.UpgradeRequired(containing_tree.branch.base)
 
3410
 
 
3411
 
 
3412
 
 
3413
class cmd_merge_directive(Command):
 
3414
    """Generate a merge directive for auto-merge tools.
 
3415
 
 
3416
    A directive requests a merge to be performed, and also provides all the
 
3417
    information necessary to do so.  This means it must either include a
 
3418
    revision bundle, or the location of a branch containing the desired
 
3419
    revision.
 
3420
 
 
3421
    A submit branch (the location to merge into) must be supplied the first
 
3422
    time the command is issued.  After it has been supplied once, it will
 
3423
    be remembered as the default.
 
3424
 
 
3425
    A public branch is optional if a revision bundle is supplied, but required
 
3426
    if --diff or --plain is specified.  It will be remembered as the default
 
3427
    after the first use.
 
3428
    """
 
3429
 
 
3430
    takes_args = ['submit_branch?', 'public_branch?']
 
3431
 
 
3432
    takes_options = [
 
3433
        RegistryOption.from_kwargs('patch-type',
 
3434
            'The type of patch to include in the directive',
 
3435
            title='Patch type', value_switches=True, enum_switch=False,
 
3436
            bundle='Bazaar revision bundle (default)',
 
3437
            diff='Normal unified diff',
 
3438
            plain='No patch, just directive'),
 
3439
        Option('sign', help='GPG-sign the directive'), 'revision',
 
3440
        Option('mail-to', type=str,
 
3441
            help='Instead of printing the directive, email to this address'),
 
3442
        Option('message', type=str, short_name='m',
 
3443
            help='Message to use when committing this merge')
 
3444
        ]
 
3445
 
 
3446
    def run(self, submit_branch=None, public_branch=None, patch_type='bundle',
 
3447
            sign=False, revision=None, mail_to=None, message=None):
 
3448
        if patch_type == 'plain':
 
3449
            patch_type = None
 
3450
        branch = Branch.open('.')
 
3451
        stored_submit_branch = branch.get_submit_branch()
 
3452
        if submit_branch is None:
 
3453
            submit_branch = stored_submit_branch
 
3454
        else:
 
3455
            if stored_submit_branch is None:
 
3456
                branch.set_submit_branch(submit_branch)
 
3457
        if submit_branch is None:
 
3458
            submit_branch = branch.get_parent()
 
3459
        if submit_branch is None:
 
3460
            raise errors.BzrCommandError('No submit branch specified or known')
 
3461
 
 
3462
        stored_public_branch = branch.get_public_branch()
 
3463
        if public_branch is None:
 
3464
            public_branch = stored_public_branch
 
3465
        elif stored_public_branch is None:
 
3466
            branch.set_public_branch(public_branch)
 
3467
        if patch_type != "bundle" and public_branch is None:
 
3468
            raise errors.BzrCommandError('No public branch specified or'
 
3469
                                         ' known')
 
3470
        if revision is not None:
 
3471
            if len(revision) != 1:
 
3472
                raise errors.BzrCommandError('bzr merge-directive takes '
 
3473
                    'exactly one revision identifier')
 
3474
            else:
 
3475
                revision_id = revision[0].in_history(branch).rev_id
 
3476
        else:
 
3477
            revision_id = branch.last_revision()
 
3478
        directive = merge_directive.MergeDirective.from_objects(
 
3479
            branch.repository, revision_id, time.time(),
 
3480
            osutils.local_time_offset(), submit_branch,
 
3481
            public_branch=public_branch, patch_type=patch_type,
 
3482
            message=message)
 
3483
        if mail_to is None:
 
3484
            if sign:
 
3485
                self.outf.write(directive.to_signed(branch))
 
3486
            else:
 
3487
                self.outf.writelines(directive.to_lines())
 
3488
        else:
 
3489
            message = directive.to_email(mail_to, branch, sign)
 
3490
            s = smtplib.SMTP()
 
3491
            server = branch.get_config().get_user_option('smtp_server')
 
3492
            if not server:
 
3493
                server = 'localhost'
 
3494
            s.connect(server)
 
3495
            s.sendmail(message['From'], message['To'], message.as_string())
 
3496
 
 
3497
 
 
3498
class cmd_tag(Command):
 
3499
    """Create a tag naming a revision.
 
3500
    
 
3501
    Tags give human-meaningful names to revisions.  Commands that take a -r
 
3502
    (--revision) option can be given -rtag:X, where X is any previously
 
3503
    created tag.
 
3504
 
 
3505
    Tags are stored in the branch.  Tags are copied from one branch to another
 
3506
    along when you branch, push, pull or merge.
 
3507
 
 
3508
    It is an error to give a tag name that already exists unless you pass 
 
3509
    --force, in which case the tag is moved to point to the new revision.
 
3510
    """
 
3511
 
 
3512
    _see_also = ['commit', 'tags']
 
3513
    takes_args = ['tag_name']
 
3514
    takes_options = [
 
3515
        Option('delete',
 
3516
            help='Delete this tag rather than placing it.',
 
3517
            ),
 
3518
        Option('directory',
 
3519
            help='Branch in which to place the tag.',
 
3520
            short_name='d',
 
3521
            type=unicode,
 
3522
            ),
 
3523
        Option('force',
 
3524
            help='Replace existing tags',
 
3525
            ),
 
3526
        'revision',
 
3527
        ]
 
3528
 
 
3529
    def run(self, tag_name,
 
3530
            delete=None,
 
3531
            directory='.',
 
3532
            force=None,
 
3533
            revision=None,
 
3534
            ):
 
3535
        branch, relpath = Branch.open_containing(directory)
 
3536
        branch.lock_write()
 
3537
        try:
 
3538
            if delete:
 
3539
                branch.tags.delete_tag(tag_name)
 
3540
                self.outf.write('Deleted tag %s.\n' % tag_name)
 
3541
            else:
 
3542
                if revision:
 
3543
                    if len(revision) != 1:
 
3544
                        raise errors.BzrCommandError(
 
3545
                            "Tags can only be placed on a single revision, "
 
3546
                            "not on a range")
 
3547
                    revision_id = revision[0].in_history(branch).rev_id
 
3548
                else:
 
3549
                    revision_id = branch.last_revision()
 
3550
                if (not force) and branch.tags.has_tag(tag_name):
 
3551
                    raise errors.TagAlreadyExists(tag_name)
 
3552
                branch.tags.set_tag(tag_name, revision_id)
 
3553
                self.outf.write('Created tag %s.\n' % tag_name)
 
3554
        finally:
 
3555
            branch.unlock()
 
3556
 
 
3557
 
 
3558
class cmd_tags(Command):
 
3559
    """List tags.
 
3560
 
 
3561
    This tag shows a table of tag names and the revisions they reference.
 
3562
    """
 
3563
 
 
3564
    _see_also = ['tag']
 
3565
    takes_options = [
 
3566
        Option('directory',
 
3567
            help='Branch whose tags should be displayed',
 
3568
            short_name='d',
 
3569
            type=unicode,
 
3570
            ),
 
3571
    ]
 
3572
 
 
3573
    @display_command
 
3574
    def run(self,
 
3575
            directory='.',
 
3576
            ):
 
3577
        branch, relpath = Branch.open_containing(directory)
 
3578
        for tag_name, target in sorted(branch.tags.get_tag_dict().items()):
 
3579
            self.outf.write('%-20s %s\n' % (tag_name, target))
 
3580
 
 
3581
 
 
3582
# command-line interpretation helper for merge-related commands
 
3583
def _merge_helper(other_revision, base_revision,
 
3584
                  check_clean=True, ignore_zero=False,
 
3585
                  this_dir=None, backup_files=False,
 
3586
                  merge_type=None,
 
3587
                  file_list=None, show_base=False, reprocess=False,
 
3588
                  pull=False,
 
3589
                  pb=DummyProgress(),
 
3590
                  change_reporter=None,
 
3591
                  other_rev_id=None):
 
3592
    """Merge changes into a tree.
 
3593
 
 
3594
    base_revision
 
3595
        list(path, revno) Base for three-way merge.  
 
3596
        If [None, None] then a base will be automatically determined.
 
3597
    other_revision
 
3598
        list(path, revno) Other revision for three-way merge.
 
3599
    this_dir
 
3600
        Directory to merge changes into; '.' by default.
 
3601
    check_clean
 
3602
        If true, this_dir must have no uncommitted changes before the
 
3603
        merge begins.
 
3604
    ignore_zero - If true, suppress the "zero conflicts" message when 
 
3605
        there are no conflicts; should be set when doing something we expect
 
3606
        to complete perfectly.
 
3607
    file_list - If supplied, merge only changes to selected files.
 
3608
 
 
3609
    All available ancestors of other_revision and base_revision are
 
3610
    automatically pulled into the branch.
 
3611
 
 
3612
    The revno may be -1 to indicate the last revision on the branch, which is
 
3613
    the typical case.
 
3614
 
 
3615
    This function is intended for use from the command line; programmatic
 
3616
    clients might prefer to call merge.merge_inner(), which has less magic 
 
3617
    behavior.
 
3618
    """
 
3619
    # Loading it late, so that we don't always have to import bzrlib.merge
 
3620
    if merge_type is None:
 
3621
        merge_type = _mod_merge.Merge3Merger
 
3622
    if this_dir is None:
 
3623
        this_dir = u'.'
 
3624
    this_tree = WorkingTree.open_containing(this_dir)[0]
 
3625
    if show_base and not merge_type is _mod_merge.Merge3Merger:
 
3626
        raise errors.BzrCommandError("Show-base is not supported for this merge"
 
3627
                                     " type. %s" % merge_type)
 
3628
    if reprocess and not merge_type.supports_reprocess:
 
3629
        raise errors.BzrCommandError("Conflict reduction is not supported for merge"
 
3630
                                     " type %s." % merge_type)
 
3631
    if reprocess and show_base:
 
3632
        raise errors.BzrCommandError("Cannot do conflict reduction and show base.")
 
3633
    # TODO: jam 20070226 We should really lock these trees earlier. However, we
 
3634
    #       only want to take out a lock_tree_write() if we don't have to pull
 
3635
    #       any ancestry. But merge might fetch ancestry in the middle, in
 
3636
    #       which case we would need a lock_write().
 
3637
    #       Because we cannot upgrade locks, for now we live with the fact that
 
3638
    #       the tree will be locked multiple times during a merge. (Maybe
 
3639
    #       read-only some of the time, but it means things will get read
 
3640
    #       multiple times.)
 
3641
    try:
 
3642
        merger = _mod_merge.Merger(this_tree.branch, this_tree=this_tree,
 
3643
                                   pb=pb, change_reporter=change_reporter)
 
3644
        merger.pp = ProgressPhase("Merge phase", 5, pb)
 
3645
        merger.pp.next_phase()
 
3646
        merger.check_basis(check_clean)
 
3647
        if other_rev_id is not None:
 
3648
            merger.set_other_revision(other_rev_id, this_tree.branch)
 
3649
        else:
 
3650
            merger.set_other(other_revision)
 
3651
        merger.pp.next_phase()
 
3652
        merger.set_base(base_revision)
 
3653
        if merger.base_rev_id == merger.other_rev_id:
 
3654
            note('Nothing to do.')
 
3655
            return 0
 
3656
        if file_list is None:
 
3657
            if pull and merger.base_rev_id == merger.this_rev_id:
 
3658
                # FIXME: deduplicate with pull
 
3659
                result = merger.this_tree.pull(merger.this_branch,
 
3660
                        False, merger.other_rev_id)
 
3661
                if result.old_revid == result.new_revid:
 
3662
                    note('No revisions to pull.')
 
3663
                else:
 
3664
                    note('Now on revision %d.' % result.new_revno)
 
3665
                return 0
 
3666
        merger.backup_files = backup_files
 
3667
        merger.merge_type = merge_type 
 
3668
        merger.set_interesting_files(file_list)
 
3669
        merger.show_base = show_base 
 
3670
        merger.reprocess = reprocess
 
3671
        conflicts = merger.do_merge()
 
3672
        if file_list is None:
 
3673
            merger.set_pending()
 
3674
    finally:
 
3675
        pb.clear()
 
3676
    return conflicts
 
3677
 
 
3678
 
 
3679
# Compatibility
 
3680
merge = _merge_helper
 
3681
 
 
3682
 
 
3683
# these get imported and then picked up by the scan for cmd_*
 
3684
# TODO: Some more consistent way to split command definitions across files;
 
3685
# we do need to load at least some information about them to know of 
 
3686
# aliases.  ideally we would avoid loading the implementation until the
 
3687
# details were needed.
 
3688
from bzrlib.cmd_version_info import cmd_version_info
 
3689
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore
 
3690
from bzrlib.bundle.commands import cmd_bundle_revisions
 
3691
from bzrlib.sign_my_commits import cmd_sign_my_commits
 
3692
from bzrlib.weave_commands import cmd_weave_list, cmd_weave_join, \
 
3693
        cmd_weave_plan_merge, cmd_weave_merge_text