/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
1553.5.34 by Martin Pool
Stub lock-breaking command
1
# Copyright (C) 2004, 2005, 2006 by Canonical Ltd
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
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
1185.33.90 by Martin Pool
[merge] add --dry-run option (mpe)
17
"""builtin bzr commands"""
18
19
1508.1.20 by Robert Collins
Create a checkout command.
20
import errno
1185.65.29 by Robert Collins
Implement final review suggestions.
21
import os
1185.85.12 by John Arbash Meinel
Refactoring AddAction to allow redirecting to an encoding file.
22
import codecs
1508.1.20 by Robert Collins
Create a checkout command.
23
from shutil import rmtree
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
24
import sys
25
26
import bzrlib
1508.1.25 by Robert Collins
Update per review comments.
27
import bzrlib.branch
28
from bzrlib.branch import Branch
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
29
import bzrlib.bzrdir as bzrdir
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
30
from bzrlib.commands import Command, display_command
1185.35.4 by Aaron Bentley
Implemented remerge
31
from bzrlib.revision import common_ancestor
1505.1.10 by John Arbash Meinel
Brought back 'optimized' version, for better errors, cleaned up exception handling.
32
import bzrlib.errors as errors
1185.35.4 by Aaron Bentley
Implemented remerge
33
from bzrlib.errors import (BzrError, BzrCheckError, BzrCommandError, 
1185.35.13 by Aaron Bentley
Merged Martin
34
                           NotBranchError, DivergedBranches, NotConflicted,
1558.2.1 by Aaron Bentley
Ensure remerge errors when file-id is None
35
                           NoSuchFile, NoWorkingTree, FileInWrongBranch,
36
                           NotVersionedError)
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
37
from bzrlib.log import show_one_log
1534.7.140 by Aaron Bentley
Moved the merge stuff into merge.py
38
from bzrlib.merge import Merge3Merger
1185.16.43 by Martin Pool
- clean up handling of option objects
39
from bzrlib.option import Option
1685.1.37 by John Arbash Meinel
builtins now use urlfordisplay to display nicer paths to the user.
40
import bzrlib.osutils
1551.2.32 by Aaron Bentley
Handle progress phases more nicely in merge
41
from bzrlib.progress import DummyProgress, ProgressPhase
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
42
from bzrlib.revisionspec import RevisionSpec
1460 by Robert Collins
merge from martin.
43
import bzrlib.trace
1185.33.42 by Martin Pool
[patch] make --quiet a global option (robey)
44
from bzrlib.trace import mutter, note, log_error, warning, is_quiet
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
45
from bzrlib.transport.local import LocalTransport
1534.9.10 by Aaron Bentley
Fixed use of ui_factory (which can't be imported directly)
46
import bzrlib.ui
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
47
import bzrlib.urlutils as urlutils
1457.1.4 by Robert Collins
Branch.relpath has been moved to WorkingTree.relpath.
48
from bzrlib.workingtree import WorkingTree
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
49
50
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
51
def tree_files(file_list, default_branch=u'.'):
1185.35.28 by Aaron Bentley
Support diff with two branches as input.
52
    try:
1508.1.15 by Robert Collins
Merge from mpool.
53
        return internal_tree_files(file_list, default_branch)
1185.35.32 by Aaron Bentley
Fixed handling of files in mixed branches
54
    except FileInWrongBranch, e:
1185.35.28 by Aaron Bentley
Support diff with two branches as input.
55
        raise BzrCommandError("%s is not in the same branch as %s" %
1185.35.32 by Aaron Bentley
Fixed handling of files in mixed branches
56
                             (e.path, file_list[0]))
1185.35.28 by Aaron Bentley
Support diff with two branches as input.
57
1185.85.12 by John Arbash Meinel
Refactoring AddAction to allow redirecting to an encoding file.
58
1658.1.9 by Martin Pool
Give an error for bzr diff on an nonexistent file (Malone #3619)
59
# XXX: Bad function name; should possibly also be a class method of
60
# WorkingTree rather than a function.
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
61
def internal_tree_files(file_list, default_branch=u'.'):
1658.1.8 by Martin Pool
(internal_tree_files) Better docstring
62
    """Convert command-line paths to a WorkingTree and relative paths.
63
64
    This is typically used for command-line processors that take one or
65
    more filenames, and infer the workingtree that contains them.
66
67
    The filenames given are not required to exist.
68
69
    :param file_list: Filenames to convert.  
70
71
    :param default_branch: Fallback tree path to use if file_list is empty or None.
72
73
    :return: workingtree, [relative_paths]
1185.12.101 by Aaron Bentley
Made commit take branch from first argument, if supplied.
74
    """
75
    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
76
        return WorkingTree.open_containing(default_branch)[0], file_list
77
    tree = WorkingTree.open_containing(file_list[0])[0]
1185.12.101 by Aaron Bentley
Made commit take branch from first argument, if supplied.
78
    new_list = []
79
    for filename in file_list:
1185.35.32 by Aaron Bentley
Fixed handling of files in mixed branches
80
        try:
81
            new_list.append(tree.relpath(filename))
1185.31.45 by John Arbash Meinel
Refactoring Exceptions found some places where the wrong exception was caught.
82
        except errors.PathNotChild:
1508.1.15 by Robert Collins
Merge from mpool.
83
            raise FileInWrongBranch(tree.branch, filename)
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
84
    return tree, new_list
1185.12.101 by Aaron Bentley
Made commit take branch from first argument, if supplied.
85
86
1553.5.78 by Martin Pool
New bzr init --format option and test
87
def get_format_type(typestring):
88
    """Parse and return a format specifier."""
1666.1.3 by Robert Collins
Fix and test upgrades from bzrdir 6 over SFTP.
89
    if typestring == "weave":
90
        return bzrdir.BzrDirFormat6()
1553.5.78 by Martin Pool
New bzr init --format option and test
91
    if typestring == "metadir":
92
        return bzrdir.BzrDirMetaFormat1()
93
    if typestring == "knit":
94
        format = bzrdir.BzrDirMetaFormat1()
95
        format.repository_format = bzrlib.repository.RepositoryFormatKnit1()
96
        return format
1666.1.3 by Robert Collins
Fix and test upgrades from bzrdir 6 over SFTP.
97
    msg = "No known bzr-dir format %s. Supported types are: weave, metadir\n" %\
1553.5.78 by Martin Pool
New bzr init --format option and test
98
        (typestring)
99
    raise BzrCommandError(msg)
100
101
1185.16.112 by mbp at sourcefrog
todo
102
# TODO: Make sure no commands unconditionally use the working directory as a
103
# branch.  If a filename argument is used, the first of them should be used to
104
# specify the branch.  (Perhaps this can be factored out into some kind of
105
# Argument class, representing a file in a branch, where the first occurrence
106
# opens the branch?)
107
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
108
class cmd_status(Command):
109
    """Display status summary.
110
111
    This reports on versioned and unknown files, reporting them
112
    grouped by state.  Possible states are:
113
114
    added
115
        Versioned in the working copy but not in the previous revision.
116
117
    removed
118
        Versioned in the previous revision but removed or deleted
119
        in the working copy.
120
121
    renamed
122
        Path of this file changed from the previous revision;
123
        the text may also have changed.  This includes files whose
124
        parent directory was renamed.
125
126
    modified
127
        Text has changed since the previous revision.
128
129
    unchanged
130
        Nothing about this file has changed since the previous revision.
131
        Only shown with --all.
132
133
    unknown
134
        Not versioned and not matching an ignore pattern.
135
136
    To see ignored files use 'bzr ignored'.  For details in the
137
    changes to file texts, use 'bzr diff'.
138
139
    If no arguments are specified, the status of the entire working
140
    directory is shown.  Otherwise, only the status of the specified
141
    files or directories is reported.  If a directory is given, status
142
    is reported for everything inside that directory.
1185.1.35 by Robert Collins
Heikki Paajanen's status -r patch
143
144
    If a revision argument is given, the status is calculated against
145
    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
146
    """
1185.16.76 by Martin Pool
doc
147
    
148
    # TODO: --no-recurse, --recurse options
149
    
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
150
    takes_args = ['file*']
1185.34.4 by Jelmer Vernooij
Support -r option to bzr status. The backend code already handled
151
    takes_options = ['all', 'show-ids', 'revision']
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
152
    aliases = ['st', 'stat']
1185.85.22 by John Arbash Meinel
Updated cmd_inventory. Changing from having each Command request an encoded stdout to providing one before calling run()
153
154
    encoding_type = 'replace'
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
155
    
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
156
    @display_command
1185.1.35 by Robert Collins
Heikki Paajanen's status -r patch
157
    def run(self, all=False, show_ids=False, file_list=None, revision=None):
1551.2.9 by Aaron Bentley
Fix status to work with checkouts
158
        from bzrlib.status import show_tree_status
1185.85.15 by John Arbash Meinel
Updated bzr status, adding test_cat
159
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
160
        tree, file_list = tree_files(file_list)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
161
            
1551.2.9 by Aaron Bentley
Fix status to work with checkouts
162
        show_tree_status(tree, show_unchanged=all, show_ids=show_ids,
1185.85.84 by John Arbash Meinel
[merge] bzr.dev 1573, lots of updates
163
                         specific_files=file_list, revision=revision,
164
                         to_file=self.outf)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
165
166
167
class cmd_cat_revision(Command):
1185.5.3 by John Arbash Meinel
cat-revision allows --revision for easier investigation.
168
    """Write out metadata for a revision.
169
    
170
    The revision to print can either be specified by a specific
171
    revision identifier, or you can use --revision.
172
    """
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
173
174
    hidden = True
1185.5.3 by John Arbash Meinel
cat-revision allows --revision for easier investigation.
175
    takes_args = ['revision_id?']
176
    takes_options = ['revision']
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
177
    
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
178
    @display_command
1185.5.3 by John Arbash Meinel
cat-revision allows --revision for easier investigation.
179
    def run(self, revision_id=None, revision=None):
180
181
        if revision_id is not None and revision is not None:
182
            raise BzrCommandError('You can only supply one of revision_id or --revision')
183
        if revision_id is None and revision is None:
184
            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)
185
        b = WorkingTree.open_containing(u'.')[0].branch
1185.85.72 by John Arbash Meinel
Fix some of the tests.
186
187
        # TODO: jam 20060112 should cat-revision always output utf-8?
1185.5.3 by John Arbash Meinel
cat-revision allows --revision for easier investigation.
188
        if revision_id is not None:
1185.85.78 by John Arbash Meinel
[merge] jam-integration 1512, includes Storage changes.
189
            self.outf.write(b.repository.get_revision_xml(revision_id).decode('utf-8'))
1185.5.3 by John Arbash Meinel
cat-revision allows --revision for easier investigation.
190
        elif revision is not None:
191
            for rev in revision:
192
                if rev is None:
193
                    raise BzrCommandError('You cannot specify a NULL revision.')
194
                revno, rev_id = rev.in_history(b)
1185.85.78 by John Arbash Meinel
[merge] jam-integration 1512, includes Storage changes.
195
                self.outf.write(b.repository.get_revision_xml(rev_id).decode('utf-8'))
1185.1.29 by Robert Collins
merge merge tweaks from aaron, which includes latest .dev
196
    
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
197
198
class cmd_revno(Command):
199
    """Show current revision number.
200
1185.85.24 by John Arbash Meinel
Moved run_bzr_decode into TestCase
201
    This is equal to the number of revisions on this branch.
202
    """
203
1185.50.16 by John Arbash Meinel
[patch] Michael Ellerman: 'Trivial patch to allow revno to take a location'
204
    takes_args = ['location?']
1185.85.24 by John Arbash Meinel
Moved run_bzr_decode into TestCase
205
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
206
    @display_command
1185.50.16 by John Arbash Meinel
[patch] Michael Ellerman: 'Trivial patch to allow revno to take a location'
207
    def run(self, location=u'.'):
1185.85.24 by John Arbash Meinel
Moved run_bzr_decode into TestCase
208
        self.outf.write(str(Branch.open_containing(location)[0].revno()))
209
        self.outf.write('\n')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
210
1182 by Martin Pool
- more disentangling of xml storage format from objects
211
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
212
class cmd_revision_info(Command):
213
    """Show revision number and revision id for a given revision identifier.
214
    """
215
    hidden = True
216
    takes_args = ['revision_info*']
217
    takes_options = ['revision']
1185.85.24 by John Arbash Meinel
Moved run_bzr_decode into TestCase
218
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
219
    @display_command
1185.5.4 by John Arbash Meinel
Updated bzr revision-info, created tests.
220
    def run(self, revision=None, revision_info_list=[]):
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
221
222
        revs = []
223
        if revision is not None:
224
            revs.extend(revision)
1185.5.4 by John Arbash Meinel
Updated bzr revision-info, created tests.
225
        if revision_info_list is not None:
226
            for rev in revision_info_list:
227
                revs.append(RevisionSpec(rev))
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
228
        if len(revs) == 0:
229
            raise BzrCommandError('You must supply a revision identifier')
230
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
231
        b = WorkingTree.open_containing(u'.')[0].branch
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
232
233
        for rev in revs:
1185.5.4 by John Arbash Meinel
Updated bzr revision-info, created tests.
234
            revinfo = rev.in_history(b)
235
            if revinfo.revno is None:
236
                print '     %s' % revinfo.rev_id
237
            else:
238
                print '%4d %s' % (revinfo.revno, revinfo.rev_id)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
239
240
    
241
class cmd_add(Command):
242
    """Add specified files or directories.
243
244
    In non-recursive mode, all the named items are added, regardless
245
    of whether they were previously ignored.  A warning is given if
246
    any of the named files are already versioned.
247
248
    In recursive mode (the default), files are treated the same way
249
    but the behaviour for directories is different.  Directories that
250
    are already versioned do not give a warning.  All directories,
251
    whether already versioned or not, are searched for files or
252
    subdirectories that are neither versioned or ignored, and these
253
    are added.  This search proceeds recursively into versioned
254
    directories.  If no names are given '.' is assumed.
255
256
    Therefore simply saying 'bzr add' will version all files that
257
    are currently unknown.
258
1185.3.3 by Martin Pool
- patch from mpe to automatically add parent directories
259
    Adding a file whose parent directory is not versioned will
260
    implicitly add the parent, and so on up to the root. This means
261
    you should never need to explictly add a directory, they'll just
262
    get added when you add a file in the directory.
1185.33.90 by Martin Pool
[merge] add --dry-run option (mpe)
263
264
    --dry-run will show which files would be added, but not actually 
265
    add them.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
266
    """
267
    takes_args = ['file*']
1185.46.9 by Aaron Bentley
Added verbose option to bzr add, to list all ignored files.
268
    takes_options = ['no-recurse', 'dry-run', 'verbose']
1185.85.22 by John Arbash Meinel
Updated cmd_inventory. Changing from having each Command request an encoded stdout to providing one before calling run()
269
    encoding_type = 'replace'
1185.53.1 by Michael Ellerman
Add support for bzr add --dry-run
270
1185.46.9 by Aaron Bentley
Added verbose option to bzr add, to list all ignored files.
271
    def run(self, file_list, no_recurse=False, dry_run=False, verbose=False):
1185.53.1 by Michael Ellerman
Add support for bzr add --dry-run
272
        import bzrlib.add
273
1185.85.22 by John Arbash Meinel
Updated cmd_inventory. Changing from having each Command request an encoded stdout to providing one before calling run()
274
        action = bzrlib.add.AddAction(to_file=self.outf,
1185.85.12 by John Arbash Meinel
Refactoring AddAction to allow redirecting to an encoding file.
275
            should_add=(not dry_run), should_print=(not is_quiet()))
1185.53.1 by Michael Ellerman
Add support for bzr add --dry-run
276
1185.46.8 by Aaron Bentley
bzr add reports ignored patterns.
277
        added, ignored = bzrlib.add.smart_add(file_list, not no_recurse, 
1185.85.12 by John Arbash Meinel
Refactoring AddAction to allow redirecting to an encoding file.
278
                                              action=action)
1185.46.8 by Aaron Bentley
bzr add reports ignored patterns.
279
        if len(ignored) > 0:
280
            for glob in sorted(ignored.keys()):
281
                match_len = len(ignored[glob])
1185.46.9 by Aaron Bentley
Added verbose option to bzr add, to list all ignored files.
282
                if verbose:
283
                    for path in ignored[glob]:
1185.85.22 by John Arbash Meinel
Updated cmd_inventory. Changing from having each Command request an encoded stdout to providing one before calling run()
284
                        self.outf.write("ignored %s matching \"%s\"\n" 
285
                                        % (path, glob))
1185.46.9 by Aaron Bentley
Added verbose option to bzr add, to list all ignored files.
286
                else:
1185.85.22 by John Arbash Meinel
Updated cmd_inventory. Changing from having each Command request an encoded stdout to providing one before calling run()
287
                    self.outf.write("ignored %d file(s) matching \"%s\"\n"
288
                                    % (match_len, glob))
289
            self.outf.write("If you wish to add some of these files,"
290
                            " please add them by name.\n")
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
291
292
293
class cmd_mkdir(Command):
294
    """Create a new versioned directory.
295
296
    This is equivalent to creating the directory and then adding it.
297
    """
298
    takes_args = ['dir+']
1185.85.22 by John Arbash Meinel
Updated cmd_inventory. Changing from having each Command request an encoded stdout to providing one before calling run()
299
    encoding_type = 'replace'
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
300
301
    def run(self, dir_list):
302
        for d in dir_list:
303
            os.mkdir(d)
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
304
            wt, dd = WorkingTree.open_containing(d)
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
305
            wt.add([dd])
1685.1.23 by John Arbash Meinel
mkdir was adding an extra space before the path.
306
            print >>self.outf, 'added', d
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
307
308
309
class cmd_relpath(Command):
310
    """Show path of a file relative to root"""
311
    takes_args = ['filename']
312
    hidden = True
313
    
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
314
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
315
    def run(self, filename):
1185.85.19 by John Arbash Meinel
Updated bzr relpath
316
        # TODO: jam 20050106 Can relpath return a munged path if
317
        #       sys.stdout encoding cannot represent it?
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
318
        tree, relpath = WorkingTree.open_containing(filename)
1185.85.22 by John Arbash Meinel
Updated cmd_inventory. Changing from having each Command request an encoded stdout to providing one before calling run()
319
        self.outf.write(relpath)
320
        self.outf.write('\n')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
321
322
323
class cmd_inventory(Command):
1185.33.33 by Martin Pool
[patch] add 'bzr inventory --kind directory'; remove 'bzr directories'
324
    """Show inventory of the current working copy or a revision.
325
326
    It is possible to limit the output to a particular entry
327
    type using the --kind option.  For example; --kind file.
328
    """
329
    takes_options = ['revision', 'show-ids', 'kind']
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
330
    
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
331
    @display_command
1185.33.33 by Martin Pool
[patch] add 'bzr inventory --kind directory'; remove 'bzr directories'
332
    def run(self, revision=None, show_ids=False, kind=None):
333
        if kind and kind not in ['file', 'directory', 'symlink']:
334
            raise BzrCommandError('invalid kind specified')
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
335
        tree = WorkingTree.open_containing(u'.')[0]
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
336
        if revision is None:
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
337
            inv = tree.read_working_inventory()
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
338
        else:
339
            if len(revision) > 1:
340
                raise BzrCommandError('bzr inventory --revision takes'
341
                    ' exactly one revision identifier')
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
342
            inv = tree.branch.repository.get_revision_inventory(
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
343
                revision[0].in_history(tree.branch).rev_id)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
344
345
        for path, entry in inv.entries():
1185.33.33 by Martin Pool
[patch] add 'bzr inventory --kind directory'; remove 'bzr directories'
346
            if kind and kind != entry.kind:
347
                continue
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
348
            if show_ids:
1185.85.22 by John Arbash Meinel
Updated cmd_inventory. Changing from having each Command request an encoded stdout to providing one before calling run()
349
                self.outf.write('%-50s %s\n' % (path, entry.file_id))
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
350
            else:
1185.85.22 by John Arbash Meinel
Updated cmd_inventory. Changing from having each Command request an encoded stdout to providing one before calling run()
351
                self.outf.write(path)
352
                self.outf.write('\n')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
353
354
355
class cmd_mv(Command):
356
    """Move or rename a file.
357
358
    usage:
359
        bzr mv OLDNAME NEWNAME
360
        bzr mv SOURCE... DESTINATION
361
362
    If the last argument is a versioned directory, all the other names
363
    are moved into it.  Otherwise, there must be exactly two arguments
364
    and the file is changed to a new name, which must not already exist.
365
366
    Files cannot be moved between branches.
367
    """
368
    takes_args = ['names*']
1616.1.8 by Martin Pool
Unify 'mv', 'move', 'rename'. (#5379, Matthew Fuller)
369
    aliases = ['move', 'rename']
370
1185.85.26 by John Arbash Meinel
bzr mv should succeed even if it can't display the paths.
371
    encoding_type = 'replace'
372
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
373
    def run(self, names_list):
374
        if len(names_list) < 2:
375
            raise BzrCommandError("missing file argument")
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
376
        tree, rel_names = tree_files(names_list)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
377
        
378
        if os.path.isdir(names_list[-1]):
379
            # move into existing directory
1508.1.8 by Robert Collins
move move() from Branch to WorkingTree.
380
            for pair in tree.move(rel_names[:-1], rel_names[-1]):
1185.85.25 by John Arbash Meinel
updated 'bzr mv'
381
                self.outf.write("%s => %s\n" % pair)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
382
        else:
383
            if len(names_list) != 2:
384
                raise BzrCommandError('to mv multiple files the destination '
385
                                      'must be a versioned directory')
1508.1.7 by Robert Collins
Move rename_one from Branch to WorkingTree. (Robert Collins).
386
            tree.rename_one(rel_names[0], rel_names[1])
1185.85.25 by John Arbash Meinel
updated 'bzr mv'
387
            self.outf.write("%s => %s\n" % (rel_names[0], rel_names[1]))
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
388
            
389
    
390
class cmd_pull(Command):
1649.1.1 by Robert Collins
* 'pull' and 'push' now normalise the revision history, so that any two
391
    """Turn this branch into a mirror of another branch.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
392
393
    This command only works on branches that have not diverged.  Branches are
1649.1.1 by Robert Collins
* 'pull' and 'push' now normalise the revision history, so that any two
394
    considered diverged if the destination branch's most recent commit is one
395
    that has not been merged (directly or indirectly) into the parent.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
396
1661.1.1 by Martin Pool
[merge] olaf's --remember changes
397
    If branches have diverged, you can use 'bzr merge' to integrate the changes
398
    from one into the other.  Once one branch has merged, the other should
399
    be able to pull it again.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
400
401
    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
402
    from one into the other.  Once one branch has merged, the other should
403
    be able to pull it again.
404
405
    If you want to forget your local changes and just update your branch to
1661.1.1 by Martin Pool
[merge] olaf's --remember changes
406
    match the remote one, use pull --overwrite.
1614.2.3 by Olaf Conradi
In commands push and pull, moved help text for --remember down. It's not
407
408
    If there is no default location set, the first pull will set it.  After
409
    that, you can omit the location to use the default.  To change the
410
    default, use --remember.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
411
    """
1185.76.1 by Erik BÃ¥gfors
Support for --revision in pull
412
    takes_options = ['remember', 'overwrite', 'revision', 'verbose']
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
413
    takes_args = ['location?']
1185.85.27 by John Arbash Meinel
Updated bzr branch and bzr pull
414
    encoding_type = 'replace'
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
415
1185.76.1 by Erik BÃ¥gfors
Support for --revision in pull
416
    def run(self, location=None, remember=False, overwrite=False, revision=None, verbose=False):
1558.5.6 by Aaron Bentley
Renamed make-repo init-repo
417
        # FIXME: too much stuff is in the command class
418
        try:
419
            tree_to = WorkingTree.open_containing(u'.')[0]
420
            branch_to = tree_to.branch
421
        except NoWorkingTree:
422
            tree_to = None
423
            branch_to = Branch.open_containing(u'.')[0] 
424
        stored_loc = branch_to.get_parent()
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
425
        if location is None:
426
            if stored_loc is None:
427
                raise BzrCommandError("No pull location known or specified.")
428
            else:
1685.1.37 by John Arbash Meinel
builtins now use urlfordisplay to display nicer paths to the user.
429
                self.outf.write("Using saved location: %s\n" 
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
430
                    % urlutils.unescape_for_display(stored_loc))
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
431
                location = stored_loc
1185.56.1 by Michael Ellerman
Simplify handling of DivergedBranches in cmd_pull()
432
1685.1.19 by John Arbash Meinel
pull/merge/branch/missing should all save the absolute path to the other branch, not the relative one
433
        branch_from = Branch.open(location)
434
1614.2.12 by Olaf Conradi
Merge bzr.dev
435
        if branch_to.get_parent() is None or remember:
1685.1.19 by John Arbash Meinel
pull/merge/branch/missing should all save the absolute path to the other branch, not the relative one
436
            branch_to.set_parent(branch_from.base)
1614.2.8 by Olaf Conradi
Added testcases for using pull with --remember. Moved remember code to
437
1185.56.1 by Michael Ellerman
Simplify handling of DivergedBranches in cmd_pull()
438
1185.76.4 by Erik BÃ¥gfors
expanded tabs
439
        if revision is None:
440
            rev_id = None
1185.76.3 by Erik BÃ¥gfors
changes for pull --revision based on input from John
441
        elif len(revision) == 1:
1614.2.12 by Olaf Conradi
Merge bzr.dev
442
            rev_id = revision[0].in_history(branch_from).rev_id
1185.76.4 by Erik BÃ¥gfors
expanded tabs
443
        else:
444
            raise BzrCommandError('bzr pull --revision takes one value.')
1185.76.1 by Erik BÃ¥gfors
Support for --revision in pull
445
1558.5.6 by Aaron Bentley
Renamed make-repo init-repo
446
        old_rh = branch_to.revision_history()
447
        if tree_to is not None:
1614.2.12 by Olaf Conradi
Merge bzr.dev
448
            count = tree_to.pull(branch_from, overwrite, rev_id)
1558.5.6 by Aaron Bentley
Renamed make-repo init-repo
449
        else:
1614.2.12 by Olaf Conradi
Merge bzr.dev
450
            count = branch_to.pull(branch_from, overwrite, rev_id)
1185.40.2 by Robey Pointer
when doing a 'pull', display the number of revisions pulled; on 'commit', display the current (new) revision number
451
        note('%d revision(s) pulled.' % (count,))
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
452
1185.31.5 by John Arbash Meinel
Merged pull --verbose changes
453
        if verbose:
1558.5.6 by Aaron Bentley
Renamed make-repo init-repo
454
            new_rh = branch_to.revision_history()
1185.31.5 by John Arbash Meinel
Merged pull --verbose changes
455
            if old_rh != new_rh:
456
                # Something changed
457
                from bzrlib.log import show_changed_revisions
1685.1.1 by John Arbash Meinel
[merge] the old bzr-encoding changes, reparenting them on bzr.dev
458
                show_changed_revisions(branch_to, old_rh, new_rh,
1185.85.27 by John Arbash Meinel
Updated bzr branch and bzr pull
459
                                       to_file=self.outf)
1185.31.5 by John Arbash Meinel
Merged pull --verbose changes
460
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
461
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
462
class cmd_push(Command):
1649.1.1 by Robert Collins
* 'pull' and 'push' now normalise the revision history, so that any two
463
    """Update a mirror of this branch.
464
    
465
    The target branch will not have its working tree populated because this
466
    is both expensive, and is not supported on remote file systems.
467
    
468
    Some smart servers or protocols *may* put the working tree in place in
469
    the future.
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
470
471
    This command only works on branches that have not diverged.  Branches are
1649.1.1 by Robert Collins
* 'pull' and 'push' now normalise the revision history, so that any two
472
    considered diverged if the destination branch's most recent commit is one
473
    that has not been merged (directly or indirectly) by the source branch.
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
474
475
    If branches have diverged, you can use 'bzr push --overwrite' to replace
1649.1.1 by Robert Collins
* 'pull' and 'push' now normalise the revision history, so that any two
476
    the other branch completely, discarding its unmerged changes.
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
477
    
478
    If you want to ensure you have the different changes in the other branch,
1649.1.1 by Robert Collins
* 'pull' and 'push' now normalise the revision history, so that any two
479
    do a merge (see bzr help merge) from the other branch, and commit that.
480
    After that you will be able to do a push without '--overwrite'.
1614.2.3 by Olaf Conradi
In commands push and pull, moved help text for --remember down. It's not
481
482
    If there is no default push location set, the first push will set it.
483
    After that, you can omit the location to use the default.  To change the
484
    default, use --remember.
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
485
    """
1185.85.31 by John Arbash Meinel
Updated bzr push, including bringing in the unused --verbose flag.
486
    takes_options = ['remember', 'overwrite', 'verbose',
1495 by Robert Collins
Add a --create-prefix to the new push command.
487
                     Option('create-prefix', 
488
                            help='Create the path leading up to the branch '
489
                                 'if it does not already exist')]
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
490
    takes_args = ['location?']
1185.85.31 by John Arbash Meinel
Updated bzr push, including bringing in the unused --verbose flag.
491
    encoding_type = 'replace'
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
492
1495 by Robert Collins
Add a --create-prefix to the new push command.
493
    def run(self, location=None, remember=False, overwrite=False,
1185.31.5 by John Arbash Meinel
Merged pull --verbose changes
494
            create_prefix=False, verbose=False):
1185.33.45 by Martin Pool
[merge] refactoring of branch vs working tree, etc (robertc)
495
        # FIXME: Way too big!  Put this into a function called from the
496
        # command.
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
497
        from bzrlib.transport import get_transport
498
        
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
499
        tree_from = WorkingTree.open_containing(u'.')[0]
1185.33.45 by Martin Pool
[merge] refactoring of branch vs working tree, etc (robertc)
500
        br_from = tree_from.branch
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
501
        stored_loc = tree_from.branch.get_push_location()
1685.1.22 by John Arbash Meinel
cmd_push was passing the location directly to relpath, rather than a URL
502
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
503
        if location is None:
504
            if stored_loc is None:
505
                raise BzrCommandError("No push location known or specified.")
506
            else:
1685.1.37 by John Arbash Meinel
builtins now use urlfordisplay to display nicer paths to the user.
507
                self.outf.write("Using saved location: %s" 
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
508
                    % urlutils.unescape_for_display(stored_loc))
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
509
                location = stored_loc
1685.1.22 by John Arbash Meinel
cmd_push was passing the location directly to relpath, rather than a URL
510
511
        transport = get_transport(location)
512
        location_url = transport.base
1614.2.9 by Olaf Conradi
Added testcases for using push with --remember. Moved remember code to
513
        if br_from.get_push_location() is None or remember:
1685.1.24 by John Arbash Meinel
cmd_push should use URLs throughout.
514
            br_from.set_push_location(location_url)
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
515
        try:
1685.1.24 by John Arbash Meinel
cmd_push should use URLs throughout.
516
            dir_to = bzrlib.bzrdir.BzrDir.open(location_url)
1563.2.38 by Robert Collins
make push preserve tree formats.
517
            br_to = dir_to.open_branch()
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
518
        except NotBranchError:
519
            # create a branch.
1685.1.22 by John Arbash Meinel
cmd_push was passing the location directly to relpath, rather than a URL
520
            transport = transport.clone('..')
1495 by Robert Collins
Add a --create-prefix to the new push command.
521
            if not create_prefix:
522
                try:
1685.1.24 by John Arbash Meinel
cmd_push should use URLs throughout.
523
                    relurl = transport.relpath(location_url)
524
                    mutter('creating directory %s => %s', location_url, relurl)
525
                    transport.mkdir(relurl)
1495 by Robert Collins
Add a --create-prefix to the new push command.
526
                except NoSuchFile:
527
                    raise BzrCommandError("Parent directory of %s "
528
                                          "does not exist." % location)
529
            else:
530
                current = transport.base
1685.1.22 by John Arbash Meinel
cmd_push was passing the location directly to relpath, rather than a URL
531
                needed = [(transport, transport.relpath(location_url))]
1495 by Robert Collins
Add a --create-prefix to the new push command.
532
                while needed:
533
                    try:
534
                        transport, relpath = needed[-1]
535
                        transport.mkdir(relpath)
536
                        needed.pop()
537
                    except NoSuchFile:
538
                        new_transport = transport.clone('..')
539
                        needed.append((new_transport,
540
                                       new_transport.relpath(transport.base)))
541
                        if new_transport.base == transport.base:
1616.1.16 by Martin Pool
typo
542
                            raise BzrCommandError("Could not create "
1495 by Robert Collins
Add a --create-prefix to the new push command.
543
                                                  "path prefix.")
1685.1.24 by John Arbash Meinel
cmd_push should use URLs throughout.
544
            dir_to = br_from.bzrdir.clone(location_url)
1563.2.38 by Robert Collins
make push preserve tree formats.
545
            br_to = dir_to.open_branch()
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.
546
        old_rh = br_to.revision_history()
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
547
        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.
548
            try:
1563.2.38 by Robert Collins
make push preserve tree formats.
549
                tree_to = dir_to.open_workingtree()
550
            except errors.NotLocalUrl:
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.
551
                # TODO: This should be updated for branches which don't have a
552
                # working tree, as opposed to ones where we just couldn't 
553
                # update the tree.
1558.7.4 by Aaron Bentley
Adjust push warning [Matthew Fuller]
554
                warning('This transport does not update the working '
555
                        'tree of: %s' % (br_to.base,))
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.
556
                count = br_to.pull(br_from, overwrite)
1563.2.38 by Robert Collins
make push preserve tree formats.
557
            except NoWorkingTree:
558
                count = br_to.pull(br_from, overwrite)
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.
559
            else:
560
                count = tree_to.pull(br_from, overwrite)
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
561
        except DivergedBranches:
562
            raise BzrCommandError("These branches have diverged."
563
                                  "  Try a merge then push with overwrite.")
1185.33.44 by Martin Pool
[patch] show number of revisions pushed/pulled/merged (Robey Pointer)
564
        note('%d revision(s) pushed.' % (count,))
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
565
1185.31.5 by John Arbash Meinel
Merged pull --verbose changes
566
        if verbose:
567
            new_rh = br_to.revision_history()
568
            if old_rh != new_rh:
569
                # Something changed
570
                from bzrlib.log import show_changed_revisions
1185.85.31 by John Arbash Meinel
Updated bzr push, including bringing in the unused --verbose flag.
571
                show_changed_revisions(br_to, old_rh, new_rh,
572
                                       to_file=self.outf)
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
573
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
574
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
575
class cmd_branch(Command):
576
    """Create a new copy of a branch.
577
578
    If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
579
    be used.  In other words, "branch ../foo/bar" will attempt to create ./bar.
580
581
    To retrieve the branch as of a particular revision, supply the --revision
582
    parameter, as in "branch foo/bar -r 5".
1185.10.2 by Aaron Bentley
Updated help message
583
584
    --basis is to speed up branching from remote branches.  When specified, it
585
    copies all the file-contents, inventory and revision data from the basis
586
    branch before copying anything from the remote branch.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
587
    """
588
    takes_args = ['from_location', 'to_location?']
1587.1.14 by Robert Collins
Make bound branch creation happen via 'checkout'
589
    takes_options = ['revision', 'basis']
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
590
    aliases = ['get', 'clone']
591
1587.1.14 by Robert Collins
Make bound branch creation happen via 'checkout'
592
    def run(self, from_location, to_location=None, revision=None, basis=None):
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
593
        from bzrlib.transport import get_transport
1185.17.3 by Martin Pool
[pick] larger read lock scope for branch command
594
        if revision is None:
595
            revision = [None]
596
        elif len(revision) > 1:
597
            raise BzrCommandError(
598
                'bzr branch --revision takes exactly 1 revision value')
599
        try:
600
            br_from = Branch.open(from_location)
601
        except OSError, e:
602
            if e.errno == errno.ENOENT:
603
                raise BzrCommandError('Source location "%s" does not'
604
                                      ' exist.' % to_location)
605
            else:
606
                raise
607
        br_from.lock_read()
608
        try:
1185.10.1 by Aaron Bentley
Added --basis option to bzr branch
609
            if basis is not None:
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
610
                basis_dir = bzrdir.BzrDir.open_containing(basis)[0]
1185.10.1 by Aaron Bentley
Added --basis option to bzr branch
611
            else:
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
612
                basis_dir = None
1185.8.4 by Aaron Bentley
Fixed branch -r
613
            if len(revision) == 1 and revision[0] is not None:
1390 by Robert Collins
pair programming worx... merge integration and weave
614
                revision_id = revision[0].in_history(br_from)[1]
1185.8.4 by Aaron Bentley
Fixed branch -r
615
            else:
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
616
                # FIXME - wt.last_revision, fallback to branch, fall back to
617
                # None or perhaps NULL_REVISION to mean copy nothing
618
                # RBC 20060209
619
                revision_id = br_from.last_revision()
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
620
            if to_location is None:
621
                to_location = os.path.basename(from_location.rstrip("/\\"))
1442.1.71 by Robert Collins
'bzr branch' sets the branch-name,
622
                name = None
623
            else:
624
                name = os.path.basename(to_location) + '\n'
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
625
626
            to_transport = get_transport(to_location)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
627
            try:
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
628
                to_transport.mkdir('.')
629
            except bzrlib.errors.FileExists:
630
                raise BzrCommandError('Target directory "%s" already'
631
                                      ' exists.' % to_location)
632
            except bzrlib.errors.NoSuchFile:
633
                raise BzrCommandError('Parent of "%s" does not exist.' %
634
                                      to_location)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
635
            try:
1587.1.14 by Robert Collins
Make bound branch creation happen via 'checkout'
636
                # preserve whatever source format we have.
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
637
                dir = br_from.bzrdir.sprout(to_transport.base,
638
                        revision_id, basis_dir)
1587.1.14 by Robert Collins
Make bound branch creation happen via 'checkout'
639
                branch = dir.open_branch()
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
640
            except bzrlib.errors.NoSuchRevision:
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
641
                # TODO: jam 20060426 This only works on local paths
642
                #       and it would be nice if 'bzr branch' could
643
                #       work on a remote path
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
644
                rmtree(to_location)
1466 by Robert Collins
revision may be None in cmd_branch, do not treat as an int.
645
                msg = "The branch %s has no revision %s." % (from_location, revision[0])
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
646
                raise BzrCommandError(msg)
1185.10.1 by Aaron Bentley
Added --basis option to bzr branch
647
            except bzrlib.errors.UnlistableBranch:
1442.1.71 by Robert Collins
'bzr branch' sets the branch-name,
648
                rmtree(to_location)
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
649
                msg = "The branch %s cannot be used as a --basis" % (basis,)
1442.1.71 by Robert Collins
'bzr branch' sets the branch-name,
650
                raise BzrCommandError(msg)
651
            if name:
1185.65.27 by Robert Collins
Tweak storage towards mergability.
652
                branch.control_files.put_utf8('branch-name', name)
1185.33.44 by Martin Pool
[patch] show number of revisions pushed/pulled/merged (Robey Pointer)
653
            note('Branched %d revision(s).' % branch.revno())
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
654
        finally:
1185.17.3 by Martin Pool
[pick] larger read lock scope for branch command
655
            br_from.unlock()
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
656
657
1508.1.20 by Robert Collins
Create a checkout command.
658
class cmd_checkout(Command):
659
    """Create a new checkout of an existing branch.
660
1508.1.28 by Robert Collins
Test using bzr checkout to reconstitute working trees.
661
    If BRANCH_LOCATION is omitted, checkout will reconstitute a working tree for
662
    the branch found in '.'. This is useful if you have removed the working tree
663
    or if it was never created - i.e. if you pushed the branch to its current
664
    location using SFTP.
665
    
1508.1.20 by Robert Collins
Create a checkout command.
666
    If the TO_LOCATION is omitted, the last component of the BRANCH_LOCATION will
667
    be used.  In other words, "checkout ../foo/bar" will attempt to create ./bar.
668
669
    To retrieve the branch as of a particular revision, supply the --revision
670
    parameter, as in "checkout foo/bar -r 5". Note that this will be immediately
671
    out of date [so you cannot commit] but it may be useful (i.e. to examine old
672
    code.)
673
674
    --basis is to speed up checking out from remote branches.  When specified, it
675
    uses the inventory and file contents from the basis branch in preference to the
676
    branch being checked out. [Not implemented yet.]
677
    """
1508.1.28 by Robert Collins
Test using bzr checkout to reconstitute working trees.
678
    takes_args = ['branch_location?', 'to_location?']
1587.1.14 by Robert Collins
Make bound branch creation happen via 'checkout'
679
    takes_options = ['revision', # , 'basis']
680
                     Option('lightweight',
681
                            help="perform a lightweight checkout. Lightweight "
682
                                 "checkouts depend on access to the branch for "
683
                                 "every operation. Normal checkouts can perform "
684
                                 "common operations like diff and status without "
685
                                 "such access, and also support local commits."
686
                            ),
687
                     ]
1508.1.20 by Robert Collins
Create a checkout command.
688
1508.1.28 by Robert Collins
Test using bzr checkout to reconstitute working trees.
689
    def run(self, branch_location=None, to_location=None, revision=None, basis=None,
1587.1.14 by Robert Collins
Make bound branch creation happen via 'checkout'
690
            lightweight=False):
1508.1.20 by Robert Collins
Create a checkout command.
691
        if revision is None:
692
            revision = [None]
693
        elif len(revision) > 1:
694
            raise BzrCommandError(
695
                'bzr checkout --revision takes exactly 1 revision value')
1508.1.28 by Robert Collins
Test using bzr checkout to reconstitute working trees.
696
        if branch_location is None:
697
            branch_location = bzrlib.osutils.getcwd()
698
            to_location = branch_location
1508.1.20 by Robert Collins
Create a checkout command.
699
        source = Branch.open(branch_location)
700
        if len(revision) == 1 and revision[0] is not None:
701
            revision_id = revision[0].in_history(source)[1]
702
        else:
703
            revision_id = None
704
        if to_location is None:
705
            to_location = os.path.basename(branch_location.rstrip("/\\"))
1508.1.28 by Robert Collins
Test using bzr checkout to reconstitute working trees.
706
        # if the source and to_location are the same, 
707
        # and there is no working tree,
708
        # then reconstitute a branch
709
        if (bzrlib.osutils.abspath(to_location) == 
710
            bzrlib.osutils.abspath(branch_location)):
711
            try:
712
                source.bzrdir.open_workingtree()
713
            except errors.NoWorkingTree:
714
                source.bzrdir.create_workingtree()
715
                return
1508.1.20 by Robert Collins
Create a checkout command.
716
        try:
717
            os.mkdir(to_location)
718
        except OSError, e:
719
            if e.errno == errno.EEXIST:
720
                raise BzrCommandError('Target directory "%s" already'
721
                                      ' exists.' % to_location)
722
            if e.errno == errno.ENOENT:
723
                raise BzrCommandError('Parent of "%s" does not exist.' %
724
                                      to_location)
725
            else:
726
                raise
1587.1.14 by Robert Collins
Make bound branch creation happen via 'checkout'
727
        old_format = bzrlib.bzrdir.BzrDirFormat.get_default_format()
728
        bzrlib.bzrdir.BzrDirFormat.set_default_format(bzrdir.BzrDirMetaFormat1())
729
        try:
730
            if lightweight:
731
                checkout = bzrdir.BzrDirMetaFormat1().initialize(to_location)
732
                bzrlib.branch.BranchReferenceFormat().initialize(checkout, source)
733
            else:
734
                checkout_branch =  bzrlib.bzrdir.BzrDir.create_branch_convenience(
735
                    to_location, force_new_tree=False)
736
                checkout = checkout_branch.bzrdir
737
                checkout_branch.bind(source)
738
                if revision_id is not None:
739
                    rh = checkout_branch.revision_history()
740
                    checkout_branch.set_revision_history(rh[:rh.index(revision_id) + 1])
741
            checkout.create_workingtree(revision_id)
742
        finally:
743
            bzrlib.bzrdir.BzrDirFormat.set_default_format(old_format)
1508.1.20 by Robert Collins
Create a checkout command.
744
745
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
746
class cmd_renames(Command):
747
    """Show list of renamed files.
748
    """
1185.16.3 by Martin Pool
- remove all TODOs from bzr help messages
749
    # TODO: Option to show renames between two historical versions.
750
751
    # TODO: Only show renames under dir, rather than in the whole branch.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
752
    takes_args = ['dir?']
753
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
754
    @display_command
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
755
    def run(self, dir=u'.'):
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
756
        tree = WorkingTree.open_containing(dir)[0]
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
757
        old_inv = tree.basis_tree().inventory
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
758
        new_inv = tree.read_working_inventory()
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
759
760
        renames = list(bzrlib.tree.find_renames(old_inv, new_inv))
761
        renames.sort()
762
        for old_name, new_name in renames:
1185.85.32 by John Arbash Meinel
Updated bzr renames
763
            self.outf.write("%s => %s\n" % (old_name, new_name))
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
764
765
1508.1.24 by Robert Collins
Add update command for use with checkouts.
766
class cmd_update(Command):
767
    """Update a tree to have the latest code committed to its branch.
768
    
769
    This will perform a merge into the working tree, and may generate
1587.1.10 by Robert Collins
update updates working tree and branch together.
770
    conflicts. If you have any local changes, you will still 
771
    need to commit them after the update for the update to be complete.
772
    
773
    If you want to discard your local changes, you can just do a 
774
    'bzr revert' instead of 'bzr commit' after the update.
1508.1.24 by Robert Collins
Add update command for use with checkouts.
775
    """
776
    takes_args = ['dir?']
777
778
    def run(self, dir='.'):
779
        tree = WorkingTree.open_containing(dir)[0]
780
        tree.lock_write()
781
        try:
782
            if tree.last_revision() == tree.branch.last_revision():
1587.1.11 by Robert Collins
Local commits appear to be working properly.
783
                # may be up to date, check master too.
784
                master = tree.branch.get_master_branch()
1587.1.14 by Robert Collins
Make bound branch creation happen via 'checkout'
785
                if master is None or master.last_revision == tree.last_revision():
1587.1.11 by Robert Collins
Local commits appear to be working properly.
786
                    note("Tree is up to date.")
787
                    return
1508.1.24 by Robert Collins
Add update command for use with checkouts.
788
            conflicts = tree.update()
789
            note('Updated to revision %d.' %
790
                 (tree.branch.revision_id_to_revno(tree.last_revision()),))
791
            if conflicts != 0:
792
                return 1
793
            else:
794
                return 0
795
        finally:
796
            tree.unlock()
797
798
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
799
class cmd_info(Command):
800
    """Show statistical information about a branch."""
801
    takes_args = ['branch?']
1624.3.21 by Olaf Conradi
Make bzr info command work on both local and remote locations. Support
802
    takes_options = ['verbose']
1624.3.18 by Olaf Conradi
Move to using bzrlib API for blackbox test cases.
803
    
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
804
    @display_command
1624.3.21 by Olaf Conradi
Make bzr info command work on both local and remote locations. Support
805
    def run(self, branch=None, verbose=False):
1534.5.15 by Robert Collins
Review fixups
806
        import bzrlib.info
1624.3.21 by Olaf Conradi
Make bzr info command work on both local and remote locations. Support
807
        bzrlib.info.show_bzrdir_info(bzrdir.BzrDir.open_containing(branch)[0],
808
                                     verbose=verbose)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
809
810
811
class cmd_remove(Command):
812
    """Make a file unversioned.
813
814
    This makes bzr stop tracking changes to a versioned file.  It does
815
    not delete the working copy.
816
    """
817
    takes_args = ['file+']
818
    takes_options = ['verbose']
1424 by Robert Collins
add rm alias to remove
819
    aliases = ['rm']
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
820
    
821
    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
822
        tree, file_list = tree_files(file_list)
1185.12.105 by Aaron Bentley
Substituted branch_files for equivalent code
823
        tree.remove(file_list, verbose=verbose)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
824
825
826
class cmd_file_id(Command):
827
    """Print file_id of a particular file or directory.
828
829
    The file_id is assigned when the file is first added and remains the
830
    same through all revisions where the file exists, even when it is
831
    moved or renamed.
832
    """
833
    hidden = True
834
    takes_args = ['filename']
1185.85.35 by John Arbash Meinel
Updated file-path
835
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
836
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
837
    def run(self, filename):
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
838
        tree, relpath = WorkingTree.open_containing(filename)
839
        i = tree.inventory.path2id(relpath)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
840
        if i == None:
841
            raise BzrError("%r is not a versioned file" % filename)
842
        else:
1185.85.34 by John Arbash Meinel
Updating 'bzr file-id' exposed that we weren't allowing unicode file ids. Enabling them reveals a lot more bugs.
843
            self.outf.write(i)
844
            self.outf.write('\n')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
845
846
847
class cmd_file_path(Command):
848
    """Print path of file_ids to a file or directory.
849
850
    This prints one line for each directory down to the target,
1185.85.35 by John Arbash Meinel
Updated file-path
851
    starting at the branch root.
852
    """
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
853
    hidden = True
854
    takes_args = ['filename']
1185.85.35 by John Arbash Meinel
Updated file-path
855
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
856
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
857
    def run(self, filename):
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
858
        tree, relpath = WorkingTree.open_containing(filename)
859
        inv = tree.inventory
1442.1.64 by Robert Collins
Branch.open_containing now returns a tuple (Branch, relative-path).
860
        fid = inv.path2id(relpath)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
861
        if fid == None:
862
            raise BzrError("%r is not a versioned file" % filename)
863
        for fip in inv.get_idpath(fid):
1185.85.43 by John Arbash Meinel
Found a bug in 'bzr file-path'
864
            self.outf.write(fip)
1185.85.35 by John Arbash Meinel
Updated file-path
865
            self.outf.write('\n')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
866
867
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
868
class cmd_reconcile(Command):
869
    """Reconcile bzr metadata in a branch.
870
871
    This can correct data mismatches that may have been caused by
872
    previous ghost operations or bzr upgrades. You should only
873
    need to run this command if 'bzr check' or a bzr developer 
874
    advises you to run it.
875
876
    If a second branch is provided, cross-branch reconciliation is
877
    also attempted, which will check that data like the tree root
878
    id which was not present in very early bzr versions is represented
879
    correctly in both branches.
880
881
    At the same time it is run it may recompress data resulting in 
882
    a potential saving in disk space or performance gain.
883
884
    The branch *MUST* be on a listable system such as local disk or sftp.
885
    """
886
    takes_args = ['branch?']
887
888
    def run(self, branch="."):
889
        from bzrlib.reconcile import reconcile
890
        dir = bzrlib.bzrdir.BzrDir.open(branch)
891
        reconcile(dir)
892
893
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
894
class cmd_revision_history(Command):
895
    """Display list of revision ids on this branch."""
896
    hidden = True
1185.85.36 by John Arbash Meinel
Working on tests for revision-history, ancestry, and diff
897
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
898
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
899
    def run(self):
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
900
        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
901
        for patchid in branch.revision_history():
1185.85.36 by John Arbash Meinel
Working on tests for revision-history, ancestry, and diff
902
            self.outf.write(patchid)
903
            self.outf.write('\n')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
904
905
1225 by Martin Pool
- branch now tracks ancestry - all merged revisions
906
class cmd_ancestry(Command):
907
    """List all revisions merged into this branch."""
908
    hidden = True
1185.85.36 by John Arbash Meinel
Working on tests for revision-history, ancestry, and diff
909
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
910
    @display_command
1225 by Martin Pool
- branch now tracks ancestry - all merged revisions
911
    def run(self):
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
912
        tree = WorkingTree.open_containing(u'.')[0]
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
913
        b = tree.branch
914
        # FIXME. should be tree.last_revision
1551.3.11 by Aaron Bentley
Merge from Robert
915
        for revision_id in b.repository.get_ancestry(b.last_revision()):
1185.85.42 by John Arbash Meinel
I haven't been running the full test enough. Found some bugs in bzr ancestry.
916
            if revision_id is None:
917
                continue
918
            self.outf.write(revision_id)
919
            self.outf.write('\n')
1225 by Martin Pool
- branch now tracks ancestry - all merged revisions
920
921
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
922
class cmd_init(Command):
923
    """Make a directory into a versioned branch.
924
925
    Use this to create an empty branch, or before importing an
926
    existing project.
927
1662.1.19 by Martin Pool
Better error message when initting existing tree
928
    If there is a repository in a parent directory of the location, then 
929
    the history of the branch will be stored in the repository.  Otherwise
930
    init creates a standalone branch which carries its own history in 
931
    .bzr.
932
933
    If there is already a branch at the location but it has no working tree,
934
    the tree can be populated with 'bzr checkout'.
935
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
936
    Recipe for importing a tree of files:
937
        cd ~/project
938
        bzr init
1185.12.93 by Aaron Bentley
Fixed obsolete help
939
        bzr add .
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
940
        bzr status
941
        bzr commit -m 'imported project'
942
    """
1185.16.138 by Martin Pool
[patch] 'bzr init DIR' (John)
943
    takes_args = ['location?']
1553.5.78 by Martin Pool
New bzr init --format option and test
944
    takes_options = [
945
                     Option('format', 
946
                            help='Create a specific format rather than the'
947
                                 ' current default format. Currently this '
1626.1.3 by Martin Pool
Better help for --format options (Jos Backus)
948
                                 ' option only accepts "metadir"',
1553.5.78 by Martin Pool
New bzr init --format option and test
949
                            type=get_format_type),
950
                     ]
951
    def run(self, location=None, format=None):
1185.16.138 by Martin Pool
[patch] 'bzr init DIR' (John)
952
        from bzrlib.branch import Branch
953
        if location is None:
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
954
            location = u'.'
1185.16.138 by Martin Pool
[patch] 'bzr init DIR' (John)
955
        else:
956
            # The path has to exist to initialize a
957
            # branch inside of it.
958
            # Just using os.mkdir, since I don't
959
            # believe that we want to create a bunch of
960
            # locations if the user supplies an extended path
961
            if not os.path.exists(location):
962
                os.mkdir(location)
1654.1.4 by Robert Collins
Teach `bzr init` how to init at the root of a repository.
963
        try:
1662.1.19 by Martin Pool
Better error message when initting existing tree
964
            existing_bzrdir = bzrdir.BzrDir.open(location)
1654.1.4 by Robert Collins
Teach `bzr init` how to init at the root of a repository.
965
        except NotBranchError:
1662.1.19 by Martin Pool
Better error message when initting existing tree
966
            # really a NotBzrDir error...
1654.1.4 by Robert Collins
Teach `bzr init` how to init at the root of a repository.
967
            bzrdir.BzrDir.create_branch_convenience(location, format=format)
968
        else:
1662.1.19 by Martin Pool
Better error message when initting existing tree
969
            if existing_bzrdir.has_branch():
970
                if existing_bzrdir.has_workingtree():
971
                    raise errors.AlreadyBranchError(location)
972
                else:
973
                    raise errors.BranchExistsWithoutWorkingTree(location)
1654.1.4 by Robert Collins
Teach `bzr init` how to init at the root of a repository.
974
            else:
1662.1.19 by Martin Pool
Better error message when initting existing tree
975
                existing_bzrdir.create_branch()
976
                existing_bzrdir.create_workingtree()
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
977
978
1558.5.6 by Aaron Bentley
Renamed make-repo init-repo
979
class cmd_init_repository(Command):
1658.1.6 by Martin Pool
init-repo shouldn't insist on creating a new directory (Malone #38331)
980
    """Create a shared repository to hold branches.
981
982
    New branches created under the repository directory will store their revisions
983
    in the repository, not in the branch directory, if the branch format supports
984
    shared storage.
985
1662.1.11 by Martin Pool
Better help for init-repo (Erik)
986
    example:
1658.1.6 by Martin Pool
init-repo shouldn't insist on creating a new directory (Malone #38331)
987
        bzr init-repo repo
1662.1.11 by Martin Pool
Better help for init-repo (Erik)
988
        bzr init repo/trunk
989
        bzr checkout --lightweight repo/trunk trunk-checkout
990
        cd trunk-checkout
1658.1.6 by Martin Pool
init-repo shouldn't insist on creating a new directory (Malone #38331)
991
        (add files here)
992
    """
1558.5.6 by Aaron Bentley
Renamed make-repo init-repo
993
    takes_args = ["location"] 
994
    takes_options = [Option('format', 
995
                            help='Use a specific format rather than the'
1624.1.1 by Robert Collins
Trivial ui change to make knits clearly experimental.
996
                            ' current default format. Currently this'
1666.1.10 by Robert Collins
Oops, formating error.
997
                            ' option accepts "weave", "metadir" and "knit"',
1624.2.1 by Erik BÃ¥gfors
support for --tree in bzr init-repo
998
                            type=get_format_type),
1624.2.4 by Erik BÃ¥gfors
rename --tree to --trees
999
                     Option('trees',
1624.2.1 by Erik BÃ¥gfors
support for --tree in bzr init-repo
1000
                             help='Allows branches in repository to have'
1001
                             ' a working tree')]
1558.5.6 by Aaron Bentley
Renamed make-repo init-repo
1002
    aliases = ["init-repo"]
1624.2.4 by Erik BÃ¥gfors
rename --tree to --trees
1003
    def run(self, location, format=None, trees=False):
1558.5.1 by Aaron Bentley
Added make-repository command
1004
        from bzrlib.bzrdir import BzrDirMetaFormat1
1005
        from bzrlib.transport import get_transport
1558.5.6 by Aaron Bentley
Renamed make-repo init-repo
1006
        if format is None:
1007
            format = BzrDirMetaFormat1()
1658.1.6 by Martin Pool
init-repo shouldn't insist on creating a new directory (Malone #38331)
1008
        transport = get_transport(location)
1009
        if not transport.has('.'):
1010
            transport.mkdir('')
1011
        newdir = format.initialize_on_transport(transport)
1558.5.2 by Aaron Bentley
Created *shared* repositories...
1012
        repo = newdir.create_repository(shared=True)
1624.2.4 by Erik BÃ¥gfors
rename --tree to --trees
1013
        repo.set_make_working_trees(trees)
1558.5.1 by Aaron Bentley
Added make-repository command
1014
1015
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1016
class cmd_diff(Command):
1017
    """Show differences in working tree.
1018
    
1019
    If files are listed, only the changes in those files are listed.
1020
    Otherwise, all changes for the tree are listed.
1021
1022
    examples:
1023
        bzr diff
1024
        bzr diff -r1
1185.1.2 by Martin Pool
- merge various windows and other fixes from Ollie Rutherfurd
1025
        bzr diff -r1..2
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1026
    """
1185.16.3 by Martin Pool
- remove all TODOs from bzr help messages
1027
    # TODO: Allow diff across branches.
1028
    # TODO: Option to use external diff command; could be GNU diff, wdiff,
1029
    #       or a graphical diff.
1030
1031
    # TODO: Python difflib is not exactly the same as unidiff; should
1032
    #       either fix it up or prefer to use an external diff.
1033
1034
    # TODO: If a directory is given, diff everything under that.
1035
1036
    # TODO: Selected-file diff is inefficient and doesn't show you
1037
    #       deleted files.
1038
1039
    # TODO: This probably handles non-Unix newlines poorly.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1040
    
1041
    takes_args = ['file*']
1042
    takes_options = ['revision', 'diff-options']
1043
    aliases = ['di', 'dif']
1185.85.36 by John Arbash Meinel
Working on tests for revision-history, ancestry, and diff
1044
    encoding_type = 'exact'
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1045
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1046
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1047
    def run(self, revision=None, file_list=None, diff_options=None):
1551.2.15 by Aaron Bentley
Rename cmd_show_diff to diff_cmd_helper
1048
        from bzrlib.diff import diff_cmd_helper, show_diff_trees
1185.35.28 by Aaron Bentley
Support diff with two branches as input.
1049
        try:
1551.2.13 by Aaron Bentley
Got diff working properly with checkouts
1050
            tree1, file_list = internal_tree_files(file_list)
1051
            tree2 = None
1508.1.15 by Robert Collins
Merge from mpool.
1052
            b = None
1185.35.28 by Aaron Bentley
Support diff with two branches as input.
1053
            b2 = None
1185.35.32 by Aaron Bentley
Fixed handling of files in mixed branches
1054
        except FileInWrongBranch:
1185.35.28 by Aaron Bentley
Support diff with two branches as input.
1055
            if len(file_list) != 2:
1056
                raise BzrCommandError("Files are in different branches")
1057
1551.2.13 by Aaron Bentley
Got diff working properly with checkouts
1058
            tree1, file1 = WorkingTree.open_containing(file_list[0])
1059
            tree2, file2 = WorkingTree.open_containing(file_list[1])
1185.35.28 by Aaron Bentley
Support diff with two branches as input.
1060
            if file1 != "" or file2 != "":
1508.1.15 by Robert Collins
Merge from mpool.
1061
                # FIXME diff those two files. rbc 20051123
1185.35.28 by Aaron Bentley
Support diff with two branches as input.
1062
                raise BzrCommandError("Files are in different branches")
1063
            file_list = None
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1064
        if revision is not None:
1551.2.13 by Aaron Bentley
Got diff working properly with checkouts
1065
            if tree2 is not None:
1185.35.28 by Aaron Bentley
Support diff with two branches as input.
1066
                raise BzrCommandError("Can't specify -r with two branches")
1185.50.44 by John Arbash Meinel
[patch] Robey Pointer: diff -r 1.. should diff against working tree.
1067
            if (len(revision) == 1) or (revision[1].spec is None):
1551.2.15 by Aaron Bentley
Rename cmd_show_diff to diff_cmd_helper
1068
                return diff_cmd_helper(tree1, file_list, diff_options,
1069
                                       revision[0])
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1070
            elif len(revision) == 2:
1551.2.15 by Aaron Bentley
Rename cmd_show_diff to diff_cmd_helper
1071
                return diff_cmd_helper(tree1, file_list, diff_options,
1072
                                       revision[0], revision[1])
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1073
            else:
1074
                raise BzrCommandError('bzr diff --revision takes exactly one or two revision identifiers')
1075
        else:
1551.2.13 by Aaron Bentley
Got diff working properly with checkouts
1076
            if tree2 is not None:
1077
                return show_diff_trees(tree1, tree2, sys.stdout, 
1078
                                       specific_files=file_list,
1079
                                       external_diff_options=diff_options)
1508.1.15 by Robert Collins
Merge from mpool.
1080
            else:
1551.2.15 by Aaron Bentley
Rename cmd_show_diff to diff_cmd_helper
1081
                return diff_cmd_helper(tree1, file_list, diff_options)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1082
1083
1084
class cmd_deleted(Command):
1085
    """List files deleted in the working tree.
1086
    """
1185.16.3 by Martin Pool
- remove all TODOs from bzr help messages
1087
    # TODO: Show files deleted since a previous revision, or
1088
    # between two revisions.
1089
    # TODO: Much more efficient way to do this: read in new
1090
    # directories with readdir, rather than stating each one.  Same
1091
    # level of effort but possibly much less IO.  (Or possibly not,
1092
    # if the directories are very large...)
1185.85.49 by John Arbash Meinel
Updated cmd_deleted, including adding --show-ids option.
1093
    takes_options = ['show-ids']
1094
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1095
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1096
    def run(self, show_ids=False):
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
1097
        tree = WorkingTree.open_containing(u'.')[0]
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
1098
        old = tree.basis_tree()
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1099
        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
1100
            if not tree.has_id(ie.file_id):
1185.85.49 by John Arbash Meinel
Updated cmd_deleted, including adding --show-ids option.
1101
                self.outf.write(path)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1102
                if show_ids:
1185.85.49 by John Arbash Meinel
Updated cmd_deleted, including adding --show-ids option.
1103
                    self.outf.write(' ')
1104
                    self.outf.write(ie.file_id)
1105
                self.outf.write('\n')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1106
1107
1108
class cmd_modified(Command):
1109
    """List files modified in working tree."""
1110
    hidden = True
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1111
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1112
    def run(self):
1113
        from bzrlib.delta import compare_trees
1114
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
1115
        tree = WorkingTree.open_containing(u'.')[0]
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
1116
        td = compare_trees(tree.basis_tree(), tree)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1117
1398 by Robert Collins
integrate in Gustavos x-bit patch
1118
        for path, id, kind, text_modified, meta_modified in td.modified:
1185.85.50 by John Arbash Meinel
Updated cmd_modified
1119
            self.outf.write(path)
1120
            self.outf.write('\n')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1121
1122
1123
class cmd_added(Command):
1124
    """List files added in working tree."""
1125
    hidden = True
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1126
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1127
    def run(self):
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
1128
        wt = WorkingTree.open_containing(u'.')[0]
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
1129
        basis_inv = wt.basis_tree().inventory
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1130
        inv = wt.inventory
1131
        for file_id in inv:
1132
            if file_id in basis_inv:
1133
                continue
1134
            path = inv.id2path(file_id)
1548 by Martin Pool
Fix 'bzr added' typo, and tests for that command.
1135
            if not os.access(bzrlib.osutils.abspath(path), os.F_OK):
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1136
                continue
1185.85.52 by John Arbash Meinel
Updated cmd_added, which obviously had no tests, because it had a bug in it.
1137
            self.outf.write(path)
1138
            self.outf.write('\n')
1185.85.53 by John Arbash Meinel
Updated cmd_root
1139
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1140
1141
class cmd_root(Command):
1142
    """Show the tree root directory.
1143
1144
    The root is the nearest enclosing directory with a .bzr control
1145
    directory."""
1146
    takes_args = ['filename?']
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1147
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1148
    def run(self, filename=None):
1149
        """Print the branch root."""
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
1150
        tree = WorkingTree.open_containing(filename)[0]
1185.85.53 by John Arbash Meinel
Updated cmd_root
1151
        self.outf.write(tree.basedir)
1152
        self.outf.write('\n')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1153
1154
1155
class cmd_log(Command):
1626.1.2 by Martin Pool
Better help message for log command.
1156
    """Show log of a branch, file, or directory.
1157
1158
    By default show the log of the branch containing the working directory.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1159
1185.16.153 by Martin Pool
[patch] fix help for bzr log (Matthieu)
1160
    To request a range of logs, you can use the command -r begin..end
1161
    -r revision requests a specific revision, -r ..end or -r begin.. are
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1162
    also valid.
1626.1.2 by Martin Pool
Better help message for log command.
1163
1164
    examples:
1165
        bzr log
1166
        bzr log foo.c
1167
        bzr log -r -10.. http://server/branch
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1168
    """
1169
1393.1.55 by Martin Pool
doc
1170
    # TODO: Make --revision support uuid: and hash: [future tag:] notation.
1171
1626.1.2 by Martin Pool
Better help message for log command.
1172
    takes_args = ['location?']
1185.16.46 by mbp at sourcefrog
- add help strings to some options
1173
    takes_options = [Option('forward', 
1174
                            help='show from oldest to newest'),
1626.1.2 by Martin Pool
Better help message for log command.
1175
                     'timezone', 
1176
                     Option('verbose', 
1177
                             help='show files changed in each revision'),
1185.16.46 by mbp at sourcefrog
- add help strings to some options
1178
                     'show-ids', 'revision',
1553.2.1 by Erik BÃ¥gfors
Support for plugins to register log formatters and set default formatter
1179
                     'log-format',
1185.54.12 by Aaron Bentley
Added log formatter selection and show-ids to missing
1180
                     'line', 'long', 
1185.16.46 by mbp at sourcefrog
- add help strings to some options
1181
                     Option('message',
1185.16.48 by mbp at sourcefrog
- more refactoring of and tests for option parsing
1182
                            help='show revisions whose message matches this regexp',
1183
                            type=str),
1185.54.12 by Aaron Bentley
Added log formatter selection and show-ids to missing
1184
                     'short',
1185.16.57 by Martin Pool
[merge] from aaron
1185
                     ]
1185.85.22 by John Arbash Meinel
Updated cmd_inventory. Changing from having each Command request an encoded stdout to providing one before calling run()
1186
    encoding_type = 'replace'
1187
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1188
    @display_command
1626.1.2 by Martin Pool
Better help message for log command.
1189
    def run(self, location=None, timezone='original',
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1190
            verbose=False,
1191
            show_ids=False,
1192
            forward=False,
1193
            revision=None,
1553.2.1 by Erik BÃ¥gfors
Support for plugins to register log formatters and set default formatter
1194
            log_format=None,
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1195
            message=None,
1196
            long=False,
1185.12.25 by Aaron Bentley
Added one-line log format
1197
            short=False,
1198
            line=False):
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1199
        from bzrlib.log import log_formatter, show_log
1185.16.49 by mbp at sourcefrog
- more refactoring and tests of commandline
1200
        assert message is None or isinstance(message, basestring), \
1185.16.48 by mbp at sourcefrog
- more refactoring of and tests for option parsing
1201
            "invalid message argument %r" % message
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1202
        direction = (forward and 'forward') or 'reverse'
1203
        
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1204
        # log everything
1205
        file_id = None
1626.1.2 by Martin Pool
Better help message for log command.
1206
        if location:
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1207
            # find the file id to log:
1208
1626.1.2 by Martin Pool
Better help message for log command.
1209
            dir, fp = bzrdir.BzrDir.open_containing(location)
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1210
            b = dir.open_branch()
1442.1.64 by Robert Collins
Branch.open_containing now returns a tuple (Branch, relative-path).
1211
            if fp != '':
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1212
                try:
1213
                    # might be a tree:
1214
                    inv = dir.open_workingtree().inventory
1215
                except (errors.NotBranchError, errors.NotLocalUrl):
1216
                    # either no tree, or is remote.
1217
                    inv = b.basis_tree().inventory
1497 by Robert Collins
Move Branch.read_working_inventory to WorkingTree.
1218
                file_id = inv.path2id(fp)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1219
        else:
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1220
            # local dir only
1221
            # FIXME ? log the current subdir only RBC 20060203 
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1222
            dir, relpath = bzrdir.BzrDir.open_containing('.')
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1223
            b = dir.open_branch()
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1224
1225
        if revision is None:
1226
            rev1 = None
1227
            rev2 = None
1228
        elif len(revision) == 1:
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
1229
            rev1 = rev2 = revision[0].in_history(b).revno
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1230
        elif len(revision) == 2:
1553.4.2 by Michael Ellerman
Make bzr log -r .. work, fixes bug #4609. Add a bunch of tests to make sure
1231
            if revision[0].spec is None:
1232
                # missing begin-range means first revision
1233
                rev1 = 1
1234
            else:
1235
                rev1 = revision[0].in_history(b).revno
1236
1540.2.6 by Robey Pointer
make 'log' and 'status' treat '-r N..' as implicitly '-r N..-1'
1237
            if revision[1].spec is None:
1238
                # missing end-range means last known revision
1239
                rev2 = b.revno()
1240
            else:
1241
                rev2 = revision[1].in_history(b).revno
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1242
        else:
1243
            raise BzrCommandError('bzr log --revision takes one or two values.')
1244
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
1245
        # By this point, the revision numbers are converted to the +ve
1246
        # form if they were supplied in the -ve form, so we can do
1247
        # this comparison in relative safety
1248
        if rev1 > rev2:
1249
            (rev2, rev1) = (rev1, rev2)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1250
1553.2.1 by Erik BÃ¥gfors
Support for plugins to register log formatters and set default formatter
1251
        if (log_format == None):
1553.2.9 by Erik BÃ¥gfors
log_formatter => log_format for "named" formatters
1252
            default = bzrlib.config.BranchConfig(b).log_format()
1553.2.4 by Erik BÃ¥gfors
Support for setting the default log format at a configuration option
1253
            log_format = get_log_format(long=long, short=short, line=line, default=default)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1254
        lf = log_formatter(log_format,
1255
                           show_ids=show_ids,
1185.85.22 by John Arbash Meinel
Updated cmd_inventory. Changing from having each Command request an encoded stdout to providing one before calling run()
1256
                           to_file=self.outf,
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1257
                           show_timezone=timezone)
1258
1259
        show_log(b,
1260
                 lf,
1261
                 file_id,
1262
                 verbose=verbose,
1263
                 direction=direction,
1264
                 start_revision=rev1,
1265
                 end_revision=rev2,
1266
                 search=message)
1267
1185.85.4 by John Arbash Meinel
currently broken, trying to fix things up.
1268
1553.2.4 by Erik BÃ¥gfors
Support for setting the default log format at a configuration option
1269
def get_log_format(long=False, short=False, line=False, default='long'):
1185.54.12 by Aaron Bentley
Added log formatter selection and show-ids to missing
1270
    log_format = default
1271
    if long:
1272
        log_format = 'long'
1273
    if short:
1274
        log_format = 'short'
1275
    if line:
1276
        log_format = 'line'
1277
    return log_format
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1278
1279
1280
class cmd_touching_revisions(Command):
1281
    """Return revision-ids which affected a particular file.
1282
1283
    A more user-friendly interface is "bzr log FILE"."""
1284
    hidden = True
1285
    takes_args = ["filename"]
1185.85.55 by John Arbash Meinel
Updated cmd_touching_revisions
1286
    encoding_type = 'replace'
1287
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1288
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1289
    def run(self, filename):
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
1290
        tree, relpath = WorkingTree.open_containing(filename)
1291
        b = tree.branch
1292
        inv = tree.read_working_inventory()
1442.1.64 by Robert Collins
Branch.open_containing now returns a tuple (Branch, relative-path).
1293
        file_id = inv.path2id(relpath)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1294
        for revno, revision_id, what in bzrlib.log.find_touching_revisions(b, file_id):
1185.85.55 by John Arbash Meinel
Updated cmd_touching_revisions
1295
            self.outf.write("%6d %s\n" % (revno, what))
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1296
1297
1298
class cmd_ls(Command):
1299
    """List files in a tree.
1300
    """
1185.16.3 by Martin Pool
- remove all TODOs from bzr help messages
1301
    # TODO: Take a revision or remote path and list that tree instead.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1302
    hidden = True
1185.26.1 by John Arbash Meinel
Made ls work again, and take extra arguments.
1303
    takes_options = ['verbose', 'revision',
1304
                     Option('non-recursive',
1305
                            help='don\'t recurse into sub-directories'),
1306
                     Option('from-root',
1307
                            help='Print all paths from the root of the branch.'),
1308
                     Option('unknown', help='Print unknown files'),
1309
                     Option('versioned', help='Print versioned files'),
1310
                     Option('ignored', help='Print ignored files'),
1311
1312
                     Option('null', help='Null separate the files'),
1313
                    ]
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1314
    @display_command
1185.26.1 by John Arbash Meinel
Made ls work again, and take extra arguments.
1315
    def run(self, revision=None, verbose=False, 
1316
            non_recursive=False, from_root=False,
1317
            unknown=False, versioned=False, ignored=False,
1318
            null=False):
1319
1320
        if verbose and null:
1321
            raise BzrCommandError('Cannot set both --verbose and --null')
1322
        all = not (unknown or versioned or ignored)
1323
1324
        selection = {'I':ignored, '?':unknown, 'V':versioned}
1325
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
1326
        tree, relpath = WorkingTree.open_containing(u'.')
1185.26.1 by John Arbash Meinel
Made ls work again, and take extra arguments.
1327
        if from_root:
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
1328
            relpath = u''
1185.26.1 by John Arbash Meinel
Made ls work again, and take extra arguments.
1329
        elif relpath:
1330
            relpath += '/'
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
1331
        if revision is not None:
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
1332
            tree = tree.branch.repository.revision_tree(
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
1333
                revision[0].in_history(tree.branch).rev_id)
1185.85.13 by John Arbash Meinel
Moving bzr ls to encoded output.
1334
1399.1.2 by Robert Collins
push kind character creation into InventoryEntry and TreeEntry
1335
        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.
1336
            if fp.startswith(relpath):
1337
                fp = fp[len(relpath):]
1338
                if non_recursive and '/' in fp:
1339
                    continue
1340
                if not all and not selection[fc]:
1341
                    continue
1342
                if verbose:
1343
                    kindch = entry.kind_character()
1185.85.22 by John Arbash Meinel
Updated cmd_inventory. Changing from having each Command request an encoded stdout to providing one before calling run()
1344
                    self.outf.write('%-8s %s%s\n' % (fc, fp, kindch))
1185.26.1 by John Arbash Meinel
Made ls work again, and take extra arguments.
1345
                elif null:
1185.85.22 by John Arbash Meinel
Updated cmd_inventory. Changing from having each Command request an encoded stdout to providing one before calling run()
1346
                    self.outf.write(fp)
1347
                    self.outf.write('\0')
1348
                    self.outf.flush()
1185.26.1 by John Arbash Meinel
Made ls work again, and take extra arguments.
1349
                else:
1185.85.22 by John Arbash Meinel
Updated cmd_inventory. Changing from having each Command request an encoded stdout to providing one before calling run()
1350
                    self.outf.write(fp)
1351
                    self.outf.write('\n')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1352
1353
1354
class cmd_unknowns(Command):
1355
    """List unknown files."""
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1356
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1357
    def run(self):
1358
        from bzrlib.osutils import quotefn
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
1359
        for f in WorkingTree.open_containing(u'.')[0].unknowns():
1185.85.57 by John Arbash Meinel
Updated cmd_unknowns
1360
            self.outf.write(quotefn(f))
1361
            self.outf.write('\n')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1362
1363
1364
class cmd_ignore(Command):
1365
    """Ignore a command or pattern.
1366
1367
    To remove patterns from the ignore list, edit the .bzrignore file.
1368
1369
    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
1370
    from the branch root.  Otherwise, it is compared to only the last
1371
    component of the path.  To match a file only in the root directory,
1372
    prepend './'.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1373
1374
    Ignore patterns are case-insensitive on case-insensitive systems.
1375
1376
    Note: wildcards must be quoted from the shell on Unix.
1377
1378
    examples:
1379
        bzr ignore ./Makefile
1380
        bzr ignore '*.class'
1381
    """
1185.16.4 by Martin Pool
- doc and todo for ignore command
1382
    # TODO: Complain if the filename is absolute
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1383
    takes_args = ['name_pattern']
1384
    
1385
    def run(self, name_pattern):
1386
        from bzrlib.atomicfile import AtomicFile
1387
        import os.path
1388
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
1389
        tree, relpath = WorkingTree.open_containing(u'.')
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
1390
        ifn = tree.abspath('.bzrignore')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1391
1392
        if os.path.exists(ifn):
1393
            f = open(ifn, 'rt')
1394
            try:
1395
                igns = f.read().decode('utf-8')
1396
            finally:
1397
                f.close()
1398
        else:
1399
            igns = ''
1400
1401
        # TODO: If the file already uses crlf-style termination, maybe
1402
        # we should use that for the newly added lines?
1403
1404
        if igns and igns[-1] != '\n':
1405
            igns += '\n'
1406
        igns += name_pattern + '\n'
1407
1408
        try:
1409
            f = AtomicFile(ifn, 'wt')
1410
            f.write(igns.encode('utf-8'))
1411
            f.commit()
1412
        finally:
1413
            f.close()
1414
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
1415
        inv = tree.inventory
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1416
        if inv.path2id('.bzrignore'):
1417
            mutter('.bzrignore is already versioned')
1418
        else:
1419
            mutter('need to make new .bzrignore file versioned')
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
1420
            tree.add(['.bzrignore'])
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1421
1422
1423
class cmd_ignored(Command):
1424
    """List ignored files and the patterns that matched them.
1425
1426
    See also: bzr ignore"""
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1427
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1428
    def run(self):
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
1429
        tree = WorkingTree.open_containing(u'.')[0]
1399.1.2 by Robert Collins
push kind character creation into InventoryEntry and TreeEntry
1430
        for path, file_class, kind, file_id, entry in tree.list_files():
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1431
            if file_class != 'I':
1432
                continue
1433
            ## XXX: Slightly inefficient since this was already calculated
1434
            pat = tree.is_ignored(path)
1435
            print '%-50s %s' % (path, pat)
1436
1437
1438
class cmd_lookup_revision(Command):
1439
    """Lookup the revision-id from a revision-number
1440
1441
    example:
1442
        bzr lookup-revision 33
1443
    """
1444
    hidden = True
1445
    takes_args = ['revno']
1446
    
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1447
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1448
    def run(self, revno):
1449
        try:
1450
            revno = int(revno)
1451
        except ValueError:
1452
            raise BzrCommandError("not a valid revision-number: %r" % revno)
1453
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
1454
        print WorkingTree.open_containing(u'.')[0].branch.get_rev_id(revno)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1455
1456
1457
class cmd_export(Command):
1458
    """Export past revision to destination directory.
1459
1460
    If no revision is specified this exports the last committed revision.
1461
1462
    Format may be an "exporter" name, such as tar, tgz, tbz2.  If none is
1463
    given, try to find the format with the extension. If no extension
1464
    is found exports to a directory (equivalent to --format=dir).
1465
1466
    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
1467
    is given, the top directory will be the root name of the file.
1468
1469
    Note: export of tree with non-ascii filenames to zip is not supported.
1470
1551.3.11 by Aaron Bentley
Merge from Robert
1471
     Supported formats       Autodetected by extension
1472
     -----------------       -------------------------
1185.31.11 by John Arbash Meinel
Merging Alexander's zip export patch
1473
         dir                            -
1474
         tar                          .tar
1475
         tbz2                    .tar.bz2, .tbz2
1476
         tgz                      .tar.gz, .tgz
1477
         zip                          .zip
1478
    """
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1479
    takes_args = ['dest']
1480
    takes_options = ['revision', 'format', 'root']
1481
    def run(self, dest, revision=None, format=None, root=None):
1482
        import os.path
1185.31.12 by John Arbash Meinel
Refactored the export code to make it easier to add new export formats.
1483
        from bzrlib.export import export
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
1484
        tree = WorkingTree.open_containing(u'.')[0]
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
1485
        b = tree.branch
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1486
        if revision is None:
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
1487
            # should be tree.last_revision  FIXME
1241 by Martin Pool
- rename last_patch to last_revision
1488
            rev_id = b.last_revision()
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1489
        else:
1490
            if len(revision) != 1:
1491
                raise BzrError('bzr export --revision takes exactly 1 argument')
1185.11.5 by John Arbash Meinel
Merged up-to-date against mainline, still broken.
1492
            rev_id = revision[0].in_history(b).rev_id
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
1493
        t = b.repository.revision_tree(rev_id)
1185.31.12 by John Arbash Meinel
Refactored the export code to make it easier to add new export formats.
1494
        try:
1495
            export(t, dest, format, root)
1496
        except errors.NoSuchExportFormat, e:
1497
            raise BzrCommandError('Unsupported export format: %s' % e.format)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1498
1499
1500
class cmd_cat(Command):
1501
    """Write a file's text from a previous revision."""
1502
1503
    takes_options = ['revision']
1504
    takes_args = ['filename']
1505
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1506
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1507
    def run(self, filename, revision=None):
1185.50.9 by John Arbash Meinel
[bug 3632] Matthieu Moy- bzr cat should default to last revision
1508
        if revision is not None and len(revision) != 1:
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1509
            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
1510
        tree = None
1511
        try:
1512
            tree, relpath = WorkingTree.open_containing(filename)
1513
            b = tree.branch
1514
        except NotBranchError:
1515
            pass
1185.50.9 by John Arbash Meinel
[bug 3632] Matthieu Moy- bzr cat should default to last revision
1516
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
1517
        if tree is None:
1518
            b, relpath = Branch.open_containing(filename)
1185.50.9 by John Arbash Meinel
[bug 3632] Matthieu Moy- bzr cat should default to last revision
1519
        if revision is None:
1520
            revision_id = b.last_revision()
1521
        else:
1522
            revision_id = revision[0].in_history(b).rev_id
1523
        b.print_file(relpath, revision_id)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1524
1525
1526
class cmd_local_time_offset(Command):
1527
    """Show the offset in seconds from GMT to local time."""
1528
    hidden = True    
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1529
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1530
    def run(self):
1531
        print bzrlib.osutils.local_time_offset()
1532
1533
1534
1535
class cmd_commit(Command):
1536
    """Commit changes into a new revision.
1537
    
1538
    If no arguments are given, the entire tree is committed.
1539
1540
    If selected files are specified, only changes to those files are
1541
    committed.  If a directory is specified then the directory and everything 
1542
    within it is committed.
1543
1544
    A selected-file commit may fail in some cases where the committed
1545
    tree would be invalid, such as trying to commit a file in a
1546
    newly-added directory that is not itself committed.
1547
    """
1185.16.3 by Martin Pool
- remove all TODOs from bzr help messages
1548
    # TODO: Run hooks on tree to-be-committed, and after commit.
1549
1185.16.65 by mbp at sourcefrog
- new commit --strict option
1550
    # TODO: Strict commit that fails if there are deleted files.
1551
    #       (what does "deleted files" mean ??)
1552
1185.16.3 by Martin Pool
- remove all TODOs from bzr help messages
1553
    # TODO: Give better message for -s, --summary, used by tla people
1554
1555
    # XXX: verbose currently does nothing
1556
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1557
    takes_args = ['selected*']
1185.16.48 by mbp at sourcefrog
- more refactoring of and tests for option parsing
1558
    takes_options = ['message', 'verbose', 
1559
                     Option('unchanged',
1560
                            help='commit even if nothing has changed'),
1561
                     Option('file', type=str, 
1562
                            argname='msgfile',
1563
                            help='file containing commit message'),
1185.16.65 by mbp at sourcefrog
- new commit --strict option
1564
                     Option('strict',
1565
                            help="refuse to commit if there are unknown "
1566
                            "files in the working tree."),
1587.1.8 by Robert Collins
Local commits on unbound branches fail.
1567
                     Option('local',
1568
                            help="perform a local only commit in a bound "
1569
                                 "branch. Such commits are not pushed to "
1570
                                 "the master branch until a normal commit "
1571
                                 "is performed."
1572
                            ),
1185.16.43 by Martin Pool
- clean up handling of option objects
1573
                     ]
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1574
    aliases = ['ci', 'checkin']
1575
1576
    def run(self, message=None, file=None, verbose=True, selected_list=None,
1587.1.8 by Robert Collins
Local commits on unbound branches fail.
1577
            unchanged=False, strict=False, local=False):
1607.1.5 by Robert Collins
Make commit verbose mode work!.
1578
        from bzrlib.commit import (NullCommitReporter, ReportCommitToLog)
1185.16.65 by mbp at sourcefrog
- new commit --strict option
1579
        from bzrlib.errors import (PointlessCommit, ConflictsInTree,
1580
                StrictCommitFailed)
1185.33.76 by Martin Pool
Fix import error.
1581
        from bzrlib.msgeditor import edit_commit_message, \
1582
                make_commit_message_template
1185.33.72 by Martin Pool
Fix commit message template for non-ascii files, and add test for handling of
1583
        from tempfile import TemporaryFile
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1584
1185.33.77 by Martin Pool
doc
1585
        # TODO: Need a blackbox test for invoking the external editor; may be
1586
        # slightly problematic to run this cross-platform.
1587
1185.33.72 by Martin Pool
Fix commit message template for non-ascii files, and add test for handling of
1588
        # TODO: do more checks that the commit will succeed before 
1589
        # spending the user's valuable time typing a commit message.
1590
        #
1591
        # TODO: if the commit *does* happen to fail, then save the commit 
1592
        # 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
1593
        tree, selected_list = tree_files(selected_list)
1587.1.8 by Robert Collins
Local commits on unbound branches fail.
1594
        if local and not tree.branch.get_bound_location():
1595
            raise errors.LocalRequiresBoundBranch()
1414 by Robert Collins
merge in an adjusted version of Jelmer's empty-log detection patch.
1596
        if message is None and not file:
1185.33.76 by Martin Pool
Fix import error.
1597
            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
1598
            message = edit_commit_message(template)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1599
            if message is None:
1169 by Martin Pool
- clean up nasty code for inserting the status summary into commit template
1600
                raise BzrCommandError("please specify a commit message"
1601
                                      " with either --message or --file")
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1602
        elif message and file:
1603
            raise BzrCommandError("please specify either --message or --file")
1604
        
1605
        if file:
1606
            message = codecs.open(file, 'rt', bzrlib.user_encoding).read()
1607
1414 by Robert Collins
merge in an adjusted version of Jelmer's empty-log detection patch.
1608
        if message == "":
1609
                raise BzrCommandError("empty commit message specified")
1607.1.5 by Robert Collins
Make commit verbose mode work!.
1610
        
1611
        if verbose:
1612
            reporter = ReportCommitToLog()
1613
        else:
1614
            reporter = NullCommitReporter()
1615
        
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1616
        try:
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
1617
            tree.commit(message, specific_files=selected_list,
1607.1.5 by Robert Collins
Make commit verbose mode work!.
1618
                        allow_pointless=unchanged, strict=strict, local=local,
1619
                        reporter=reporter)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1620
        except PointlessCommit:
1621
            # FIXME: This should really happen before the file is read in;
1622
            # perhaps prepare the commit; get the message; then actually commit
1623
            raise BzrCommandError("no changes to commit",
1624
                                  ["use --unchanged to commit anyhow"])
1185.14.10 by Aaron Bentley
Commit aborts with conflicts in the tree.
1625
        except ConflictsInTree:
1626
            raise BzrCommandError("Conflicts detected in working tree.  "
1627
                'Use "bzr conflicts" to list, "bzr resolve FILE" to resolve.')
1185.16.65 by mbp at sourcefrog
- new commit --strict option
1628
        except StrictCommitFailed:
1629
            raise BzrCommandError("Commit refused because there are unknown "
1630
                                  "files in the working tree.")
1505.1.24 by John Arbash Meinel
Updated commit to handle bound branches. Included test to handle commit after merge
1631
        except errors.BoundBranchOutOfDate, e:
1632
            raise BzrCommandError(str(e)
1587.1.12 by Robert Collins
Update help message to be more bound branch friendly.
1633
                                  + ' Either unbind, update, or'
1634
                                    ' pass --local to commit.')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1635
1636
1637
class cmd_check(Command):
1638
    """Validate consistency of branch history.
1639
1640
    This command checks various invariants about the branch storage to
1641
    detect data corruption or bzr bugs.
1642
    """
1512 by Robert Collins
Merge from Martin. Adjust check to work with HTTP again.
1643
    takes_args = ['branch?']
1449 by Robert Collins
teach check about ghosts
1644
    takes_options = ['verbose']
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1645
1512 by Robert Collins
Merge from Martin. Adjust check to work with HTTP again.
1646
    def run(self, branch=None, verbose=False):
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1647
        from bzrlib.check import check
1512 by Robert Collins
Merge from Martin. Adjust check to work with HTTP again.
1648
        if branch is None:
1649
            tree = WorkingTree.open_containing()[0]
1650
            branch = tree.branch
1651
        else:
1652
            branch = Branch.open(branch)
1653
        check(branch, verbose)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1654
1655
1656
class cmd_scan_cache(Command):
1657
    hidden = True
1658
    def run(self):
1659
        from bzrlib.hashcache import HashCache
1660
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
1661
        c = HashCache(u'.')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1662
        c.read()
1663
        c.scan()
1664
            
1665
        print '%6d stats' % c.stat_count
1666
        print '%6d in hashcache' % len(c._cache)
1667
        print '%6d files removed from cache' % c.removed_count
1668
        print '%6d hashes updated' % c.update_count
1669
        print '%6d files changed too recently to cache' % c.danger_count
1670
1671
        if c.needs_write:
1672
            c.write()
1534.5.16 by Robert Collins
Review feedback.
1673
1674
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1675
class cmd_upgrade(Command):
1676
    """Upgrade branch storage to current format.
1677
1678
    The check command or bzr developers may sometimes advise you to run
1534.4.13 by Robert Collins
Give a reasonable warning on attempts to upgrade a readonly url.
1679
    this command. When the default format has changed you may also be warned
1680
    during other operations to upgrade.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1681
    """
1534.4.13 by Robert Collins
Give a reasonable warning on attempts to upgrade a readonly url.
1682
    takes_args = ['url?']
1534.5.13 by Robert Collins
Correct buggy test.
1683
    takes_options = [
1684
                     Option('format', 
1685
                            help='Upgrade to a specific format rather than the'
1624.1.1 by Robert Collins
Trivial ui change to make knits clearly experimental.
1686
                                 ' current default format. Currently this'
1666.1.10 by Robert Collins
Oops, formating error.
1687
                                 ' option accepts "weave", "metadir" and'
1688
                                 ' "knit".',
1534.5.13 by Robert Collins
Correct buggy test.
1689
                            type=get_format_type),
1690
                    ]
1691
1692
1693
    def run(self, url='.', format=None):
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1694
        from bzrlib.upgrade import upgrade
1534.5.13 by Robert Collins
Correct buggy test.
1695
        upgrade(url, format)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1696
1697
1698
class cmd_whoami(Command):
1699
    """Show bzr user id."""
1700
    takes_options = ['email']
1701
    
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1702
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1703
    def run(self, email=False):
1371 by Martin Pool
- raise NotBranchError if format file can't be read
1704
        try:
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
1705
            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
1706
            config = bzrlib.config.BranchConfig(b)
1371 by Martin Pool
- raise NotBranchError if format file can't be read
1707
        except NotBranchError:
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1708
            config = bzrlib.config.GlobalConfig()
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1709
        
1710
        if email:
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1711
            print config.user_email()
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1712
        else:
1442.1.6 by Robert Collins
first stage major overhaul of configs, giving use BranchConfigs, LocationConfigs and GlobalConfigs
1713
            print config.username()
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1714
1534.4.25 by Robert Collins
Add a --transport parameter to the test suite to set the default transport to be used in the test suite.
1715
1185.35.14 by Aaron Bentley
Implemented nick command
1716
class cmd_nick(Command):
1551.3.11 by Aaron Bentley
Merge from Robert
1717
    """Print or set the branch nickname.  
1718
1185.35.14 by Aaron Bentley
Implemented nick command
1719
    If unset, the tree root directory name is used as the nickname
1720
    To print the current nickname, execute with no argument.  
1721
    """
1722
    takes_args = ['nickname?']
1723
    def run(self, nickname=None):
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
1724
        branch = Branch.open_containing(u'.')[0]
1185.35.14 by Aaron Bentley
Implemented nick command
1725
        if nickname is None:
1726
            self.printme(branch)
1727
        else:
1728
            branch.nick = nickname
1729
1730
    @display_command
1731
    def printme(self, branch):
1732
        print branch.nick 
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1733
1534.4.25 by Robert Collins
Add a --transport parameter to the test suite to set the default transport to be used in the test suite.
1734
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1735
class cmd_selftest(Command):
1393.1.46 by Martin Pool
- bzr selftest arguments can be partial ids of tests to run
1736
    """Run internal test suite.
1737
    
1738
    This creates temporary test directories in the working directory,
1739
    but not existing data is affected.  These directories are deleted
1740
    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
1741
    fail and --keep-output is specified.
1393.1.46 by Martin Pool
- bzr selftest arguments can be partial ids of tests to run
1742
    
1743
    If arguments are given, they are regular expressions that say
1185.16.58 by mbp at sourcefrog
- run all selftests by default
1744
    which tests should run.
1552 by Martin Pool
Improved help text for bzr selftest
1745
1746
    If the global option '--no-plugins' is given, plugins are not loaded
1747
    before running the selftests.  This has two effects: features provided or
1748
    modified by plugins will not be tested, and tests provided by plugins will
1749
    not be run.
1750
1751
    examples:
1752
        bzr selftest ignore
1753
        bzr --no-plugins selftest -v
1185.16.58 by mbp at sourcefrog
- run all selftests by default
1754
    """
1393.1.46 by Martin Pool
- bzr selftest arguments can be partial ids of tests to run
1755
    # TODO: --list should give a list of all available tests
1534.4.25 by Robert Collins
Add a --transport parameter to the test suite to set the default transport to be used in the test suite.
1756
1757
    # NB: this is used from the class without creating an instance, which is
1758
    # why it does not have a self parameter.
1759
    def get_transport_type(typestring):
1760
        """Parse and return a transport specifier."""
1761
        if typestring == "sftp":
1762
            from bzrlib.transport.sftp import SFTPAbsoluteServer
1763
            return SFTPAbsoluteServer
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
1764
        if typestring == "memory":
1765
            from bzrlib.transport.memory import MemoryServer
1766
            return MemoryServer
1558.10.1 by Aaron Bentley
Handle lockdirs over NFS properly
1767
        if typestring == "fakenfs":
1558.10.2 by Robert Collins
Refactor the FakeNFS support into a TransportDecorator.
1768
            from bzrlib.transport.fakenfs import FakeNFSServer
1558.10.1 by Aaron Bentley
Handle lockdirs over NFS properly
1769
            return FakeNFSServer
1534.4.25 by Robert Collins
Add a --transport parameter to the test suite to set the default transport to be used in the test suite.
1770
        msg = "No known transport type %s. Supported types are: sftp\n" %\
1771
            (typestring)
1772
        raise BzrCommandError(msg)
1773
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1774
    hidden = True
1185.1.57 by Robert Collins
nuke --pattern to selftest, replace with regexp.search calls.
1775
    takes_args = ['testspecs*']
1552 by Martin Pool
Improved help text for bzr selftest
1776
    takes_options = ['verbose',
1185.16.58 by mbp at sourcefrog
- run all selftests by default
1777
                     Option('one', help='stop when one test fails'),
1185.35.20 by Aaron Bentley
Only keep test failure directories if --keep-output is specified
1778
                     Option('keep-output', 
1534.4.25 by Robert Collins
Add a --transport parameter to the test suite to set the default transport to be used in the test suite.
1779
                            help='keep output directories when tests fail'),
1780
                     Option('transport', 
1781
                            help='Use a different transport by default '
1782
                                 'throughout the test suite.',
1783
                            type=get_transport_type),
1185.16.58 by mbp at sourcefrog
- run all selftests by default
1784
                    ]
1785
1185.35.20 by Aaron Bentley
Only keep test failure directories if --keep-output is specified
1786
    def run(self, testspecs_list=None, verbose=False, one=False,
1534.4.25 by Robert Collins
Add a --transport parameter to the test suite to set the default transport to be used in the test suite.
1787
            keep_output=False, transport=None):
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1788
        import bzrlib.ui
1185.31.25 by John Arbash Meinel
Renamed all of the tests from selftest/foo.py to tests/test_foo.py
1789
        from bzrlib.tests import selftest
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1790
        # we don't want progress meters from the tests to go to the
1791
        # real output; and we don't want log messages cluttering up
1792
        # the real logs.
1793
        save_ui = bzrlib.ui.ui_factory
1794
        bzrlib.trace.info('running tests...')
1795
        try:
1796
            bzrlib.ui.ui_factory = bzrlib.ui.SilentUIFactory()
1185.1.57 by Robert Collins
nuke --pattern to selftest, replace with regexp.search calls.
1797
            if testspecs_list is not None:
1798
                pattern = '|'.join(testspecs_list)
1799
            else:
1800
                pattern = ".*"
1393.1.46 by Martin Pool
- bzr selftest arguments can be partial ids of tests to run
1801
            result = selftest(verbose=verbose, 
1185.16.58 by mbp at sourcefrog
- run all selftests by default
1802
                              pattern=pattern,
1185.35.20 by Aaron Bentley
Only keep test failure directories if --keep-output is specified
1803
                              stop_on_failure=one, 
1534.4.25 by Robert Collins
Add a --transport parameter to the test suite to set the default transport to be used in the test suite.
1804
                              keep_output=keep_output,
1805
                              transport=transport)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1806
            if result:
1807
                bzrlib.trace.info('tests passed')
1808
            else:
1809
                bzrlib.trace.info('tests failed')
1810
            return int(not result)
1811
        finally:
1812
            bzrlib.ui.ui_factory = save_ui
1813
1814
1185.62.8 by John Arbash Meinel
Deprecating bzrlib.get_bzr_revision, in favor of bzrlib.builtins._get_bzr_branch
1815
def _get_bzr_branch():
1816
    """If bzr is run from a branch, return Branch or None"""
1817
    import bzrlib.errors
1818
    from bzrlib.branch import Branch
1819
    from bzrlib.osutils import abspath
1820
    from os.path import dirname
1821
    
1822
    try:
1823
        branch = Branch.open(dirname(abspath(dirname(__file__))))
1824
        return branch
1825
    except bzrlib.errors.BzrError:
1826
        return None
1827
    
1828
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1829
def show_version():
1830
    print "bzr (bazaar-ng) %s" % bzrlib.__version__
1831
    # is bzrlib itself in a branch?
1185.62.8 by John Arbash Meinel
Deprecating bzrlib.get_bzr_revision, in favor of bzrlib.builtins._get_bzr_branch
1832
    branch = _get_bzr_branch()
1833
    if branch:
1834
        rh = branch.revision_history()
1835
        revno = len(rh)
1185.62.1 by John Arbash Meinel
bzr --version prints branch nickname.
1836
        print "  bzr checkout, revision %d" % (revno,)
1837
        print "  nick: %s" % (branch.nick,)
1185.62.8 by John Arbash Meinel
Deprecating bzrlib.get_bzr_revision, in favor of bzrlib.builtins._get_bzr_branch
1838
        if rh:
1839
            print "  revid: %s" % (rh[-1],)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1840
    print bzrlib.__copyright__
1841
    print "http://bazaar-ng.org/"
1842
    print
1843
    print "bzr comes with ABSOLUTELY NO WARRANTY.  bzr is free software, and"
1844
    print "you may use, modify and redistribute it under the terms of the GNU"
1845
    print "General Public License version 2 or later."
1846
1847
1848
class cmd_version(Command):
1849
    """Show version of bzr."""
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1850
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1851
    def run(self):
1852
        show_version()
1853
1854
class cmd_rocks(Command):
1855
    """Statement of optimism."""
1856
    hidden = True
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1857
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1858
    def run(self):
1859
        print "it sure does!"
1860
1861
1862
class cmd_find_merge_base(Command):
1863
    """Find and print a base revision for merging two branches.
1864
    """
1185.16.3 by Martin Pool
- remove all TODOs from bzr help messages
1865
    # TODO: Options to specify revisions on either side, as if
1866
    #       merging only part of the history.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1867
    takes_args = ['branch', 'other']
1868
    hidden = True
1869
    
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1870
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1871
    def run(self, branch, other):
1155 by Martin Pool
- update find-merge-base to use new common_ancestor code
1872
        from bzrlib.revision import common_ancestor, MultipleRevisionSources
1873
        
1442.1.64 by Robert Collins
Branch.open_containing now returns a tuple (Branch, relative-path).
1874
        branch1 = Branch.open_containing(branch)[0]
1875
        branch2 = Branch.open_containing(other)[0]
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1876
1155 by Martin Pool
- update find-merge-base to use new common_ancestor code
1877
        history_1 = branch1.revision_history()
1878
        history_2 = branch2.revision_history()
1879
1241 by Martin Pool
- rename last_patch to last_revision
1880
        last1 = branch1.last_revision()
1881
        last2 = branch2.last_revision()
1155 by Martin Pool
- update find-merge-base to use new common_ancestor code
1882
1551.2.2 by Aaron Bentley
Fix find-merge-base for new API [recommit]
1883
        source = MultipleRevisionSources(branch1.repository, 
1884
                                         branch2.repository)
1155 by Martin Pool
- update find-merge-base to use new common_ancestor code
1885
        
1886
        base_rev_id = common_ancestor(last1, last2, source)
1887
1888
        print 'merge base is revision %s' % base_rev_id
1889
        
1890
        return
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1891
1892
        if base_revno is None:
1893
            raise bzrlib.errors.UnrelatedBranches()
1894
1895
        print ' r%-6d in %s' % (base_revno, branch)
1896
1897
        other_revno = branch2.revision_id_to_revno(base_revid)
1898
        
1899
        print ' r%-6d in %s' % (other_revno, other)
1900
1901
1902
1903
class cmd_merge(Command):
1904
    """Perform a three-way merge.
1905
    
1614.2.4 by Olaf Conradi
Renamed argument location in command merge back to branch.
1906
    The branch is the branch you will merge from.  By default, it will
1172 by Martin Pool
- better explanation when merge fails with AmbiguousBase
1907
    merge the latest revision.  If you specify a revision, that
1908
    revision will be merged.  If you specify two revisions, the first
1909
    will be used as a BASE, and the second one as OTHER.  Revision
1910
    numbers are always relative to the specified branch.
1911
1551.2.19 by Aaron Bentley
Added See Conflicts to merge help
1912
    By default, bzr will try to merge in all new work from the other
1172 by Martin Pool
- better explanation when merge fails with AmbiguousBase
1913
    branch, automatically determining an appropriate base.  If this
1914
    fails, you may need to give an explicit base.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1915
    
1551.2.18 by Aaron Bentley
Updated docs to clarify conflict handling
1916
    Merge will do its best to combine the changes in two branches, but there
1917
    are some kinds of problems only a human can fix.  When it encounters those,
1918
    it will mark a conflict.  A conflict means that you need to fix something,
1919
    before you should commit.
1920
1551.2.19 by Aaron Bentley
Added See Conflicts to merge help
1921
    Use bzr resolve when you have fixed a problem.  See also bzr conflicts.
1551.2.18 by Aaron Bentley
Updated docs to clarify conflict handling
1922
1614.2.4 by Olaf Conradi
Renamed argument location in command merge back to branch.
1923
    If there is no default branch set, the first merge will set it. After
1924
    that, you can omit the branch to use the default.  To change the
1614.2.2 by Olaf Conradi
Merge command:
1925
    default, use --remember.
1926
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1927
    Examples:
1928
1929
    To merge the latest revision from bzr.dev
1930
    bzr merge ../bzr.dev
1931
1932
    To merge changes up to and including revision 82 from bzr.dev
1933
    bzr merge -r 82 ../bzr.dev
1934
1935
    To merge the changes introduced by 82, without previous changes:
1936
    bzr merge -r 81..82 ../bzr.dev
1937
    
1938
    merge refuses to run if there are any uncommitted changes, unless
1939
    --force is given.
1940
    """
1614.2.4 by Olaf Conradi
Renamed argument location in command merge back to branch.
1941
    takes_args = ['branch?']
1614.2.2 by Olaf Conradi
Merge command:
1942
    takes_options = ['revision', 'force', 'merge-type', 'reprocess', 'remember',
1185.18.1 by Aaron Bentley
Added --show-base to merge
1943
                     Option('show-base', help="Show base revision text in "
1944
                            "conflicts")]
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1945
1614.2.4 by Olaf Conradi
Renamed argument location in command merge back to branch.
1946
    def run(self, branch=None, revision=None, force=False, merge_type=None,
1614.2.2 by Olaf Conradi
Merge command:
1947
            show_base=False, reprocess=False, remember=False):
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1948
        if merge_type is None:
1534.7.139 by Aaron Bentley
ApplyMerge3 -> Merge3Merger
1949
            merge_type = Merge3Merger
1614.2.2 by Olaf Conradi
Merge command:
1950
1951
        tree = WorkingTree.open_containing(u'.')[0]
1952
        stored_loc = tree.branch.get_parent()
1614.2.4 by Olaf Conradi
Renamed argument location in command merge back to branch.
1953
        if branch is None:
1614.2.2 by Olaf Conradi
Merge command:
1954
            if stored_loc is None:
1614.2.4 by Olaf Conradi
Renamed argument location in command merge back to branch.
1955
                raise BzrCommandError("No merge branch known or specified.")
1185.12.12 by Aaron Bentley
Made merge use pull location or die if no branch specified.
1956
            else:
1685.1.37 by John Arbash Meinel
builtins now use urlfordisplay to display nicer paths to the user.
1957
                print (u"Using saved branch: %s" 
1685.1.45 by John Arbash Meinel
Moved url functions into bzrlib.urlutils
1958
                    % urlutils.unescape_for_display(stored_loc))
1614.2.4 by Olaf Conradi
Renamed argument location in command merge back to branch.
1959
                branch = stored_loc
1614.2.2 by Olaf Conradi
Merge command:
1960
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1961
        if revision is None or len(revision) < 1:
1962
            base = [None, None]
1614.2.4 by Olaf Conradi
Renamed argument location in command merge back to branch.
1963
            other = [branch, -1]
1645.1.1 by Aaron Bentley
Implement single-file merge
1964
            other_branch, path = Branch.open_containing(branch)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1965
        else:
1966
            if len(revision) == 1:
974.1.52 by aaron.bentley at utoronto
Merged mpool's latest changes (~0.0.7)
1967
                base = [None, None]
1645.1.1 by Aaron Bentley
Implement single-file merge
1968
                other_branch, path = Branch.open_containing(branch)
1185.12.46 by Aaron Bentley
Fixed -r brokenness in merge
1969
                revno = revision[0].in_history(other_branch).revno
1614.2.4 by Olaf Conradi
Renamed argument location in command merge back to branch.
1970
                other = [branch, revno]
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1971
            else:
1972
                assert len(revision) == 2
1973
                if None in revision:
1974
                    raise BzrCommandError(
1975
                        "Merge doesn't permit that revision specifier.")
1685.1.19 by John Arbash Meinel
pull/merge/branch/missing should all save the absolute path to the other branch, not the relative one
1976
                other_branch, path = Branch.open_containing(branch)
1977
1978
                base = [branch, revision[0].in_history(other_branch).revno]
1979
                other = [branch, revision[1].in_history(other_branch).revno]
1980
1981
        if tree.branch.get_parent() is None or remember:
1982
            tree.branch.set_parent(other_branch.base)
1983
1645.1.1 by Aaron Bentley
Implement single-file merge
1984
        if path != "":
1985
            interesting_files = [path]
1986
        else:
1987
            interesting_files = None
1551.2.25 by Aaron Bentley
Stop using deprecated methods in merge and revert
1988
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
1172 by Martin Pool
- better explanation when merge fails with AmbiguousBase
1989
        try:
1551.2.25 by Aaron Bentley
Stop using deprecated methods in merge and revert
1990
            try:
1991
                conflict_count = merge(other, base, check_clean=(not force),
1992
                                       merge_type=merge_type, 
1993
                                       reprocess=reprocess,
1994
                                       show_base=show_base, 
1645.1.1 by Aaron Bentley
Implement single-file merge
1995
                                       pb=pb, file_list=interesting_files)
1551.2.25 by Aaron Bentley
Stop using deprecated methods in merge and revert
1996
            finally:
1997
                pb.finished()
1476 by Robert Collins
Merge now has a retcode of 1 when conflicts occur. (Robert Collins)
1998
            if conflict_count != 0:
1999
                return 1
2000
            else:
2001
                return 0
1172 by Martin Pool
- better explanation when merge fails with AmbiguousBase
2002
        except bzrlib.errors.AmbiguousBase, e:
1173 by Martin Pool
- message typo
2003
            m = ("sorry, bzr can't determine the right merge base yet\n"
1172 by Martin Pool
- better explanation when merge fails with AmbiguousBase
2004
                 "candidates are:\n  "
2005
                 + "\n  ".join(e.bases)
2006
                 + "\n"
2007
                 "please specify an explicit base with -r,\n"
2008
                 "and (if you want) report this to the bzr developers\n")
2009
            log_error(m)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2010
2011
1185.35.4 by Aaron Bentley
Implemented remerge
2012
class cmd_remerge(Command):
2013
    """Redo a merge.
2014
    """
2015
    takes_args = ['file*']
2016
    takes_options = ['merge-type', 'reprocess',
2017
                     Option('show-base', help="Show base revision text in "
2018
                            "conflicts")]
2019
2020
    def run(self, file_list=None, merge_type=None, show_base=False,
2021
            reprocess=False):
2022
        from bzrlib.merge import merge_inner, transform_tree
2023
        if merge_type is None:
1534.7.139 by Aaron Bentley
ApplyMerge3 -> Merge3Merger
2024
            merge_type = Merge3Merger
1508.1.15 by Robert Collins
Merge from mpool.
2025
        tree, file_list = tree_files(file_list)
2026
        tree.lock_write()
1185.35.4 by Aaron Bentley
Implemented remerge
2027
        try:
1508.1.15 by Robert Collins
Merge from mpool.
2028
            pending_merges = tree.pending_merges() 
1185.35.4 by Aaron Bentley
Implemented remerge
2029
            if len(pending_merges) != 1:
2030
                raise BzrCommandError("Sorry, remerge only works after normal"
2031
                                      + " merges.  Not cherrypicking or"
2032
                                      + "multi-merges.")
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
2033
            repository = tree.branch.repository
1508.1.15 by Robert Collins
Merge from mpool.
2034
            base_revision = common_ancestor(tree.branch.last_revision(), 
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
2035
                                            pending_merges[0], repository)
2036
            base_tree = repository.revision_tree(base_revision)
2037
            other_tree = repository.revision_tree(pending_merges[0])
1185.35.4 by Aaron Bentley
Implemented remerge
2038
            interesting_ids = None
2039
            if file_list is not None:
2040
                interesting_ids = set()
2041
                for filename in file_list:
1508.1.15 by Robert Collins
Merge from mpool.
2042
                    file_id = tree.path2id(filename)
1558.2.1 by Aaron Bentley
Ensure remerge errors when file-id is None
2043
                    if file_id is None:
2044
                        raise NotVersionedError(filename)
1185.35.4 by Aaron Bentley
Implemented remerge
2045
                    interesting_ids.add(file_id)
1508.1.15 by Robert Collins
Merge from mpool.
2046
                    if tree.kind(file_id) != "directory":
1185.35.4 by Aaron Bentley
Implemented remerge
2047
                        continue
1185.35.13 by Aaron Bentley
Merged Martin
2048
                    
1508.1.15 by Robert Collins
Merge from mpool.
2049
                    for name, ie in tree.inventory.iter_entries(file_id):
1185.35.4 by Aaron Bentley
Implemented remerge
2050
                        interesting_ids.add(ie.file_id)
1534.4.35 by Robert Collins
Give branch its own basis tree and last_revision methods; deprecated branch.working_tree()
2051
            transform_tree(tree, tree.basis_tree(), interesting_ids)
1185.35.4 by Aaron Bentley
Implemented remerge
2052
            if file_list is None:
1508.1.15 by Robert Collins
Merge from mpool.
2053
                restore_files = list(tree.iter_conflicts())
1185.35.4 by Aaron Bentley
Implemented remerge
2054
            else:
2055
                restore_files = file_list
2056
            for filename in restore_files:
2057
                try:
1508.1.15 by Robert Collins
Merge from mpool.
2058
                    restore(tree.abspath(filename))
1185.35.4 by Aaron Bentley
Implemented remerge
2059
                except NotConflicted:
2060
                    pass
1551.5.1 by Aaron Bentley
Stop using deprecated api in remerge
2061
            conflicts =  merge_inner(tree.branch, other_tree, base_tree,
2062
                                     this_tree=tree,
1185.35.4 by Aaron Bentley
Implemented remerge
2063
                                     interesting_ids = interesting_ids, 
2064
                                     other_rev_id=pending_merges[0], 
2065
                                     merge_type=merge_type, 
2066
                                     show_base=show_base,
2067
                                     reprocess=reprocess)
2068
        finally:
1508.1.15 by Robert Collins
Merge from mpool.
2069
            tree.unlock()
1185.35.4 by Aaron Bentley
Implemented remerge
2070
        if conflicts > 0:
2071
            return 1
2072
        else:
2073
            return 0
2074
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2075
class cmd_revert(Command):
2076
    """Reverse all changes since the last commit.
2077
2078
    Only versioned files are affected.  Specify filenames to revert only 
2079
    those files.  By default, any files that are changed will be backed up
2080
    first.  Backup files have a '~' appended to their name.
2081
    """
2082
    takes_options = ['revision', 'no-backup']
2083
    takes_args = ['file*']
2084
    aliases = ['merge-revert']
2085
2086
    def run(self, revision=None, no_backup=False, file_list=None):
2087
        from bzrlib.commands import parse_spec
2088
        if file_list is not None:
2089
            if len(file_list) == 0:
2090
                raise BzrCommandError("No files specified")
1457.1.9 by Robert Collins
Change cmd_revert implementation to call workingtree.Revert.
2091
        else:
2092
            file_list = []
1185.50.53 by John Arbash Meinel
[patch] Aaron Bentley: make revert work in a subdirectory.
2093
        
2094
        tree, file_list = tree_files(file_list)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2095
        if revision is None:
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
2096
            # FIXME should be tree.last_revision
1558.4.2 by Aaron Bentley
Revert in checkout works properly
2097
            rev_id = tree.last_revision()
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2098
        elif len(revision) != 1:
2099
            raise BzrCommandError('bzr revert --revision takes exactly 1 argument')
1185.5.8 by John Arbash Meinel
Fixed bzr revert with the new RevisionSpec code.
2100
        else:
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
2101
            rev_id = revision[0].in_history(tree.branch).rev_id
1551.2.25 by Aaron Bentley
Stop using deprecated methods in merge and revert
2102
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
2103
        try:
2104
            tree.revert(file_list, 
2105
                        tree.branch.repository.revision_tree(rev_id),
2106
                        not no_backup, pb)
2107
        finally:
2108
            pb.finished()
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2109
2110
2111
class cmd_assert_fail(Command):
2112
    """Test reporting of assertion failures"""
2113
    hidden = True
2114
    def run(self):
2115
        assert False, "always fails"
2116
2117
2118
class cmd_help(Command):
2119
    """Show help on a command or other topic.
2120
2121
    For a list of all available commands, say 'bzr help commands'."""
1553.4.3 by Michael Ellerman
Add custom description for help's --long option, this fixes bug #31217.
2122
    takes_options = [Option('long', 'show help on all commands')]
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2123
    takes_args = ['topic?']
1616.1.15 by Martin Pool
Handle 'bzr ?', etc.
2124
    aliases = ['?', '--help', '-?', '-h']
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2125
    
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
2126
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2127
    def run(self, topic=None, long=False):
2128
        import help
2129
        if topic is None and long:
2130
            topic = "commands"
2131
        help.help(topic)
2132
2133
2134
class cmd_shell_complete(Command):
2135
    """Show appropriate completions for context.
2136
2137
    For a list of all available commands, say 'bzr shell-complete'."""
2138
    takes_args = ['context?']
2139
    aliases = ['s-c']
2140
    hidden = True
2141
    
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
2142
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2143
    def run(self, context=None):
2144
        import shellcomplete
2145
        shellcomplete.shellcomplete(context)
2146
2147
1228 by Martin Pool
- add fetch command as builtin
2148
class cmd_fetch(Command):
2149
    """Copy in history from another branch but don't merge it.
2150
2151
    This is an internal method used for pull and merge."""
2152
    hidden = True
2153
    takes_args = ['from_branch', 'to_branch']
2154
    def run(self, from_branch, to_branch):
2155
        from bzrlib.fetch import Fetcher
2156
        from bzrlib.branch import Branch
1185.16.100 by mbp at sourcefrog
Update fetch command for new Branch constructors.
2157
        from_b = Branch.open(from_branch)
2158
        to_b = Branch.open(to_branch)
1185.65.27 by Robert Collins
Tweak storage towards mergability.
2159
        Fetcher(to_b, from_b)
1228 by Martin Pool
- add fetch command as builtin
2160
2161
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2162
class cmd_missing(Command):
1185.54.3 by Aaron Bentley
Factored out find_unmerged
2163
    """Show unmerged/unpulled revisions between two branches.
1185.54.1 by Aaron Bentley
Import Kinnison's plugin
2164
1185.54.3 by Aaron Bentley
Factored out find_unmerged
2165
    OTHER_BRANCH may be local or remote."""
1185.54.1 by Aaron Bentley
Import Kinnison's plugin
2166
    takes_args = ['other_branch?']
2167
    takes_options = [Option('reverse', 'Reverse the order of revisions'),
1185.54.12 by Aaron Bentley
Added log formatter selection and show-ids to missing
2168
                     Option('mine-only', 
2169
                            'Display changes in the local branch only'),
2170
                     Option('theirs-only', 
2171
                            'Display changes in the remote branch only'), 
1553.2.3 by Erik BÃ¥gfors
cover the missing command with formatters as well
2172
                     'log-format',
1185.54.12 by Aaron Bentley
Added log formatter selection and show-ids to missing
2173
                     'line',
2174
                     'long', 
2175
                     'short',
2176
                     'show-ids',
1185.54.19 by Aaron Bentley
All tests pass
2177
                     'verbose'
1185.54.12 by Aaron Bentley
Added log formatter selection and show-ids to missing
2178
                     ]
1185.54.1 by Aaron Bentley
Import Kinnison's plugin
2179
2180
    def run(self, other_branch=None, reverse=False, mine_only=False,
1553.2.6 by Erik BÃ¥gfors
Make default formatter work for the missing command
2181
            theirs_only=False, log_format=None, long=False, short=False, line=False, 
1185.54.19 by Aaron Bentley
All tests pass
2182
            show_ids=False, verbose=False):
2183
        from bzrlib.missing import find_unmerged, iter_log_data
1185.54.12 by Aaron Bentley
Added log formatter selection and show-ids to missing
2184
        from bzrlib.log import log_formatter
1185.46.5 by Aaron Bentley
Use unicode pathname in cmd_missing
2185
        local_branch = bzrlib.branch.Branch.open_containing(u".")[0]
1185.54.16 by Aaron Bentley
fixed location handling to match old missing
2186
        parent = local_branch.get_parent()
1185.54.1 by Aaron Bentley
Import Kinnison's plugin
2187
        if other_branch is None:
1185.54.16 by Aaron Bentley
fixed location handling to match old missing
2188
            other_branch = parent
2189
            if other_branch is None:
2190
                raise BzrCommandError("No missing location known or specified.")
1185.54.1 by Aaron Bentley
Import Kinnison's plugin
2191
            print "Using last location: " + local_branch.get_parent()
2192
        remote_branch = bzrlib.branch.Branch.open(other_branch)
1551.2.46 by abentley
Made bzr missing . work on win32
2193
        if remote_branch.base == local_branch.base:
2194
            remote_branch = local_branch
1666.1.5 by Robert Collins
Merge bound branch test performance improvements.
2195
        local_branch.lock_read()
1594.3.6 by Robert Collins
Take out appropriate locks for missing.
2196
        try:
1551.2.46 by abentley
Made bzr missing . work on win32
2197
            remote_branch.lock_read()
1594.3.6 by Robert Collins
Take out appropriate locks for missing.
2198
            try:
2199
                local_extra, remote_extra = find_unmerged(local_branch, remote_branch)
2200
                if (log_format == None):
2201
                    default = bzrlib.config.BranchConfig(local_branch).log_format()
2202
                    log_format = get_log_format(long=long, short=short, line=line, default=default)
2203
                lf = log_formatter(log_format, sys.stdout,
2204
                                   show_ids=show_ids,
2205
                                   show_timezone='original')
2206
                if reverse is False:
2207
                    local_extra.reverse()
2208
                    remote_extra.reverse()
2209
                if local_extra and not theirs_only:
2210
                    print "You have %d extra revision(s):" % len(local_extra)
2211
                    for data in iter_log_data(local_extra, local_branch.repository,
2212
                                              verbose):
2213
                        lf.show(*data)
2214
                    printed_local = True
2215
                else:
2216
                    printed_local = False
2217
                if remote_extra and not mine_only:
2218
                    if printed_local is True:
2219
                        print "\n\n"
2220
                    print "You are missing %d revision(s):" % len(remote_extra)
2221
                    for data in iter_log_data(remote_extra, remote_branch.repository, 
2222
                                              verbose):
2223
                        lf.show(*data)
2224
                if not remote_extra and not local_extra:
2225
                    status_code = 0
2226
                    print "Branches are up to date."
2227
                else:
2228
                    status_code = 1
2229
            finally:
1666.1.5 by Robert Collins
Merge bound branch test performance improvements.
2230
                remote_branch.unlock()
2231
        finally:
2232
            local_branch.unlock()
2233
        if not status_code and parent is None and other_branch is not None:
2234
            local_branch.lock_write()
2235
            try:
2236
                # handle race conditions - a parent might be set while we run.
2237
                if local_branch.get_parent() is None:
1685.1.19 by John Arbash Meinel
pull/merge/branch/missing should all save the absolute path to the other branch, not the relative one
2238
                    local_branch.set_parent(remote_branch.base)
1594.3.6 by Robert Collins
Take out appropriate locks for missing.
2239
            finally:
2240
                local_branch.unlock()
1666.1.5 by Robert Collins
Merge bound branch test performance improvements.
2241
        return status_code
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2242
2243
2244
class cmd_plugins(Command):
2245
    """List plugins"""
2246
    hidden = True
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
2247
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2248
    def run(self):
2249
        import bzrlib.plugin
2250
        from inspect import getdoc
1516 by Robert Collins
* bzrlib.plugin.all_plugins has been changed from an attribute to a
2251
        for name, plugin in bzrlib.plugin.all_plugins().items():
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2252
            if hasattr(plugin, '__path__'):
2253
                print plugin.__path__[0]
2254
            elif hasattr(plugin, '__file__'):
2255
                print plugin.__file__
2256
            else:
2257
                print `plugin`
2258
                
2259
            d = getdoc(plugin)
2260
            if d:
2261
                print '\t', d.split('\n')[0]
2262
2263
1185.16.24 by Martin Pool
- add and test 'testament' builtin command
2264
class cmd_testament(Command):
2265
    """Show testament (signing-form) of a revision."""
2266
    takes_options = ['revision', 'long']
2267
    takes_args = ['branch?']
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
2268
    @display_command
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
2269
    def run(self, branch=u'.', revision=None, long=False):
1185.16.24 by Martin Pool
- add and test 'testament' builtin command
2270
        from bzrlib.testament import Testament
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
2271
        b = WorkingTree.open_containing(branch)[0].branch
1185.16.24 by Martin Pool
- add and test 'testament' builtin command
2272
        b.lock_read()
2273
        try:
2274
            if revision is None:
2275
                rev_id = b.last_revision()
2276
            else:
2277
                rev_id = revision[0].in_history(b).rev_id
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
2278
            t = Testament.from_revision(b.repository, rev_id)
1185.16.24 by Martin Pool
- add and test 'testament' builtin command
2279
            if long:
2280
                sys.stdout.writelines(t.as_text_lines())
2281
            else:
2282
                sys.stdout.write(t.as_short_text())
2283
        finally:
2284
            b.unlock()
1185.16.32 by Martin Pool
- add a basic annotate built-in command
2285
2286
2287
class cmd_annotate(Command):
2288
    """Show the origin of each line in a file.
2289
1185.16.53 by Martin Pool
- annotate improvements from Goffreddo, with extra bug fixes and tests
2290
    This prints out the given file with an annotation on the left side
2291
    indicating which revision, author and date introduced the change.
2292
2293
    If the origin is the same for a run of consecutive lines, it is 
2294
    shown only at the top, unless the --all option is given.
1185.16.32 by Martin Pool
- add a basic annotate built-in command
2295
    """
2296
    # TODO: annotate directories; showing when each file was last changed
2297
    # TODO: annotate a previous version of a file
1185.16.53 by Martin Pool
- annotate improvements from Goffreddo, with extra bug fixes and tests
2298
    # TODO: if the working copy is modified, show annotations on that 
2299
    #       with new uncommitted lines marked
1185.16.32 by Martin Pool
- add a basic annotate built-in command
2300
    aliases = ['blame', 'praise']
2301
    takes_args = ['filename']
1185.16.53 by Martin Pool
- annotate improvements from Goffreddo, with extra bug fixes and tests
2302
    takes_options = [Option('all', help='show annotations on all lines'),
2303
                     Option('long', help='show date in annotations'),
2304
                     ]
1185.16.32 by Martin Pool
- add a basic annotate built-in command
2305
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
2306
    @display_command
1185.16.53 by Martin Pool
- annotate improvements from Goffreddo, with extra bug fixes and tests
2307
    def run(self, filename, all=False, long=False):
1185.16.32 by Martin Pool
- add a basic annotate built-in command
2308
        from bzrlib.annotate import annotate_file
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
2309
        tree, relpath = WorkingTree.open_containing(filename)
2310
        branch = tree.branch
2311
        branch.lock_read()
1185.16.32 by Martin Pool
- add a basic annotate built-in command
2312
        try:
1442.1.64 by Robert Collins
Branch.open_containing now returns a tuple (Branch, relative-path).
2313
            file_id = tree.inventory.path2id(relpath)
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
2314
            tree = branch.repository.revision_tree(branch.last_revision())
1185.16.32 by Martin Pool
- add a basic annotate built-in command
2315
            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
2316
            annotate_file(branch, file_version, file_id, long, all, sys.stdout)
1185.16.32 by Martin Pool
- add a basic annotate built-in command
2317
        finally:
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
2318
            branch.unlock()
1185.16.33 by Martin Pool
- move 'conflict' and 'resolved' from shipped plugin to regular builtins
2319
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
2320
2321
class cmd_re_sign(Command):
2322
    """Create a digital signature for an existing revision."""
2323
    # TODO be able to replace existing ones.
2324
2325
    hidden = True # is this right ?
1185.78.1 by John Arbash Meinel
Updating bzr re-sign to allow multiple arguments, and updating tests
2326
    takes_args = ['revision_id*']
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
2327
    takes_options = ['revision']
2328
    
1185.78.1 by John Arbash Meinel
Updating bzr re-sign to allow multiple arguments, and updating tests
2329
    def run(self, revision_id_list=None, revision=None):
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
2330
        import bzrlib.config as config
2331
        import bzrlib.gpg as gpg
1185.78.1 by John Arbash Meinel
Updating bzr re-sign to allow multiple arguments, and updating tests
2332
        if revision_id_list is not None and revision is not None:
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
2333
            raise BzrCommandError('You can only supply one of revision_id or --revision')
1185.78.1 by John Arbash Meinel
Updating bzr re-sign to allow multiple arguments, and updating tests
2334
        if revision_id_list is None and revision is None:
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
2335
            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)
2336
        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.
2337
        gpg_strategy = gpg.GPGStrategy(config.BranchConfig(b))
1185.78.1 by John Arbash Meinel
Updating bzr re-sign to allow multiple arguments, and updating tests
2338
        if revision_id_list is not None:
2339
            for revision_id in revision_id_list:
2340
                b.repository.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.
2341
        elif revision is not None:
1483 by Robert Collins
BUGFIX: re-sign should accept ranges
2342
            if len(revision) == 1:
2343
                revno, rev_id = revision[0].in_history(b)
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
2344
                b.repository.sign_revision(rev_id, gpg_strategy)
1483 by Robert Collins
BUGFIX: re-sign should accept ranges
2345
            elif len(revision) == 2:
2346
                # are they both on rh- if so we can walk between them
2347
                # might be nice to have a range helper for arbitrary
2348
                # revision paths. hmm.
2349
                from_revno, from_revid = revision[0].in_history(b)
2350
                to_revno, to_revid = revision[1].in_history(b)
2351
                if to_revid is None:
2352
                    to_revno = b.revno()
2353
                if from_revno is None or to_revno is None:
2354
                    raise BzrCommandError('Cannot sign a range of non-revision-history revisions')
2355
                for revno in range(from_revno, to_revno + 1):
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
2356
                    b.repository.sign_revision(b.get_rev_id(revno), 
2357
                                               gpg_strategy)
1483 by Robert Collins
BUGFIX: re-sign should accept ranges
2358
            else:
2359
                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.
2360
1505.1.22 by John Arbash Meinel
Some small cleanup and discussion in preparation for modifying commit, pull, and merge
2361
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
2362
class cmd_bind(Command):
1587.1.14 by Robert Collins
Make bound branch creation happen via 'checkout'
2363
    """Bind the current branch to a master branch.
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
2364
1587.1.14 by Robert Collins
Make bound branch creation happen via 'checkout'
2365
    After binding, commits must succeed on the master branch
2366
    before they are executed on the local one.
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
2367
    """
2368
1587.1.14 by Robert Collins
Make bound branch creation happen via 'checkout'
2369
    takes_args = ['location']
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
2370
    takes_options = []
2371
2372
    def run(self, location=None):
1505.1.22 by John Arbash Meinel
Some small cleanup and discussion in preparation for modifying commit, pull, and merge
2373
        b, relpath = Branch.open_containing(u'.')
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
2374
        b_other = Branch.open(location)
1505.1.3 by John Arbash Meinel
(broken) Adding more tests, and some functionality
2375
        try:
2376
            b.bind(b_other)
2377
        except DivergedBranches:
2378
            raise BzrCommandError('These branches have diverged.'
1505.1.12 by John Arbash Meinel
Fixing up the error message for a failed bind.
2379
                                  ' Try merging, and then bind again.')
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
2380
1505.1.22 by John Arbash Meinel
Some small cleanup and discussion in preparation for modifying commit, pull, and merge
2381
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
2382
class cmd_unbind(Command):
2383
    """Bind the current branch to its parent.
2384
2385
    After unbinding, the local branch is considered independent.
2386
    """
2387
2388
    takes_args = []
2389
    takes_options = []
2390
2391
    def run(self):
1505.1.22 by John Arbash Meinel
Some small cleanup and discussion in preparation for modifying commit, pull, and merge
2392
        b, relpath = Branch.open_containing(u'.')
2393
        if not b.unbind():
2394
            raise BzrCommandError('Local branch is not bound')
2395
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
2396
1185.31.24 by John Arbash Meinel
[merge] Added the uncommit plugin
2397
class cmd_uncommit(bzrlib.commands.Command):
2398
    """Remove the last committed revision.
2399
2400
    By supplying the --all flag, it will not only remove the entry 
2401
    from revision_history, but also remove all of the entries in the
2402
    stores.
2403
2404
    --verbose will print out what is being removed.
2405
    --dry-run will go through all the motions, but not actually
2406
    remove anything.
2407
    
2408
    In the future, uncommit will create a changeset, which can then
2409
    be re-applied.
1553.5.34 by Martin Pool
Stub lock-breaking command
2410
    """
1185.62.11 by John Arbash Meinel
Added TODO for bzr uncommit to remove unreferenced information.
2411
1553.5.34 by Martin Pool
Stub lock-breaking command
2412
    # TODO: jam 20060108 Add an option to allow uncommit to remove
2413
    # unreferenced information in 'branch-as-repostory' branches.
2414
    # TODO: jam 20060108 Add the ability for uncommit to remove unreferenced
2415
    # information in shared branches as well.
1185.62.10 by John Arbash Meinel
Removed --all from bzr uncommit, it was broken anyway.
2416
    takes_options = ['verbose', 'revision',
1185.31.24 by John Arbash Meinel
[merge] Added the uncommit plugin
2417
                    Option('dry-run', help='Don\'t actually make changes'),
2418
                    Option('force', help='Say yes to all questions.')]
2419
    takes_args = ['location?']
2420
    aliases = []
2421
1185.62.10 by John Arbash Meinel
Removed --all from bzr uncommit, it was broken anyway.
2422
    def run(self, location=None, 
1185.31.24 by John Arbash Meinel
[merge] Added the uncommit plugin
2423
            dry_run=False, verbose=False,
2424
            revision=None, force=False):
2425
        from bzrlib.branch import Branch
2426
        from bzrlib.log import log_formatter
2427
        import sys
2428
        from bzrlib.uncommit import uncommit
2429
2430
        if location is None:
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
2431
            location = u'.'
1558.1.12 by Aaron Bentley
Got uncommit working properly with checkouts
2432
        control, relpath = bzrdir.BzrDir.open_containing(location)
2433
        try:
2434
            tree = control.open_workingtree()
1558.9.1 by Aaron Bentley
Fix uncommit to handle bound branches, and to do locking
2435
            b = tree.branch
1558.1.12 by Aaron Bentley
Got uncommit working properly with checkouts
2436
        except (errors.NoWorkingTree, errors.NotLocalUrl):
2437
            tree = None
1558.9.1 by Aaron Bentley
Fix uncommit to handle bound branches, and to do locking
2438
            b = control.open_branch()
1185.31.24 by John Arbash Meinel
[merge] Added the uncommit plugin
2439
2440
        if revision is None:
2441
            revno = b.revno()
2442
            rev_id = b.last_revision()
2443
        else:
2444
            revno, rev_id = revision[0].in_history(b)
2445
        if rev_id is None:
2446
            print 'No revisions to uncommit.'
2447
2448
        for r in range(revno, b.revno()+1):
2449
            rev_id = b.get_rev_id(r)
2450
            lf = log_formatter('short', to_file=sys.stdout,show_timezone='original')
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
2451
            lf.show(r, b.repository.get_revision(rev_id), None)
1185.31.24 by John Arbash Meinel
[merge] Added the uncommit plugin
2452
2453
        if dry_run:
2454
            print 'Dry-run, pretending to remove the above revisions.'
2455
            if not force:
2456
                val = raw_input('Press <enter> to continue')
2457
        else:
2458
            print 'The above revision(s) will be removed.'
2459
            if not force:
2460
                val = raw_input('Are you sure [y/N]? ')
2461
                if val.lower() not in ('y', 'yes'):
2462
                    print 'Canceled'
2463
                    return 0
2464
1558.1.12 by Aaron Bentley
Got uncommit working properly with checkouts
2465
        uncommit(b, tree=tree, dry_run=dry_run, verbose=verbose,
1185.31.24 by John Arbash Meinel
[merge] Added the uncommit plugin
2466
                revno=revno)
2467
2468
1553.5.34 by Martin Pool
Stub lock-breaking command
2469
class cmd_break_lock(Command):
2470
    """Break a dead lock on a repository, branch or working directory.
2471
1553.5.35 by Martin Pool
Start break-lock --show
2472
    CAUTION: Locks should only be broken when you are sure that the process
1553.5.34 by Martin Pool
Stub lock-breaking command
2473
    holding the lock has been stopped.
1553.5.35 by Martin Pool
Start break-lock --show
2474
    
2475
    example:
2476
        bzr break-lock .
1553.5.34 by Martin Pool
Stub lock-breaking command
2477
    """
1553.5.35 by Martin Pool
Start break-lock --show
2478
    takes_args = ['location']
2479
    takes_options = [Option('show',
2480
                            help="just show information on the lock, " \
2481
                                 "don't break it"),
2482
                    ]
2483
    def run(self, location, show=False):
1626.1.1 by Martin Pool
Disable break-lock command until it works properly
2484
        raise NotImplementedError("sorry, break-lock is not complete yet; "
2485
                "you can remove the 'held' directory manually to break the lock")
1553.5.35 by Martin Pool
Start break-lock --show
2486
2487
2488
# command-line interpretation helper for merge-related commands
1545.2.9 by Aaron Bentley
Moved merge.merge to builtins
2489
def merge(other_revision, base_revision,
2490
          check_clean=True, ignore_zero=False,
1534.7.118 by Aaron Bentley
Dirty merge of the mainline
2491
          this_dir=None, backup_files=False, merge_type=Merge3Merger,
1553.5.35 by Martin Pool
Start break-lock --show
2492
          file_list=None, show_base=False, reprocess=False,
1534.9.6 by Aaron Bentley
Disable merge progress bars, except from the merge command
2493
          pb=DummyProgress()):
1545.2.9 by Aaron Bentley
Moved merge.merge to builtins
2494
    """Merge changes into a tree.
2495
2496
    base_revision
2497
        list(path, revno) Base for three-way merge.  
2498
        If [None, None] then a base will be automatically determined.
2499
    other_revision
2500
        list(path, revno) Other revision for three-way merge.
2501
    this_dir
2502
        Directory to merge changes into; '.' by default.
2503
    check_clean
2504
        If true, this_dir must have no uncommitted changes before the
2505
        merge begins.
2506
    ignore_zero - If true, suppress the "zero conflicts" message when 
2507
        there are no conflicts; should be set when doing something we expect
2508
        to complete perfectly.
2509
    file_list - If supplied, merge only changes to selected files.
2510
2511
    All available ancestors of other_revision and base_revision are
2512
    automatically pulled into the branch.
2513
2514
    The revno may be -1 to indicate the last revision on the branch, which is
2515
    the typical case.
2516
2517
    This function is intended for use from the command line; programmatic
2518
    clients might prefer to call merge.merge_inner(), which has less magic 
2519
    behavior.
2520
    """
1534.7.129 by Aaron Bentley
Converted test cases to Tree Transform
2521
    from bzrlib.merge import Merger
1545.2.9 by Aaron Bentley
Moved merge.merge to builtins
2522
    if this_dir is None:
2523
        this_dir = u'.'
1534.4.28 by Robert Collins
first cut at merge from integration.
2524
    this_tree = WorkingTree.open_containing(this_dir)[0]
1534.7.118 by Aaron Bentley
Dirty merge of the mainline
2525
    if show_base and not merge_type is Merge3Merger:
1545.2.9 by Aaron Bentley
Moved merge.merge to builtins
2526
        raise BzrCommandError("Show-base is not supported for this merge"
2527
                              " type. %s" % merge_type)
1551.6.8 by Aaron Bentley
Implemented reprocess for weave
2528
    if reprocess and not merge_type.supports_reprocess:
1551.6.14 by Aaron Bentley
Tweaks from merge review
2529
        raise BzrCommandError("Conflict reduction is not supported for merge"
2530
                              " type %s." % merge_type)
1545.2.9 by Aaron Bentley
Moved merge.merge to builtins
2531
    if reprocess and show_base:
1551.6.14 by Aaron Bentley
Tweaks from merge review
2532
        raise BzrCommandError("Cannot do conflict reduction and show base.")
1551.2.32 by Aaron Bentley
Handle progress phases more nicely in merge
2533
    try:
2534
        merger = Merger(this_tree.branch, this_tree=this_tree, pb=pb)
2535
        merger.pp = ProgressPhase("Merge phase", 5, pb)
2536
        merger.pp.next_phase()
2537
        merger.check_basis(check_clean)
2538
        merger.set_other(other_revision)
2539
        merger.pp.next_phase()
2540
        merger.set_base(base_revision)
2541
        if merger.base_rev_id == merger.other_rev_id:
2542
            note('Nothing to do.')
2543
            return 0
2544
        merger.backup_files = backup_files
2545
        merger.merge_type = merge_type 
2546
        merger.set_interesting_files(file_list)
2547
        merger.show_base = show_base 
2548
        merger.reprocess = reprocess
2549
        conflicts = merger.do_merge()
1645.1.1 by Aaron Bentley
Implement single-file merge
2550
        if file_list is None:
2551
            merger.set_pending()
1551.2.32 by Aaron Bentley
Handle progress phases more nicely in merge
2552
    finally:
2553
        pb.clear()
1545.2.9 by Aaron Bentley
Moved merge.merge to builtins
2554
    return conflicts
2555
2556
1185.16.33 by Martin Pool
- move 'conflict' and 'resolved' from shipped plugin to regular builtins
2557
# these get imported and then picked up by the scan for cmd_*
2558
# TODO: Some more consistent way to split command definitions across files;
2559
# we do need to load at least some information about them to know of 
1616.1.7 by Martin Pool
New developer commands 'weave-list' and 'weave-join'.
2560
# aliases.  ideally we would avoid loading the implementation until the
2561
# details were needed.
1185.35.4 by Aaron Bentley
Implemented remerge
2562
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore
1185.78.6 by John Arbash Meinel
Adding sign-my-commits as a builtin, along with some simple tests.
2563
from bzrlib.sign_my_commits import cmd_sign_my_commits
1616.1.17 by Martin Pool
New 'weave-plan-merge' and 'weave-merge-text' commands lifted from weave.py
2564
from bzrlib.weave_commands import cmd_weave_list, cmd_weave_join, \
2565
        cmd_weave_plan_merge, cmd_weave_merge_text