~bzr-pqm/bzr/bzr.dev

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