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