/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/builtins.py

  • Committer: Robert Collins
  • Date: 2006-03-04 13:03:57 UTC
  • mfrom: (1505.1.30 bzr-bound-branch)
  • mto: This revision was merged to the branch mainline in revision 1590.
  • Revision ID: robertc@robertcollins.net-20060304130357-95990a95920f57bb
Update bound branch implementation to 0.8.

Show diffs side-by-side

added added

removed removed

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