/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-05-02 20:46:11 UTC
  • mto: This revision was merged to the branch mainline in revision 1752.
  • Revision ID: john@arbash-meinel.com-20060502204611-02caa5c20fb84ef8
Moved url functions into bzrlib.urlutils

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