/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-22 23:23:56 UTC
  • mto: (1185.25.1)
  • mto: This revision was merged to the branch mainline in revision 1488.
  • Revision ID: aaron.bentley@utoronto.ca-20051022232356-861a8b02872b132f
Added mode preservation to AtomicFile

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