~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/builtins.py

Late bind to PatienceSequenceMatcher in merge3.py

Show diffs side-by-side

added added

removed removed

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