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