~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
1225 by Martin Pool
- branch now tracks ancestry - all merged revisions
487
class cmd_ancestry(Command):
488
    """List all revisions merged into this branch."""
489
    hidden = True
490
    def run(self):
491
        b = find_branch('.')
1241 by Martin Pool
- rename last_patch to last_revision
492
        for revision_id in b.get_ancestry(b.last_revision()):
1225 by Martin Pool
- branch now tracks ancestry - all merged revisions
493
            print revision_id
494
495
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
496
class cmd_directories(Command):
497
    """Display list of versioned directories in this branch."""
498
    def run(self):
499
        for name, ie in find_branch('.').read_working_inventory().directories():
500
            if name == '':
501
                print '.'
502
            else:
503
                print name
504
505
506
class cmd_init(Command):
507
    """Make a directory into a versioned branch.
508
509
    Use this to create an empty branch, or before importing an
510
    existing project.
511
512
    Recipe for importing a tree of files:
513
        cd ~/project
514
        bzr init
515
        bzr add -v .
516
        bzr status
517
        bzr commit -m 'imported project'
518
    """
519
    def run(self):
520
        from bzrlib.branch import Branch
521
        Branch('.', init=True)
522
523
524
class cmd_diff(Command):
525
    """Show differences in working tree.
526
    
527
    If files are listed, only the changes in those files are listed.
528
    Otherwise, all changes for the tree are listed.
529
530
    TODO: Allow diff across branches.
531
532
    TODO: Option to use external diff command; could be GNU diff, wdiff,
533
          or a graphical diff.
534
535
    TODO: Python difflib is not exactly the same as unidiff; should
536
          either fix it up or prefer to use an external diff.
537
538
    TODO: If a directory is given, diff everything under that.
539
540
    TODO: Selected-file diff is inefficient and doesn't show you
541
          deleted files.
542
543
    TODO: This probably handles non-Unix newlines poorly.
544
545
    examples:
546
        bzr diff
547
        bzr diff -r1
548
        bzr diff -r1:2
549
    """
550
    
551
    takes_args = ['file*']
552
    takes_options = ['revision', 'diff-options']
553
    aliases = ['di', 'dif']
554
555
    def run(self, revision=None, file_list=None, diff_options=None):
556
        from bzrlib.diff import show_diff
557
558
        if file_list:
559
            b = find_branch(file_list[0])
560
            file_list = [b.relpath(f) for f in file_list]
561
            if file_list == ['']:
562
                # just pointing to top-of-tree
563
                file_list = None
564
        else:
565
            b = find_branch('.')
566
567
        if revision is not None:
568
            if len(revision) == 1:
569
                show_diff(b, revision[0], specific_files=file_list,
570
                          external_diff_options=diff_options)
571
            elif len(revision) == 2:
572
                show_diff(b, revision[0], specific_files=file_list,
573
                          external_diff_options=diff_options,
574
                          revision2=revision[1])
575
            else:
576
                raise BzrCommandError('bzr diff --revision takes exactly one or two revision identifiers')
577
        else:
578
            show_diff(b, None, specific_files=file_list,
579
                      external_diff_options=diff_options)
580
581
        
582
583
584
class cmd_deleted(Command):
585
    """List files deleted in the working tree.
586
587
    TODO: Show files deleted since a previous revision, or between two revisions.
588
    """
589
    def run(self, show_ids=False):
590
        b = find_branch('.')
591
        old = b.basis_tree()
592
        new = b.working_tree()
593
594
        ## TODO: Much more efficient way to do this: read in new
595
        ## directories with readdir, rather than stating each one.  Same
596
        ## level of effort but possibly much less IO.  (Or possibly not,
597
        ## if the directories are very large...)
598
599
        for path, ie in old.inventory.iter_entries():
600
            if not new.has_id(ie.file_id):
601
                if show_ids:
602
                    print '%-50s %s' % (path, ie.file_id)
603
                else:
604
                    print path
605
606
607
class cmd_modified(Command):
608
    """List files modified in working tree."""
609
    hidden = True
610
    def run(self):
611
        from bzrlib.delta import compare_trees
612
613
        b = find_branch('.')
614
        td = compare_trees(b.basis_tree(), b.working_tree())
615
616
        for path, id, kind in td.modified:
617
            print path
618
619
620
621
class cmd_added(Command):
622
    """List files added in working tree."""
623
    hidden = True
624
    def run(self):
625
        b = find_branch('.')
626
        wt = b.working_tree()
627
        basis_inv = b.basis_tree().inventory
628
        inv = wt.inventory
629
        for file_id in inv:
630
            if file_id in basis_inv:
631
                continue
632
            path = inv.id2path(file_id)
633
            if not os.access(b.abspath(path), os.F_OK):
634
                continue
635
            print path
636
                
637
        
638
639
class cmd_root(Command):
640
    """Show the tree root directory.
641
642
    The root is the nearest enclosing directory with a .bzr control
643
    directory."""
644
    takes_args = ['filename?']
645
    def run(self, filename=None):
646
        """Print the branch root."""
647
        b = find_branch(filename)
648
        print getattr(b, 'base', None) or getattr(b, 'baseurl')
649
650
651
class cmd_log(Command):
652
    """Show log of this branch.
653
654
    To request a range of logs, you can use the command -r begin:end
655
    -r revision requests a specific revision, -r :end or -r begin: are
656
    also valid.
657
658
    --message allows you to give a regular expression, which will be evaluated
659
    so that only matching entries will be displayed.
660
661
    TODO: Make --revision support uuid: and hash: [future tag:] notation.
662
  
663
    """
664
665
    takes_args = ['filename?']
666
    takes_options = ['forward', 'timezone', 'verbose', 'show-ids', 'revision',
667
                     'long', 'message', 'short',]
668
    
669
    def run(self, filename=None, timezone='original',
670
            verbose=False,
671
            show_ids=False,
672
            forward=False,
673
            revision=None,
674
            message=None,
675
            long=False,
676
            short=False):
677
        from bzrlib.log import log_formatter, show_log
678
        import codecs
679
680
        direction = (forward and 'forward') or 'reverse'
681
        
682
        if filename:
683
            b = find_branch(filename)
684
            fp = b.relpath(filename)
685
            if fp:
686
                file_id = b.read_working_inventory().path2id(fp)
687
            else:
688
                file_id = None  # points to branch root
689
        else:
690
            b = find_branch('.')
691
            file_id = None
692
693
        if revision is None:
694
            rev1 = None
695
            rev2 = None
696
        elif len(revision) == 1:
697
            rev1 = rev2 = b.get_revision_info(revision[0])[0]
698
        elif len(revision) == 2:
699
            rev1 = b.get_revision_info(revision[0])[0]
700
            rev2 = b.get_revision_info(revision[1])[0]
701
        else:
702
            raise BzrCommandError('bzr log --revision takes one or two values.')
703
704
        if rev1 == 0:
705
            rev1 = None
706
        if rev2 == 0:
707
            rev2 = None
708
709
        mutter('encoding log as %r' % bzrlib.user_encoding)
710
711
        # use 'replace' so that we don't abort if trying to write out
712
        # in e.g. the default C locale.
713
        outf = codecs.getwriter(bzrlib.user_encoding)(sys.stdout, errors='replace')
714
715
        if not short:
716
            log_format = 'long'
717
        else:
718
            log_format = 'short'
719
        lf = log_formatter(log_format,
720
                           show_ids=show_ids,
721
                           to_file=outf,
722
                           show_timezone=timezone)
723
724
        show_log(b,
725
                 lf,
726
                 file_id,
727
                 verbose=verbose,
728
                 direction=direction,
729
                 start_revision=rev1,
730
                 end_revision=rev2,
731
                 search=message)
732
733
734
735
class cmd_touching_revisions(Command):
736
    """Return revision-ids which affected a particular file.
737
738
    A more user-friendly interface is "bzr log FILE"."""
739
    hidden = True
740
    takes_args = ["filename"]
741
    def run(self, filename):
742
        b = find_branch(filename)
743
        inv = b.read_working_inventory()
744
        file_id = inv.path2id(b.relpath(filename))
745
        for revno, revision_id, what in bzrlib.log.find_touching_revisions(b, file_id):
746
            print "%6d %s" % (revno, what)
747
748
749
class cmd_ls(Command):
750
    """List files in a tree.
751
752
    TODO: Take a revision or remote path and list that tree instead.
753
    """
754
    hidden = True
755
    def run(self, revision=None, verbose=False):
756
        b = find_branch('.')
757
        if revision == None:
758
            tree = b.working_tree()
759
        else:
760
            tree = b.revision_tree(b.lookup_revision(revision))
761
762
        for fp, fc, kind, fid in tree.list_files():
763
            if verbose:
764
                if kind == 'directory':
765
                    kindch = '/'
766
                elif kind == 'file':
767
                    kindch = ''
768
                else:
769
                    kindch = '???'
770
771
                print '%-8s %s%s' % (fc, fp, kindch)
772
            else:
773
                print fp
774
775
776
777
class cmd_unknowns(Command):
778
    """List unknown files."""
779
    def run(self):
780
        from bzrlib.osutils import quotefn
781
        for f in find_branch('.').unknowns():
782
            print quotefn(f)
783
784
785
786
class cmd_ignore(Command):
787
    """Ignore a command or pattern.
788
789
    To remove patterns from the ignore list, edit the .bzrignore file.
790
791
    If the pattern contains a slash, it is compared to the whole path
792
    from the branch root.  Otherwise, it is comapred to only the last
793
    component of the path.
794
795
    Ignore patterns are case-insensitive on case-insensitive systems.
796
797
    Note: wildcards must be quoted from the shell on Unix.
798
799
    examples:
800
        bzr ignore ./Makefile
801
        bzr ignore '*.class'
802
    """
803
    takes_args = ['name_pattern']
804
    
805
    def run(self, name_pattern):
806
        from bzrlib.atomicfile import AtomicFile
807
        import os.path
808
809
        b = find_branch('.')
810
        ifn = b.abspath('.bzrignore')
811
812
        if os.path.exists(ifn):
813
            f = open(ifn, 'rt')
814
            try:
815
                igns = f.read().decode('utf-8')
816
            finally:
817
                f.close()
818
        else:
819
            igns = ''
820
821
        # TODO: If the file already uses crlf-style termination, maybe
822
        # we should use that for the newly added lines?
823
824
        if igns and igns[-1] != '\n':
825
            igns += '\n'
826
        igns += name_pattern + '\n'
827
828
        try:
829
            f = AtomicFile(ifn, 'wt')
830
            f.write(igns.encode('utf-8'))
831
            f.commit()
832
        finally:
833
            f.close()
834
835
        inv = b.working_tree().inventory
836
        if inv.path2id('.bzrignore'):
837
            mutter('.bzrignore is already versioned')
838
        else:
839
            mutter('need to make new .bzrignore file versioned')
840
            b.add(['.bzrignore'])
841
842
843
844
class cmd_ignored(Command):
845
    """List ignored files and the patterns that matched them.
846
847
    See also: bzr ignore"""
848
    def run(self):
849
        tree = find_branch('.').working_tree()
850
        for path, file_class, kind, file_id in tree.list_files():
851
            if file_class != 'I':
852
                continue
853
            ## XXX: Slightly inefficient since this was already calculated
854
            pat = tree.is_ignored(path)
855
            print '%-50s %s' % (path, pat)
856
857
858
class cmd_lookup_revision(Command):
859
    """Lookup the revision-id from a revision-number
860
861
    example:
862
        bzr lookup-revision 33
863
    """
864
    hidden = True
865
    takes_args = ['revno']
866
    
867
    def run(self, revno):
868
        try:
869
            revno = int(revno)
870
        except ValueError:
871
            raise BzrCommandError("not a valid revision-number: %r" % revno)
872
873
        print find_branch('.').lookup_revision(revno)
874
875
876
class cmd_export(Command):
877
    """Export past revision to destination directory.
878
879
    If no revision is specified this exports the last committed revision.
880
881
    Format may be an "exporter" name, such as tar, tgz, tbz2.  If none is
882
    given, try to find the format with the extension. If no extension
883
    is found exports to a directory (equivalent to --format=dir).
884
885
    Root may be the top directory for tar, tgz and tbz2 formats. If none
886
    is given, the top directory will be the root name of the file."""
887
    # TODO: list known exporters
888
    takes_args = ['dest']
889
    takes_options = ['revision', 'format', 'root']
890
    def run(self, dest, revision=None, format=None, root=None):
891
        import os.path
892
        b = find_branch('.')
893
        if revision is None:
1241 by Martin Pool
- rename last_patch to last_revision
894
            rev_id = b.last_revision()
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
895
        else:
896
            if len(revision) != 1:
897
                raise BzrError('bzr export --revision takes exactly 1 argument')
898
            revno, rev_id = b.get_revision_info(revision[0])
899
        t = b.revision_tree(rev_id)
900
        root, ext = os.path.splitext(dest)
901
        if not format:
902
            if ext in (".tar",):
903
                format = "tar"
904
            elif ext in (".gz", ".tgz"):
905
                format = "tgz"
906
            elif ext in (".bz2", ".tbz2"):
907
                format = "tbz2"
908
            else:
909
                format = "dir"
910
        t.export(dest, format, root)
911
912
913
class cmd_cat(Command):
914
    """Write a file's text from a previous revision."""
915
916
    takes_options = ['revision']
917
    takes_args = ['filename']
918
919
    def run(self, filename, revision=None):
920
        if revision == None:
921
            raise BzrCommandError("bzr cat requires a revision number")
922
        elif len(revision) != 1:
923
            raise BzrCommandError("bzr cat --revision takes exactly one number")
924
        b = find_branch('.')
925
        b.print_file(b.relpath(filename), revision[0])
926
927
928
class cmd_local_time_offset(Command):
929
    """Show the offset in seconds from GMT to local time."""
930
    hidden = True    
931
    def run(self):
932
        print bzrlib.osutils.local_time_offset()
933
934
935
936
class cmd_commit(Command):
937
    """Commit changes into a new revision.
938
    
939
    If no arguments are given, the entire tree is committed.
940
941
    If selected files are specified, only changes to those files are
942
    committed.  If a directory is specified then the directory and everything 
943
    within it is committed.
944
945
    A selected-file commit may fail in some cases where the committed
946
    tree would be invalid, such as trying to commit a file in a
947
    newly-added directory that is not itself committed.
948
949
    TODO: Run hooks on tree to-be-committed, and after commit.
950
951
    TODO: Strict commit that fails if there are unknown or deleted files.
952
    """
953
    takes_args = ['selected*']
954
    takes_options = ['message', 'file', 'verbose', 'unchanged']
955
    aliases = ['ci', 'checkin']
956
957
    # TODO: Give better message for -s, --summary, used by tla people
1189 by Martin Pool
- BROKEN: partial support for commit into weave
958
959
    # XXX: verbose currently does nothing
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
960
    
961
    def run(self, message=None, file=None, verbose=True, selected_list=None,
962
            unchanged=False):
963
        from bzrlib.errors import PointlessCommit
1167 by Martin Pool
- split commit message editor functions out into own file
964
        from bzrlib.msgeditor import edit_commit_message
1169 by Martin Pool
- clean up nasty code for inserting the status summary into commit template
965
        from bzrlib.status import show_status
966
        from cStringIO import StringIO
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
967
1169 by Martin Pool
- clean up nasty code for inserting the status summary into commit template
968
        b = find_branch('.')
969
        if selected_list:
970
            selected_list = [b.relpath(s) for s in selected_list]
971
            
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
972
        if not message and not file:
1169 by Martin Pool
- clean up nasty code for inserting the status summary into commit template
973
            catcher = StringIO()
974
            show_status(b, specific_files=selected_list,
975
                        to_file=catcher)
976
            message = edit_commit_message(catcher.getvalue())
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
977
            
978
            if message is None:
1169 by Martin Pool
- clean up nasty code for inserting the status summary into commit template
979
                raise BzrCommandError("please specify a commit message"
980
                                      " with either --message or --file")
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
981
        elif message and file:
982
            raise BzrCommandError("please specify either --message or --file")
983
        
984
        if file:
985
            import codecs
986
            message = codecs.open(file, 'rt', bzrlib.user_encoding).read()
987
988
        try:
1189 by Martin Pool
- BROKEN: partial support for commit into weave
989
            b.commit(message,
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
990
                     specific_files=selected_list,
991
                     allow_pointless=unchanged)
992
        except PointlessCommit:
993
            # FIXME: This should really happen before the file is read in;
994
            # perhaps prepare the commit; get the message; then actually commit
995
            raise BzrCommandError("no changes to commit",
996
                                  ["use --unchanged to commit anyhow"])
997
998
999
class cmd_check(Command):
1000
    """Validate consistency of branch history.
1001
1002
    This command checks various invariants about the branch storage to
1003
    detect data corruption or bzr bugs.
1004
1005
    If given the --update flag, it will update some optional fields
1006
    to help ensure data consistency.
1007
    """
1008
    takes_args = ['dir?']
1009
1010
    def run(self, dir='.'):
1011
        from bzrlib.check import check
1012
1013
        check(find_branch(dir))
1014
1015
1016
class cmd_scan_cache(Command):
1017
    hidden = True
1018
    def run(self):
1019
        from bzrlib.hashcache import HashCache
1020
1021
        c = HashCache('.')
1022
        c.read()
1023
        c.scan()
1024
            
1025
        print '%6d stats' % c.stat_count
1026
        print '%6d in hashcache' % len(c._cache)
1027
        print '%6d files removed from cache' % c.removed_count
1028
        print '%6d hashes updated' % c.update_count
1029
        print '%6d files changed too recently to cache' % c.danger_count
1030
1031
        if c.needs_write:
1032
            c.write()
1033
            
1034
1035
1036
class cmd_upgrade(Command):
1037
    """Upgrade branch storage to current format.
1038
1039
    The check command or bzr developers may sometimes advise you to run
1040
    this command.
1041
    """
1042
    takes_args = ['dir?']
1043
1044
    def run(self, dir='.'):
1045
        from bzrlib.upgrade import upgrade
1046
        upgrade(find_branch(dir))
1047
1048
1049
1050
class cmd_whoami(Command):
1051
    """Show bzr user id."""
1052
    takes_options = ['email']
1053
    
1054
    def run(self, email=False):
1055
        try:
1056
            b = bzrlib.branch.find_branch('.')
1057
        except:
1058
            b = None
1059
        
1060
        if email:
1061
            print bzrlib.osutils.user_email(b)
1062
        else:
1063
            print bzrlib.osutils.username(b)
1064
1065
1066
class cmd_selftest(Command):
1067
    """Run internal test suite"""
1068
    hidden = True
1069
    takes_options = ['verbose', 'pattern']
1070
    def run(self, verbose=False, pattern=".*"):
1071
        import bzrlib.ui
1072
        from bzrlib.selftest import selftest
1073
        # we don't want progress meters from the tests to go to the
1074
        # real output; and we don't want log messages cluttering up
1075
        # the real logs.
1076
        save_ui = bzrlib.ui.ui_factory
1077
        bzrlib.trace.info('running tests...')
1078
        try:
1079
            bzrlib.ui.ui_factory = bzrlib.ui.SilentUIFactory()
1080
            result = selftest(verbose=verbose, pattern=pattern)
1081
            if result:
1082
                bzrlib.trace.info('tests passed')
1083
            else:
1084
                bzrlib.trace.info('tests failed')
1085
            return int(not result)
1086
        finally:
1087
            bzrlib.ui.ui_factory = save_ui
1088
1089
1090
def show_version():
1091
    print "bzr (bazaar-ng) %s" % bzrlib.__version__
1092
    # is bzrlib itself in a branch?
1093
    bzrrev = bzrlib.get_bzr_revision()
1094
    if bzrrev:
1095
        print "  (bzr checkout, revision %d {%s})" % bzrrev
1096
    print bzrlib.__copyright__
1097
    print "http://bazaar-ng.org/"
1098
    print
1099
    print "bzr comes with ABSOLUTELY NO WARRANTY.  bzr is free software, and"
1100
    print "you may use, modify and redistribute it under the terms of the GNU"
1101
    print "General Public License version 2 or later."
1102
1103
1104
class cmd_version(Command):
1105
    """Show version of bzr."""
1106
    def run(self):
1107
        show_version()
1108
1109
class cmd_rocks(Command):
1110
    """Statement of optimism."""
1111
    hidden = True
1112
    def run(self):
1113
        print "it sure does!"
1114
1115
1116
class cmd_find_merge_base(Command):
1117
    """Find and print a base revision for merging two branches.
1118
1119
    TODO: Options to specify revisions on either side, as if
1120
          merging only part of the history.
1121
    """
1122
    takes_args = ['branch', 'other']
1123
    hidden = True
1124
    
1125
    def run(self, branch, other):
1155 by Martin Pool
- update find-merge-base to use new common_ancestor code
1126
        from bzrlib.revision import common_ancestor, MultipleRevisionSources
1127
        
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1128
        branch1 = find_branch(branch)
1129
        branch2 = find_branch(other)
1130
1155 by Martin Pool
- update find-merge-base to use new common_ancestor code
1131
        history_1 = branch1.revision_history()
1132
        history_2 = branch2.revision_history()
1133
1241 by Martin Pool
- rename last_patch to last_revision
1134
        last1 = branch1.last_revision()
1135
        last2 = branch2.last_revision()
1155 by Martin Pool
- update find-merge-base to use new common_ancestor code
1136
1137
        source = MultipleRevisionSources(branch1, branch2)
1138
        
1139
        base_rev_id = common_ancestor(last1, last2, source)
1140
1141
        print 'merge base is revision %s' % base_rev_id
1142
        
1143
        return
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1144
1145
        if base_revno is None:
1146
            raise bzrlib.errors.UnrelatedBranches()
1147
1148
        print ' r%-6d in %s' % (base_revno, branch)
1149
1150
        other_revno = branch2.revision_id_to_revno(base_revid)
1151
        
1152
        print ' r%-6d in %s' % (other_revno, other)
1153
1154
1155
1156
class cmd_merge(Command):
1157
    """Perform a three-way merge.
1158
    
1172 by Martin Pool
- better explanation when merge fails with AmbiguousBase
1159
    The branch is the branch you will merge from.  By default, it will
1160
    merge the latest revision.  If you specify a revision, that
1161
    revision will be merged.  If you specify two revisions, the first
1162
    will be used as a BASE, and the second one as OTHER.  Revision
1163
    numbers are always relative to the specified branch.
1164
1165
    By default bzr will try to merge in all new work from the other
1166
    branch, automatically determining an appropriate base.  If this
1167
    fails, you may need to give an explicit base.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1168
    
1169
    Examples:
1170
1171
    To merge the latest revision from bzr.dev
1172
    bzr merge ../bzr.dev
1173
1174
    To merge changes up to and including revision 82 from bzr.dev
1175
    bzr merge -r 82 ../bzr.dev
1176
1177
    To merge the changes introduced by 82, without previous changes:
1178
    bzr merge -r 81..82 ../bzr.dev
1179
    
1180
    merge refuses to run if there are any uncommitted changes, unless
1181
    --force is given.
1182
    """
1183
    takes_args = ['branch?']
1184
    takes_options = ['revision', 'force', 'merge-type']
1185
1186
    def run(self, branch='.', revision=None, force=False, 
1187
            merge_type=None):
1188
        from bzrlib.merge import merge
1189
        from bzrlib.merge_core import ApplyMerge3
1190
        if merge_type is None:
1191
            merge_type = ApplyMerge3
1192
1193
        if revision is None or len(revision) < 1:
1194
            base = [None, None]
974.1.52 by aaron.bentley at utoronto
Merged mpool's latest changes (~0.0.7)
1195
            other = [branch, -1]
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1196
        else:
1197
            if len(revision) == 1:
974.1.52 by aaron.bentley at utoronto
Merged mpool's latest changes (~0.0.7)
1198
                other = [branch, revision[0]]
1199
                base = [None, None]
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1200
            else:
1201
                assert len(revision) == 2
1202
                if None in revision:
1203
                    raise BzrCommandError(
1204
                        "Merge doesn't permit that revision specifier.")
974.1.52 by aaron.bentley at utoronto
Merged mpool's latest changes (~0.0.7)
1205
                base = [branch, revision[0]]
1206
                other = [branch, revision[1]]
1172 by Martin Pool
- better explanation when merge fails with AmbiguousBase
1207
1208
        try:
1209
            merge(other, base, check_clean=(not force), merge_type=merge_type)
1210
        except bzrlib.errors.AmbiguousBase, e:
1173 by Martin Pool
- message typo
1211
            m = ("sorry, bzr can't determine the right merge base yet\n"
1172 by Martin Pool
- better explanation when merge fails with AmbiguousBase
1212
                 "candidates are:\n  "
1213
                 + "\n  ".join(e.bases)
1214
                 + "\n"
1215
                 "please specify an explicit base with -r,\n"
1216
                 "and (if you want) report this to the bzr developers\n")
1217
            log_error(m)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1218
1219
1220
class cmd_revert(Command):
1221
    """Reverse all changes since the last commit.
1222
1223
    Only versioned files are affected.  Specify filenames to revert only 
1224
    those files.  By default, any files that are changed will be backed up
1225
    first.  Backup files have a '~' appended to their name.
1226
    """
1227
    takes_options = ['revision', 'no-backup']
1228
    takes_args = ['file*']
1229
    aliases = ['merge-revert']
1230
1231
    def run(self, revision=None, no_backup=False, file_list=None):
1232
        from bzrlib.merge import merge
1233
        from bzrlib.branch import Branch
1234
        from bzrlib.commands import parse_spec
1235
1236
        if file_list is not None:
1237
            if len(file_list) == 0:
1238
                raise BzrCommandError("No files specified")
1239
        if revision is None:
1240
            revision = [-1]
1241
        elif len(revision) != 1:
1242
            raise BzrCommandError('bzr revert --revision takes exactly 1 argument')
1243
        merge(('.', revision[0]), parse_spec('.'),
1244
              check_clean=False,
1245
              ignore_zero=True,
1246
              backup_files=not no_backup,
1247
              file_list=file_list)
1248
        if not file_list:
1249
            Branch('.').set_pending_merges([])
1250
1251
1252
class cmd_assert_fail(Command):
1253
    """Test reporting of assertion failures"""
1254
    hidden = True
1255
    def run(self):
1256
        assert False, "always fails"
1257
1258
1259
class cmd_help(Command):
1260
    """Show help on a command or other topic.
1261
1262
    For a list of all available commands, say 'bzr help commands'."""
1263
    takes_options = ['long']
1264
    takes_args = ['topic?']
1265
    aliases = ['?']
1266
    
1267
    def run(self, topic=None, long=False):
1268
        import help
1269
        if topic is None and long:
1270
            topic = "commands"
1271
        help.help(topic)
1272
1273
1274
class cmd_shell_complete(Command):
1275
    """Show appropriate completions for context.
1276
1277
    For a list of all available commands, say 'bzr shell-complete'."""
1278
    takes_args = ['context?']
1279
    aliases = ['s-c']
1280
    hidden = True
1281
    
1282
    def run(self, context=None):
1283
        import shellcomplete
1284
        shellcomplete.shellcomplete(context)
1285
1286
1228 by Martin Pool
- add fetch command as builtin
1287
class cmd_fetch(Command):
1288
    """Copy in history from another branch but don't merge it.
1289
1290
    This is an internal method used for pull and merge."""
1291
    hidden = True
1292
    takes_args = ['from_branch', 'to_branch']
1293
    def run(self, from_branch, to_branch):
1294
        from bzrlib.fetch import Fetcher
1295
        from bzrlib.branch import Branch
1296
        from_b = Branch(from_branch)
1297
        to_b = Branch(to_branch)
1298
        Fetcher(to_b, from_b)
1299
        
1300
1301
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1302
class cmd_missing(Command):
1303
    """What is missing in this branch relative to other branch.
1304
    """
1228 by Martin Pool
- add fetch command as builtin
1305
    # TODO: rewrite this in terms of ancestry so that it shows only
1306
    # unmerged things
1307
    
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1308
    takes_args = ['remote?']
1309
    aliases = ['mis', 'miss']
1310
    # We don't have to add quiet to the list, because 
1311
    # unknown options are parsed as booleans
1312
    takes_options = ['verbose', 'quiet']
1313
1314
    def run(self, remote=None, verbose=False, quiet=False):
1315
        from bzrlib.errors import BzrCommandError
1149 by Martin Pool
- make get_parent() be a method of Branch; add simple tests for it
1316
        from bzrlib.missing import show_missing
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1317
1318
        if verbose and quiet:
1319
            raise BzrCommandError('Cannot pass both quiet and verbose')
1320
1321
        b = find_branch('.')
1149 by Martin Pool
- make get_parent() be a method of Branch; add simple tests for it
1322
        parent = b.get_parent()
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1323
        if remote is None:
1324
            if parent is None:
1325
                raise BzrCommandError("No missing location known or specified.")
1326
            else:
1327
                if not quiet:
1328
                    print "Using last location: %s" % parent
1329
                remote = parent
1330
        elif parent is None:
1331
            # We only update x-pull if it did not exist, missing should not change the parent
1332
            b.controlfile('x-pull', 'wb').write(remote + '\n')
1333
        br_remote = find_branch(remote)
1334
1335
        return show_missing(b, br_remote, verbose=verbose, quiet=quiet)
1336
1337
1338
1339
class cmd_plugins(Command):
1340
    """List plugins"""
1341
    hidden = True
1342
    def run(self):
1343
        import bzrlib.plugin
1344
        from inspect import getdoc
1345
        for plugin in bzrlib.plugin.all_plugins:
1346
            if hasattr(plugin, '__path__'):
1347
                print plugin.__path__[0]
1348
            elif hasattr(plugin, '__file__'):
1349
                print plugin.__file__
1350
            else:
1351
                print `plugin`
1352
                
1353
            d = getdoc(plugin)
1354
            if d:
1355
                print '\t', d.split('\n')[0]
1356
1357