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