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