/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: Aaron Bentley
  • Date: 2005-10-19 19:01:03 UTC
  • mto: (1185.25.1)
  • mto: This revision was merged to the branch mainline in revision 1474.
  • Revision ID: abentley@panoramicfeedback.com-20051019190103-7592b0cfc94e4109
Included configobj in setup.py

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
 
 
18
import sys
 
19
import os
 
20
 
 
21
import bzrlib
 
22
from bzrlib import BZRDIR
 
23
from bzrlib.commands import Command, display_command
 
24
from bzrlib.branch import Branch
 
25
from bzrlib.errors import BzrError, BzrCheckError, BzrCommandError, NotBranchError
 
26
from bzrlib.errors import DivergedBranches
 
27
from bzrlib.option import Option
 
28
from bzrlib.revisionspec import RevisionSpec
 
29
import bzrlib.trace
 
30
from bzrlib.trace import mutter, note, log_error, warning
 
31
from bzrlib.workingtree import WorkingTree
 
32
 
 
33
 
 
34
class cmd_status(Command):
 
35
    """Display status summary.
 
36
 
 
37
    This reports on versioned and unknown files, reporting them
 
38
    grouped by state.  Possible states are:
 
39
 
 
40
    added
 
41
        Versioned in the working copy but not in the previous revision.
 
42
 
 
43
    removed
 
44
        Versioned in the previous revision but removed or deleted
 
45
        in the working copy.
 
46
 
 
47
    renamed
 
48
        Path of this file changed from the previous revision;
 
49
        the text may also have changed.  This includes files whose
 
50
        parent directory was renamed.
 
51
 
 
52
    modified
 
53
        Text has changed since the previous revision.
 
54
 
 
55
    unchanged
 
56
        Nothing about this file has changed since the previous revision.
 
57
        Only shown with --all.
 
58
 
 
59
    unknown
 
60
        Not versioned and not matching an ignore pattern.
 
61
 
 
62
    To see ignored files use 'bzr ignored'.  For details in the
 
63
    changes to file texts, use 'bzr diff'.
 
64
 
 
65
    If no arguments are specified, the status of the entire working
 
66
    directory is shown.  Otherwise, only the status of the specified
 
67
    files or directories is reported.  If a directory is given, status
 
68
    is reported for everything inside that directory.
 
69
 
 
70
    If a revision argument is given, the status is calculated against
 
71
    that revision, or between two revisions if two are provided.
 
72
    """
 
73
    # XXX: FIXME: bzr status should accept a -r option to show changes
 
74
    # relative to a revision, or between revisions
 
75
 
 
76
    takes_args = ['file*']
 
77
    takes_options = ['all', 'show-ids']
 
78
    aliases = ['st', 'stat']
 
79
    
 
80
    @display_command
 
81
    def run(self, all=False, show_ids=False, file_list=None, revision=None):
 
82
        if file_list:
 
83
            b, relpath = Branch.open_containing(file_list[0])
 
84
            if relpath == '' and len(file_list) == 1:
 
85
                file_list = None
 
86
            else:
 
87
                # generate relative paths.
 
88
                # note that if this is a remote branch, we would want
 
89
                # relpath against the transport. RBC 20051018
 
90
                tree = WorkingTree(b.base, b)
 
91
                file_list = [tree.relpath(x) for x in file_list]
 
92
        else:
 
93
            b = Branch.open_containing('.')[0]
 
94
            
 
95
        from bzrlib.status import show_status
 
96
        show_status(b, show_unchanged=all, show_ids=show_ids,
 
97
                    specific_files=file_list, revision=revision)
 
98
 
 
99
 
 
100
class cmd_cat_revision(Command):
 
101
    """Write out metadata for a revision.
 
102
    
 
103
    The revision to print can either be specified by a specific
 
104
    revision identifier, or you can use --revision.
 
105
    """
 
106
 
 
107
    hidden = True
 
108
    takes_args = ['revision_id?']
 
109
    takes_options = ['revision']
 
110
    
 
111
    @display_command
 
112
    def run(self, revision_id=None, revision=None):
 
113
 
 
114
        if revision_id is not None and revision is not None:
 
115
            raise BzrCommandError('You can only supply one of revision_id or --revision')
 
116
        if revision_id is None and revision is None:
 
117
            raise BzrCommandError('You must supply either --revision or a revision_id')
 
118
        b = Branch.open_containing('.')[0]
 
119
        if revision_id is not None:
 
120
            sys.stdout.write(b.get_revision_xml_file(revision_id).read())
 
121
        elif revision is not None:
 
122
            for rev in revision:
 
123
                if rev is None:
 
124
                    raise BzrCommandError('You cannot specify a NULL revision.')
 
125
                revno, rev_id = rev.in_history(b)
 
126
                sys.stdout.write(b.get_revision_xml_file(rev_id).read())
 
127
    
 
128
 
 
129
class cmd_revno(Command):
 
130
    """Show current revision number.
 
131
 
 
132
    This is equal to the number of revisions on this branch."""
 
133
    @display_command
 
134
    def run(self):
 
135
        print Branch.open_containing('.')[0].revno()
 
136
 
 
137
 
 
138
class cmd_revision_info(Command):
 
139
    """Show revision number and revision id for a given revision identifier.
 
140
    """
 
141
    hidden = True
 
142
    takes_args = ['revision_info*']
 
143
    takes_options = ['revision']
 
144
    @display_command
 
145
    def run(self, revision=None, revision_info_list=[]):
 
146
 
 
147
        revs = []
 
148
        if revision is not None:
 
149
            revs.extend(revision)
 
150
        if revision_info_list is not None:
 
151
            for rev in revision_info_list:
 
152
                revs.append(RevisionSpec(rev))
 
153
        if len(revs) == 0:
 
154
            raise BzrCommandError('You must supply a revision identifier')
 
155
 
 
156
        b = Branch.open_containing('.')[0]
 
157
 
 
158
        for rev in revs:
 
159
            revinfo = rev.in_history(b)
 
160
            if revinfo.revno is None:
 
161
                print '     %s' % revinfo.rev_id
 
162
            else:
 
163
                print '%4d %s' % (revinfo.revno, revinfo.rev_id)
 
164
 
 
165
    
 
166
class cmd_add(Command):
 
167
    """Add specified files or directories.
 
168
 
 
169
    In non-recursive mode, all the named items are added, regardless
 
170
    of whether they were previously ignored.  A warning is given if
 
171
    any of the named files are already versioned.
 
172
 
 
173
    In recursive mode (the default), files are treated the same way
 
174
    but the behaviour for directories is different.  Directories that
 
175
    are already versioned do not give a warning.  All directories,
 
176
    whether already versioned or not, are searched for files or
 
177
    subdirectories that are neither versioned or ignored, and these
 
178
    are added.  This search proceeds recursively into versioned
 
179
    directories.  If no names are given '.' is assumed.
 
180
 
 
181
    Therefore simply saying 'bzr add' will version all files that
 
182
    are currently unknown.
 
183
 
 
184
    Adding a file whose parent directory is not versioned will
 
185
    implicitly add the parent, and so on up to the root. This means
 
186
    you should never need to explictly add a directory, they'll just
 
187
    get added when you add a file in the directory.
 
188
    """
 
189
    takes_args = ['file*']
 
190
    takes_options = ['no-recurse', 'quiet']
 
191
    
 
192
    def run(self, file_list, no_recurse=False, quiet=False):
 
193
        from bzrlib.add import smart_add, add_reporter_print, add_reporter_null
 
194
        if quiet:
 
195
            reporter = add_reporter_null
 
196
        else:
 
197
            reporter = add_reporter_print
 
198
        smart_add(file_list, not no_recurse, reporter)
 
199
 
 
200
 
 
201
class cmd_mkdir(Command):
 
202
    """Create a new versioned directory.
 
203
 
 
204
    This is equivalent to creating the directory and then adding it.
 
205
    """
 
206
    takes_args = ['dir+']
 
207
 
 
208
    def run(self, dir_list):
 
209
        b = None
 
210
        
 
211
        for d in dir_list:
 
212
            os.mkdir(d)
 
213
            if not b:
 
214
                b = Branch.open_containing(d)[0]
 
215
            b.add([d])
 
216
            print 'added', d
 
217
 
 
218
 
 
219
class cmd_relpath(Command):
 
220
    """Show path of a file relative to root"""
 
221
    takes_args = ['filename']
 
222
    hidden = True
 
223
    
 
224
    @display_command
 
225
    def run(self, filename):
 
226
        branch, relpath = Branch.open_containing(filename)
 
227
        print relpath
 
228
 
 
229
 
 
230
class cmd_inventory(Command):
 
231
    """Show inventory of the current working copy or a revision."""
 
232
    takes_options = ['revision', 'show-ids']
 
233
    
 
234
    @display_command
 
235
    def run(self, revision=None, show_ids=False):
 
236
        b = Branch.open_containing('.')[0]
 
237
        if revision is None:
 
238
            inv = b.read_working_inventory()
 
239
        else:
 
240
            if len(revision) > 1:
 
241
                raise BzrCommandError('bzr inventory --revision takes'
 
242
                    ' exactly one revision identifier')
 
243
            inv = b.get_revision_inventory(revision[0].in_history(b).rev_id)
 
244
 
 
245
        for path, entry in inv.entries():
 
246
            if show_ids:
 
247
                print '%-50s %s' % (path, entry.file_id)
 
248
            else:
 
249
                print path
 
250
 
 
251
 
 
252
class cmd_move(Command):
 
253
    """Move files to a different directory.
 
254
 
 
255
    examples:
 
256
        bzr move *.txt doc
 
257
 
 
258
    The destination must be a versioned directory in the same branch.
 
259
    """
 
260
    takes_args = ['source$', 'dest']
 
261
    def run(self, source_list, dest):
 
262
        b = Branch.open_containing('.')[0]
 
263
 
 
264
        # TODO: glob expansion on windows?
 
265
        tree = WorkingTree(b.base, b)
 
266
        b.move([tree.relpath(s) for s in source_list], tree.relpath(dest))
 
267
 
 
268
 
 
269
class cmd_rename(Command):
 
270
    """Change the name of an entry.
 
271
 
 
272
    examples:
 
273
      bzr rename frob.c frobber.c
 
274
      bzr rename src/frob.c lib/frob.c
 
275
 
 
276
    It is an error if the destination name exists.
 
277
 
 
278
    See also the 'move' command, which moves files into a different
 
279
    directory without changing their name.
 
280
    """
 
281
    # TODO: Some way to rename multiple files without invoking 
 
282
    # bzr for each one?"""
 
283
    takes_args = ['from_name', 'to_name']
 
284
    
 
285
    def run(self, from_name, to_name):
 
286
        b = Branch.open_containing('.')[0]
 
287
        tree = WorkingTree(b.base, b)
 
288
        b.rename_one(tree.relpath(from_name), tree.relpath(to_name))
 
289
 
 
290
 
 
291
class cmd_mv(Command):
 
292
    """Move or rename a file.
 
293
 
 
294
    usage:
 
295
        bzr mv OLDNAME NEWNAME
 
296
        bzr mv SOURCE... DESTINATION
 
297
 
 
298
    If the last argument is a versioned directory, all the other names
 
299
    are moved into it.  Otherwise, there must be exactly two arguments
 
300
    and the file is changed to a new name, which must not already exist.
 
301
 
 
302
    Files cannot be moved between branches.
 
303
    """
 
304
    takes_args = ['names*']
 
305
    def run(self, names_list):
 
306
        if len(names_list) < 2:
 
307
            raise BzrCommandError("missing file argument")
 
308
        b = Branch.open_containing(names_list[0])[0]
 
309
        tree = WorkingTree(b.base, b)
 
310
        rel_names = [tree.relpath(x) for x in names_list]
 
311
        
 
312
        if os.path.isdir(names_list[-1]):
 
313
            # move into existing directory
 
314
            for pair in b.move(rel_names[:-1], rel_names[-1]):
 
315
                print "%s => %s" % pair
 
316
        else:
 
317
            if len(names_list) != 2:
 
318
                raise BzrCommandError('to mv multiple files the destination '
 
319
                                      'must be a versioned directory')
 
320
            b.rename_one(rel_names[0], rel_names[1])
 
321
            print "%s => %s" % (rel_names[0], rel_names[1])
 
322
            
 
323
    
 
324
 
 
325
 
 
326
class cmd_pull(Command):
 
327
    """Pull any changes from another branch into the current one.
 
328
 
 
329
    If the location is omitted, the last-used location will be used.
 
330
    Both the revision history and the working directory will be
 
331
    updated.
 
332
 
 
333
    This command only works on branches that have not diverged.  Branches are
 
334
    considered diverged if both branches have had commits without first
 
335
    pulling from the other.
 
336
 
 
337
    If branches have diverged, you can use 'bzr merge' to pull the text changes
 
338
    from one into the other.
 
339
    """
 
340
    takes_options = ['remember', 'clobber']
 
341
    takes_args = ['location?']
 
342
 
 
343
    def run(self, location=None, remember=False, clobber=False):
 
344
        from bzrlib.merge import merge
 
345
        import tempfile
 
346
        from shutil import rmtree
 
347
        import errno
 
348
        
 
349
        br_to = Branch.open_containing('.')[0]
 
350
        stored_loc = br_to.get_parent()
 
351
        if location is None:
 
352
            if stored_loc is None:
 
353
                raise BzrCommandError("No pull location known or specified.")
 
354
            else:
 
355
                print "Using saved location: %s" % stored_loc
 
356
                location = stored_loc
 
357
        br_from = Branch.open(location)
 
358
        try:
 
359
            br_to.working_tree().pull(br_from, remember, clobber)
 
360
        except DivergedBranches:
 
361
            raise BzrCommandError("These branches have diverged."
 
362
                                  "  Try merge.")
 
363
 
 
364
 
 
365
class cmd_branch(Command):
 
366
    """Create a new copy of a branch.
 
367
 
 
368
    If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
 
369
    be used.  In other words, "branch ../foo/bar" will attempt to create ./bar.
 
370
 
 
371
    To retrieve the branch as of a particular revision, supply the --revision
 
372
    parameter, as in "branch foo/bar -r 5".
 
373
 
 
374
    --basis is to speed up branching from remote branches.  When specified, it
 
375
    copies all the file-contents, inventory and revision data from the basis
 
376
    branch before copying anything from the remote branch.
 
377
    """
 
378
    takes_args = ['from_location', 'to_location?']
 
379
    takes_options = ['revision', 'basis']
 
380
    aliases = ['get', 'clone']
 
381
 
 
382
    def run(self, from_location, to_location=None, revision=None, basis=None):
 
383
        from bzrlib.clone import copy_branch
 
384
        import tempfile
 
385
        import errno
 
386
        from shutil import rmtree
 
387
        cache_root = tempfile.mkdtemp()
 
388
        if revision is None:
 
389
            revision = [None]
 
390
        elif len(revision) > 1:
 
391
            raise BzrCommandError(
 
392
                'bzr branch --revision takes exactly 1 revision value')
 
393
        try:
 
394
            br_from = Branch.open(from_location)
 
395
        except OSError, e:
 
396
            if e.errno == errno.ENOENT:
 
397
                raise BzrCommandError('Source location "%s" does not'
 
398
                                      ' exist.' % to_location)
 
399
            else:
 
400
                raise
 
401
        br_from.lock_read()
 
402
        try:
 
403
            br_from.setup_caching(cache_root)
 
404
            if basis is not None:
 
405
                basis_branch = Branch.open_containing(basis)[0]
 
406
            else:
 
407
                basis_branch = None
 
408
            if len(revision) == 1 and revision[0] is not None:
 
409
                revision_id = revision[0].in_history(br_from)[1]
 
410
            else:
 
411
                revision_id = None
 
412
            if to_location is None:
 
413
                to_location = os.path.basename(from_location.rstrip("/\\"))
 
414
            try:
 
415
                os.mkdir(to_location)
 
416
            except OSError, e:
 
417
                if e.errno == errno.EEXIST:
 
418
                    raise BzrCommandError('Target directory "%s" already'
 
419
                                          ' exists.' % to_location)
 
420
                if e.errno == errno.ENOENT:
 
421
                    raise BzrCommandError('Parent of "%s" does not exist.' %
 
422
                                          to_location)
 
423
                else:
 
424
                    raise
 
425
            try:
 
426
                copy_branch(br_from, to_location, revision_id, basis_branch)
 
427
            except bzrlib.errors.NoSuchRevision:
 
428
                rmtree(to_location)
 
429
                msg = "The branch %s has no revision %d." % (from_location, revision[0])
 
430
                raise BzrCommandError(msg)
 
431
            except bzrlib.errors.UnlistableBranch:
 
432
                msg = "The branch %s cannot be used as a --basis"
 
433
        finally:
 
434
            br_from.unlock()
 
435
            rmtree(cache_root)
 
436
 
 
437
 
 
438
class cmd_renames(Command):
 
439
    """Show list of renamed files.
 
440
    """
 
441
    # TODO: Option to show renames between two historical versions.
 
442
 
 
443
    # TODO: Only show renames under dir, rather than in the whole branch.
 
444
    takes_args = ['dir?']
 
445
 
 
446
    @display_command
 
447
    def run(self, dir='.'):
 
448
        b = Branch.open_containing(dir)[0]
 
449
        old_inv = b.basis_tree().inventory
 
450
        new_inv = b.read_working_inventory()
 
451
 
 
452
        renames = list(bzrlib.tree.find_renames(old_inv, new_inv))
 
453
        renames.sort()
 
454
        for old_name, new_name in renames:
 
455
            print "%s => %s" % (old_name, new_name)        
 
456
 
 
457
 
 
458
class cmd_info(Command):
 
459
    """Show statistical information about a branch."""
 
460
    takes_args = ['branch?']
 
461
    
 
462
    @display_command
 
463
    def run(self, branch=None):
 
464
        import info
 
465
        b = Branch.open_containing(branch)[0]
 
466
        info.show_info(b)
 
467
 
 
468
 
 
469
class cmd_remove(Command):
 
470
    """Make a file unversioned.
 
471
 
 
472
    This makes bzr stop tracking changes to a versioned file.  It does
 
473
    not delete the working copy.
 
474
    """
 
475
    takes_args = ['file+']
 
476
    takes_options = ['verbose']
 
477
    aliases = ['rm']
 
478
    
 
479
    def run(self, file_list, verbose=False):
 
480
        b = Branch.open_containing(file_list[0])[0]
 
481
        tree = WorkingTree(b.base, b)
 
482
        tree.remove([tree.relpath(f) for f in file_list], verbose=verbose)
 
483
 
 
484
 
 
485
class cmd_file_id(Command):
 
486
    """Print file_id of a particular file or directory.
 
487
 
 
488
    The file_id is assigned when the file is first added and remains the
 
489
    same through all revisions where the file exists, even when it is
 
490
    moved or renamed.
 
491
    """
 
492
    hidden = True
 
493
    takes_args = ['filename']
 
494
    @display_command
 
495
    def run(self, filename):
 
496
        b, relpath = Branch.open_containing(filename)
 
497
        i = b.inventory.path2id(relpath)
 
498
        if i == None:
 
499
            raise BzrError("%r is not a versioned file" % filename)
 
500
        else:
 
501
            print i
 
502
 
 
503
 
 
504
class cmd_file_path(Command):
 
505
    """Print path of file_ids to a file or directory.
 
506
 
 
507
    This prints one line for each directory down to the target,
 
508
    starting at the branch root."""
 
509
    hidden = True
 
510
    takes_args = ['filename']
 
511
    @display_command
 
512
    def run(self, filename):
 
513
        b, relpath = Branch.open_containing(filename)
 
514
        inv = b.inventory
 
515
        fid = inv.path2id(relpath)
 
516
        if fid == None:
 
517
            raise BzrError("%r is not a versioned file" % filename)
 
518
        for fip in inv.get_idpath(fid):
 
519
            print fip
 
520
 
 
521
 
 
522
class cmd_revision_history(Command):
 
523
    """Display list of revision ids on this branch."""
 
524
    hidden = True
 
525
    @display_command
 
526
    def run(self):
 
527
        for patchid in Branch.open_containing('.')[0].revision_history():
 
528
            print patchid
 
529
 
 
530
 
 
531
class cmd_ancestry(Command):
 
532
    """List all revisions merged into this branch."""
 
533
    hidden = True
 
534
    @display_command
 
535
    def run(self):
 
536
        b = Branch.open_containing('.')[0]
 
537
        for revision_id in b.get_ancestry(b.last_revision()):
 
538
            print revision_id
 
539
 
 
540
 
 
541
class cmd_directories(Command):
 
542
    """Display list of versioned directories in this branch."""
 
543
    @display_command
 
544
    def run(self):
 
545
        for name, ie in Branch.open_containing('.')[0].read_working_inventory().directories():
 
546
            if name == '':
 
547
                print '.'
 
548
            else:
 
549
                print name
 
550
 
 
551
 
 
552
class cmd_init(Command):
 
553
    """Make a directory into a versioned branch.
 
554
 
 
555
    Use this to create an empty branch, or before importing an
 
556
    existing project.
 
557
 
 
558
    Recipe for importing a tree of files:
 
559
        cd ~/project
 
560
        bzr init
 
561
        bzr add -v .
 
562
        bzr status
 
563
        bzr commit -m 'imported project'
 
564
    """
 
565
    def run(self):
 
566
        Branch.initialize('.')
 
567
 
 
568
 
 
569
class cmd_diff(Command):
 
570
    """Show differences in working tree.
 
571
    
 
572
    If files are listed, only the changes in those files are listed.
 
573
    Otherwise, all changes for the tree are listed.
 
574
 
 
575
    examples:
 
576
        bzr diff
 
577
        bzr diff -r1
 
578
        bzr diff -r1..2
 
579
    """
 
580
    # TODO: Allow diff across branches.
 
581
    # TODO: Option to use external diff command; could be GNU diff, wdiff,
 
582
    #       or a graphical diff.
 
583
 
 
584
    # TODO: Python difflib is not exactly the same as unidiff; should
 
585
    #       either fix it up or prefer to use an external diff.
 
586
 
 
587
    # TODO: If a directory is given, diff everything under that.
 
588
 
 
589
    # TODO: Selected-file diff is inefficient and doesn't show you
 
590
    #       deleted files.
 
591
 
 
592
    # TODO: This probably handles non-Unix newlines poorly.
 
593
    
 
594
    takes_args = ['file*']
 
595
    takes_options = ['revision', 'diff-options']
 
596
    aliases = ['di', 'dif']
 
597
 
 
598
    @display_command
 
599
    def run(self, revision=None, file_list=None, diff_options=None):
 
600
        from bzrlib.diff import show_diff
 
601
 
 
602
        if file_list:
 
603
            b = Branch.open_containing(file_list[0])[0]
 
604
            tree = WorkingTree(b.base, b)
 
605
            file_list = [tree.relpath(f) for f in file_list]
 
606
            if file_list == ['']:
 
607
                # just pointing to top-of-tree
 
608
                file_list = None
 
609
        else:
 
610
            b = Branch.open_containing('.')[0]
 
611
 
 
612
        if revision is not None:
 
613
            if len(revision) == 1:
 
614
                show_diff(b, revision[0], specific_files=file_list,
 
615
                          external_diff_options=diff_options)
 
616
            elif len(revision) == 2:
 
617
                show_diff(b, revision[0], specific_files=file_list,
 
618
                          external_diff_options=diff_options,
 
619
                          revision2=revision[1])
 
620
            else:
 
621
                raise BzrCommandError('bzr diff --revision takes exactly one or two revision identifiers')
 
622
        else:
 
623
            show_diff(b, None, specific_files=file_list,
 
624
                      external_diff_options=diff_options)
 
625
 
 
626
        
 
627
 
 
628
 
 
629
class cmd_deleted(Command):
 
630
    """List files deleted in the working tree.
 
631
    """
 
632
    # TODO: Show files deleted since a previous revision, or
 
633
    # between two revisions.
 
634
    # TODO: Much more efficient way to do this: read in new
 
635
    # directories with readdir, rather than stating each one.  Same
 
636
    # level of effort but possibly much less IO.  (Or possibly not,
 
637
    # if the directories are very large...)
 
638
    @display_command
 
639
    def run(self, show_ids=False):
 
640
        b = Branch.open_containing('.')[0]
 
641
        old = b.basis_tree()
 
642
        new = b.working_tree()
 
643
        for path, ie in old.inventory.iter_entries():
 
644
            if not new.has_id(ie.file_id):
 
645
                if show_ids:
 
646
                    print '%-50s %s' % (path, ie.file_id)
 
647
                else:
 
648
                    print path
 
649
 
 
650
 
 
651
class cmd_modified(Command):
 
652
    """List files modified in working tree."""
 
653
    hidden = True
 
654
    @display_command
 
655
    def run(self):
 
656
        from bzrlib.delta import compare_trees
 
657
 
 
658
        b = Branch.open_containing('.')[0]
 
659
        td = compare_trees(b.basis_tree(), b.working_tree())
 
660
 
 
661
        for path, id, kind, text_modified, meta_modified in td.modified:
 
662
            print path
 
663
 
 
664
 
 
665
 
 
666
class cmd_added(Command):
 
667
    """List files added in working tree."""
 
668
    hidden = True
 
669
    @display_command
 
670
    def run(self):
 
671
        b = Branch.open_containing('.')[0]
 
672
        wt = b.working_tree()
 
673
        basis_inv = b.basis_tree().inventory
 
674
        inv = wt.inventory
 
675
        for file_id in inv:
 
676
            if file_id in basis_inv:
 
677
                continue
 
678
            path = inv.id2path(file_id)
 
679
            if not os.access(b.abspath(path), os.F_OK):
 
680
                continue
 
681
            print path
 
682
                
 
683
        
 
684
 
 
685
class cmd_root(Command):
 
686
    """Show the tree root directory.
 
687
 
 
688
    The root is the nearest enclosing directory with a .bzr control
 
689
    directory."""
 
690
    takes_args = ['filename?']
 
691
    @display_command
 
692
    def run(self, filename=None):
 
693
        """Print the branch root."""
 
694
        b = Branch.open_containing(filename)[0]
 
695
        print b.base
 
696
 
 
697
 
 
698
class cmd_log(Command):
 
699
    """Show log of this branch.
 
700
 
 
701
    To request a range of logs, you can use the command -r begin:end
 
702
    -r revision requests a specific revision, -r :end or -r begin: are
 
703
    also valid.
 
704
    """
 
705
 
 
706
    # TODO: Make --revision support uuid: and hash: [future tag:] notation.
 
707
 
 
708
    takes_args = ['filename?']
 
709
    takes_options = [Option('forward', 
 
710
                            help='show from oldest to newest'),
 
711
                     'timezone', 'verbose', 
 
712
                     'show-ids', 'revision',
 
713
                     Option('line', help='format with one line per revision'),
 
714
                     'long', 
 
715
                     Option('message',
 
716
                            help='show revisions whose message matches this regexp',
 
717
                            type=str),
 
718
                     Option('short', help='use moderately short format'),
 
719
                     ]
 
720
    @display_command
 
721
    def run(self, filename=None, timezone='original',
 
722
            verbose=False,
 
723
            show_ids=False,
 
724
            forward=False,
 
725
            revision=None,
 
726
            message=None,
 
727
            long=False,
 
728
            short=False,
 
729
            line=False):
 
730
        from bzrlib.log import log_formatter, show_log
 
731
        import codecs
 
732
        assert message is None or isinstance(message, basestring), \
 
733
            "invalid message argument %r" % message
 
734
        direction = (forward and 'forward') or 'reverse'
 
735
        
 
736
        if filename:
 
737
            b, fp = Branch.open_containing(filename)
 
738
            if fp != '':
 
739
                file_id = b.read_working_inventory().path2id(fp)
 
740
            else:
 
741
                file_id = None  # points to branch root
 
742
        else:
 
743
            b, relpath = Branch.open_containing('.')
 
744
            file_id = None
 
745
 
 
746
        if revision is None:
 
747
            rev1 = None
 
748
            rev2 = None
 
749
        elif len(revision) == 1:
 
750
            rev1 = rev2 = revision[0].in_history(b).revno
 
751
        elif len(revision) == 2:
 
752
            rev1 = revision[0].in_history(b).revno
 
753
            rev2 = revision[1].in_history(b).revno
 
754
        else:
 
755
            raise BzrCommandError('bzr log --revision takes one or two values.')
 
756
 
 
757
        if rev1 == 0:
 
758
            rev1 = None
 
759
        if rev2 == 0:
 
760
            rev2 = None
 
761
 
 
762
        mutter('encoding log as %r' % bzrlib.user_encoding)
 
763
 
 
764
        # use 'replace' so that we don't abort if trying to write out
 
765
        # in e.g. the default C locale.
 
766
        outf = codecs.getwriter(bzrlib.user_encoding)(sys.stdout, errors='replace')
 
767
 
 
768
        log_format = 'long'
 
769
        if short:
 
770
            log_format = 'short'
 
771
        if line:
 
772
            log_format = 'line'
 
773
        lf = log_formatter(log_format,
 
774
                           show_ids=show_ids,
 
775
                           to_file=outf,
 
776
                           show_timezone=timezone)
 
777
 
 
778
        show_log(b,
 
779
                 lf,
 
780
                 file_id,
 
781
                 verbose=verbose,
 
782
                 direction=direction,
 
783
                 start_revision=rev1,
 
784
                 end_revision=rev2,
 
785
                 search=message)
 
786
 
 
787
 
 
788
 
 
789
class cmd_touching_revisions(Command):
 
790
    """Return revision-ids which affected a particular file.
 
791
 
 
792
    A more user-friendly interface is "bzr log FILE"."""
 
793
    hidden = True
 
794
    takes_args = ["filename"]
 
795
    @display_command
 
796
    def run(self, filename):
 
797
        b, relpath = Branch.open_containing(filename)[0]
 
798
        inv = b.read_working_inventory()
 
799
        file_id = inv.path2id(relpath)
 
800
        for revno, revision_id, what in bzrlib.log.find_touching_revisions(b, file_id):
 
801
            print "%6d %s" % (revno, what)
 
802
 
 
803
 
 
804
class cmd_ls(Command):
 
805
    """List files in a tree.
 
806
    """
 
807
    # TODO: Take a revision or remote path and list that tree instead.
 
808
    hidden = True
 
809
    @display_command
 
810
    def run(self, revision=None, verbose=False):
 
811
        b, relpath = Branch.open_containing('.')[0]
 
812
        if revision == None:
 
813
            tree = b.working_tree()
 
814
        else:
 
815
            tree = b.revision_tree(revision.in_history(b).rev_id)
 
816
        for fp, fc, kind, fid, entry in tree.list_files():
 
817
            if verbose:
 
818
                kindch = entry.kind_character()
 
819
                print '%-8s %s%s' % (fc, fp, kindch)
 
820
            else:
 
821
                print fp
 
822
 
 
823
 
 
824
 
 
825
class cmd_unknowns(Command):
 
826
    """List unknown files."""
 
827
    @display_command
 
828
    def run(self):
 
829
        from bzrlib.osutils import quotefn
 
830
        for f in Branch.open_containing('.')[0].unknowns():
 
831
            print quotefn(f)
 
832
 
 
833
 
 
834
 
 
835
class cmd_ignore(Command):
 
836
    """Ignore a command or pattern.
 
837
 
 
838
    To remove patterns from the ignore list, edit the .bzrignore file.
 
839
 
 
840
    If the pattern contains a slash, it is compared to the whole path
 
841
    from the branch root.  Otherwise, it is compared to only the last
 
842
    component of the path.  To match a file only in the root directory,
 
843
    prepend './'.
 
844
 
 
845
    Ignore patterns are case-insensitive on case-insensitive systems.
 
846
 
 
847
    Note: wildcards must be quoted from the shell on Unix.
 
848
 
 
849
    examples:
 
850
        bzr ignore ./Makefile
 
851
        bzr ignore '*.class'
 
852
    """
 
853
    # TODO: Complain if the filename is absolute
 
854
    takes_args = ['name_pattern']
 
855
    
 
856
    def run(self, name_pattern):
 
857
        from bzrlib.atomicfile import AtomicFile
 
858
        import os.path
 
859
 
 
860
        b, relpath = Branch.open_containing('.')
 
861
        ifn = b.abspath('.bzrignore')
 
862
 
 
863
        if os.path.exists(ifn):
 
864
            f = open(ifn, 'rt')
 
865
            try:
 
866
                igns = f.read().decode('utf-8')
 
867
            finally:
 
868
                f.close()
 
869
        else:
 
870
            igns = ''
 
871
 
 
872
        # TODO: If the file already uses crlf-style termination, maybe
 
873
        # we should use that for the newly added lines?
 
874
 
 
875
        if igns and igns[-1] != '\n':
 
876
            igns += '\n'
 
877
        igns += name_pattern + '\n'
 
878
 
 
879
        try:
 
880
            f = AtomicFile(ifn, 'wt')
 
881
            f.write(igns.encode('utf-8'))
 
882
            f.commit()
 
883
        finally:
 
884
            f.close()
 
885
 
 
886
        inv = b.working_tree().inventory
 
887
        if inv.path2id('.bzrignore'):
 
888
            mutter('.bzrignore is already versioned')
 
889
        else:
 
890
            mutter('need to make new .bzrignore file versioned')
 
891
            b.add(['.bzrignore'])
 
892
 
 
893
 
 
894
 
 
895
class cmd_ignored(Command):
 
896
    """List ignored files and the patterns that matched them.
 
897
 
 
898
    See also: bzr ignore"""
 
899
    @display_command
 
900
    def run(self):
 
901
        tree = Branch.open_containing('.')[0].working_tree()
 
902
        for path, file_class, kind, file_id, entry in tree.list_files():
 
903
            if file_class != 'I':
 
904
                continue
 
905
            ## XXX: Slightly inefficient since this was already calculated
 
906
            pat = tree.is_ignored(path)
 
907
            print '%-50s %s' % (path, pat)
 
908
 
 
909
 
 
910
class cmd_lookup_revision(Command):
 
911
    """Lookup the revision-id from a revision-number
 
912
 
 
913
    example:
 
914
        bzr lookup-revision 33
 
915
    """
 
916
    hidden = True
 
917
    takes_args = ['revno']
 
918
    
 
919
    @display_command
 
920
    def run(self, revno):
 
921
        try:
 
922
            revno = int(revno)
 
923
        except ValueError:
 
924
            raise BzrCommandError("not a valid revision-number: %r" % revno)
 
925
 
 
926
        print Branch.open_containing('.')[0].get_rev_id(revno)
 
927
 
 
928
 
 
929
class cmd_export(Command):
 
930
    """Export past revision to destination directory.
 
931
 
 
932
    If no revision is specified this exports the last committed revision.
 
933
 
 
934
    Format may be an "exporter" name, such as tar, tgz, tbz2.  If none is
 
935
    given, try to find the format with the extension. If no extension
 
936
    is found exports to a directory (equivalent to --format=dir).
 
937
 
 
938
    Root may be the top directory for tar, tgz and tbz2 formats. If none
 
939
    is given, the top directory will be the root name of the file."""
 
940
    # TODO: list known exporters
 
941
    takes_args = ['dest']
 
942
    takes_options = ['revision', 'format', 'root']
 
943
    def run(self, dest, revision=None, format=None, root=None):
 
944
        import os.path
 
945
        b = Branch.open_containing('.')[0]
 
946
        if revision is None:
 
947
            rev_id = b.last_revision()
 
948
        else:
 
949
            if len(revision) != 1:
 
950
                raise BzrError('bzr export --revision takes exactly 1 argument')
 
951
            rev_id = revision[0].in_history(b).rev_id
 
952
        t = b.revision_tree(rev_id)
 
953
        arg_root, ext = os.path.splitext(os.path.basename(dest))
 
954
        if ext in ('.gz', '.bz2'):
 
955
            new_root, new_ext = os.path.splitext(arg_root)
 
956
            if new_ext == '.tar':
 
957
                arg_root = new_root
 
958
                ext = new_ext + ext
 
959
        if root is None:
 
960
            root = arg_root
 
961
        if not format:
 
962
            if ext in (".tar",):
 
963
                format = "tar"
 
964
            elif ext in (".tar.gz", ".tgz"):
 
965
                format = "tgz"
 
966
            elif ext in (".tar.bz2", ".tbz2"):
 
967
                format = "tbz2"
 
968
            else:
 
969
                format = "dir"
 
970
        t.export(dest, format, root)
 
971
 
 
972
 
 
973
class cmd_cat(Command):
 
974
    """Write a file's text from a previous revision."""
 
975
 
 
976
    takes_options = ['revision']
 
977
    takes_args = ['filename']
 
978
 
 
979
    @display_command
 
980
    def run(self, filename, revision=None):
 
981
        if revision is None:
 
982
            raise BzrCommandError("bzr cat requires a revision number")
 
983
        elif len(revision) != 1:
 
984
            raise BzrCommandError("bzr cat --revision takes exactly one number")
 
985
        b, relpath = Branch.open_containing(filename)
 
986
        b.print_file(relpath, revision[0].in_history(b).revno)
 
987
 
 
988
 
 
989
class cmd_local_time_offset(Command):
 
990
    """Show the offset in seconds from GMT to local time."""
 
991
    hidden = True    
 
992
    @display_command
 
993
    def run(self):
 
994
        print bzrlib.osutils.local_time_offset()
 
995
 
 
996
 
 
997
 
 
998
class cmd_commit(Command):
 
999
    """Commit changes into a new revision.
 
1000
    
 
1001
    If no arguments are given, the entire tree is committed.
 
1002
 
 
1003
    If selected files are specified, only changes to those files are
 
1004
    committed.  If a directory is specified then the directory and everything 
 
1005
    within it is committed.
 
1006
 
 
1007
    A selected-file commit may fail in some cases where the committed
 
1008
    tree would be invalid, such as trying to commit a file in a
 
1009
    newly-added directory that is not itself committed.
 
1010
    """
 
1011
    # TODO: Run hooks on tree to-be-committed, and after commit.
 
1012
 
 
1013
    # TODO: Strict commit that fails if there are unknown or deleted files.
 
1014
    # TODO: Give better message for -s, --summary, used by tla people
 
1015
 
 
1016
    # XXX: verbose currently does nothing
 
1017
 
 
1018
    takes_args = ['selected*']
 
1019
    takes_options = ['message', 'verbose', 
 
1020
                     Option('unchanged',
 
1021
                            help='commit even if nothing has changed'),
 
1022
                     Option('file', type=str, 
 
1023
                            argname='msgfile',
 
1024
                            help='file containing commit message'),
 
1025
                     ]
 
1026
    aliases = ['ci', 'checkin']
 
1027
 
 
1028
    def run(self, message=None, file=None, verbose=True, selected_list=None,
 
1029
            unchanged=False):
 
1030
        from bzrlib.errors import PointlessCommit, ConflictsInTree
 
1031
        from bzrlib.msgeditor import edit_commit_message
 
1032
        from bzrlib.status import show_status
 
1033
        from cStringIO import StringIO
 
1034
 
 
1035
        b = Branch.open_containing('.')[0]
 
1036
        tree = WorkingTree(b.base, b)
 
1037
        if selected_list:
 
1038
            selected_list = [tree.relpath(s) for s in selected_list]
 
1039
        if message is None and not file:
 
1040
            catcher = StringIO()
 
1041
            show_status(b, specific_files=selected_list,
 
1042
                        to_file=catcher)
 
1043
            message = edit_commit_message(catcher.getvalue())
 
1044
 
 
1045
            if message is None:
 
1046
                raise BzrCommandError("please specify a commit message"
 
1047
                                      " with either --message or --file")
 
1048
        elif message and file:
 
1049
            raise BzrCommandError("please specify either --message or --file")
 
1050
        
 
1051
        if file:
 
1052
            import codecs
 
1053
            message = codecs.open(file, 'rt', bzrlib.user_encoding).read()
 
1054
 
 
1055
        if message == "":
 
1056
                raise BzrCommandError("empty commit message specified")
 
1057
            
 
1058
        try:
 
1059
            b.commit(message,
 
1060
                     specific_files=selected_list,
 
1061
                     allow_pointless=unchanged)
 
1062
        except PointlessCommit:
 
1063
            # FIXME: This should really happen before the file is read in;
 
1064
            # perhaps prepare the commit; get the message; then actually commit
 
1065
            raise BzrCommandError("no changes to commit",
 
1066
                                  ["use --unchanged to commit anyhow"])
 
1067
        except ConflictsInTree:
 
1068
            raise BzrCommandError("Conflicts detected in working tree.  "
 
1069
                'Use "bzr conflicts" to list, "bzr resolve FILE" to resolve.')
 
1070
 
 
1071
 
 
1072
class cmd_check(Command):
 
1073
    """Validate consistency of branch history.
 
1074
 
 
1075
    This command checks various invariants about the branch storage to
 
1076
    detect data corruption or bzr bugs.
 
1077
    """
 
1078
    takes_args = ['dir?']
 
1079
    takes_options = ['verbose']
 
1080
 
 
1081
    def run(self, dir='.', verbose=False):
 
1082
        from bzrlib.check import check
 
1083
        check(Branch.open_containing(dir)[0], verbose)
 
1084
 
 
1085
 
 
1086
class cmd_scan_cache(Command):
 
1087
    hidden = True
 
1088
    def run(self):
 
1089
        from bzrlib.hashcache import HashCache
 
1090
 
 
1091
        c = HashCache('.')
 
1092
        c.read()
 
1093
        c.scan()
 
1094
            
 
1095
        print '%6d stats' % c.stat_count
 
1096
        print '%6d in hashcache' % len(c._cache)
 
1097
        print '%6d files removed from cache' % c.removed_count
 
1098
        print '%6d hashes updated' % c.update_count
 
1099
        print '%6d files changed too recently to cache' % c.danger_count
 
1100
 
 
1101
        if c.needs_write:
 
1102
            c.write()
 
1103
            
 
1104
 
 
1105
 
 
1106
class cmd_upgrade(Command):
 
1107
    """Upgrade branch storage to current format.
 
1108
 
 
1109
    The check command or bzr developers may sometimes advise you to run
 
1110
    this command.
 
1111
 
 
1112
    This version of this command upgrades from the full-text storage
 
1113
    used by bzr 0.0.8 and earlier to the weave format (v5).
 
1114
    """
 
1115
    takes_args = ['dir?']
 
1116
 
 
1117
    def run(self, dir='.'):
 
1118
        from bzrlib.upgrade import upgrade
 
1119
        upgrade(dir)
 
1120
 
 
1121
 
 
1122
class cmd_whoami(Command):
 
1123
    """Show bzr user id."""
 
1124
    takes_options = ['email']
 
1125
    
 
1126
    @display_command
 
1127
    def run(self, email=False):
 
1128
        try:
 
1129
            b = bzrlib.branch.Branch.open_containing('.')[0]
 
1130
            config = bzrlib.config.BranchConfig(b)
 
1131
        except NotBranchError:
 
1132
            config = bzrlib.config.GlobalConfig()
 
1133
        
 
1134
        if email:
 
1135
            print config.user_email()
 
1136
        else:
 
1137
            print config.username()
 
1138
 
 
1139
 
 
1140
class cmd_selftest(Command):
 
1141
    """Run internal test suite.
 
1142
    
 
1143
    This creates temporary test directories in the working directory,
 
1144
    but not existing data is affected.  These directories are deleted
 
1145
    if the tests pass, or left behind to help in debugging if they
 
1146
    fail.
 
1147
    
 
1148
    If arguments are given, they are regular expressions that say
 
1149
    which tests should run.
 
1150
    """
 
1151
    # TODO: --list should give a list of all available tests
 
1152
    hidden = True
 
1153
    takes_args = ['testspecs*']
 
1154
    takes_options = ['verbose', 
 
1155
                     Option('one', help='stop when one test fails'),
 
1156
                    ]
 
1157
 
 
1158
    def run(self, testspecs_list=None, verbose=False, one=False):
 
1159
        import bzrlib.ui
 
1160
        from bzrlib.selftest import selftest
 
1161
        # we don't want progress meters from the tests to go to the
 
1162
        # real output; and we don't want log messages cluttering up
 
1163
        # the real logs.
 
1164
        save_ui = bzrlib.ui.ui_factory
 
1165
        bzrlib.trace.info('running tests...')
 
1166
        try:
 
1167
            bzrlib.ui.ui_factory = bzrlib.ui.SilentUIFactory()
 
1168
            if testspecs_list is not None:
 
1169
                pattern = '|'.join(testspecs_list)
 
1170
            else:
 
1171
                pattern = ".*"
 
1172
            result = selftest(verbose=verbose, 
 
1173
                              pattern=pattern,
 
1174
                              stop_on_failure=one)
 
1175
            if result:
 
1176
                bzrlib.trace.info('tests passed')
 
1177
            else:
 
1178
                bzrlib.trace.info('tests failed')
 
1179
            return int(not result)
 
1180
        finally:
 
1181
            bzrlib.ui.ui_factory = save_ui
 
1182
 
 
1183
 
 
1184
def show_version():
 
1185
    print "bzr (bazaar-ng) %s" % bzrlib.__version__
 
1186
    # is bzrlib itself in a branch?
 
1187
    bzrrev = bzrlib.get_bzr_revision()
 
1188
    if bzrrev:
 
1189
        print "  (bzr checkout, revision %d {%s})" % bzrrev
 
1190
    print bzrlib.__copyright__
 
1191
    print "http://bazaar-ng.org/"
 
1192
    print
 
1193
    print "bzr comes with ABSOLUTELY NO WARRANTY.  bzr is free software, and"
 
1194
    print "you may use, modify and redistribute it under the terms of the GNU"
 
1195
    print "General Public License version 2 or later."
 
1196
 
 
1197
 
 
1198
class cmd_version(Command):
 
1199
    """Show version of bzr."""
 
1200
    @display_command
 
1201
    def run(self):
 
1202
        show_version()
 
1203
 
 
1204
class cmd_rocks(Command):
 
1205
    """Statement of optimism."""
 
1206
    hidden = True
 
1207
    @display_command
 
1208
    def run(self):
 
1209
        print "it sure does!"
 
1210
 
 
1211
 
 
1212
class cmd_find_merge_base(Command):
 
1213
    """Find and print a base revision for merging two branches.
 
1214
    """
 
1215
    # TODO: Options to specify revisions on either side, as if
 
1216
    #       merging only part of the history.
 
1217
    takes_args = ['branch', 'other']
 
1218
    hidden = True
 
1219
    
 
1220
    @display_command
 
1221
    def run(self, branch, other):
 
1222
        from bzrlib.revision import common_ancestor, MultipleRevisionSources
 
1223
        
 
1224
        branch1 = Branch.open_containing(branch)[0]
 
1225
        branch2 = Branch.open_containing(other)[0]
 
1226
 
 
1227
        history_1 = branch1.revision_history()
 
1228
        history_2 = branch2.revision_history()
 
1229
 
 
1230
        last1 = branch1.last_revision()
 
1231
        last2 = branch2.last_revision()
 
1232
 
 
1233
        source = MultipleRevisionSources(branch1, branch2)
 
1234
        
 
1235
        base_rev_id = common_ancestor(last1, last2, source)
 
1236
 
 
1237
        print 'merge base is revision %s' % base_rev_id
 
1238
        
 
1239
        return
 
1240
 
 
1241
        if base_revno is None:
 
1242
            raise bzrlib.errors.UnrelatedBranches()
 
1243
 
 
1244
        print ' r%-6d in %s' % (base_revno, branch)
 
1245
 
 
1246
        other_revno = branch2.revision_id_to_revno(base_revid)
 
1247
        
 
1248
        print ' r%-6d in %s' % (other_revno, other)
 
1249
 
 
1250
 
 
1251
 
 
1252
class cmd_merge(Command):
 
1253
    """Perform a three-way merge.
 
1254
    
 
1255
    The branch is the branch you will merge from.  By default, it will
 
1256
    merge the latest revision.  If you specify a revision, that
 
1257
    revision will be merged.  If you specify two revisions, the first
 
1258
    will be used as a BASE, and the second one as OTHER.  Revision
 
1259
    numbers are always relative to the specified branch.
 
1260
 
 
1261
    By default bzr will try to merge in all new work from the other
 
1262
    branch, automatically determining an appropriate base.  If this
 
1263
    fails, you may need to give an explicit base.
 
1264
    
 
1265
    Examples:
 
1266
 
 
1267
    To merge the latest revision from bzr.dev
 
1268
    bzr merge ../bzr.dev
 
1269
 
 
1270
    To merge changes up to and including revision 82 from bzr.dev
 
1271
    bzr merge -r 82 ../bzr.dev
 
1272
 
 
1273
    To merge the changes introduced by 82, without previous changes:
 
1274
    bzr merge -r 81..82 ../bzr.dev
 
1275
    
 
1276
    merge refuses to run if there are any uncommitted changes, unless
 
1277
    --force is given.
 
1278
    """
 
1279
    takes_args = ['branch?']
 
1280
    takes_options = ['revision', 'force', 'merge-type']
 
1281
 
 
1282
    def run(self, branch=None, revision=None, force=False, 
 
1283
            merge_type=None):
 
1284
        from bzrlib.merge import merge
 
1285
        from bzrlib.merge_core import ApplyMerge3
 
1286
        if merge_type is None:
 
1287
            merge_type = ApplyMerge3
 
1288
        if branch is None:
 
1289
            branch = Branch.open_containing('.')[0].get_parent()
 
1290
            if branch is None:
 
1291
                raise BzrCommandError("No merge location known or specified.")
 
1292
            else:
 
1293
                print "Using saved location: %s" % branch 
 
1294
        if revision is None or len(revision) < 1:
 
1295
            base = [None, None]
 
1296
            other = [branch, -1]
 
1297
        else:
 
1298
            if len(revision) == 1:
 
1299
                base = [None, None]
 
1300
                other_branch = Branch.open_containing(branch)[0]
 
1301
                revno = revision[0].in_history(other_branch).revno
 
1302
                other = [branch, revno]
 
1303
            else:
 
1304
                assert len(revision) == 2
 
1305
                if None in revision:
 
1306
                    raise BzrCommandError(
 
1307
                        "Merge doesn't permit that revision specifier.")
 
1308
                b = Branch.open_containing(branch)[0]
 
1309
 
 
1310
                base = [branch, revision[0].in_history(b).revno]
 
1311
                other = [branch, revision[1].in_history(b).revno]
 
1312
 
 
1313
        try:
 
1314
            merge(other, base, check_clean=(not force), merge_type=merge_type)
 
1315
        except bzrlib.errors.AmbiguousBase, e:
 
1316
            m = ("sorry, bzr can't determine the right merge base yet\n"
 
1317
                 "candidates are:\n  "
 
1318
                 + "\n  ".join(e.bases)
 
1319
                 + "\n"
 
1320
                 "please specify an explicit base with -r,\n"
 
1321
                 "and (if you want) report this to the bzr developers\n")
 
1322
            log_error(m)
 
1323
 
 
1324
 
 
1325
class cmd_revert(Command):
 
1326
    """Reverse all changes since the last commit.
 
1327
 
 
1328
    Only versioned files are affected.  Specify filenames to revert only 
 
1329
    those files.  By default, any files that are changed will be backed up
 
1330
    first.  Backup files have a '~' appended to their name.
 
1331
    """
 
1332
    takes_options = ['revision', 'no-backup']
 
1333
    takes_args = ['file*']
 
1334
    aliases = ['merge-revert']
 
1335
 
 
1336
    def run(self, revision=None, no_backup=False, file_list=None):
 
1337
        from bzrlib.merge import merge
 
1338
        from bzrlib.commands import parse_spec
 
1339
 
 
1340
        if file_list is not None:
 
1341
            if len(file_list) == 0:
 
1342
                raise BzrCommandError("No files specified")
 
1343
        if revision is None:
 
1344
            revno = -1
 
1345
        elif len(revision) != 1:
 
1346
            raise BzrCommandError('bzr revert --revision takes exactly 1 argument')
 
1347
        else:
 
1348
            b = Branch.open_containing('.')[0]
 
1349
            revno = revision[0].in_history(b).revno
 
1350
        merge(('.', revno), parse_spec('.'),
 
1351
              check_clean=False,
 
1352
              ignore_zero=True,
 
1353
              backup_files=not no_backup,
 
1354
              file_list=file_list)
 
1355
        if not file_list:
 
1356
            Branch.open_containing('.')[0].set_pending_merges([])
 
1357
 
 
1358
 
 
1359
class cmd_assert_fail(Command):
 
1360
    """Test reporting of assertion failures"""
 
1361
    hidden = True
 
1362
    def run(self):
 
1363
        assert False, "always fails"
 
1364
 
 
1365
 
 
1366
class cmd_help(Command):
 
1367
    """Show help on a command or other topic.
 
1368
 
 
1369
    For a list of all available commands, say 'bzr help commands'."""
 
1370
    takes_options = ['long']
 
1371
    takes_args = ['topic?']
 
1372
    aliases = ['?']
 
1373
    
 
1374
    @display_command
 
1375
    def run(self, topic=None, long=False):
 
1376
        import help
 
1377
        if topic is None and long:
 
1378
            topic = "commands"
 
1379
        help.help(topic)
 
1380
 
 
1381
 
 
1382
class cmd_shell_complete(Command):
 
1383
    """Show appropriate completions for context.
 
1384
 
 
1385
    For a list of all available commands, say 'bzr shell-complete'."""
 
1386
    takes_args = ['context?']
 
1387
    aliases = ['s-c']
 
1388
    hidden = True
 
1389
    
 
1390
    @display_command
 
1391
    def run(self, context=None):
 
1392
        import shellcomplete
 
1393
        shellcomplete.shellcomplete(context)
 
1394
 
 
1395
 
 
1396
class cmd_fetch(Command):
 
1397
    """Copy in history from another branch but don't merge it.
 
1398
 
 
1399
    This is an internal method used for pull and merge."""
 
1400
    hidden = True
 
1401
    takes_args = ['from_branch', 'to_branch']
 
1402
    def run(self, from_branch, to_branch):
 
1403
        from bzrlib.fetch import Fetcher
 
1404
        from bzrlib.branch import Branch
 
1405
        from_b = Branch(from_branch)
 
1406
        to_b = Branch(to_branch)
 
1407
        Fetcher(to_b, from_b)
 
1408
        
 
1409
 
 
1410
 
 
1411
class cmd_missing(Command):
 
1412
    """What is missing in this branch relative to other branch.
 
1413
    """
 
1414
    # TODO: rewrite this in terms of ancestry so that it shows only
 
1415
    # unmerged things
 
1416
    
 
1417
    takes_args = ['remote?']
 
1418
    aliases = ['mis', 'miss']
 
1419
    # We don't have to add quiet to the list, because 
 
1420
    # unknown options are parsed as booleans
 
1421
    takes_options = ['verbose', 'quiet']
 
1422
 
 
1423
    @display_command
 
1424
    def run(self, remote=None, verbose=False, quiet=False):
 
1425
        from bzrlib.errors import BzrCommandError
 
1426
        from bzrlib.missing import show_missing
 
1427
 
 
1428
        if verbose and quiet:
 
1429
            raise BzrCommandError('Cannot pass both quiet and verbose')
 
1430
 
 
1431
        b = Branch.open_containing('.')[0]
 
1432
        parent = b.get_parent()
 
1433
        if remote is None:
 
1434
            if parent is None:
 
1435
                raise BzrCommandError("No missing location known or specified.")
 
1436
            else:
 
1437
                if not quiet:
 
1438
                    print "Using last location: %s" % parent
 
1439
                remote = parent
 
1440
        elif parent is None:
 
1441
            # We only update parent if it did not exist, missing
 
1442
            # should not change the parent
 
1443
            b.set_parent(remote)
 
1444
        br_remote = Branch.open_containing(remote)[0]
 
1445
        return show_missing(b, br_remote, verbose=verbose, quiet=quiet)
 
1446
 
 
1447
 
 
1448
class cmd_plugins(Command):
 
1449
    """List plugins"""
 
1450
    hidden = True
 
1451
    @display_command
 
1452
    def run(self):
 
1453
        import bzrlib.plugin
 
1454
        from inspect import getdoc
 
1455
        for plugin in bzrlib.plugin.all_plugins:
 
1456
            if hasattr(plugin, '__path__'):
 
1457
                print plugin.__path__[0]
 
1458
            elif hasattr(plugin, '__file__'):
 
1459
                print plugin.__file__
 
1460
            else:
 
1461
                print `plugin`
 
1462
                
 
1463
            d = getdoc(plugin)
 
1464
            if d:
 
1465
                print '\t', d.split('\n')[0]
 
1466
 
 
1467
 
 
1468
class cmd_testament(Command):
 
1469
    """Show testament (signing-form) of a revision."""
 
1470
    takes_options = ['revision', 'long']
 
1471
    takes_args = ['branch?']
 
1472
    @display_command
 
1473
    def run(self, branch='.', revision=None, long=False):
 
1474
        from bzrlib.testament import Testament
 
1475
        b = Branch.open_containing(branch)[0]
 
1476
        b.lock_read()
 
1477
        try:
 
1478
            if revision is None:
 
1479
                rev_id = b.last_revision()
 
1480
            else:
 
1481
                rev_id = revision[0].in_history(b).rev_id
 
1482
            t = Testament.from_revision(b, rev_id)
 
1483
            if long:
 
1484
                sys.stdout.writelines(t.as_text_lines())
 
1485
            else:
 
1486
                sys.stdout.write(t.as_short_text())
 
1487
        finally:
 
1488
            b.unlock()
 
1489
 
 
1490
 
 
1491
class cmd_annotate(Command):
 
1492
    """Show the origin of each line in a file.
 
1493
 
 
1494
    This prints out the given file with an annotation on the left side
 
1495
    indicating which revision, author and date introduced the change.
 
1496
 
 
1497
    If the origin is the same for a run of consecutive lines, it is 
 
1498
    shown only at the top, unless the --all option is given.
 
1499
    """
 
1500
    # TODO: annotate directories; showing when each file was last changed
 
1501
    # TODO: annotate a previous version of a file
 
1502
    # TODO: if the working copy is modified, show annotations on that 
 
1503
    #       with new uncommitted lines marked
 
1504
    aliases = ['blame', 'praise']
 
1505
    takes_args = ['filename']
 
1506
    takes_options = [Option('all', help='show annotations on all lines'),
 
1507
                     Option('long', help='show date in annotations'),
 
1508
                     ]
 
1509
 
 
1510
    @display_command
 
1511
    def run(self, filename, all=False, long=False):
 
1512
        from bzrlib.annotate import annotate_file
 
1513
        b, relpath = Branch.open_containing(filename)
 
1514
        b.lock_read()
 
1515
        try:
 
1516
            tree = WorkingTree(b.base, b)
 
1517
            tree = b.revision_tree(b.last_revision())
 
1518
            file_id = tree.inventory.path2id(relpath)
 
1519
            file_version = tree.inventory[file_id].revision
 
1520
            annotate_file(b, file_version, file_id, long, all, sys.stdout)
 
1521
        finally:
 
1522
            b.unlock()
 
1523
 
 
1524
 
 
1525
class cmd_re_sign(Command):
 
1526
    """Create a digital signature for an existing revision."""
 
1527
    # TODO be able to replace existing ones.
 
1528
 
 
1529
    hidden = True # is this right ?
 
1530
    takes_args = ['revision_id?']
 
1531
    takes_options = ['revision']
 
1532
    
 
1533
    def run(self, revision_id=None, revision=None):
 
1534
        import bzrlib.config as config
 
1535
        import bzrlib.gpg as gpg
 
1536
        if revision_id is not None and revision is not None:
 
1537
            raise BzrCommandError('You can only supply one of revision_id or --revision')
 
1538
        if revision_id is None and revision is None:
 
1539
            raise BzrCommandError('You must supply either --revision or a revision_id')
 
1540
        b = Branch.open_containing('.')[0]
 
1541
        gpg_strategy = gpg.GPGStrategy(config.BranchConfig(b))
 
1542
        if revision_id is not None:
 
1543
            b.sign_revision(revision_id, gpg_strategy)
 
1544
        elif revision is not None:
 
1545
            for rev in revision:
 
1546
                if rev is None:
 
1547
                    raise BzrCommandError('You cannot specify a NULL revision.')
 
1548
                revno, rev_id = rev.in_history(b)
 
1549
                b.sign_revision(rev_id, gpg_strategy)
 
1550
 
 
1551
 
 
1552
# these get imported and then picked up by the scan for cmd_*
 
1553
# TODO: Some more consistent way to split command definitions across files;
 
1554
# we do need to load at least some information about them to know of 
 
1555
# aliases.
 
1556
from bzrlib.conflicts import cmd_resolve, cmd_conflicts