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