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