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