/brz/remove-bazaar

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