/brz/remove-bazaar

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