~bzr-pqm/bzr/bzr.dev

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