/brz/remove-bazaar

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