/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/builtins.py

  • Committer: John Arbash Meinel
  • Date: 2006-04-27 15:14:36 UTC
  • mto: This revision was merged to the branch mainline in revision 1752.
  • Revision ID: john@arbash-meinel.com-20060427151436-eb8c2328f7ea15f3
Repository had a bug with what exception was raised when a file was missing

Show diffs side-by-side

added added

removed removed

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