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