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