/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: Matthieu Moy
  • Date: 2006-09-03 15:58:15 UTC
  • mto: (1998.1.1 jam-integration)
  • mto: This revision was merged to the branch mainline in revision 1999.
  • Revision ID: Matthieu.Moy@imag.fr-20060903155815-9009ac7d567b0c2a
missing newline

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2004, 2005, 2006 by 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
 
 
20
import codecs
 
21
import errno
 
22
import os
 
23
import os.path
 
24
import sys
 
25
 
 
26
import bzrlib
 
27
from bzrlib import (
 
28
    branch,
 
29
    bundle,
 
30
    bzrdir,
 
31
    config,
 
32
    errors,
 
33
    ignores,
 
34
    log,
 
35
    osutils,
 
36
    repository,
 
37
    transport,
 
38
    ui,
 
39
    urlutils,
 
40
    )
 
41
from bzrlib.branch import Branch, BranchReferenceFormat
 
42
from bzrlib.bundle import read_bundle_from_url
 
43
from bzrlib.bundle.apply_bundle import install_bundle, merge_bundle
 
44
from bzrlib.conflicts import ConflictList
 
45
from bzrlib.commands import Command, display_command
 
46
from bzrlib.errors import (BzrError, BzrCheckError, BzrCommandError, 
 
47
                           NotBranchError, DivergedBranches, NotConflicted,
 
48
                           NoSuchFile, NoWorkingTree, FileInWrongBranch,
 
49
                           NotVersionedError, NotABundle)
 
50
from bzrlib.merge import Merge3Merger
 
51
from bzrlib.option import Option
 
52
from bzrlib.progress import DummyProgress, ProgressPhase
 
53
from bzrlib.revision import common_ancestor
 
54
from bzrlib.revisionspec import RevisionSpec
 
55
from bzrlib.trace import mutter, note, log_error, warning, is_quiet, info
 
56
from bzrlib.transport.local import LocalTransport
 
57
from bzrlib.workingtree import WorkingTree
 
58
 
 
59
 
 
60
def tree_files(file_list, default_branch=u'.'):
 
61
    try:
 
62
        return internal_tree_files(file_list, default_branch)
 
63
    except FileInWrongBranch, e:
 
64
        raise BzrCommandError("%s is not in the same branch as %s" %
 
65
                             (e.path, file_list[0]))
 
66
 
 
67
 
 
68
# XXX: Bad function name; should possibly also be a class method of
 
69
# WorkingTree rather than a function.
 
70
def internal_tree_files(file_list, default_branch=u'.'):
 
71
    """Convert command-line paths to a WorkingTree and relative paths.
 
72
 
 
73
    This is typically used for command-line processors that take one or
 
74
    more filenames, and infer the workingtree that contains them.
 
75
 
 
76
    The filenames given are not required to exist.
 
77
 
 
78
    :param file_list: Filenames to convert.  
 
79
 
 
80
    :param default_branch: Fallback tree path to use if file_list is empty or None.
 
81
 
 
82
    :return: workingtree, [relative_paths]
 
83
    """
 
84
    if file_list is None or len(file_list) == 0:
 
85
        return WorkingTree.open_containing(default_branch)[0], file_list
 
86
    tree = WorkingTree.open_containing(file_list[0])[0]
 
87
    new_list = []
 
88
    for filename in file_list:
 
89
        try:
 
90
            new_list.append(tree.relpath(filename))
 
91
        except errors.PathNotChild:
 
92
            raise FileInWrongBranch(tree.branch, filename)
 
93
    return tree, new_list
 
94
 
 
95
 
 
96
def get_format_type(typestring):
 
97
    """Parse and return a format specifier."""
 
98
    if typestring == "weave":
 
99
        return bzrdir.BzrDirFormat6()
 
100
    if typestring == "default":
 
101
        return bzrdir.BzrDirMetaFormat1()
 
102
    if typestring == "metaweave":
 
103
        format = bzrdir.BzrDirMetaFormat1()
 
104
        format.repository_format = repository.RepositoryFormat7()
 
105
        return format
 
106
    if typestring == "knit":
 
107
        format = bzrdir.BzrDirMetaFormat1()
 
108
        format.repository_format = repository.RepositoryFormatKnit1()
 
109
        return format
 
110
    msg = "Unknown bzr format %s. Current formats are: default, knit,\n" \
 
111
          "metaweave and weave" % typestring
 
112
    raise BzrCommandError(msg)
 
113
 
 
114
 
 
115
# TODO: Make sure no commands unconditionally use the working directory as a
 
116
# branch.  If a filename argument is used, the first of them should be used to
 
117
# specify the branch.  (Perhaps this can be factored out into some kind of
 
118
# Argument class, representing a file in a branch, where the first occurrence
 
119
# opens the branch?)
 
120
 
 
121
class cmd_status(Command):
 
122
    """Display status summary.
 
123
 
 
124
    This reports on versioned and unknown files, reporting them
 
125
    grouped by state.  Possible states are:
 
126
 
 
127
    added
 
128
        Versioned in the working copy but not in the previous revision.
 
129
 
 
130
    removed
 
131
        Versioned in the previous revision but removed or deleted
 
132
        in the working copy.
 
133
 
 
134
    renamed
 
135
        Path of this file changed from the previous revision;
 
136
        the text may also have changed.  This includes files whose
 
137
        parent directory was renamed.
 
138
 
 
139
    modified
 
140
        Text has changed since the previous revision.
 
141
 
 
142
    unknown
 
143
        Not versioned and not matching an ignore pattern.
 
144
 
 
145
    To see ignored files use 'bzr ignored'.  For details in the
 
146
    changes to file texts, use 'bzr diff'.
 
147
 
 
148
    If no arguments are specified, the status of the entire working
 
149
    directory is shown.  Otherwise, only the status of the specified
 
150
    files or directories is reported.  If a directory is given, status
 
151
    is reported for everything inside that directory.
 
152
 
 
153
    If a revision argument is given, the status is calculated against
 
154
    that revision, or between two revisions if two are provided.
 
155
    """
 
156
    
 
157
    # TODO: --no-recurse, --recurse options
 
158
    
 
159
    takes_args = ['file*']
 
160
    takes_options = ['show-ids', 'revision']
 
161
    aliases = ['st', 'stat']
 
162
 
 
163
    encoding_type = 'replace'
 
164
    
 
165
    @display_command
 
166
    def run(self, show_ids=False, file_list=None, revision=None):
 
167
        from bzrlib.status import show_tree_status
 
168
 
 
169
        tree, file_list = tree_files(file_list)
 
170
            
 
171
        show_tree_status(tree, show_ids=show_ids,
 
172
                         specific_files=file_list, revision=revision,
 
173
                         to_file=self.outf)
 
174
 
 
175
 
 
176
class cmd_cat_revision(Command):
 
177
    """Write out metadata for a revision.
 
178
    
 
179
    The revision to print can either be specified by a specific
 
180
    revision identifier, or you can use --revision.
 
181
    """
 
182
 
 
183
    hidden = True
 
184
    takes_args = ['revision_id?']
 
185
    takes_options = ['revision']
 
186
    # cat-revision is more for frontends so should be exact
 
187
    encoding = 'strict'
 
188
    
 
189
    @display_command
 
190
    def run(self, revision_id=None, revision=None):
 
191
 
 
192
        if revision_id is not None and revision is not None:
 
193
            raise BzrCommandError('You can only supply one of revision_id or --revision')
 
194
        if revision_id is None and revision is None:
 
195
            raise BzrCommandError('You must supply either --revision or a revision_id')
 
196
        b = WorkingTree.open_containing(u'.')[0].branch
 
197
 
 
198
        # TODO: jam 20060112 should cat-revision always output utf-8?
 
199
        if revision_id is not None:
 
200
            self.outf.write(b.repository.get_revision_xml(revision_id).decode('utf-8'))
 
201
        elif revision is not None:
 
202
            for rev in revision:
 
203
                if rev is None:
 
204
                    raise BzrCommandError('You cannot specify a NULL revision.')
 
205
                revno, rev_id = rev.in_history(b)
 
206
                self.outf.write(b.repository.get_revision_xml(rev_id).decode('utf-8'))
 
207
    
 
208
 
 
209
class cmd_revno(Command):
 
210
    """Show current revision number.
 
211
 
 
212
    This is equal to the number of revisions on this branch.
 
213
    """
 
214
 
 
215
    takes_args = ['location?']
 
216
 
 
217
    @display_command
 
218
    def run(self, location=u'.'):
 
219
        self.outf.write(str(Branch.open_containing(location)[0].revno()))
 
220
        self.outf.write('\n')
 
221
 
 
222
 
 
223
class cmd_revision_info(Command):
 
224
    """Show revision number and revision id for a given revision identifier.
 
225
    """
 
226
    hidden = True
 
227
    takes_args = ['revision_info*']
 
228
    takes_options = ['revision']
 
229
 
 
230
    @display_command
 
231
    def run(self, revision=None, revision_info_list=[]):
 
232
 
 
233
        revs = []
 
234
        if revision is not None:
 
235
            revs.extend(revision)
 
236
        if revision_info_list is not None:
 
237
            for rev in revision_info_list:
 
238
                revs.append(RevisionSpec.from_string(rev))
 
239
        if len(revs) == 0:
 
240
            raise BzrCommandError('You must supply a revision identifier')
 
241
 
 
242
        b = WorkingTree.open_containing(u'.')[0].branch
 
243
 
 
244
        for rev in revs:
 
245
            revinfo = rev.in_history(b)
 
246
            if revinfo.revno is None:
 
247
                print '     %s' % revinfo.rev_id
 
248
            else:
 
249
                print '%4d %s' % (revinfo.revno, revinfo.rev_id)
 
250
 
 
251
    
 
252
class cmd_add(Command):
 
253
    """Add specified files or directories.
 
254
 
 
255
    In non-recursive mode, all the named items are added, regardless
 
256
    of whether they were previously ignored.  A warning is given if
 
257
    any of the named files are already versioned.
 
258
 
 
259
    In recursive mode (the default), files are treated the same way
 
260
    but the behaviour for directories is different.  Directories that
 
261
    are already versioned do not give a warning.  All directories,
 
262
    whether already versioned or not, are searched for files or
 
263
    subdirectories that are neither versioned or ignored, and these
 
264
    are added.  This search proceeds recursively into versioned
 
265
    directories.  If no names are given '.' is assumed.
 
266
 
 
267
    Therefore simply saying 'bzr add' will version all files that
 
268
    are currently unknown.
 
269
 
 
270
    Adding a file whose parent directory is not versioned will
 
271
    implicitly add the parent, and so on up to the root. This means
 
272
    you should never need to explicitly add a directory, they'll just
 
273
    get added when you add a file in the directory.
 
274
 
 
275
    --dry-run will show which files would be added, but not actually 
 
276
    add them.
 
277
 
 
278
    --file-ids-from will try to use the file ids from the supplied path.
 
279
    It looks up ids trying to find a matching parent directory with the
 
280
    same filename, and then by pure path.
 
281
    """
 
282
    takes_args = ['file*']
 
283
    takes_options = ['no-recurse', 'dry-run', 'verbose',
 
284
                     Option('file-ids-from', type=unicode,
 
285
                            help='Lookup file ids from here')]
 
286
    encoding_type = 'replace'
 
287
 
 
288
    def run(self, file_list, no_recurse=False, dry_run=False, verbose=False,
 
289
            file_ids_from=None):
 
290
        import bzrlib.add
 
291
 
 
292
        if file_ids_from is not None:
 
293
            try:
 
294
                base_tree, base_path = WorkingTree.open_containing(
 
295
                                            file_ids_from)
 
296
            except errors.NoWorkingTree:
 
297
                base_branch, base_path = branch.Branch.open_containing(
 
298
                                            file_ids_from)
 
299
                base_tree = base_branch.basis_tree()
 
300
 
 
301
            action = bzrlib.add.AddFromBaseAction(base_tree, base_path,
 
302
                          to_file=self.outf, should_print=(not is_quiet()))
 
303
        else:
 
304
            action = bzrlib.add.AddAction(to_file=self.outf,
 
305
                should_print=(not is_quiet()))
 
306
 
 
307
        added, ignored = bzrlib.add.smart_add(file_list, not no_recurse,
 
308
                                              action=action, save=not dry_run)
 
309
        if len(ignored) > 0:
 
310
            if verbose:
 
311
                for glob in sorted(ignored.keys()):
 
312
                    for path in ignored[glob]:
 
313
                        self.outf.write("ignored %s matching \"%s\"\n" 
 
314
                                        % (path, glob))
 
315
            else:
 
316
                match_len = 0
 
317
                for glob, paths in ignored.items():
 
318
                    match_len += len(paths)
 
319
                self.outf.write("ignored %d file(s).\n" % match_len)
 
320
            self.outf.write("If you wish to add some of these files,"
 
321
                            " please add them by name.\n")
 
322
 
 
323
 
 
324
class cmd_mkdir(Command):
 
325
    """Create a new versioned directory.
 
326
 
 
327
    This is equivalent to creating the directory and then adding it.
 
328
    """
 
329
 
 
330
    takes_args = ['dir+']
 
331
    encoding_type = 'replace'
 
332
 
 
333
    def run(self, dir_list):
 
334
        for d in dir_list:
 
335
            os.mkdir(d)
 
336
            wt, dd = WorkingTree.open_containing(d)
 
337
            wt.add([dd])
 
338
            self.outf.write('added %s\n' % d)
 
339
 
 
340
 
 
341
class cmd_relpath(Command):
 
342
    """Show path of a file relative to root"""
 
343
 
 
344
    takes_args = ['filename']
 
345
    hidden = True
 
346
    
 
347
    @display_command
 
348
    def run(self, filename):
 
349
        # TODO: jam 20050106 Can relpath return a munged path if
 
350
        #       sys.stdout encoding cannot represent it?
 
351
        tree, relpath = WorkingTree.open_containing(filename)
 
352
        self.outf.write(relpath)
 
353
        self.outf.write('\n')
 
354
 
 
355
 
 
356
class cmd_inventory(Command):
 
357
    """Show inventory of the current working copy or a revision.
 
358
 
 
359
    It is possible to limit the output to a particular entry
 
360
    type using the --kind option.  For example; --kind file.
 
361
    """
 
362
 
 
363
    takes_options = ['revision', 'show-ids', 'kind']
 
364
    
 
365
    @display_command
 
366
    def run(self, revision=None, show_ids=False, kind=None):
 
367
        if kind and kind not in ['file', 'directory', 'symlink']:
 
368
            raise BzrCommandError('invalid kind specified')
 
369
        tree = WorkingTree.open_containing(u'.')[0]
 
370
        if revision is None:
 
371
            inv = tree.read_working_inventory()
 
372
        else:
 
373
            if len(revision) > 1:
 
374
                raise BzrCommandError('bzr inventory --revision takes'
 
375
                    ' exactly one revision identifier')
 
376
            inv = tree.branch.repository.get_revision_inventory(
 
377
                revision[0].in_history(tree.branch).rev_id)
 
378
 
 
379
        for path, entry in inv.entries():
 
380
            if kind and kind != entry.kind:
 
381
                continue
 
382
            if show_ids:
 
383
                self.outf.write('%-50s %s\n' % (path, entry.file_id))
 
384
            else:
 
385
                self.outf.write(path)
 
386
                self.outf.write('\n')
 
387
 
 
388
 
 
389
class cmd_mv(Command):
 
390
    """Move or rename a file.
 
391
 
 
392
    usage:
 
393
        bzr mv OLDNAME NEWNAME
 
394
        bzr mv SOURCE... DESTINATION
 
395
 
 
396
    If the last argument is a versioned directory, all the other names
 
397
    are moved into it.  Otherwise, there must be exactly two arguments
 
398
    and the file is changed to a new name, which must not already exist.
 
399
 
 
400
    Files cannot be moved between branches.
 
401
    """
 
402
 
 
403
    takes_args = ['names*']
 
404
    aliases = ['move', 'rename']
 
405
    encoding_type = 'replace'
 
406
 
 
407
    def run(self, names_list):
 
408
        if names_list is None:
 
409
            names_list = []
 
410
 
 
411
        if len(names_list) < 2:
 
412
            raise BzrCommandError("missing file argument")
 
413
        tree, rel_names = tree_files(names_list)
 
414
        
 
415
        if os.path.isdir(names_list[-1]):
 
416
            # move into existing directory
 
417
            for pair in tree.move(rel_names[:-1], rel_names[-1]):
 
418
                self.outf.write("%s => %s\n" % pair)
 
419
        else:
 
420
            if len(names_list) != 2:
 
421
                raise BzrCommandError('to mv multiple files the destination '
 
422
                                      'must be a versioned directory')
 
423
            tree.rename_one(rel_names[0], rel_names[1])
 
424
            self.outf.write("%s => %s\n" % (rel_names[0], rel_names[1]))
 
425
            
 
426
    
 
427
class cmd_pull(Command):
 
428
    """Turn this branch into a mirror of another branch.
 
429
 
 
430
    This command only works on branches that have not diverged.  Branches are
 
431
    considered diverged if the destination branch's most recent commit is one
 
432
    that has not been merged (directly or indirectly) into the parent.
 
433
 
 
434
    If branches have diverged, you can use 'bzr merge' to integrate the changes
 
435
    from one into the other.  Once one branch has merged, the other should
 
436
    be able to pull it again.
 
437
 
 
438
    If you want to forget your local changes and just update your branch to
 
439
    match the remote one, use pull --overwrite.
 
440
 
 
441
    If there is no default location set, the first pull will set it.  After
 
442
    that, you can omit the location to use the default.  To change the
 
443
    default, use --remember. The value will only be saved if the remote
 
444
    location can be accessed.
 
445
    """
 
446
 
 
447
    takes_options = ['remember', 'overwrite', 'revision', 'verbose']
 
448
    takes_args = ['location?']
 
449
    encoding_type = 'replace'
 
450
 
 
451
    def run(self, location=None, remember=False, overwrite=False, revision=None, verbose=False):
 
452
        # FIXME: too much stuff is in the command class
 
453
        try:
 
454
            tree_to = WorkingTree.open_containing(u'.')[0]
 
455
            branch_to = tree_to.branch
 
456
        except NoWorkingTree:
 
457
            tree_to = None
 
458
            branch_to = Branch.open_containing(u'.')[0]
 
459
 
 
460
        reader = None
 
461
        if location is not None:
 
462
            try:
 
463
                reader = bundle.read_bundle_from_url(location)
 
464
            except NotABundle:
 
465
                pass # Continue on considering this url a Branch
 
466
 
 
467
        stored_loc = branch_to.get_parent()
 
468
        if location is None:
 
469
            if stored_loc is None:
 
470
                raise BzrCommandError("No pull location known or specified.")
 
471
            else:
 
472
                display_url = urlutils.unescape_for_display(stored_loc,
 
473
                        self.outf.encoding)
 
474
                self.outf.write("Using saved location: %s\n" % display_url)
 
475
                location = stored_loc
 
476
 
 
477
 
 
478
        if reader is not None:
 
479
            install_bundle(branch_to.repository, reader)
 
480
            branch_from = branch_to
 
481
        else:
 
482
            branch_from = Branch.open(location)
 
483
 
 
484
            if branch_to.get_parent() is None or remember:
 
485
                branch_to.set_parent(branch_from.base)
 
486
 
 
487
        rev_id = None
 
488
        if revision is None:
 
489
            if reader is not None:
 
490
                rev_id = reader.target
 
491
        elif len(revision) == 1:
 
492
            rev_id = revision[0].in_history(branch_from).rev_id
 
493
        else:
 
494
            raise BzrCommandError('bzr pull --revision takes one value.')
 
495
 
 
496
        old_rh = branch_to.revision_history()
 
497
        if tree_to is not None:
 
498
            count = tree_to.pull(branch_from, overwrite, rev_id)
 
499
        else:
 
500
            count = branch_to.pull(branch_from, overwrite, rev_id)
 
501
        note('%d revision(s) pulled.' % (count,))
 
502
 
 
503
        if verbose:
 
504
            new_rh = branch_to.revision_history()
 
505
            if old_rh != new_rh:
 
506
                # Something changed
 
507
                from bzrlib.log import show_changed_revisions
 
508
                show_changed_revisions(branch_to, old_rh, new_rh,
 
509
                                       to_file=self.outf)
 
510
 
 
511
 
 
512
class cmd_push(Command):
 
513
    """Update a mirror of this branch.
 
514
    
 
515
    The target branch will not have its working tree populated because this
 
516
    is both expensive, and is not supported on remote file systems.
 
517
    
 
518
    Some smart servers or protocols *may* put the working tree in place in
 
519
    the future.
 
520
 
 
521
    This command only works on branches that have not diverged.  Branches are
 
522
    considered diverged if the destination branch's most recent commit is one
 
523
    that has not been merged (directly or indirectly) by the source branch.
 
524
 
 
525
    If branches have diverged, you can use 'bzr push --overwrite' to replace
 
526
    the other branch completely, discarding its unmerged changes.
 
527
    
 
528
    If you want to ensure you have the different changes in the other branch,
 
529
    do a merge (see bzr help merge) from the other branch, and commit that.
 
530
    After that you will be able to do a push without '--overwrite'.
 
531
 
 
532
    If there is no default push location set, the first push will set it.
 
533
    After that, you can omit the location to use the default.  To change the
 
534
    default, use --remember. The value will only be saved if the remote
 
535
    location can be accessed.
 
536
    """
 
537
 
 
538
    takes_options = ['remember', 'overwrite', 'verbose',
 
539
                     Option('create-prefix', 
 
540
                            help='Create the path leading up to the branch '
 
541
                                 'if it does not already exist')]
 
542
    takes_args = ['location?']
 
543
    encoding_type = 'replace'
 
544
 
 
545
    def run(self, location=None, remember=False, overwrite=False,
 
546
            create_prefix=False, verbose=False):
 
547
        # FIXME: Way too big!  Put this into a function called from the
 
548
        # command.
 
549
        
 
550
        br_from = Branch.open_containing('.')[0]
 
551
        stored_loc = br_from.get_push_location()
 
552
        if location is None:
 
553
            if stored_loc is None:
 
554
                raise BzrCommandError("No push location known or specified.")
 
555
            else:
 
556
                display_url = urlutils.unescape_for_display(stored_loc,
 
557
                        self.outf.encoding)
 
558
                self.outf.write("Using saved location: %s\n" % display_url)
 
559
                location = stored_loc
 
560
 
 
561
        to_transport = transport.get_transport(location)
 
562
        location_url = to_transport.base
 
563
 
 
564
        old_rh = []
 
565
        try:
 
566
            dir_to = bzrdir.BzrDir.open(location_url)
 
567
            br_to = dir_to.open_branch()
 
568
        except NotBranchError:
 
569
            # create a branch.
 
570
            to_transport = to_transport.clone('..')
 
571
            if not create_prefix:
 
572
                try:
 
573
                    relurl = to_transport.relpath(location_url)
 
574
                    mutter('creating directory %s => %s', location_url, relurl)
 
575
                    to_transport.mkdir(relurl)
 
576
                except NoSuchFile:
 
577
                    raise BzrCommandError("Parent directory of %s "
 
578
                                          "does not exist." % location)
 
579
            else:
 
580
                current = to_transport.base
 
581
                needed = [(to_transport, to_transport.relpath(location_url))]
 
582
                while needed:
 
583
                    try:
 
584
                        to_transport, relpath = needed[-1]
 
585
                        to_transport.mkdir(relpath)
 
586
                        needed.pop()
 
587
                    except NoSuchFile:
 
588
                        new_transport = to_transport.clone('..')
 
589
                        needed.append((new_transport,
 
590
                                       new_transport.relpath(to_transport.base)))
 
591
                        if new_transport.base == to_transport.base:
 
592
                            raise BzrCommandError("Could not create "
 
593
                                                  "path prefix.")
 
594
            dir_to = br_from.bzrdir.clone(location_url,
 
595
                revision_id=br_from.last_revision())
 
596
            br_to = dir_to.open_branch()
 
597
            count = len(br_to.revision_history())
 
598
            # We successfully created the target, remember it
 
599
            if br_from.get_push_location() is None or remember:
 
600
                br_from.set_push_location(br_to.base)
 
601
        else:
 
602
            # We were able to connect to the remote location, so remember it
 
603
            # we don't need to successfully push because of possible divergence.
 
604
            if br_from.get_push_location() is None or remember:
 
605
                br_from.set_push_location(br_to.base)
 
606
            old_rh = br_to.revision_history()
 
607
            try:
 
608
                try:
 
609
                    tree_to = dir_to.open_workingtree()
 
610
                except errors.NotLocalUrl:
 
611
                    warning('This transport does not update the working '
 
612
                            'tree of: %s' % (br_to.base,))
 
613
                    count = br_to.pull(br_from, overwrite)
 
614
                except NoWorkingTree:
 
615
                    count = br_to.pull(br_from, overwrite)
 
616
                else:
 
617
                    count = tree_to.pull(br_from, overwrite)
 
618
            except DivergedBranches:
 
619
                raise BzrCommandError("These branches have diverged."
 
620
                                      "  Try a merge then push with overwrite.")
 
621
        note('%d revision(s) pushed.' % (count,))
 
622
 
 
623
        if verbose:
 
624
            new_rh = br_to.revision_history()
 
625
            if old_rh != new_rh:
 
626
                # Something changed
 
627
                from bzrlib.log import show_changed_revisions
 
628
                show_changed_revisions(br_to, old_rh, new_rh,
 
629
                                       to_file=self.outf)
 
630
 
 
631
 
 
632
class cmd_branch(Command):
 
633
    """Create a new copy of a branch.
 
634
 
 
635
    If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
 
636
    be used.  In other words, "branch ../foo/bar" will attempt to create ./bar.
 
637
 
 
638
    To retrieve the branch as of a particular revision, supply the --revision
 
639
    parameter, as in "branch foo/bar -r 5".
 
640
 
 
641
    --basis is to speed up branching from remote branches.  When specified, it
 
642
    copies all the file-contents, inventory and revision data from the basis
 
643
    branch before copying anything from the remote branch.
 
644
    """
 
645
    takes_args = ['from_location', 'to_location?']
 
646
    takes_options = ['revision', 'basis']
 
647
    aliases = ['get', 'clone']
 
648
 
 
649
    def run(self, from_location, to_location=None, revision=None, basis=None):
 
650
        if revision is None:
 
651
            revision = [None]
 
652
        elif len(revision) > 1:
 
653
            raise BzrCommandError(
 
654
                'bzr branch --revision takes exactly 1 revision value')
 
655
        try:
 
656
            br_from = Branch.open(from_location)
 
657
        except OSError, e:
 
658
            if e.errno == errno.ENOENT:
 
659
                raise BzrCommandError('Source location "%s" does not'
 
660
                                      ' exist.' % to_location)
 
661
            else:
 
662
                raise
 
663
        br_from.lock_read()
 
664
        try:
 
665
            if basis is not None:
 
666
                basis_dir = bzrdir.BzrDir.open_containing(basis)[0]
 
667
            else:
 
668
                basis_dir = None
 
669
            if len(revision) == 1 and revision[0] is not None:
 
670
                revision_id = revision[0].in_history(br_from)[1]
 
671
            else:
 
672
                # FIXME - wt.last_revision, fallback to branch, fall back to
 
673
                # None or perhaps NULL_REVISION to mean copy nothing
 
674
                # RBC 20060209
 
675
                revision_id = br_from.last_revision()
 
676
            if to_location is None:
 
677
                to_location = os.path.basename(from_location.rstrip("/\\"))
 
678
                name = None
 
679
            else:
 
680
                name = os.path.basename(to_location) + '\n'
 
681
 
 
682
            to_transport = transport.get_transport(to_location)
 
683
            try:
 
684
                to_transport.mkdir('.')
 
685
            except errors.FileExists:
 
686
                raise BzrCommandError('Target directory "%s" already'
 
687
                                      ' exists.' % to_location)
 
688
            except errors.NoSuchFile:
 
689
                raise BzrCommandError('Parent of "%s" does not exist.' %
 
690
                                      to_location)
 
691
            try:
 
692
                # preserve whatever source format we have.
 
693
                dir = br_from.bzrdir.sprout(to_transport.base,
 
694
                        revision_id, basis_dir)
 
695
                branch = dir.open_branch()
 
696
            except errors.NoSuchRevision:
 
697
                to_transport.delete_tree('.')
 
698
                msg = "The branch %s has no revision %s." % (from_location, revision[0])
 
699
                raise BzrCommandError(msg)
 
700
            except errors.UnlistableBranch:
 
701
                osutils.rmtree(to_location)
 
702
                msg = "The branch %s cannot be used as a --basis" % (basis,)
 
703
                raise BzrCommandError(msg)
 
704
            if name:
 
705
                branch.control_files.put_utf8('branch-name', name)
 
706
            note('Branched %d revision(s).' % branch.revno())
 
707
        finally:
 
708
            br_from.unlock()
 
709
 
 
710
 
 
711
class cmd_checkout(Command):
 
712
    """Create a new checkout of an existing branch.
 
713
 
 
714
    If BRANCH_LOCATION is omitted, checkout will reconstitute a working tree for
 
715
    the branch found in '.'. This is useful if you have removed the working tree
 
716
    or if it was never created - i.e. if you pushed the branch to its current
 
717
    location using SFTP.
 
718
    
 
719
    If the TO_LOCATION is omitted, the last component of the BRANCH_LOCATION will
 
720
    be used.  In other words, "checkout ../foo/bar" will attempt to create ./bar.
 
721
 
 
722
    To retrieve the branch as of a particular revision, supply the --revision
 
723
    parameter, as in "checkout foo/bar -r 5". Note that this will be immediately
 
724
    out of date [so you cannot commit] but it may be useful (i.e. to examine old
 
725
    code.)
 
726
 
 
727
    --basis is to speed up checking out from remote branches.  When specified, it
 
728
    uses the inventory and file contents from the basis branch in preference to the
 
729
    branch being checked out.
 
730
    """
 
731
    takes_args = ['branch_location?', 'to_location?']
 
732
    takes_options = ['revision', # , 'basis']
 
733
                     Option('lightweight',
 
734
                            help="perform a lightweight checkout. Lightweight "
 
735
                                 "checkouts depend on access to the branch for "
 
736
                                 "every operation. Normal checkouts can perform "
 
737
                                 "common operations like diff and status without "
 
738
                                 "such access, and also support local commits."
 
739
                            ),
 
740
                     ]
 
741
    aliases = ['co']
 
742
 
 
743
    def run(self, branch_location=None, to_location=None, revision=None, basis=None,
 
744
            lightweight=False):
 
745
        if revision is None:
 
746
            revision = [None]
 
747
        elif len(revision) > 1:
 
748
            raise BzrCommandError(
 
749
                'bzr checkout --revision takes exactly 1 revision value')
 
750
        if branch_location is None:
 
751
            branch_location = osutils.getcwd()
 
752
            to_location = branch_location
 
753
        source = Branch.open(branch_location)
 
754
        if len(revision) == 1 and revision[0] is not None:
 
755
            revision_id = revision[0].in_history(source)[1]
 
756
        else:
 
757
            revision_id = None
 
758
        if to_location is None:
 
759
            to_location = os.path.basename(branch_location.rstrip("/\\"))
 
760
        # if the source and to_location are the same, 
 
761
        # and there is no working tree,
 
762
        # then reconstitute a branch
 
763
        if (osutils.abspath(to_location) == 
 
764
            osutils.abspath(branch_location)):
 
765
            try:
 
766
                source.bzrdir.open_workingtree()
 
767
            except errors.NoWorkingTree:
 
768
                source.bzrdir.create_workingtree()
 
769
                return
 
770
        try:
 
771
            os.mkdir(to_location)
 
772
        except OSError, e:
 
773
            if e.errno == errno.EEXIST:
 
774
                raise BzrCommandError('Target directory "%s" already'
 
775
                                      ' exists.' % to_location)
 
776
            if e.errno == errno.ENOENT:
 
777
                raise BzrCommandError('Parent of "%s" does not exist.' %
 
778
                                      to_location)
 
779
            else:
 
780
                raise
 
781
        old_format = bzrdir.BzrDirFormat.get_default_format()
 
782
        bzrdir.BzrDirFormat.set_default_format(bzrdir.BzrDirMetaFormat1())
 
783
        try:
 
784
            source.create_checkout(to_location, revision_id, lightweight)
 
785
        finally:
 
786
            bzrdir.BzrDirFormat.set_default_format(old_format)
 
787
 
 
788
 
 
789
class cmd_renames(Command):
 
790
    """Show list of renamed files.
 
791
    """
 
792
    # TODO: Option to show renames between two historical versions.
 
793
 
 
794
    # TODO: Only show renames under dir, rather than in the whole branch.
 
795
    takes_args = ['dir?']
 
796
 
 
797
    @display_command
 
798
    def run(self, dir=u'.'):
 
799
        from bzrlib.tree import find_renames
 
800
        tree = WorkingTree.open_containing(dir)[0]
 
801
        old_inv = tree.basis_tree().inventory
 
802
        new_inv = tree.read_working_inventory()
 
803
        renames = list(find_renames(old_inv, new_inv))
 
804
        renames.sort()
 
805
        for old_name, new_name in renames:
 
806
            self.outf.write("%s => %s\n" % (old_name, new_name))
 
807
 
 
808
 
 
809
class cmd_update(Command):
 
810
    """Update a tree to have the latest code committed to its branch.
 
811
    
 
812
    This will perform a merge into the working tree, and may generate
 
813
    conflicts. If you have any local changes, you will still 
 
814
    need to commit them after the update for the update to be complete.
 
815
    
 
816
    If you want to discard your local changes, you can just do a 
 
817
    'bzr revert' instead of 'bzr commit' after the update.
 
818
    """
 
819
    takes_args = ['dir?']
 
820
    aliases = ['up']
 
821
 
 
822
    def run(self, dir='.'):
 
823
        tree = WorkingTree.open_containing(dir)[0]
 
824
        tree.lock_write()
 
825
        try:
 
826
            existing_pending_merges = tree.pending_merges()
 
827
            last_rev = tree.last_revision()
 
828
            if last_rev == tree.branch.last_revision():
 
829
                # may be up to date, check master too.
 
830
                master = tree.branch.get_master_branch()
 
831
                if master is None or last_rev == master.last_revision():
 
832
                    revno = tree.branch.revision_id_to_revno(last_rev)
 
833
                    note("Tree is up to date at revision %d." % (revno,))
 
834
                    return 0
 
835
            conflicts = tree.update()
 
836
            revno = tree.branch.revision_id_to_revno(tree.last_revision())
 
837
            note('Updated to revision %d.' % (revno,))
 
838
            if tree.pending_merges() != existing_pending_merges:
 
839
                note('Your local commits will now show as pending merges with '
 
840
                     "'bzr status', and can be committed with 'bzr commit'.")
 
841
            if conflicts != 0:
 
842
                return 1
 
843
            else:
 
844
                return 0
 
845
        finally:
 
846
            tree.unlock()
 
847
 
 
848
 
 
849
class cmd_info(Command):
 
850
    """Show information about a working tree, branch or repository.
 
851
 
 
852
    This command will show all known locations and formats associated to the
 
853
    tree, branch or repository.  Statistical information is included with
 
854
    each report.
 
855
 
 
856
    Branches and working trees will also report any missing revisions.
 
857
    """
 
858
    takes_args = ['location?']
 
859
    takes_options = ['verbose']
 
860
 
 
861
    @display_command
 
862
    def run(self, location=None, verbose=False):
 
863
        from bzrlib.info import show_bzrdir_info
 
864
        show_bzrdir_info(bzrdir.BzrDir.open_containing(location)[0],
 
865
                         verbose=verbose)
 
866
 
 
867
 
 
868
class cmd_remove(Command):
 
869
    """Make a file unversioned.
 
870
 
 
871
    This makes bzr stop tracking changes to a versioned file.  It does
 
872
    not delete the working copy.
 
873
 
 
874
    You can specify one or more files, and/or --new.  If you specify --new,
 
875
    only 'added' files will be removed.  If you specify both, then new files
 
876
    in the specified directories will be removed.  If the directories are
 
877
    also new, they will also be removed.
 
878
    """
 
879
    takes_args = ['file*']
 
880
    takes_options = ['verbose', Option('new', help='remove newly-added files')]
 
881
    aliases = ['rm']
 
882
    encoding_type = 'replace'
 
883
    
 
884
    def run(self, file_list, verbose=False, new=False):
 
885
        tree, file_list = tree_files(file_list)
 
886
        if new is False:
 
887
            if file_list is None:
 
888
                raise BzrCommandError('Specify one or more files to remove, or'
 
889
                                      ' use --new.')
 
890
        else:
 
891
            added = tree.changes_from(tree.basis_tree(),
 
892
                specific_files=file_list).added
 
893
            file_list = sorted([f[0] for f in added], reverse=True)
 
894
            if len(file_list) == 0:
 
895
                raise BzrCommandError('No matching files.')
 
896
        tree.remove(file_list, verbose=verbose, to_file=self.outf)
 
897
 
 
898
 
 
899
class cmd_file_id(Command):
 
900
    """Print file_id of a particular file or directory.
 
901
 
 
902
    The file_id is assigned when the file is first added and remains the
 
903
    same through all revisions where the file exists, even when it is
 
904
    moved or renamed.
 
905
    """
 
906
 
 
907
    hidden = True
 
908
    takes_args = ['filename']
 
909
 
 
910
    @display_command
 
911
    def run(self, filename):
 
912
        tree, relpath = WorkingTree.open_containing(filename)
 
913
        i = tree.inventory.path2id(relpath)
 
914
        if i == None:
 
915
            raise BzrError("%r is not a versioned file" % filename)
 
916
        else:
 
917
            self.outf.write(i + '\n')
 
918
 
 
919
 
 
920
class cmd_file_path(Command):
 
921
    """Print path of file_ids to a file or directory.
 
922
 
 
923
    This prints one line for each directory down to the target,
 
924
    starting at the branch root.
 
925
    """
 
926
 
 
927
    hidden = True
 
928
    takes_args = ['filename']
 
929
 
 
930
    @display_command
 
931
    def run(self, filename):
 
932
        tree, relpath = WorkingTree.open_containing(filename)
 
933
        inv = tree.inventory
 
934
        fid = inv.path2id(relpath)
 
935
        if fid == None:
 
936
            raise BzrError("%r is not a versioned file" % filename)
 
937
        for fip in inv.get_idpath(fid):
 
938
            self.outf.write(fip + '\n')
 
939
 
 
940
 
 
941
class cmd_reconcile(Command):
 
942
    """Reconcile bzr metadata in a branch.
 
943
 
 
944
    This can correct data mismatches that may have been caused by
 
945
    previous ghost operations or bzr upgrades. You should only
 
946
    need to run this command if 'bzr check' or a bzr developer 
 
947
    advises you to run it.
 
948
 
 
949
    If a second branch is provided, cross-branch reconciliation is
 
950
    also attempted, which will check that data like the tree root
 
951
    id which was not present in very early bzr versions is represented
 
952
    correctly in both branches.
 
953
 
 
954
    At the same time it is run it may recompress data resulting in 
 
955
    a potential saving in disk space or performance gain.
 
956
 
 
957
    The branch *MUST* be on a listable system such as local disk or sftp.
 
958
    """
 
959
    takes_args = ['branch?']
 
960
 
 
961
    def run(self, branch="."):
 
962
        from bzrlib.reconcile import reconcile
 
963
        dir = bzrdir.BzrDir.open(branch)
 
964
        reconcile(dir)
 
965
 
 
966
 
 
967
class cmd_revision_history(Command):
 
968
    """Display the list of revision ids on a branch."""
 
969
    takes_args = ['location?']
 
970
 
 
971
    hidden = True
 
972
 
 
973
    @display_command
 
974
    def run(self, location="."):
 
975
        branch = Branch.open_containing(location)[0]
 
976
        for revid in branch.revision_history():
 
977
            self.outf.write(revid)
 
978
            self.outf.write('\n')
 
979
 
 
980
 
 
981
class cmd_ancestry(Command):
 
982
    """List all revisions merged into this branch."""
 
983
    takes_args = ['location?']
 
984
 
 
985
    hidden = True
 
986
 
 
987
    @display_command
 
988
    def run(self, location="."):
 
989
        try:
 
990
            wt = WorkingTree.open_containing(location)[0]
 
991
        except errors.NoWorkingTree:
 
992
            b = Branch.open(location)
 
993
            last_revision = b.last_revision()
 
994
        else:
 
995
            b = wt.branch
 
996
            last_revision = wt.last_revision()
 
997
 
 
998
        revision_ids = b.repository.get_ancestry(last_revision)
 
999
        assert revision_ids[0] == None
 
1000
        revision_ids.pop(0)
 
1001
        for revision_id in revision_ids:
 
1002
            self.outf.write(revision_id + '\n')
 
1003
 
 
1004
 
 
1005
class cmd_init(Command):
 
1006
    """Make a directory into a versioned branch.
 
1007
 
 
1008
    Use this to create an empty branch, or before importing an
 
1009
    existing project.
 
1010
 
 
1011
    If there is a repository in a parent directory of the location, then 
 
1012
    the history of the branch will be stored in the repository.  Otherwise
 
1013
    init creates a standalone branch which carries its own history in 
 
1014
    .bzr.
 
1015
 
 
1016
    If there is already a branch at the location but it has no working tree,
 
1017
    the tree can be populated with 'bzr checkout'.
 
1018
 
 
1019
    Recipe for importing a tree of files:
 
1020
        cd ~/project
 
1021
        bzr init
 
1022
        bzr add .
 
1023
        bzr status
 
1024
        bzr commit -m 'imported project'
 
1025
    """
 
1026
    takes_args = ['location?']
 
1027
    takes_options = [
 
1028
                     Option('format', 
 
1029
                            help='Specify a format for this branch. Current'
 
1030
                                 ' formats are: default, knit, metaweave and'
 
1031
                                 ' weave. Default is knit; metaweave and'
 
1032
                                 ' weave are deprecated',
 
1033
                            type=get_format_type),
 
1034
                     ]
 
1035
    def run(self, location=None, format=None):
 
1036
        if format is None:
 
1037
            format = get_format_type('default')
 
1038
        if location is None:
 
1039
            location = u'.'
 
1040
 
 
1041
        to_transport = transport.get_transport(location)
 
1042
 
 
1043
        # The path has to exist to initialize a
 
1044
        # branch inside of it.
 
1045
        # Just using os.mkdir, since I don't
 
1046
        # believe that we want to create a bunch of
 
1047
        # locations if the user supplies an extended path
 
1048
        # TODO: create-prefix
 
1049
        try:
 
1050
            to_transport.mkdir('.')
 
1051
        except errors.FileExists:
 
1052
            pass
 
1053
                    
 
1054
        try:
 
1055
            existing_bzrdir = bzrdir.BzrDir.open(location)
 
1056
        except NotBranchError:
 
1057
            # really a NotBzrDir error...
 
1058
            bzrdir.BzrDir.create_branch_convenience(location, format=format)
 
1059
        else:
 
1060
            if existing_bzrdir.has_branch():
 
1061
                if (isinstance(to_transport, LocalTransport)
 
1062
                    and not existing_bzrdir.has_workingtree()):
 
1063
                        raise errors.BranchExistsWithoutWorkingTree(location)
 
1064
                raise errors.AlreadyBranchError(location)
 
1065
            else:
 
1066
                existing_bzrdir.create_branch()
 
1067
                existing_bzrdir.create_workingtree()
 
1068
 
 
1069
 
 
1070
class cmd_init_repository(Command):
 
1071
    """Create a shared repository to hold branches.
 
1072
 
 
1073
    New branches created under the repository directory will store their revisions
 
1074
    in the repository, not in the branch directory, if the branch format supports
 
1075
    shared storage.
 
1076
 
 
1077
    example:
 
1078
        bzr init-repo repo
 
1079
        bzr init repo/trunk
 
1080
        bzr checkout --lightweight repo/trunk trunk-checkout
 
1081
        cd trunk-checkout
 
1082
        (add files here)
 
1083
    """
 
1084
    takes_args = ["location"] 
 
1085
    takes_options = [Option('format', 
 
1086
                            help='Specify a format for this repository.'
 
1087
                                 ' Current formats are: default, knit,'
 
1088
                                 ' metaweave and weave. Default is knit;'
 
1089
                                 ' metaweave and weave are deprecated',
 
1090
                            type=get_format_type),
 
1091
                     Option('trees',
 
1092
                             help='Allows branches in repository to have'
 
1093
                             ' a working tree')]
 
1094
    aliases = ["init-repo"]
 
1095
    def run(self, location, format=None, trees=False):
 
1096
        if format is None:
 
1097
            format = get_format_type('default')
 
1098
 
 
1099
        if location is None:
 
1100
            location = '.'
 
1101
 
 
1102
        to_transport = transport.get_transport(location)
 
1103
        try:
 
1104
            to_transport.mkdir('.')
 
1105
        except errors.FileExists:
 
1106
            pass
 
1107
 
 
1108
        newdir = format.initialize_on_transport(to_transport)
 
1109
        repo = newdir.create_repository(shared=True)
 
1110
        repo.set_make_working_trees(trees)
 
1111
 
 
1112
 
 
1113
class cmd_diff(Command):
 
1114
    """Show differences in the working tree or between revisions.
 
1115
    
 
1116
    If files are listed, only the changes in those files are listed.
 
1117
    Otherwise, all changes for the tree are listed.
 
1118
 
 
1119
    "bzr diff -p1" is equivalent to "bzr diff --prefix old/:new/", and
 
1120
    produces patches suitable for "patch -p1".
 
1121
 
 
1122
    examples:
 
1123
        bzr diff
 
1124
            Shows the difference in the working tree versus the last commit
 
1125
        bzr diff -r1
 
1126
            Difference between the working tree and revision 1
 
1127
        bzr diff -r1..2
 
1128
            Difference between revision 2 and revision 1
 
1129
        bzr diff --diff-prefix old/:new/
 
1130
            Same as 'bzr diff' but prefix paths with old/ and new/
 
1131
        bzr diff bzr.mine bzr.dev
 
1132
            Show the differences between the two working trees
 
1133
        bzr diff foo.c
 
1134
            Show just the differences for 'foo.c'
 
1135
    """
 
1136
    # TODO: Option to use external diff command; could be GNU diff, wdiff,
 
1137
    #       or a graphical diff.
 
1138
 
 
1139
    # TODO: Python difflib is not exactly the same as unidiff; should
 
1140
    #       either fix it up or prefer to use an external diff.
 
1141
 
 
1142
    # TODO: Selected-file diff is inefficient and doesn't show you
 
1143
    #       deleted files.
 
1144
 
 
1145
    # TODO: This probably handles non-Unix newlines poorly.
 
1146
    
 
1147
    takes_args = ['file*']
 
1148
    takes_options = ['revision', 'diff-options', 'prefix']
 
1149
    aliases = ['di', 'dif']
 
1150
    encoding_type = 'exact'
 
1151
 
 
1152
    @display_command
 
1153
    def run(self, revision=None, file_list=None, diff_options=None,
 
1154
            prefix=None):
 
1155
        from bzrlib.diff import diff_cmd_helper, show_diff_trees
 
1156
 
 
1157
        if (prefix is None) or (prefix == '0'):
 
1158
            # diff -p0 format
 
1159
            old_label = ''
 
1160
            new_label = ''
 
1161
        elif prefix == '1':
 
1162
            old_label = 'old/'
 
1163
            new_label = 'new/'
 
1164
        else:
 
1165
            if not ':' in prefix:
 
1166
                 raise BzrError("--diff-prefix expects two values separated by a colon")
 
1167
            old_label, new_label = prefix.split(":")
 
1168
        
 
1169
        try:
 
1170
            tree1, file_list = internal_tree_files(file_list)
 
1171
            tree2 = None
 
1172
            b = None
 
1173
            b2 = None
 
1174
        except FileInWrongBranch:
 
1175
            if len(file_list) != 2:
 
1176
                raise BzrCommandError("Files are in different branches")
 
1177
 
 
1178
            tree1, file1 = WorkingTree.open_containing(file_list[0])
 
1179
            tree2, file2 = WorkingTree.open_containing(file_list[1])
 
1180
            if file1 != "" or file2 != "":
 
1181
                # FIXME diff those two files. rbc 20051123
 
1182
                raise BzrCommandError("Files are in different branches")
 
1183
            file_list = None
 
1184
        except NotBranchError:
 
1185
            if (revision is not None and len(revision) == 2
 
1186
                and not revision[0].needs_branch()
 
1187
                and not revision[1].needs_branch()):
 
1188
                # If both revision specs include a branch, we can
 
1189
                # diff them without needing a local working tree
 
1190
                tree1, tree2 = None, None
 
1191
            else:
 
1192
                raise
 
1193
        if revision is not None:
 
1194
            if tree2 is not None:
 
1195
                raise BzrCommandError("Can't specify -r with two branches")
 
1196
            if (len(revision) == 1) or (revision[1].spec is None):
 
1197
                return diff_cmd_helper(tree1, file_list, diff_options,
 
1198
                                       revision[0], 
 
1199
                                       old_label=old_label, new_label=new_label)
 
1200
            elif len(revision) == 2:
 
1201
                return diff_cmd_helper(tree1, file_list, diff_options,
 
1202
                                       revision[0], revision[1],
 
1203
                                       old_label=old_label, new_label=new_label)
 
1204
            else:
 
1205
                raise BzrCommandError('bzr diff --revision takes exactly one or two revision identifiers')
 
1206
        else:
 
1207
            if tree2 is not None:
 
1208
                return show_diff_trees(tree1, tree2, sys.stdout, 
 
1209
                                       specific_files=file_list,
 
1210
                                       external_diff_options=diff_options,
 
1211
                                       old_label=old_label, new_label=new_label)
 
1212
            else:
 
1213
                return diff_cmd_helper(tree1, file_list, diff_options,
 
1214
                                       old_label=old_label, new_label=new_label)
 
1215
 
 
1216
 
 
1217
class cmd_deleted(Command):
 
1218
    """List files deleted in the working tree.
 
1219
    """
 
1220
    # TODO: Show files deleted since a previous revision, or
 
1221
    # between two revisions.
 
1222
    # TODO: Much more efficient way to do this: read in new
 
1223
    # directories with readdir, rather than stating each one.  Same
 
1224
    # level of effort but possibly much less IO.  (Or possibly not,
 
1225
    # if the directories are very large...)
 
1226
    takes_options = ['show-ids']
 
1227
 
 
1228
    @display_command
 
1229
    def run(self, show_ids=False):
 
1230
        tree = WorkingTree.open_containing(u'.')[0]
 
1231
        old = tree.basis_tree()
 
1232
        for path, ie in old.inventory.iter_entries():
 
1233
            if not tree.has_id(ie.file_id):
 
1234
                self.outf.write(path)
 
1235
                if show_ids:
 
1236
                    self.outf.write(' ')
 
1237
                    self.outf.write(ie.file_id)
 
1238
                self.outf.write('\n')
 
1239
 
 
1240
 
 
1241
class cmd_modified(Command):
 
1242
    """List files modified in working tree."""
 
1243
    hidden = True
 
1244
    @display_command
 
1245
    def run(self):
 
1246
        tree = WorkingTree.open_containing(u'.')[0]
 
1247
        td = tree.changes_from(tree.basis_tree())
 
1248
        for path, id, kind, text_modified, meta_modified in td.modified:
 
1249
            self.outf.write(path + '\n')
 
1250
 
 
1251
 
 
1252
class cmd_added(Command):
 
1253
    """List files added in working tree."""
 
1254
    hidden = True
 
1255
    @display_command
 
1256
    def run(self):
 
1257
        wt = WorkingTree.open_containing(u'.')[0]
 
1258
        basis_inv = wt.basis_tree().inventory
 
1259
        inv = wt.inventory
 
1260
        for file_id in inv:
 
1261
            if file_id in basis_inv:
 
1262
                continue
 
1263
            path = inv.id2path(file_id)
 
1264
            if not os.access(osutils.abspath(path), os.F_OK):
 
1265
                continue
 
1266
            self.outf.write(path + '\n')
 
1267
 
 
1268
 
 
1269
class cmd_root(Command):
 
1270
    """Show the tree root directory.
 
1271
 
 
1272
    The root is the nearest enclosing directory with a .bzr control
 
1273
    directory."""
 
1274
    takes_args = ['filename?']
 
1275
    @display_command
 
1276
    def run(self, filename=None):
 
1277
        """Print the branch root."""
 
1278
        tree = WorkingTree.open_containing(filename)[0]
 
1279
        self.outf.write(tree.basedir + '\n')
 
1280
 
 
1281
 
 
1282
class cmd_log(Command):
 
1283
    """Show log of a branch, file, or directory.
 
1284
 
 
1285
    By default show the log of the branch containing the working directory.
 
1286
 
 
1287
    To request a range of logs, you can use the command -r begin..end
 
1288
    -r revision requests a specific revision, -r ..end or -r begin.. are
 
1289
    also valid.
 
1290
 
 
1291
    examples:
 
1292
        bzr log
 
1293
        bzr log foo.c
 
1294
        bzr log -r -10.. http://server/branch
 
1295
    """
 
1296
 
 
1297
    # TODO: Make --revision support uuid: and hash: [future tag:] notation.
 
1298
 
 
1299
    takes_args = ['location?']
 
1300
    takes_options = [Option('forward', 
 
1301
                            help='show from oldest to newest'),
 
1302
                     'timezone', 
 
1303
                     Option('verbose', 
 
1304
                             help='show files changed in each revision'),
 
1305
                     'show-ids', 'revision',
 
1306
                     'log-format',
 
1307
                     'line', 'long', 
 
1308
                     Option('message',
 
1309
                            help='show revisions whose message matches this regexp',
 
1310
                            type=str),
 
1311
                     'short',
 
1312
                     ]
 
1313
    encoding_type = 'replace'
 
1314
 
 
1315
    @display_command
 
1316
    def run(self, location=None, timezone='original',
 
1317
            verbose=False,
 
1318
            show_ids=False,
 
1319
            forward=False,
 
1320
            revision=None,
 
1321
            log_format=None,
 
1322
            message=None,
 
1323
            long=False,
 
1324
            short=False,
 
1325
            line=False):
 
1326
        from bzrlib.log import log_formatter, show_log
 
1327
        assert message is None or isinstance(message, basestring), \
 
1328
            "invalid message argument %r" % message
 
1329
        direction = (forward and 'forward') or 'reverse'
 
1330
        
 
1331
        # log everything
 
1332
        file_id = None
 
1333
        if location:
 
1334
            # find the file id to log:
 
1335
 
 
1336
            dir, fp = bzrdir.BzrDir.open_containing(location)
 
1337
            b = dir.open_branch()
 
1338
            if fp != '':
 
1339
                try:
 
1340
                    # might be a tree:
 
1341
                    inv = dir.open_workingtree().inventory
 
1342
                except (errors.NotBranchError, errors.NotLocalUrl):
 
1343
                    # either no tree, or is remote.
 
1344
                    inv = b.basis_tree().inventory
 
1345
                file_id = inv.path2id(fp)
 
1346
        else:
 
1347
            # local dir only
 
1348
            # FIXME ? log the current subdir only RBC 20060203 
 
1349
            if revision is not None and len(revision) > 0 and revision[0].get_branch():
 
1350
                location = revision[0].get_branch()
 
1351
            else:
 
1352
                location = '.'
 
1353
            dir, relpath = bzrdir.BzrDir.open_containing(location)
 
1354
            b = dir.open_branch()
 
1355
 
 
1356
        if revision is None:
 
1357
            rev1 = None
 
1358
            rev2 = None
 
1359
        elif len(revision) == 1:
 
1360
            rev1 = rev2 = revision[0].in_history(b).revno
 
1361
        elif len(revision) == 2:
 
1362
            if revision[1].get_branch() != revision[0].get_branch():
 
1363
                # b is taken from revision[0].get_branch(), and
 
1364
                # show_log will use its revision_history. Having
 
1365
                # different branches will lead to weird behaviors.
 
1366
                raise BzrCommandError(
 
1367
                    "Log doesn't accept two revisions in different branches.")
 
1368
            if revision[0].spec is None:
 
1369
                # missing begin-range means first revision
 
1370
                rev1 = 1
 
1371
            else:
 
1372
                rev1 = revision[0].in_history(b).revno
 
1373
 
 
1374
            if revision[1].spec is None:
 
1375
                # missing end-range means last known revision
 
1376
                rev2 = b.revno()
 
1377
            else:
 
1378
                rev2 = revision[1].in_history(b).revno
 
1379
        else:
 
1380
            raise BzrCommandError('bzr log --revision takes one or two values.')
 
1381
 
 
1382
        # By this point, the revision numbers are converted to the +ve
 
1383
        # form if they were supplied in the -ve form, so we can do
 
1384
        # this comparison in relative safety
 
1385
        if rev1 > rev2:
 
1386
            (rev2, rev1) = (rev1, rev2)
 
1387
 
 
1388
        if (log_format == None):
 
1389
            default = b.get_config().log_format()
 
1390
            log_format = get_log_format(long=long, short=short, line=line, 
 
1391
                                        default=default)
 
1392
        lf = log_formatter(log_format,
 
1393
                           show_ids=show_ids,
 
1394
                           to_file=self.outf,
 
1395
                           show_timezone=timezone)
 
1396
 
 
1397
        show_log(b,
 
1398
                 lf,
 
1399
                 file_id,
 
1400
                 verbose=verbose,
 
1401
                 direction=direction,
 
1402
                 start_revision=rev1,
 
1403
                 end_revision=rev2,
 
1404
                 search=message)
 
1405
 
 
1406
 
 
1407
def get_log_format(long=False, short=False, line=False, default='long'):
 
1408
    log_format = default
 
1409
    if long:
 
1410
        log_format = 'long'
 
1411
    if short:
 
1412
        log_format = 'short'
 
1413
    if line:
 
1414
        log_format = 'line'
 
1415
    return log_format
 
1416
 
 
1417
 
 
1418
class cmd_touching_revisions(Command):
 
1419
    """Return revision-ids which affected a particular file.
 
1420
 
 
1421
    A more user-friendly interface is "bzr log FILE".
 
1422
    """
 
1423
 
 
1424
    hidden = True
 
1425
    takes_args = ["filename"]
 
1426
 
 
1427
    @display_command
 
1428
    def run(self, filename):
 
1429
        tree, relpath = WorkingTree.open_containing(filename)
 
1430
        b = tree.branch
 
1431
        inv = tree.read_working_inventory()
 
1432
        file_id = inv.path2id(relpath)
 
1433
        for revno, revision_id, what in log.find_touching_revisions(b, file_id):
 
1434
            self.outf.write("%6d %s\n" % (revno, what))
 
1435
 
 
1436
 
 
1437
class cmd_ls(Command):
 
1438
    """List files in a tree.
 
1439
    """
 
1440
    # TODO: Take a revision or remote path and list that tree instead.
 
1441
    hidden = True
 
1442
    takes_options = ['verbose', 'revision',
 
1443
                     Option('non-recursive',
 
1444
                            help='don\'t recurse into sub-directories'),
 
1445
                     Option('from-root',
 
1446
                            help='Print all paths from the root of the branch.'),
 
1447
                     Option('unknown', help='Print unknown files'),
 
1448
                     Option('versioned', help='Print versioned files'),
 
1449
                     Option('ignored', help='Print ignored files'),
 
1450
 
 
1451
                     Option('null', help='Null separate the files'),
 
1452
                    ]
 
1453
    @display_command
 
1454
    def run(self, revision=None, verbose=False, 
 
1455
            non_recursive=False, from_root=False,
 
1456
            unknown=False, versioned=False, ignored=False,
 
1457
            null=False):
 
1458
 
 
1459
        if verbose and null:
 
1460
            raise BzrCommandError('Cannot set both --verbose and --null')
 
1461
        all = not (unknown or versioned or ignored)
 
1462
 
 
1463
        selection = {'I':ignored, '?':unknown, 'V':versioned}
 
1464
 
 
1465
        tree, relpath = WorkingTree.open_containing(u'.')
 
1466
        if from_root:
 
1467
            relpath = u''
 
1468
        elif relpath:
 
1469
            relpath += '/'
 
1470
        if revision is not None:
 
1471
            tree = tree.branch.repository.revision_tree(
 
1472
                revision[0].in_history(tree.branch).rev_id)
 
1473
 
 
1474
        for fp, fc, kind, fid, entry in tree.list_files():
 
1475
            if fp.startswith(relpath):
 
1476
                fp = fp[len(relpath):]
 
1477
                if non_recursive and '/' in fp:
 
1478
                    continue
 
1479
                if not all and not selection[fc]:
 
1480
                    continue
 
1481
                if verbose:
 
1482
                    kindch = entry.kind_character()
 
1483
                    self.outf.write('%-8s %s%s\n' % (fc, fp, kindch))
 
1484
                elif null:
 
1485
                    self.outf.write(fp + '\0')
 
1486
                    self.outf.flush()
 
1487
                else:
 
1488
                    self.outf.write(fp + '\n')
 
1489
 
 
1490
 
 
1491
class cmd_unknowns(Command):
 
1492
    """List unknown files."""
 
1493
    @display_command
 
1494
    def run(self):
 
1495
        for f in WorkingTree.open_containing(u'.')[0].unknowns():
 
1496
            self.outf.write(osutils.quotefn(f) + '\n')
 
1497
 
 
1498
 
 
1499
class cmd_ignore(Command):
 
1500
    """Ignore a command or pattern.
 
1501
 
 
1502
    To remove patterns from the ignore list, edit the .bzrignore file.
 
1503
 
 
1504
    If the pattern contains a slash, it is compared to the whole path
 
1505
    from the branch root.  Otherwise, it is compared to only the last
 
1506
    component of the path.  To match a file only in the root directory,
 
1507
    prepend './'.
 
1508
 
 
1509
    Ignore patterns are case-insensitive on case-insensitive systems.
 
1510
 
 
1511
    Note: wildcards must be quoted from the shell on Unix.
 
1512
 
 
1513
    examples:
 
1514
        bzr ignore ./Makefile
 
1515
        bzr ignore '*.class'
 
1516
    """
 
1517
    # TODO: Complain if the filename is absolute
 
1518
    takes_args = ['name_pattern?']
 
1519
    takes_options = [
 
1520
                     Option('old-default-rules',
 
1521
                            help='Out the ignore rules bzr < 0.9 always used.')
 
1522
                     ]
 
1523
    
 
1524
    def run(self, name_pattern=None, old_default_rules=None):
 
1525
        from bzrlib.atomicfile import AtomicFile
 
1526
        if old_default_rules is not None:
 
1527
            # dump the rules and exit
 
1528
            for pattern in ignores.OLD_DEFAULTS:
 
1529
                print pattern
 
1530
            return
 
1531
        if name_pattern is None:
 
1532
            raise BzrCommandError("ignore requires a NAME_PATTERN")
 
1533
        tree, relpath = WorkingTree.open_containing(u'.')
 
1534
        ifn = tree.abspath('.bzrignore')
 
1535
        if os.path.exists(ifn):
 
1536
            f = open(ifn, 'rt')
 
1537
            try:
 
1538
                igns = f.read().decode('utf-8')
 
1539
            finally:
 
1540
                f.close()
 
1541
        else:
 
1542
            igns = ''
 
1543
 
 
1544
        # TODO: If the file already uses crlf-style termination, maybe
 
1545
        # we should use that for the newly added lines?
 
1546
 
 
1547
        if igns and igns[-1] != '\n':
 
1548
            igns += '\n'
 
1549
        igns += name_pattern + '\n'
 
1550
 
 
1551
        f = AtomicFile(ifn, 'wt')
 
1552
        try:
 
1553
            f.write(igns.encode('utf-8'))
 
1554
            f.commit()
 
1555
        finally:
 
1556
            f.close()
 
1557
 
 
1558
        inv = tree.inventory
 
1559
        if inv.path2id('.bzrignore'):
 
1560
            mutter('.bzrignore is already versioned')
 
1561
        else:
 
1562
            mutter('need to make new .bzrignore file versioned')
 
1563
            tree.add(['.bzrignore'])
 
1564
 
 
1565
 
 
1566
class cmd_ignored(Command):
 
1567
    """List ignored files and the patterns that matched them.
 
1568
 
 
1569
    See also: bzr ignore"""
 
1570
    @display_command
 
1571
    def run(self):
 
1572
        tree = WorkingTree.open_containing(u'.')[0]
 
1573
        for path, file_class, kind, file_id, entry in tree.list_files():
 
1574
            if file_class != 'I':
 
1575
                continue
 
1576
            ## XXX: Slightly inefficient since this was already calculated
 
1577
            pat = tree.is_ignored(path)
 
1578
            print '%-50s %s' % (path, pat)
 
1579
 
 
1580
 
 
1581
class cmd_lookup_revision(Command):
 
1582
    """Lookup the revision-id from a revision-number
 
1583
 
 
1584
    example:
 
1585
        bzr lookup-revision 33
 
1586
    """
 
1587
    hidden = True
 
1588
    takes_args = ['revno']
 
1589
    
 
1590
    @display_command
 
1591
    def run(self, revno):
 
1592
        try:
 
1593
            revno = int(revno)
 
1594
        except ValueError:
 
1595
            raise BzrCommandError("not a valid revision-number: %r" % revno)
 
1596
 
 
1597
        print WorkingTree.open_containing(u'.')[0].branch.get_rev_id(revno)
 
1598
 
 
1599
 
 
1600
class cmd_export(Command):
 
1601
    """Export past revision to destination directory.
 
1602
 
 
1603
    If no revision is specified this exports the last committed revision.
 
1604
 
 
1605
    Format may be an "exporter" name, such as tar, tgz, tbz2.  If none is
 
1606
    given, try to find the format with the extension. If no extension
 
1607
    is found exports to a directory (equivalent to --format=dir).
 
1608
 
 
1609
    Root may be the top directory for tar, tgz and tbz2 formats. If none
 
1610
    is given, the top directory will be the root name of the file.
 
1611
 
 
1612
    Note: export of tree with non-ascii filenames to zip is not supported.
 
1613
 
 
1614
     Supported formats       Autodetected by extension
 
1615
     -----------------       -------------------------
 
1616
         dir                            -
 
1617
         tar                          .tar
 
1618
         tbz2                    .tar.bz2, .tbz2
 
1619
         tgz                      .tar.gz, .tgz
 
1620
         zip                          .zip
 
1621
    """
 
1622
    takes_args = ['dest']
 
1623
    takes_options = ['revision', 'format', 'root']
 
1624
    def run(self, dest, revision=None, format=None, root=None):
 
1625
        from bzrlib.export import export
 
1626
        tree = WorkingTree.open_containing(u'.')[0]
 
1627
        b = tree.branch
 
1628
        if revision is None:
 
1629
            # should be tree.last_revision  FIXME
 
1630
            rev_id = b.last_revision()
 
1631
        else:
 
1632
            if len(revision) != 1:
 
1633
                raise BzrError('bzr export --revision takes exactly 1 argument')
 
1634
            rev_id = revision[0].in_history(b).rev_id
 
1635
        t = b.repository.revision_tree(rev_id)
 
1636
        try:
 
1637
            export(t, dest, format, root)
 
1638
        except errors.NoSuchExportFormat, e:
 
1639
            raise BzrCommandError('Unsupported export format: %s' % e.format)
 
1640
 
 
1641
 
 
1642
class cmd_cat(Command):
 
1643
    """Write a file's text from a previous revision."""
 
1644
 
 
1645
    takes_options = ['revision']
 
1646
    takes_args = ['filename']
 
1647
 
 
1648
    @display_command
 
1649
    def run(self, filename, revision=None):
 
1650
        if revision is not None and len(revision) != 1:
 
1651
            raise BzrCommandError("bzr cat --revision takes exactly one number")
 
1652
        tree = None
 
1653
        try:
 
1654
            tree, relpath = WorkingTree.open_containing(filename)
 
1655
            b = tree.branch
 
1656
        except NotBranchError:
 
1657
            pass
 
1658
 
 
1659
        if tree is None:
 
1660
            b, relpath = Branch.open_containing(filename)
 
1661
        if revision is not None and revision[0].get_branch() is not None:
 
1662
            b = Branch.open(revision[0].get_branch())
 
1663
        if revision is None:
 
1664
            revision_id = b.last_revision()
 
1665
        else:
 
1666
            revision_id = revision[0].in_history(b).rev_id
 
1667
        b.print_file(relpath, revision_id)
 
1668
 
 
1669
 
 
1670
class cmd_local_time_offset(Command):
 
1671
    """Show the offset in seconds from GMT to local time."""
 
1672
    hidden = True    
 
1673
    @display_command
 
1674
    def run(self):
 
1675
        print osutils.local_time_offset()
 
1676
 
 
1677
 
 
1678
 
 
1679
class cmd_commit(Command):
 
1680
    """Commit changes into a new revision.
 
1681
    
 
1682
    If no arguments are given, the entire tree is committed.
 
1683
 
 
1684
    If selected files are specified, only changes to those files are
 
1685
    committed.  If a directory is specified then the directory and everything 
 
1686
    within it is committed.
 
1687
 
 
1688
    A selected-file commit may fail in some cases where the committed
 
1689
    tree would be invalid, such as trying to commit a file in a
 
1690
    newly-added directory that is not itself committed.
 
1691
    """
 
1692
    # TODO: Run hooks on tree to-be-committed, and after commit.
 
1693
 
 
1694
    # TODO: Strict commit that fails if there are deleted files.
 
1695
    #       (what does "deleted files" mean ??)
 
1696
 
 
1697
    # TODO: Give better message for -s, --summary, used by tla people
 
1698
 
 
1699
    # XXX: verbose currently does nothing
 
1700
 
 
1701
    takes_args = ['selected*']
 
1702
    takes_options = ['message', 'verbose', 
 
1703
                     Option('unchanged',
 
1704
                            help='commit even if nothing has changed'),
 
1705
                     Option('file', type=str, 
 
1706
                            argname='msgfile',
 
1707
                            help='file containing commit message'),
 
1708
                     Option('strict',
 
1709
                            help="refuse to commit if there are unknown "
 
1710
                            "files in the working tree."),
 
1711
                     Option('local',
 
1712
                            help="perform a local only commit in a bound "
 
1713
                                 "branch. Such commits are not pushed to "
 
1714
                                 "the master branch until a normal commit "
 
1715
                                 "is performed."
 
1716
                            ),
 
1717
                     ]
 
1718
    aliases = ['ci', 'checkin']
 
1719
 
 
1720
    def run(self, message=None, file=None, verbose=True, selected_list=None,
 
1721
            unchanged=False, strict=False, local=False):
 
1722
        from bzrlib.commit import (NullCommitReporter, ReportCommitToLog)
 
1723
        from bzrlib.errors import (PointlessCommit, ConflictsInTree,
 
1724
                StrictCommitFailed)
 
1725
        from bzrlib.msgeditor import edit_commit_message, \
 
1726
                make_commit_message_template
 
1727
        from tempfile import TemporaryFile
 
1728
 
 
1729
        # TODO: Need a blackbox test for invoking the external editor; may be
 
1730
        # slightly problematic to run this cross-platform.
 
1731
 
 
1732
        # TODO: do more checks that the commit will succeed before 
 
1733
        # spending the user's valuable time typing a commit message.
 
1734
        #
 
1735
        # TODO: if the commit *does* happen to fail, then save the commit 
 
1736
        # message to a temporary file where it can be recovered
 
1737
        tree, selected_list = tree_files(selected_list)
 
1738
        if selected_list == ['']:
 
1739
            # workaround - commit of root of tree should be exactly the same
 
1740
            # as just default commit in that tree, and succeed even though
 
1741
            # selected-file merge commit is not done yet
 
1742
            selected_list = []
 
1743
 
 
1744
        if local and not tree.branch.get_bound_location():
 
1745
            raise errors.LocalRequiresBoundBranch()
 
1746
        if message is None and not file:
 
1747
            template = make_commit_message_template(tree, selected_list)
 
1748
            message = edit_commit_message(template)
 
1749
            if message is None:
 
1750
                raise BzrCommandError("please specify a commit message"
 
1751
                                      " with either --message or --file")
 
1752
        elif message and file:
 
1753
            raise BzrCommandError("please specify either --message or --file")
 
1754
        
 
1755
        if file:
 
1756
            message = codecs.open(file, 'rt', bzrlib.user_encoding).read()
 
1757
 
 
1758
        if message == "":
 
1759
            raise BzrCommandError("empty commit message specified")
 
1760
        
 
1761
        if verbose:
 
1762
            reporter = ReportCommitToLog()
 
1763
        else:
 
1764
            reporter = NullCommitReporter()
 
1765
        
 
1766
        try:
 
1767
            tree.commit(message, specific_files=selected_list,
 
1768
                        allow_pointless=unchanged, strict=strict, local=local,
 
1769
                        reporter=reporter)
 
1770
        except PointlessCommit:
 
1771
            # FIXME: This should really happen before the file is read in;
 
1772
            # perhaps prepare the commit; get the message; then actually commit
 
1773
            raise BzrCommandError("no changes to commit."
 
1774
                                  " use --unchanged to commit anyhow")
 
1775
        except ConflictsInTree:
 
1776
            raise BzrCommandError("Conflicts detected in working tree.  "
 
1777
                'Use "bzr conflicts" to list, "bzr resolve FILE" to resolve.')
 
1778
        except StrictCommitFailed:
 
1779
            raise BzrCommandError("Commit refused because there are unknown "
 
1780
                                  "files in the working tree.")
 
1781
        except errors.BoundBranchOutOfDate, e:
 
1782
            raise BzrCommandError(str(e) + "\n"
 
1783
                'To commit to master branch, run update and then commit.\n'
 
1784
                'You can also pass --local to commit to continue working '
 
1785
                'disconnected.')
 
1786
 
 
1787
class cmd_check(Command):
 
1788
    """Validate consistency of branch history.
 
1789
 
 
1790
    This command checks various invariants about the branch storage to
 
1791
    detect data corruption or bzr bugs.
 
1792
    """
 
1793
    takes_args = ['branch?']
 
1794
    takes_options = ['verbose']
 
1795
 
 
1796
    def run(self, branch=None, verbose=False):
 
1797
        from bzrlib.check import check
 
1798
        if branch is None:
 
1799
            tree = WorkingTree.open_containing()[0]
 
1800
            branch = tree.branch
 
1801
        else:
 
1802
            branch = Branch.open(branch)
 
1803
        check(branch, verbose)
 
1804
 
 
1805
 
 
1806
class cmd_scan_cache(Command):
 
1807
    hidden = True
 
1808
    def run(self):
 
1809
        from bzrlib.hashcache import HashCache
 
1810
 
 
1811
        c = HashCache(u'.')
 
1812
        c.read()
 
1813
        c.scan()
 
1814
            
 
1815
        print '%6d stats' % c.stat_count
 
1816
        print '%6d in hashcache' % len(c._cache)
 
1817
        print '%6d files removed from cache' % c.removed_count
 
1818
        print '%6d hashes updated' % c.update_count
 
1819
        print '%6d files changed too recently to cache' % c.danger_count
 
1820
 
 
1821
        if c.needs_write:
 
1822
            c.write()
 
1823
 
 
1824
 
 
1825
class cmd_upgrade(Command):
 
1826
    """Upgrade branch storage to current format.
 
1827
 
 
1828
    The check command or bzr developers may sometimes advise you to run
 
1829
    this command. When the default format has changed you may also be warned
 
1830
    during other operations to upgrade.
 
1831
    """
 
1832
    takes_args = ['url?']
 
1833
    takes_options = [
 
1834
                     Option('format', 
 
1835
                            help='Upgrade to a specific format. Current formats'
 
1836
                                 ' are: default, knit, metaweave and weave.'
 
1837
                                 ' Default is knit; metaweave and weave are'
 
1838
                                 ' deprecated',
 
1839
                            type=get_format_type),
 
1840
                    ]
 
1841
 
 
1842
 
 
1843
    def run(self, url='.', format=None):
 
1844
        from bzrlib.upgrade import upgrade
 
1845
        if format is None:
 
1846
            format = get_format_type('default')
 
1847
        upgrade(url, format)
 
1848
 
 
1849
 
 
1850
class cmd_whoami(Command):
 
1851
    """Show or set bzr user id.
 
1852
    
 
1853
    examples:
 
1854
        bzr whoami --email
 
1855
        bzr whoami 'Frank Chu <fchu@example.com>'
 
1856
    """
 
1857
    takes_options = [ Option('email',
 
1858
                             help='display email address only'),
 
1859
                      Option('branch',
 
1860
                             help='set identity for the current branch instead of '
 
1861
                                  'globally'),
 
1862
                    ]
 
1863
    takes_args = ['name?']
 
1864
    encoding_type = 'replace'
 
1865
    
 
1866
    @display_command
 
1867
    def run(self, email=False, branch=False, name=None):
 
1868
        if name is None:
 
1869
            # use branch if we're inside one; otherwise global config
 
1870
            try:
 
1871
                c = Branch.open_containing('.')[0].get_config()
 
1872
            except NotBranchError:
 
1873
                c = config.GlobalConfig()
 
1874
            if email:
 
1875
                self.outf.write(c.user_email() + '\n')
 
1876
            else:
 
1877
                self.outf.write(c.username() + '\n')
 
1878
            return
 
1879
 
 
1880
        # display a warning if an email address isn't included in the given name.
 
1881
        try:
 
1882
            config.extract_email_address(name)
 
1883
        except BzrError, e:
 
1884
            warning('"%s" does not seem to contain an email address.  '
 
1885
                    'This is allowed, but not recommended.', name)
 
1886
        
 
1887
        # use global config unless --branch given
 
1888
        if branch:
 
1889
            c = Branch.open_containing('.')[0].get_config()
 
1890
        else:
 
1891
            c = config.GlobalConfig()
 
1892
        c.set_user_option('email', name)
 
1893
 
 
1894
 
 
1895
class cmd_nick(Command):
 
1896
    """Print or set the branch nickname.  
 
1897
 
 
1898
    If unset, the tree root directory name is used as the nickname
 
1899
    To print the current nickname, execute with no argument.  
 
1900
    """
 
1901
    takes_args = ['nickname?']
 
1902
    def run(self, nickname=None):
 
1903
        branch = Branch.open_containing(u'.')[0]
 
1904
        if nickname is None:
 
1905
            self.printme(branch)
 
1906
        else:
 
1907
            branch.nick = nickname
 
1908
 
 
1909
    @display_command
 
1910
    def printme(self, branch):
 
1911
        print branch.nick 
 
1912
 
 
1913
 
 
1914
class cmd_selftest(Command):
 
1915
    """Run internal test suite.
 
1916
    
 
1917
    This creates temporary test directories in the working directory,
 
1918
    but not existing data is affected.  These directories are deleted
 
1919
    if the tests pass, or left behind to help in debugging if they
 
1920
    fail and --keep-output is specified.
 
1921
    
 
1922
    If arguments are given, they are regular expressions that say
 
1923
    which tests should run.
 
1924
 
 
1925
    If the global option '--no-plugins' is given, plugins are not loaded
 
1926
    before running the selftests.  This has two effects: features provided or
 
1927
    modified by plugins will not be tested, and tests provided by plugins will
 
1928
    not be run.
 
1929
 
 
1930
    examples:
 
1931
        bzr selftest ignore
 
1932
        bzr --no-plugins selftest -v
 
1933
    """
 
1934
    # TODO: --list should give a list of all available tests
 
1935
 
 
1936
    # NB: this is used from the class without creating an instance, which is
 
1937
    # why it does not have a self parameter.
 
1938
    def get_transport_type(typestring):
 
1939
        """Parse and return a transport specifier."""
 
1940
        if typestring == "sftp":
 
1941
            from bzrlib.transport.sftp import SFTPAbsoluteServer
 
1942
            return SFTPAbsoluteServer
 
1943
        if typestring == "memory":
 
1944
            from bzrlib.transport.memory import MemoryServer
 
1945
            return MemoryServer
 
1946
        if typestring == "fakenfs":
 
1947
            from bzrlib.transport.fakenfs import FakeNFSServer
 
1948
            return FakeNFSServer
 
1949
        msg = "No known transport type %s. Supported types are: sftp\n" %\
 
1950
            (typestring)
 
1951
        raise BzrCommandError(msg)
 
1952
 
 
1953
    hidden = True
 
1954
    takes_args = ['testspecs*']
 
1955
    takes_options = ['verbose',
 
1956
                     Option('one', help='stop when one test fails'),
 
1957
                     Option('keep-output', 
 
1958
                            help='keep output directories when tests fail'),
 
1959
                     Option('transport', 
 
1960
                            help='Use a different transport by default '
 
1961
                                 'throughout the test suite.',
 
1962
                            type=get_transport_type),
 
1963
                     Option('benchmark', help='run the bzr bencharks.'),
 
1964
                     Option('lsprof-timed',
 
1965
                            help='generate lsprof output for benchmarked'
 
1966
                                 ' sections of code.'),
 
1967
                     Option('cache-dir', type=str,
 
1968
                            help='a directory to cache intermediate'
 
1969
                                 ' benchmark steps'),
 
1970
                     ]
 
1971
 
 
1972
    def run(self, testspecs_list=None, verbose=None, one=False,
 
1973
            keep_output=False, transport=None, benchmark=None,
 
1974
            lsprof_timed=None, cache_dir=None):
 
1975
        import bzrlib.ui
 
1976
        from bzrlib.tests import selftest
 
1977
        import bzrlib.benchmarks as benchmarks
 
1978
        from bzrlib.benchmarks import tree_creator
 
1979
 
 
1980
        if cache_dir is not None:
 
1981
            tree_creator.TreeCreator.CACHE_ROOT = osutils.abspath(cache_dir)
 
1982
        # we don't want progress meters from the tests to go to the
 
1983
        # real output; and we don't want log messages cluttering up
 
1984
        # the real logs.
 
1985
        save_ui = ui.ui_factory
 
1986
        print '%10s: %s' % ('bzr', osutils.realpath(sys.argv[0]))
 
1987
        print '%10s: %s' % ('bzrlib', bzrlib.__path__[0])
 
1988
        print
 
1989
        info('running tests...')
 
1990
        try:
 
1991
            ui.ui_factory = ui.SilentUIFactory()
 
1992
            if testspecs_list is not None:
 
1993
                pattern = '|'.join(testspecs_list)
 
1994
            else:
 
1995
                pattern = ".*"
 
1996
            if benchmark:
 
1997
                test_suite_factory = benchmarks.test_suite
 
1998
                if verbose is None:
 
1999
                    verbose = True
 
2000
                benchfile = open(".perf_history", "at")
 
2001
            else:
 
2002
                test_suite_factory = None
 
2003
                if verbose is None:
 
2004
                    verbose = False
 
2005
                benchfile = None
 
2006
            try:
 
2007
                result = selftest(verbose=verbose, 
 
2008
                                  pattern=pattern,
 
2009
                                  stop_on_failure=one, 
 
2010
                                  keep_output=keep_output,
 
2011
                                  transport=transport,
 
2012
                                  test_suite_factory=test_suite_factory,
 
2013
                                  lsprof_timed=lsprof_timed,
 
2014
                                  bench_history=benchfile)
 
2015
            finally:
 
2016
                if benchfile is not None:
 
2017
                    benchfile.close()
 
2018
            if result:
 
2019
                info('tests passed')
 
2020
            else:
 
2021
                info('tests failed')
 
2022
            return int(not result)
 
2023
        finally:
 
2024
            ui.ui_factory = save_ui
 
2025
 
 
2026
 
 
2027
class cmd_version(Command):
 
2028
    """Show version of bzr."""
 
2029
 
 
2030
    @display_command
 
2031
    def run(self):
 
2032
        from bzrlib.version import show_version
 
2033
        show_version()
 
2034
 
 
2035
 
 
2036
class cmd_rocks(Command):
 
2037
    """Statement of optimism."""
 
2038
 
 
2039
    hidden = True
 
2040
 
 
2041
    @display_command
 
2042
    def run(self):
 
2043
        print "it sure does!"
 
2044
 
 
2045
 
 
2046
class cmd_find_merge_base(Command):
 
2047
    """Find and print a base revision for merging two branches."""
 
2048
    # TODO: Options to specify revisions on either side, as if
 
2049
    #       merging only part of the history.
 
2050
    takes_args = ['branch', 'other']
 
2051
    hidden = True
 
2052
    
 
2053
    @display_command
 
2054
    def run(self, branch, other):
 
2055
        from bzrlib.revision import common_ancestor, MultipleRevisionSources
 
2056
        
 
2057
        branch1 = Branch.open_containing(branch)[0]
 
2058
        branch2 = Branch.open_containing(other)[0]
 
2059
 
 
2060
        history_1 = branch1.revision_history()
 
2061
        history_2 = branch2.revision_history()
 
2062
 
 
2063
        last1 = branch1.last_revision()
 
2064
        last2 = branch2.last_revision()
 
2065
 
 
2066
        source = MultipleRevisionSources(branch1.repository, 
 
2067
                                         branch2.repository)
 
2068
        
 
2069
        base_rev_id = common_ancestor(last1, last2, source)
 
2070
 
 
2071
        print 'merge base is revision %s' % base_rev_id
 
2072
 
 
2073
 
 
2074
class cmd_merge(Command):
 
2075
    """Perform a three-way merge.
 
2076
    
 
2077
    The branch is the branch you will merge from.  By default, it will merge
 
2078
    the latest revision.  If you specify a revision, that revision will be
 
2079
    merged.  If you specify two revisions, the first will be used as a BASE,
 
2080
    and the second one as OTHER.  Revision numbers are always relative to the
 
2081
    specified branch.
 
2082
 
 
2083
    By default, bzr will try to merge in all new work from the other
 
2084
    branch, automatically determining an appropriate base.  If this
 
2085
    fails, you may need to give an explicit base.
 
2086
    
 
2087
    Merge will do its best to combine the changes in two branches, but there
 
2088
    are some kinds of problems only a human can fix.  When it encounters those,
 
2089
    it will mark a conflict.  A conflict means that you need to fix something,
 
2090
    before you should commit.
 
2091
 
 
2092
    Use bzr resolve when you have fixed a problem.  See also bzr conflicts.
 
2093
 
 
2094
    If there is no default branch set, the first merge will set it. After
 
2095
    that, you can omit the branch to use the default.  To change the
 
2096
    default, use --remember. The value will only be saved if the remote
 
2097
    location can be accessed.
 
2098
 
 
2099
    Examples:
 
2100
 
 
2101
    To merge the latest revision from bzr.dev
 
2102
    bzr merge ../bzr.dev
 
2103
 
 
2104
    To merge changes up to and including revision 82 from bzr.dev
 
2105
    bzr merge -r 82 ../bzr.dev
 
2106
 
 
2107
    To merge the changes introduced by 82, without previous changes:
 
2108
    bzr merge -r 81..82 ../bzr.dev
 
2109
    
 
2110
    merge refuses to run if there are any uncommitted changes, unless
 
2111
    --force is given.
 
2112
 
 
2113
    The following merge types are available:
 
2114
    """
 
2115
    takes_args = ['branch?']
 
2116
    takes_options = ['revision', 'force', 'merge-type', 'reprocess', 'remember',
 
2117
                     Option('show-base', help="Show base revision text in "
 
2118
                            "conflicts"), 
 
2119
                     Option('uncommitted', help='Apply uncommitted changes'
 
2120
                            ' from a working copy, instead of branch changes')]
 
2121
 
 
2122
    def help(self):
 
2123
        from merge import merge_type_help
 
2124
        from inspect import getdoc
 
2125
        return getdoc(self) + '\n' + merge_type_help() 
 
2126
 
 
2127
    def run(self, branch=None, revision=None, force=False, merge_type=None,
 
2128
            show_base=False, reprocess=False, remember=False, 
 
2129
            uncommitted=False):
 
2130
        if merge_type is None:
 
2131
            merge_type = Merge3Merger
 
2132
 
 
2133
        tree = WorkingTree.open_containing(u'.')[0]
 
2134
 
 
2135
        if branch is not None:
 
2136
            try:
 
2137
                reader = bundle.read_bundle_from_url(branch)
 
2138
            except NotABundle:
 
2139
                pass # Continue on considering this url a Branch
 
2140
            else:
 
2141
                conflicts = merge_bundle(reader, tree, not force, merge_type,
 
2142
                                            reprocess, show_base)
 
2143
                if conflicts == 0:
 
2144
                    return 0
 
2145
                else:
 
2146
                    return 1
 
2147
 
 
2148
        if revision is None or len(revision) < 1 or revision[0].needs_branch():
 
2149
            branch = self._get_remembered_parent(tree, branch, 'Merging from')
 
2150
 
 
2151
        if revision is None or len(revision) < 1:
 
2152
            if uncommitted:
 
2153
                base = [branch, -1]
 
2154
                other = [branch, None]
 
2155
            else:
 
2156
                base = [None, None]
 
2157
                other = [branch, -1]
 
2158
            other_branch, path = Branch.open_containing(branch)
 
2159
        else:
 
2160
            if uncommitted:
 
2161
                raise BzrCommandError('Cannot use --uncommitted and --revision'
 
2162
                                      ' at the same time.')
 
2163
            branch = revision[0].get_branch() or branch
 
2164
            if len(revision) == 1:
 
2165
                base = [None, None]
 
2166
                other_branch, path = Branch.open_containing(branch)
 
2167
                revno = revision[0].in_history(other_branch).revno
 
2168
                other = [branch, revno]
 
2169
            else:
 
2170
                assert len(revision) == 2
 
2171
                if None in revision:
 
2172
                    raise BzrCommandError(
 
2173
                        "Merge doesn't permit that revision specifier.")
 
2174
                if revision[1].get_branch() != revision[0].get_branch():
 
2175
                    # branch is obtained from
 
2176
                    # revision[0].get_branch(), and will be used for
 
2177
                    # the merge. Having two different branches here
 
2178
                    # does not work. Fix it and uncomment the relevant
 
2179
                    # section in test_merge if you want it to work.
 
2180
                    raise BzrCommandError(
 
2181
                        "Merge doesn't accept two revisions in different branches.")
 
2182
                other_branch, path = Branch.open_containing(branch)
 
2183
 
 
2184
                base = [branch, revision[0].in_history(other_branch).revno]
 
2185
                other = [branch, revision[1].in_history(other_branch).revno]
 
2186
 
 
2187
        if tree.branch.get_parent() is None or remember:
 
2188
            tree.branch.set_parent(other_branch.base)
 
2189
 
 
2190
        if path != "":
 
2191
            interesting_files = [path]
 
2192
        else:
 
2193
            interesting_files = None
 
2194
        pb = ui.ui_factory.nested_progress_bar()
 
2195
        try:
 
2196
            try:
 
2197
                conflict_count = merge(other, base, check_clean=(not force),
 
2198
                                       merge_type=merge_type,
 
2199
                                       reprocess=reprocess,
 
2200
                                       show_base=show_base,
 
2201
                                       pb=pb, file_list=interesting_files)
 
2202
            finally:
 
2203
                pb.finished()
 
2204
            if conflict_count != 0:
 
2205
                return 1
 
2206
            else:
 
2207
                return 0
 
2208
        except errors.AmbiguousBase, e:
 
2209
            m = ("sorry, bzr can't determine the right merge base yet\n"
 
2210
                 "candidates are:\n  "
 
2211
                 + "\n  ".join(e.bases)
 
2212
                 + "\n"
 
2213
                 "please specify an explicit base with -r,\n"
 
2214
                 "and (if you want) report this to the bzr developers\n")
 
2215
            log_error(m)
 
2216
 
 
2217
    # TODO: move up to common parent; this isn't merge-specific anymore. 
 
2218
    def _get_remembered_parent(self, tree, supplied_location, verb_string):
 
2219
        """Use tree.branch's parent if none was supplied.
 
2220
 
 
2221
        Report if the remembered location was used.
 
2222
        """
 
2223
        if supplied_location is not None:
 
2224
            return supplied_location
 
2225
        stored_location = tree.branch.get_parent()
 
2226
        mutter("%s", stored_location)
 
2227
        if stored_location is None:
 
2228
            raise BzrCommandError("No location specified or remembered")
 
2229
        display_url = urlutils.unescape_for_display(stored_location, self.outf.encoding)
 
2230
        self.outf.write("%s remembered location %s\n" % (verb_string, display_url))
 
2231
        return stored_location
 
2232
 
 
2233
 
 
2234
class cmd_remerge(Command):
 
2235
    """Redo a merge.
 
2236
 
 
2237
    Use this if you want to try a different merge technique while resolving
 
2238
    conflicts.  Some merge techniques are better than others, and remerge 
 
2239
    lets you try different ones on different files.
 
2240
 
 
2241
    The options for remerge have the same meaning and defaults as the ones for
 
2242
    merge.  The difference is that remerge can (only) be run when there is a
 
2243
    pending merge, and it lets you specify particular files.
 
2244
 
 
2245
    Examples:
 
2246
    $ bzr remerge --show-base
 
2247
        Re-do the merge of all conflicted files, and show the base text in
 
2248
        conflict regions, in addition to the usual THIS and OTHER texts.
 
2249
 
 
2250
    $ bzr remerge --merge-type weave --reprocess foobar
 
2251
        Re-do the merge of "foobar", using the weave merge algorithm, with
 
2252
        additional processing to reduce the size of conflict regions.
 
2253
    
 
2254
    The following merge types are available:"""
 
2255
    takes_args = ['file*']
 
2256
    takes_options = ['merge-type', 'reprocess',
 
2257
                     Option('show-base', help="Show base revision text in "
 
2258
                            "conflicts")]
 
2259
 
 
2260
    def help(self):
 
2261
        from merge import merge_type_help
 
2262
        from inspect import getdoc
 
2263
        return getdoc(self) + '\n' + merge_type_help() 
 
2264
 
 
2265
    def run(self, file_list=None, merge_type=None, show_base=False,
 
2266
            reprocess=False):
 
2267
        from bzrlib.merge import merge_inner, transform_tree
 
2268
        if merge_type is None:
 
2269
            merge_type = Merge3Merger
 
2270
        tree, file_list = tree_files(file_list)
 
2271
        tree.lock_write()
 
2272
        try:
 
2273
            parents = tree.get_parent_ids()
 
2274
            if len(parents) != 2:
 
2275
                raise BzrCommandError("Sorry, remerge only works after normal"
 
2276
                                      " merges.  Not cherrypicking or"
 
2277
                                      " multi-merges.")
 
2278
            repository = tree.branch.repository
 
2279
            base_revision = common_ancestor(parents[0],
 
2280
                                            parents[1], repository)
 
2281
            base_tree = repository.revision_tree(base_revision)
 
2282
            other_tree = repository.revision_tree(parents[1])
 
2283
            interesting_ids = None
 
2284
            new_conflicts = []
 
2285
            conflicts = tree.conflicts()
 
2286
            if file_list is not None:
 
2287
                interesting_ids = set()
 
2288
                for filename in file_list:
 
2289
                    file_id = tree.path2id(filename)
 
2290
                    if file_id is None:
 
2291
                        raise NotVersionedError(filename)
 
2292
                    interesting_ids.add(file_id)
 
2293
                    if tree.kind(file_id) != "directory":
 
2294
                        continue
 
2295
                    
 
2296
                    for name, ie in tree.inventory.iter_entries(file_id):
 
2297
                        interesting_ids.add(ie.file_id)
 
2298
                new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
 
2299
            transform_tree(tree, tree.basis_tree(), interesting_ids)
 
2300
            tree.set_conflicts(ConflictList(new_conflicts))
 
2301
            if file_list is None:
 
2302
                restore_files = list(tree.iter_conflicts())
 
2303
            else:
 
2304
                restore_files = file_list
 
2305
            for filename in restore_files:
 
2306
                try:
 
2307
                    restore(tree.abspath(filename))
 
2308
                except NotConflicted:
 
2309
                    pass
 
2310
            conflicts = merge_inner(tree.branch, other_tree, base_tree,
 
2311
                                    this_tree=tree,
 
2312
                                    interesting_ids=interesting_ids,
 
2313
                                    other_rev_id=parents[1],
 
2314
                                    merge_type=merge_type,
 
2315
                                    show_base=show_base,
 
2316
                                    reprocess=reprocess)
 
2317
        finally:
 
2318
            tree.unlock()
 
2319
        if conflicts > 0:
 
2320
            return 1
 
2321
        else:
 
2322
            return 0
 
2323
 
 
2324
class cmd_revert(Command):
 
2325
    """Reverse all changes since the last commit.
 
2326
 
 
2327
    Only versioned files are affected.  Specify filenames to revert only 
 
2328
    those files.  By default, any files that are changed will be backed up
 
2329
    first.  Backup files have a '~' appended to their name.
 
2330
    """
 
2331
    takes_options = ['revision', 'no-backup']
 
2332
    takes_args = ['file*']
 
2333
    aliases = ['merge-revert']
 
2334
 
 
2335
    def run(self, revision=None, no_backup=False, file_list=None):
 
2336
        from bzrlib.commands import parse_spec
 
2337
        if file_list is not None:
 
2338
            if len(file_list) == 0:
 
2339
                raise BzrCommandError("No files specified")
 
2340
        else:
 
2341
            file_list = []
 
2342
        
 
2343
        tree, file_list = tree_files(file_list)
 
2344
        if revision is None:
 
2345
            # FIXME should be tree.last_revision
 
2346
            rev_id = tree.last_revision()
 
2347
        elif len(revision) != 1:
 
2348
            raise BzrCommandError('bzr revert --revision takes exactly 1 argument')
 
2349
        else:
 
2350
            rev_id = revision[0].in_history(tree.branch).rev_id
 
2351
        pb = ui.ui_factory.nested_progress_bar()
 
2352
        try:
 
2353
            tree.revert(file_list, 
 
2354
                        tree.branch.repository.revision_tree(rev_id),
 
2355
                        not no_backup, pb)
 
2356
        finally:
 
2357
            pb.finished()
 
2358
 
 
2359
 
 
2360
class cmd_assert_fail(Command):
 
2361
    """Test reporting of assertion failures"""
 
2362
    hidden = True
 
2363
    def run(self):
 
2364
        assert False, "always fails"
 
2365
 
 
2366
 
 
2367
class cmd_help(Command):
 
2368
    """Show help on a command or other topic.
 
2369
 
 
2370
    For a list of all available commands, say 'bzr help commands'."""
 
2371
    takes_options = [Option('long', 'show help on all commands')]
 
2372
    takes_args = ['topic?']
 
2373
    aliases = ['?', '--help', '-?', '-h']
 
2374
    
 
2375
    @display_command
 
2376
    def run(self, topic=None, long=False):
 
2377
        import help
 
2378
        if topic is None and long:
 
2379
            topic = "commands"
 
2380
        help.help(topic)
 
2381
 
 
2382
 
 
2383
class cmd_shell_complete(Command):
 
2384
    """Show appropriate completions for context.
 
2385
 
 
2386
    For a list of all available commands, say 'bzr shell-complete'."""
 
2387
    takes_args = ['context?']
 
2388
    aliases = ['s-c']
 
2389
    hidden = True
 
2390
    
 
2391
    @display_command
 
2392
    def run(self, context=None):
 
2393
        import shellcomplete
 
2394
        shellcomplete.shellcomplete(context)
 
2395
 
 
2396
 
 
2397
class cmd_fetch(Command):
 
2398
    """Copy in history from another branch but don't merge it.
 
2399
 
 
2400
    This is an internal method used for pull and merge."""
 
2401
    hidden = True
 
2402
    takes_args = ['from_branch', 'to_branch']
 
2403
    def run(self, from_branch, to_branch):
 
2404
        from bzrlib.fetch import Fetcher
 
2405
        from_b = Branch.open(from_branch)
 
2406
        to_b = Branch.open(to_branch)
 
2407
        Fetcher(to_b, from_b)
 
2408
 
 
2409
 
 
2410
class cmd_missing(Command):
 
2411
    """Show unmerged/unpulled revisions between two branches.
 
2412
 
 
2413
    OTHER_BRANCH may be local or remote."""
 
2414
    takes_args = ['other_branch?']
 
2415
    takes_options = [Option('reverse', 'Reverse the order of revisions'),
 
2416
                     Option('mine-only', 
 
2417
                            'Display changes in the local branch only'),
 
2418
                     Option('theirs-only', 
 
2419
                            'Display changes in the remote branch only'), 
 
2420
                     'log-format',
 
2421
                     'line',
 
2422
                     'long', 
 
2423
                     'short',
 
2424
                     'show-ids',
 
2425
                     'verbose'
 
2426
                     ]
 
2427
    encoding_type = 'replace'
 
2428
 
 
2429
    @display_command
 
2430
    def run(self, other_branch=None, reverse=False, mine_only=False,
 
2431
            theirs_only=False, log_format=None, long=False, short=False, line=False, 
 
2432
            show_ids=False, verbose=False):
 
2433
        from bzrlib.missing import find_unmerged, iter_log_data
 
2434
        from bzrlib.log import log_formatter
 
2435
        local_branch = Branch.open_containing(u".")[0]
 
2436
        parent = local_branch.get_parent()
 
2437
        if other_branch is None:
 
2438
            other_branch = parent
 
2439
            if other_branch is None:
 
2440
                raise BzrCommandError("No peer location known or specified.")
 
2441
            print "Using last location: " + local_branch.get_parent()
 
2442
        remote_branch = Branch.open(other_branch)
 
2443
        if remote_branch.base == local_branch.base:
 
2444
            remote_branch = local_branch
 
2445
        local_branch.lock_read()
 
2446
        try:
 
2447
            remote_branch.lock_read()
 
2448
            try:
 
2449
                local_extra, remote_extra = find_unmerged(local_branch, remote_branch)
 
2450
                if (log_format == None):
 
2451
                    default = local_branch.get_config().log_format()
 
2452
                    log_format = get_log_format(long=long, short=short, 
 
2453
                                                line=line, default=default)
 
2454
                lf = log_formatter(log_format,
 
2455
                                   to_file=self.outf,
 
2456
                                   show_ids=show_ids,
 
2457
                                   show_timezone='original')
 
2458
                if reverse is False:
 
2459
                    local_extra.reverse()
 
2460
                    remote_extra.reverse()
 
2461
                if local_extra and not theirs_only:
 
2462
                    print "You have %d extra revision(s):" % len(local_extra)
 
2463
                    for data in iter_log_data(local_extra, local_branch.repository,
 
2464
                                              verbose):
 
2465
                        lf.show(*data)
 
2466
                    printed_local = True
 
2467
                else:
 
2468
                    printed_local = False
 
2469
                if remote_extra and not mine_only:
 
2470
                    if printed_local is True:
 
2471
                        print "\n\n"
 
2472
                    print "You are missing %d revision(s):" % len(remote_extra)
 
2473
                    for data in iter_log_data(remote_extra, remote_branch.repository, 
 
2474
                                              verbose):
 
2475
                        lf.show(*data)
 
2476
                if not remote_extra and not local_extra:
 
2477
                    status_code = 0
 
2478
                    print "Branches are up to date."
 
2479
                else:
 
2480
                    status_code = 1
 
2481
            finally:
 
2482
                remote_branch.unlock()
 
2483
        finally:
 
2484
            local_branch.unlock()
 
2485
        if not status_code and parent is None and other_branch is not None:
 
2486
            local_branch.lock_write()
 
2487
            try:
 
2488
                # handle race conditions - a parent might be set while we run.
 
2489
                if local_branch.get_parent() is None:
 
2490
                    local_branch.set_parent(remote_branch.base)
 
2491
            finally:
 
2492
                local_branch.unlock()
 
2493
        return status_code
 
2494
 
 
2495
 
 
2496
class cmd_plugins(Command):
 
2497
    """List plugins"""
 
2498
    hidden = True
 
2499
    @display_command
 
2500
    def run(self):
 
2501
        import bzrlib.plugin
 
2502
        from inspect import getdoc
 
2503
        for name, plugin in bzrlib.plugin.all_plugins().items():
 
2504
            if hasattr(plugin, '__path__'):
 
2505
                print plugin.__path__[0]
 
2506
            elif hasattr(plugin, '__file__'):
 
2507
                print plugin.__file__
 
2508
            else:
 
2509
                print `plugin`
 
2510
                
 
2511
            d = getdoc(plugin)
 
2512
            if d:
 
2513
                print '\t', d.split('\n')[0]
 
2514
 
 
2515
 
 
2516
class cmd_testament(Command):
 
2517
    """Show testament (signing-form) of a revision."""
 
2518
    takes_options = ['revision', 
 
2519
                     Option('long', help='Produce long-format testament'), 
 
2520
                     Option('strict', help='Produce a strict-format'
 
2521
                            ' testament')]
 
2522
    takes_args = ['branch?']
 
2523
    @display_command
 
2524
    def run(self, branch=u'.', revision=None, long=False, strict=False):
 
2525
        from bzrlib.testament import Testament, StrictTestament
 
2526
        if strict is True:
 
2527
            testament_class = StrictTestament
 
2528
        else:
 
2529
            testament_class = Testament
 
2530
        b = WorkingTree.open_containing(branch)[0].branch
 
2531
        b.lock_read()
 
2532
        try:
 
2533
            if revision is None:
 
2534
                rev_id = b.last_revision()
 
2535
            else:
 
2536
                rev_id = revision[0].in_history(b).rev_id
 
2537
            t = testament_class.from_revision(b.repository, rev_id)
 
2538
            if long:
 
2539
                sys.stdout.writelines(t.as_text_lines())
 
2540
            else:
 
2541
                sys.stdout.write(t.as_short_text())
 
2542
        finally:
 
2543
            b.unlock()
 
2544
 
 
2545
 
 
2546
class cmd_annotate(Command):
 
2547
    """Show the origin of each line in a file.
 
2548
 
 
2549
    This prints out the given file with an annotation on the left side
 
2550
    indicating which revision, author and date introduced the change.
 
2551
 
 
2552
    If the origin is the same for a run of consecutive lines, it is 
 
2553
    shown only at the top, unless the --all option is given.
 
2554
    """
 
2555
    # TODO: annotate directories; showing when each file was last changed
 
2556
    # TODO: if the working copy is modified, show annotations on that 
 
2557
    #       with new uncommitted lines marked
 
2558
    aliases = ['ann', 'blame', 'praise']
 
2559
    takes_args = ['filename']
 
2560
    takes_options = [Option('all', help='show annotations on all lines'),
 
2561
                     Option('long', help='show date in annotations'),
 
2562
                     'revision'
 
2563
                     ]
 
2564
 
 
2565
    @display_command
 
2566
    def run(self, filename, all=False, long=False, revision=None):
 
2567
        from bzrlib.annotate import annotate_file
 
2568
        tree, relpath = WorkingTree.open_containing(filename)
 
2569
        branch = tree.branch
 
2570
        branch.lock_read()
 
2571
        try:
 
2572
            if revision is None:
 
2573
                revision_id = branch.last_revision()
 
2574
            elif len(revision) != 1:
 
2575
                raise BzrCommandError('bzr annotate --revision takes exactly 1 argument')
 
2576
            else:
 
2577
                revision_id = revision[0].in_history(branch).rev_id
 
2578
            file_id = tree.inventory.path2id(relpath)
 
2579
            tree = branch.repository.revision_tree(revision_id)
 
2580
            file_version = tree.inventory[file_id].revision
 
2581
            annotate_file(branch, file_version, file_id, long, all, sys.stdout)
 
2582
        finally:
 
2583
            branch.unlock()
 
2584
 
 
2585
 
 
2586
class cmd_re_sign(Command):
 
2587
    """Create a digital signature for an existing revision."""
 
2588
    # TODO be able to replace existing ones.
 
2589
 
 
2590
    hidden = True # is this right ?
 
2591
    takes_args = ['revision_id*']
 
2592
    takes_options = ['revision']
 
2593
    
 
2594
    def run(self, revision_id_list=None, revision=None):
 
2595
        import bzrlib.gpg as gpg
 
2596
        if revision_id_list is not None and revision is not None:
 
2597
            raise BzrCommandError('You can only supply one of revision_id or --revision')
 
2598
        if revision_id_list is None and revision is None:
 
2599
            raise BzrCommandError('You must supply either --revision or a revision_id')
 
2600
        b = WorkingTree.open_containing(u'.')[0].branch
 
2601
        gpg_strategy = gpg.GPGStrategy(b.get_config())
 
2602
        if revision_id_list is not None:
 
2603
            for revision_id in revision_id_list:
 
2604
                b.repository.sign_revision(revision_id, gpg_strategy)
 
2605
        elif revision is not None:
 
2606
            if len(revision) == 1:
 
2607
                revno, rev_id = revision[0].in_history(b)
 
2608
                b.repository.sign_revision(rev_id, gpg_strategy)
 
2609
            elif len(revision) == 2:
 
2610
                # are they both on rh- if so we can walk between them
 
2611
                # might be nice to have a range helper for arbitrary
 
2612
                # revision paths. hmm.
 
2613
                from_revno, from_revid = revision[0].in_history(b)
 
2614
                to_revno, to_revid = revision[1].in_history(b)
 
2615
                if to_revid is None:
 
2616
                    to_revno = b.revno()
 
2617
                if from_revno is None or to_revno is None:
 
2618
                    raise BzrCommandError('Cannot sign a range of non-revision-history revisions')
 
2619
                for revno in range(from_revno, to_revno + 1):
 
2620
                    b.repository.sign_revision(b.get_rev_id(revno), 
 
2621
                                               gpg_strategy)
 
2622
            else:
 
2623
                raise BzrCommandError('Please supply either one revision, or a range.')
 
2624
 
 
2625
 
 
2626
class cmd_bind(Command):
 
2627
    """Bind the current branch to a master branch.
 
2628
 
 
2629
    After binding, commits must succeed on the master branch
 
2630
    before they are executed on the local one.
 
2631
    """
 
2632
 
 
2633
    takes_args = ['location']
 
2634
    takes_options = []
 
2635
 
 
2636
    def run(self, location=None):
 
2637
        b, relpath = Branch.open_containing(u'.')
 
2638
        b_other = Branch.open(location)
 
2639
        try:
 
2640
            b.bind(b_other)
 
2641
        except DivergedBranches:
 
2642
            raise BzrCommandError('These branches have diverged.'
 
2643
                                  ' Try merging, and then bind again.')
 
2644
 
 
2645
 
 
2646
class cmd_unbind(Command):
 
2647
    """Unbind the current branch from its master branch.
 
2648
 
 
2649
    After unbinding, the local branch is considered independent.
 
2650
    All subsequent commits will be local.
 
2651
    """
 
2652
 
 
2653
    takes_args = []
 
2654
    takes_options = []
 
2655
 
 
2656
    def run(self):
 
2657
        b, relpath = Branch.open_containing(u'.')
 
2658
        if not b.unbind():
 
2659
            raise BzrCommandError('Local branch is not bound')
 
2660
 
 
2661
 
 
2662
class cmd_uncommit(Command):
 
2663
    """Remove the last committed revision.
 
2664
 
 
2665
    --verbose will print out what is being removed.
 
2666
    --dry-run will go through all the motions, but not actually
 
2667
    remove anything.
 
2668
    
 
2669
    In the future, uncommit will create a revision bundle, which can then
 
2670
    be re-applied.
 
2671
    """
 
2672
 
 
2673
    # TODO: jam 20060108 Add an option to allow uncommit to remove
 
2674
    # unreferenced information in 'branch-as-repository' branches.
 
2675
    # TODO: jam 20060108 Add the ability for uncommit to remove unreferenced
 
2676
    # information in shared branches as well.
 
2677
    takes_options = ['verbose', 'revision',
 
2678
                    Option('dry-run', help='Don\'t actually make changes'),
 
2679
                    Option('force', help='Say yes to all questions.')]
 
2680
    takes_args = ['location?']
 
2681
    aliases = []
 
2682
 
 
2683
    def run(self, location=None,
 
2684
            dry_run=False, verbose=False,
 
2685
            revision=None, force=False):
 
2686
        from bzrlib.log import log_formatter, show_log
 
2687
        import sys
 
2688
        from bzrlib.uncommit import uncommit
 
2689
 
 
2690
        if location is None:
 
2691
            location = u'.'
 
2692
        control, relpath = bzrdir.BzrDir.open_containing(location)
 
2693
        try:
 
2694
            tree = control.open_workingtree()
 
2695
            b = tree.branch
 
2696
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
2697
            tree = None
 
2698
            b = control.open_branch()
 
2699
 
 
2700
        rev_id = None
 
2701
        if revision is None:
 
2702
            revno = b.revno()
 
2703
        else:
 
2704
            # 'bzr uncommit -r 10' actually means uncommit
 
2705
            # so that the final tree is at revno 10.
 
2706
            # but bzrlib.uncommit.uncommit() actually uncommits
 
2707
            # the revisions that are supplied.
 
2708
            # So we need to offset it by one
 
2709
            revno = revision[0].in_history(b).revno+1
 
2710
 
 
2711
        if revno <= b.revno():
 
2712
            rev_id = b.get_rev_id(revno)
 
2713
        if rev_id is None:
 
2714
            self.outf.write('No revisions to uncommit.\n')
 
2715
            return 1
 
2716
 
 
2717
        lf = log_formatter('short',
 
2718
                           to_file=self.outf,
 
2719
                           show_timezone='original')
 
2720
 
 
2721
        show_log(b,
 
2722
                 lf,
 
2723
                 verbose=False,
 
2724
                 direction='forward',
 
2725
                 start_revision=revno,
 
2726
                 end_revision=b.revno())
 
2727
 
 
2728
        if dry_run:
 
2729
            print 'Dry-run, pretending to remove the above revisions.'
 
2730
            if not force:
 
2731
                val = raw_input('Press <enter> to continue')
 
2732
        else:
 
2733
            print 'The above revision(s) will be removed.'
 
2734
            if not force:
 
2735
                val = raw_input('Are you sure [y/N]? ')
 
2736
                if val.lower() not in ('y', 'yes'):
 
2737
                    print 'Canceled'
 
2738
                    return 0
 
2739
 
 
2740
        uncommit(b, tree=tree, dry_run=dry_run, verbose=verbose,
 
2741
                revno=revno)
 
2742
 
 
2743
 
 
2744
class cmd_break_lock(Command):
 
2745
    """Break a dead lock on a repository, branch or working directory.
 
2746
 
 
2747
    CAUTION: Locks should only be broken when you are sure that the process
 
2748
    holding the lock has been stopped.
 
2749
 
 
2750
    You can get information on what locks are open via the 'bzr info' command.
 
2751
    
 
2752
    example:
 
2753
        bzr break-lock
 
2754
    """
 
2755
    takes_args = ['location?']
 
2756
 
 
2757
    def run(self, location=None, show=False):
 
2758
        if location is None:
 
2759
            location = u'.'
 
2760
        control, relpath = bzrdir.BzrDir.open_containing(location)
 
2761
        try:
 
2762
            control.break_lock()
 
2763
        except NotImplementedError:
 
2764
            pass
 
2765
        
 
2766
 
 
2767
 
 
2768
# command-line interpretation helper for merge-related commands
 
2769
def merge(other_revision, base_revision,
 
2770
          check_clean=True, ignore_zero=False,
 
2771
          this_dir=None, backup_files=False, merge_type=Merge3Merger,
 
2772
          file_list=None, show_base=False, reprocess=False,
 
2773
          pb=DummyProgress()):
 
2774
    """Merge changes into a tree.
 
2775
 
 
2776
    base_revision
 
2777
        list(path, revno) Base for three-way merge.  
 
2778
        If [None, None] then a base will be automatically determined.
 
2779
    other_revision
 
2780
        list(path, revno) Other revision for three-way merge.
 
2781
    this_dir
 
2782
        Directory to merge changes into; '.' by default.
 
2783
    check_clean
 
2784
        If true, this_dir must have no uncommitted changes before the
 
2785
        merge begins.
 
2786
    ignore_zero - If true, suppress the "zero conflicts" message when 
 
2787
        there are no conflicts; should be set when doing something we expect
 
2788
        to complete perfectly.
 
2789
    file_list - If supplied, merge only changes to selected files.
 
2790
 
 
2791
    All available ancestors of other_revision and base_revision are
 
2792
    automatically pulled into the branch.
 
2793
 
 
2794
    The revno may be -1 to indicate the last revision on the branch, which is
 
2795
    the typical case.
 
2796
 
 
2797
    This function is intended for use from the command line; programmatic
 
2798
    clients might prefer to call merge.merge_inner(), which has less magic 
 
2799
    behavior.
 
2800
    """
 
2801
    from bzrlib.merge import Merger
 
2802
    if this_dir is None:
 
2803
        this_dir = u'.'
 
2804
    this_tree = WorkingTree.open_containing(this_dir)[0]
 
2805
    if show_base and not merge_type is Merge3Merger:
 
2806
        raise BzrCommandError("Show-base is not supported for this merge"
 
2807
                              " type. %s" % merge_type)
 
2808
    if reprocess and not merge_type.supports_reprocess:
 
2809
        raise BzrCommandError("Conflict reduction is not supported for merge"
 
2810
                              " type %s." % merge_type)
 
2811
    if reprocess and show_base:
 
2812
        raise BzrCommandError("Cannot do conflict reduction and show base.")
 
2813
    try:
 
2814
        merger = Merger(this_tree.branch, this_tree=this_tree, pb=pb)
 
2815
        merger.pp = ProgressPhase("Merge phase", 5, pb)
 
2816
        merger.pp.next_phase()
 
2817
        merger.check_basis(check_clean)
 
2818
        merger.set_other(other_revision)
 
2819
        merger.pp.next_phase()
 
2820
        merger.set_base(base_revision)
 
2821
        if merger.base_rev_id == merger.other_rev_id:
 
2822
            note('Nothing to do.')
 
2823
            return 0
 
2824
        merger.backup_files = backup_files
 
2825
        merger.merge_type = merge_type 
 
2826
        merger.set_interesting_files(file_list)
 
2827
        merger.show_base = show_base 
 
2828
        merger.reprocess = reprocess
 
2829
        conflicts = merger.do_merge()
 
2830
        if file_list is None:
 
2831
            merger.set_pending()
 
2832
    finally:
 
2833
        pb.clear()
 
2834
    return conflicts
 
2835
 
 
2836
 
 
2837
# these get imported and then picked up by the scan for cmd_*
 
2838
# TODO: Some more consistent way to split command definitions across files;
 
2839
# we do need to load at least some information about them to know of 
 
2840
# aliases.  ideally we would avoid loading the implementation until the
 
2841
# details were needed.
 
2842
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore
 
2843
from bzrlib.bundle.commands import cmd_bundle_revisions
 
2844
from bzrlib.sign_my_commits import cmd_sign_my_commits
 
2845
from bzrlib.weave_commands import cmd_weave_list, cmd_weave_join, \
 
2846
        cmd_weave_plan_merge, cmd_weave_merge_text