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