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