/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
3549.1.1 by Martin Pool
rename push --reference to --stacked-on
1
# Copyright (C) 2004, 2005, 2006, 2007, 2008 Canonical Ltd
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
2
#
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
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.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
7
#
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
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.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
12
#
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
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
1996.3.1 by John Arbash Meinel
Demandloading builtins.py drops our load time from 350ms to 291ms
19
import os
1185.33.90 by Martin Pool
[merge] add --dry-run option (mpe)
20
1996.3.1 by John Arbash Meinel
Demandloading builtins.py drops our load time from 350ms to 291ms
21
from bzrlib.lazy_import import lazy_import
22
lazy_import(globals(), """
1685.1.52 by John Arbash Meinel
[merge] bzr.dev 1704
23
import codecs
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
24
import cStringIO
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
25
import sys
1551.12.8 by Aaron Bentley
Add merge-directive command
26
import time
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
27
1773.4.2 by Martin Pool
Cleanup of imports; undeprecate all_revision_ids()
28
import bzrlib
1836.1.26 by John Arbash Meinel
[merge] bzr.dev 1869
29
from bzrlib import (
2376.4.22 by Jonathan Lange
Variety of whitespace cleanups, tightening of tests and docstring changes in
30
    bugtracker,
1836.1.26 by John Arbash Meinel
[merge] bzr.dev 1869
31
    bundle,
32
    bzrdir,
2225.1.1 by Aaron Bentley
Added revert change display, with tests
33
    delta,
1836.1.26 by John Arbash Meinel
[merge] bzr.dev 1869
34
    config,
35
    errors,
2298.8.1 by Kent Gibson
Normalise ignore patterns to use '/' path separator.
36
    globbing,
1836.1.26 by John Arbash Meinel
[merge] bzr.dev 1869
37
    log,
1996.3.5 by John Arbash Meinel
Cleanup, deprecated, and get the tests passing again.
38
    merge as _mod_merge,
1551.12.8 by Aaron Bentley
Add merge-directive command
39
    merge_directive,
1836.1.26 by John Arbash Meinel
[merge] bzr.dev 1869
40
    osutils,
2796.2.5 by Aaron Bentley
Implement reconfigure command
41
    reconfigure,
2598.5.1 by Aaron Bentley
Start eliminating the use of None to indicate null revision
42
    revision as _mod_revision,
2204.5.5 by Aaron Bentley
Remove RepositoryFormat.set_default_format, deprecate get_format_type
43
    symbol_versioning,
1836.1.26 by John Arbash Meinel
[merge] bzr.dev 1869
44
    transport,
1996.3.30 by John Arbash Meinel
Don't import 'bzrlib.tree' directly in bzrlib.builtins
45
    tree as _mod_tree,
1836.1.26 by John Arbash Meinel
[merge] bzr.dev 1869
46
    ui,
47
    urlutils,
48
    )
1996.3.1 by John Arbash Meinel
Demandloading builtins.py drops our load time from 350ms to 291ms
49
from bzrlib.branch import Branch
2120.7.2 by Aaron Bentley
Move autoresolve functionality to workingtree
50
from bzrlib.conflicts import ConflictList
1996.3.1 by John Arbash Meinel
Demandloading builtins.py drops our load time from 350ms to 291ms
51
from bzrlib.revisionspec import RevisionSpec
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
52
from bzrlib.smtp_connection import SMTPConnection
1996.3.1 by John Arbash Meinel
Demandloading builtins.py drops our load time from 350ms to 291ms
53
from bzrlib.workingtree import WorkingTree
54
""")
55
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
56
from bzrlib.commands import Command, display_command
2768.1.5 by Ian Clatworthy
Wrap new std verbose option with new help instead of declaring a new one
57
from bzrlib.option import ListOption, Option, RegistryOption, custom_help
3224.5.21 by Andrew Bennetts
Tidy a bit of import cruft in builtins.py.
58
from bzrlib.trace import mutter, note, warning, is_quiet
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
59
60
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
61
def tree_files(file_list, default_branch=u'.'):
1185.35.28 by Aaron Bentley
Support diff with two branches as input.
62
    try:
1508.1.15 by Robert Collins
Merge from mpool.
63
        return internal_tree_files(file_list, default_branch)
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
64
    except errors.FileInWrongBranch, e:
65
        raise errors.BzrCommandError("%s is not in the same branch as %s" %
66
                                     (e.path, file_list[0]))
1185.35.28 by Aaron Bentley
Support diff with two branches as input.
67
1185.85.12 by John Arbash Meinel
Refactoring AddAction to allow redirecting to an encoding file.
68
3732.1.1 by Ian Clatworthy
fix bzr st -rbranch:path-to-branch (Lukas Lalinsky)
69
def _get_one_revision_tree(command_name, revisions, branch=None, tree=None):
3655.3.1 by Lukáš Lalinský
Fix `bzr st -rbranch:PATH_TO_BRANCH`
70
    if branch is None:
71
        branch = tree.branch
3732.1.1 by Ian Clatworthy
fix bzr st -rbranch:path-to-branch (Lukas Lalinsky)
72
    if revisions is None:
3655.3.1 by Lukáš Lalinský
Fix `bzr st -rbranch:PATH_TO_BRANCH`
73
        if tree is not None:
74
            rev_tree = tree.basis_tree()
75
        else:
76
            rev_tree = branch.basis_tree()
77
    else:
3732.1.1 by Ian Clatworthy
fix bzr st -rbranch:path-to-branch (Lukas Lalinsky)
78
        if len(revisions) != 1:
3655.3.1 by Lukáš Lalinský
Fix `bzr st -rbranch:PATH_TO_BRANCH`
79
            raise errors.BzrCommandError(
80
                'bzr %s --revision takes exactly one revision identifier' % (
81
                    command_name,))
3732.1.1 by Ian Clatworthy
fix bzr st -rbranch:path-to-branch (Lukas Lalinsky)
82
        rev_tree = revisions[0].as_tree(branch)
3655.3.1 by Lukáš Lalinský
Fix `bzr st -rbranch:PATH_TO_BRANCH`
83
    return rev_tree
84
85
1658.1.9 by Martin Pool
Give an error for bzr diff on an nonexistent file (Malone #3619)
86
# XXX: Bad function name; should possibly also be a class method of
87
# WorkingTree rather than a function.
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
88
def internal_tree_files(file_list, default_branch=u'.'):
1658.1.8 by Martin Pool
(internal_tree_files) Better docstring
89
    """Convert command-line paths to a WorkingTree and relative paths.
90
91
    This is typically used for command-line processors that take one or
92
    more filenames, and infer the workingtree that contains them.
93
94
    The filenames given are not required to exist.
95
96
    :param file_list: Filenames to convert.  
97
2091.3.2 by Aaron Bentley
Traverse non-terminal symlinks for mv et al
98
    :param default_branch: Fallback tree path to use if file_list is empty or
99
        None.
1658.1.8 by Martin Pool
(internal_tree_files) Better docstring
100
101
    :return: workingtree, [relative_paths]
1185.12.101 by Aaron Bentley
Made commit take branch from first argument, if supplied.
102
    """
103
    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
104
        return WorkingTree.open_containing(default_branch)[0], file_list
2091.3.5 by Aaron Bentley
Move realpath functionality into osutils
105
    tree = WorkingTree.open_containing(osutils.realpath(file_list[0]))[0]
3602.1.1 by Robert Collins
Add support for -x or --exclude to bzr commit, fixing bug 3117. (Robert Collins)
106
    return tree, safe_relpath_files(tree, file_list)
107
108
109
def safe_relpath_files(tree, file_list):
110
    """Convert file_list into a list of relpaths in tree.
111
112
    :param tree: A tree to operate on.
113
    :param file_list: A list of user provided paths or None.
114
    :return: A list of relative paths.
115
    :raises errors.PathNotChild: When a provided path is in a different tree
116
        than tree.
117
    """
118
    if file_list is None:
119
        return None
1185.12.101 by Aaron Bentley
Made commit take branch from first argument, if supplied.
120
    new_list = []
121
    for filename in file_list:
1185.35.32 by Aaron Bentley
Fixed handling of files in mixed branches
122
        try:
2091.3.7 by Aaron Bentley
Rename real_parent to dereferenced_path
123
            new_list.append(tree.relpath(osutils.dereference_path(filename)))
1185.31.45 by John Arbash Meinel
Refactoring Exceptions found some places where the wrong exception was caught.
124
        except errors.PathNotChild:
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
125
            raise errors.FileInWrongBranch(tree.branch, filename)
3602.1.1 by Robert Collins
Add support for -x or --exclude to bzr commit, fixing bug 3117. (Robert Collins)
126
    return new_list
1553.5.78 by Martin Pool
New bzr init --format option and test
127
128
1185.16.112 by mbp at sourcefrog
todo
129
# TODO: Make sure no commands unconditionally use the working directory as a
130
# branch.  If a filename argument is used, the first of them should be used to
131
# specify the branch.  (Perhaps this can be factored out into some kind of
132
# Argument class, representing a file in a branch, where the first occurrence
133
# opens the branch?)
134
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
135
class cmd_status(Command):
136
    """Display status summary.
137
138
    This reports on versioned and unknown files, reporting them
139
    grouped by state.  Possible states are:
140
1551.10.10 by Aaron Bentley
Add help text
141
    added
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
142
        Versioned in the working copy but not in the previous revision.
143
1551.10.10 by Aaron Bentley
Add help text
144
    removed
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
145
        Versioned in the previous revision but removed or deleted
146
        in the working copy.
147
1551.10.10 by Aaron Bentley
Add help text
148
    renamed
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
149
        Path of this file changed from the previous revision;
150
        the text may also have changed.  This includes files whose
151
        parent directory was renamed.
152
1551.10.10 by Aaron Bentley
Add help text
153
    modified
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
154
        Text has changed since the previous revision.
155
1551.10.10 by Aaron Bentley
Add help text
156
    kind changed
157
        File kind has been changed (e.g. from file to directory).
158
159
    unknown
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
160
        Not versioned and not matching an ignore pattern.
161
2374.1.1 by Ian Clatworthy
Help and man page fixes
162
    To see ignored files use 'bzr ignored'.  For details on the
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
163
    changes to file texts, use 'bzr diff'.
2147.2.1 by Keir Mierle
Add a --short flag to status to get svn-style status
164
    
2792.1.1 by Ian Clatworthy
Add short options to status to assist migrating svn users (Daniel Watkins)
165
    Note that --short or -S gives status flags for each item, similar
166
    to Subversion's status command. To get output similar to svn -q,
3504.3.1 by Andrew Bennetts
Fix trivial bug in 'bzr help status' reported by mlh on #bzr.
167
    use bzr status -SV.
1551.10.10 by Aaron Bentley
Add help text
168
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
169
    If no arguments are specified, the status of the entire working
170
    directory is shown.  Otherwise, only the status of the specified
171
    files or directories is reported.  If a directory is given, status
172
    is reported for everything inside that directory.
1185.1.35 by Robert Collins
Heikki Paajanen's status -r patch
173
174
    If a revision argument is given, the status is calculated against
175
    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
176
    """
1185.16.76 by Martin Pool
doc
177
    
178
    # TODO: --no-recurse, --recurse options
179
    
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
180
    takes_args = ['file*']
2745.4.1 by Lukáš Lalinsky
New option -C/--change for diff and status to show changes in one revision. (#56299)
181
    takes_options = ['show-ids', 'revision', 'change',
2792.1.1 by Ian Clatworthy
Add short options to status to assist migrating svn users (Daniel Watkins)
182
                     Option('short', help='Use short status indicators.',
2663.1.7 by Daniel Watkins
Capitalised short names.
183
                            short_name='S'),
2663.1.5 by Daniel Watkins
Changed 'bzr stat --quiet' to 'bzr stat -(vs|sv)', as per list suggestions.
184
                     Option('versioned', help='Only show versioned files.',
3270.6.1 by James Westby
Add --no-pending to status to not show the pending merges. (#202830)
185
                            short_name='V'),
186
                     Option('no-pending', help='Don\'t show pending merges.',
187
                           ),
2663.1.5 by Daniel Watkins
Changed 'bzr stat --quiet' to 'bzr stat -(vs|sv)', as per list suggestions.
188
                     ]
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
189
    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()
190
191
    encoding_type = 'replace'
2520.1.3 by Daniel Watkins
'help status' now points to 'help status-flags'.
192
    _see_also = ['diff', 'revert', 'status-flags']
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
193
    
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
194
    @display_command
2318.2.1 by Kent Gibson
Apply status versioned patch
195
    def run(self, show_ids=False, file_list=None, revision=None, short=False,
3270.6.1 by James Westby
Add --no-pending to status to not show the pending merges. (#202830)
196
            versioned=False, no_pending=False):
1551.2.9 by Aaron Bentley
Fix status to work with checkouts
197
        from bzrlib.status import show_tree_status
1185.85.15 by John Arbash Meinel
Updated bzr status, adding test_cat
198
2745.4.2 by Lukáš Lalinsky
Allow options to be stored in attributes that differ from their 'name' and use this to let '--change' and '--revision' to override each other.
199
        if revision and len(revision) > 2:
200
            raise errors.BzrCommandError('bzr status --revision takes exactly'
201
                                         ' one or two revision specifiers')
2745.4.1 by Lukáš Lalinsky
New option -C/--change for diff and status to show changes in one revision. (#56299)
202
3636.1.1 by Robert Collins
Stop passing specific_file lists to show_tree_status when the specific
203
        tree, relfile_list = tree_files(file_list)
204
        # Avoid asking for specific files when that is not needed.
205
        if relfile_list == ['']:
206
            relfile_list = None
207
            # Don't disable pending merges for full trees other than '.'.
208
            if file_list == ['.']:
209
                no_pending = True
210
        # A specific path within a tree was given.
211
        elif relfile_list is not None:
212
            no_pending = True
1773.1.2 by Robert Collins
Remove --all option from status.
213
        show_tree_status(tree, show_ids=show_ids,
3636.1.1 by Robert Collins
Stop passing specific_file lists to show_tree_status when the specific
214
                         specific_files=relfile_list, revision=revision,
3270.6.1 by James Westby
Add --no-pending to status to not show the pending merges. (#202830)
215
                         to_file=self.outf, short=short, versioned=versioned,
3636.1.1 by Robert Collins
Stop passing specific_file lists to show_tree_status when the specific
216
                         show_pending=(not no_pending))
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
217
218
219
class cmd_cat_revision(Command):
1185.5.3 by John Arbash Meinel
cat-revision allows --revision for easier investigation.
220
    """Write out metadata for a revision.
221
    
222
    The revision to print can either be specified by a specific
223
    revision identifier, or you can use --revision.
224
    """
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
225
226
    hidden = True
1185.5.3 by John Arbash Meinel
cat-revision allows --revision for easier investigation.
227
    takes_args = ['revision_id?']
228
    takes_options = ['revision']
1685.1.76 by Wouter van Heyst
codecleanup
229
    # cat-revision is more for frontends so should be exact
230
    encoding = 'strict'
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
231
    
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
232
    @display_command
1185.5.3 by John Arbash Meinel
cat-revision allows --revision for easier investigation.
233
    def run(self, revision_id=None, revision=None):
234
        if revision_id is not None and revision is not None:
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
235
            raise errors.BzrCommandError('You can only supply one of'
236
                                         ' revision_id or --revision')
1185.5.3 by John Arbash Meinel
cat-revision allows --revision for easier investigation.
237
        if revision_id is None and revision is None:
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
238
            raise errors.BzrCommandError('You must supply either'
239
                                         ' --revision or a revision_id')
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
240
        b = WorkingTree.open_containing(u'.')[0].branch
1185.85.72 by John Arbash Meinel
Fix some of the tests.
241
242
        # TODO: jam 20060112 should cat-revision always output utf-8?
1185.5.3 by John Arbash Meinel
cat-revision allows --revision for easier investigation.
243
        if revision_id is not None:
2858.2.1 by Martin Pool
Remove most calls to safe_file_id and safe_revision_id.
244
            revision_id = osutils.safe_revision_id(revision_id, warn=False)
3668.4.1 by Jelmer Vernooij
Show proper error rather than traceback when an unknown revision id is specified to bzr cat-revision.
245
            try:
246
                self.outf.write(b.repository.get_revision_xml(revision_id).decode('utf-8'))
247
            except errors.NoSuchRevision:
248
                msg = "The repository %s contains no revision %s." % (b.repository.base,
249
                    revision_id)
250
                raise errors.BzrCommandError(msg)
1185.5.3 by John Arbash Meinel
cat-revision allows --revision for easier investigation.
251
        elif revision is not None:
252
            for rev in revision:
253
                if rev is None:
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
254
                    raise errors.BzrCommandError('You cannot specify a NULL'
255
                                                 ' revision.')
3298.2.14 by Aaron Bentley
Optimize revision-info and cat-revision
256
                rev_id = rev.as_revision_id(b)
1185.85.78 by John Arbash Meinel
[merge] jam-integration 1512, includes Storage changes.
257
                self.outf.write(b.repository.get_revision_xml(rev_id).decode('utf-8'))
3770.1.1 by John Arbash Meinel
First draft of a basic dump-btree command.
258
259
260
class cmd_dump_btree(Command):
261
    """Dump the contents of a btree index file to disk.
262
263
    This is useful because the pages are compressed, so they cannot be read
264
    directly anymore.
265
    """
266
267
    # TODO: Do we want to dump the internal nodes as well?
268
    # TODO: It would be nice to be able to dump the un-parsed information,
269
    #       rather than only going through iter_all_entries. However, this is
270
    #       good enough for a start
271
    hidden = True
272
    takes_args = ['path']
273
274
    def run(self, path):
275
        from bzrlib import btree_index
276
277
        dirname, basename = osutils.split(path)
278
        t = transport.get_transport(dirname)
279
        try:
280
            st = t.stat(basename)
281
        except errors.TransportNotPossible:
282
            # We can't stat, so we'll fake it because we have to do the 'get()'
283
            # anyway.
284
            bt = btree_index.BTreeGraphIndex(t, basename, None)
285
            bytes = t.get_bytes(basename)
286
            bt._file = cStringIO.StringIO(bytes)
287
            bt._size = len(bytes)
288
        else:
289
            bt = btree_index.BTreeGraphIndex(t, basename, st.st_size)
290
        for node in bt.iter_all_entries():
291
            # Node is made up of:
292
            # (index, key, value, [references])
293
            self.outf.write('%s\n' % (node[1:],))
294
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
295
2127.2.1 by Daniel Silverstone
Add remove-tree and its blackbox tests
296
class cmd_remove_tree(Command):
297
    """Remove the working tree from a given branch/checkout.
298
299
    Since a lightweight checkout is little more than a working tree
300
    this will refuse to run against one.
2374.1.3 by Ian Clatworthy
Minor man page fixes for add, commit, export
301
2374.1.4 by Ian Clatworthy
Include feedback from mailing list.
302
    To re-create the working tree, use "bzr checkout".
2127.2.1 by Daniel Silverstone
Add remove-tree and its blackbox tests
303
    """
2485.1.2 by James Westby
Update with comments from review, thanks to John and Aaron.
304
    _see_also = ['checkout', 'working-trees']
2127.2.1 by Daniel Silverstone
Add remove-tree and its blackbox tests
305
    takes_args = ['location?']
3667.2.1 by Lukáš Lalinský
Make `bzr remove-tree` not remove trees with uncommitted changes by default
306
    takes_options = [
307
        Option('force',
308
               help='Remove the working tree even if it has '
309
                    'uncommitted changes.'),
310
        ]
2127.2.1 by Daniel Silverstone
Add remove-tree and its blackbox tests
311
3667.2.1 by Lukáš Lalinský
Make `bzr remove-tree` not remove trees with uncommitted changes by default
312
    def run(self, location='.', force=False):
2127.2.2 by Daniel Silverstone
Refactor the remove-tree stuff after review from J-A-M
313
        d = bzrdir.BzrDir.open(location)
314
        
2127.2.1 by Daniel Silverstone
Add remove-tree and its blackbox tests
315
        try:
316
            working = d.open_workingtree()
2127.2.2 by Daniel Silverstone
Refactor the remove-tree stuff after review from J-A-M
317
        except errors.NoWorkingTree:
2127.2.1 by Daniel Silverstone
Add remove-tree and its blackbox tests
318
            raise errors.BzrCommandError("No working tree to remove")
2127.2.2 by Daniel Silverstone
Refactor the remove-tree stuff after review from J-A-M
319
        except errors.NotLocalUrl:
320
            raise errors.BzrCommandError("You cannot remove the working tree of a "
321
                                         "remote path")
3667.2.1 by Lukáš Lalinský
Make `bzr remove-tree` not remove trees with uncommitted changes by default
322
        if not force:
323
            changes = working.changes_from(working.basis_tree())
324
            if changes.has_changed():
325
                raise errors.UncommittedChanges(working)
326
2127.2.2 by Daniel Silverstone
Refactor the remove-tree stuff after review from J-A-M
327
        working_path = working.bzrdir.root_transport.base
328
        branch_path = working.branch.bzrdir.root_transport.base
329
        if working_path != branch_path:
330
            raise errors.BzrCommandError("You cannot remove the working tree from "
331
                                         "a lightweight checkout")
2127.2.1 by Daniel Silverstone
Add remove-tree and its blackbox tests
332
        
333
        d.destroy_workingtree()
334
        
335
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
336
class cmd_revno(Command):
337
    """Show current revision number.
338
1185.85.24 by John Arbash Meinel
Moved run_bzr_decode into TestCase
339
    This is equal to the number of revisions on this branch.
340
    """
341
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
342
    _see_also = ['info']
1185.50.16 by John Arbash Meinel
[patch] Michael Ellerman: 'Trivial patch to allow revno to take a location'
343
    takes_args = ['location?']
1185.85.24 by John Arbash Meinel
Moved run_bzr_decode into TestCase
344
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
345
    @display_command
1185.50.16 by John Arbash Meinel
[patch] Michael Ellerman: 'Trivial patch to allow revno to take a location'
346
    def run(self, location=u'.'):
1185.85.24 by John Arbash Meinel
Moved run_bzr_decode into TestCase
347
        self.outf.write(str(Branch.open_containing(location)[0].revno()))
348
        self.outf.write('\n')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
349
1182 by Martin Pool
- more disentangling of xml storage format from objects
350
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
351
class cmd_revision_info(Command):
352
    """Show revision number and revision id for a given revision identifier.
353
    """
354
    hidden = True
355
    takes_args = ['revision_info*']
356
    takes_options = ['revision']
1185.85.24 by John Arbash Meinel
Moved run_bzr_decode into TestCase
357
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
358
    @display_command
1185.5.4 by John Arbash Meinel
Updated bzr revision-info, created tests.
359
    def run(self, revision=None, revision_info_list=[]):
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
360
361
        revs = []
362
        if revision is not None:
363
            revs.extend(revision)
1185.5.4 by John Arbash Meinel
Updated bzr revision-info, created tests.
364
        if revision_info_list is not None:
365
            for rev in revision_info_list:
1948.4.33 by John Arbash Meinel
Switch from get_revision_spec() to RevisionSpec.from_string() (as advised by Martin)
366
                revs.append(RevisionSpec.from_string(rev))
2512.2.3 by Matthew Fuller
Default revision-info to the head of the branch when no revision is
367
368
        b = Branch.open_containing(u'.')[0]
369
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
370
        if len(revs) == 0:
2512.2.3 by Matthew Fuller
Default revision-info to the head of the branch when no revision is
371
            revs.append(RevisionSpec.from_string('-1'))
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
372
373
        for rev in revs:
3298.2.14 by Aaron Bentley
Optimize revision-info and cat-revision
374
            revision_id = rev.as_revision_id(b)
375
            try:
376
                revno = '%4d' % (b.revision_id_to_revno(revision_id))
377
            except errors.NoSuchRevision:
2512.2.2 by Matthew Fuller
Update revision-info to show dotted revnos.
378
                dotted_map = b.get_revision_id_to_revno_map()
3298.2.14 by Aaron Bentley
Optimize revision-info and cat-revision
379
                revno = '.'.join(str(i) for i in dotted_map[revision_id])
380
            print '%s %s' % (revno, revision_id)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
381
382
    
383
class cmd_add(Command):
384
    """Add specified files or directories.
385
386
    In non-recursive mode, all the named items are added, regardless
387
    of whether they were previously ignored.  A warning is given if
388
    any of the named files are already versioned.
389
390
    In recursive mode (the default), files are treated the same way
391
    but the behaviour for directories is different.  Directories that
392
    are already versioned do not give a warning.  All directories,
393
    whether already versioned or not, are searched for files or
394
    subdirectories that are neither versioned or ignored, and these
395
    are added.  This search proceeds recursively into versioned
396
    directories.  If no names are given '.' is assumed.
397
398
    Therefore simply saying 'bzr add' will version all files that
399
    are currently unknown.
400
1185.3.3 by Martin Pool
- patch from mpe to automatically add parent directories
401
    Adding a file whose parent directory is not versioned will
402
    implicitly add the parent, and so on up to the root. This means
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
403
    you should never need to explicitly add a directory, they'll just
1185.3.3 by Martin Pool
- patch from mpe to automatically add parent directories
404
    get added when you add a file in the directory.
1185.33.90 by Martin Pool
[merge] add --dry-run option (mpe)
405
406
    --dry-run will show which files would be added, but not actually 
407
    add them.
1911.3.2 by John Arbash Meinel
Adding the AddFromBaseAction, which tries to reuse file ids from another tree
408
409
    --file-ids-from will try to use the file ids from the supplied path.
410
    It looks up ids trying to find a matching parent directory with the
2374.1.3 by Ian Clatworthy
Minor man page fixes for add, commit, export
411
    same filename, and then by pure path. This option is rarely needed
412
    but can be useful when adding the same logical file into two
413
    branches that will be merged later (without showing the two different
2374.1.4 by Ian Clatworthy
Include feedback from mailing list.
414
    adds as a conflict). It is also useful when merging another project
415
    into a subdirectory of this one.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
416
    """
417
    takes_args = ['file*']
2598.1.10 by Martin Pool
Clean up options that are registered globally and used once or not at all.
418
    takes_options = [
419
        Option('no-recurse',
2598.1.11 by Martin Pool
Insist that all options have a help string and fix those that don't.
420
               help="Don't recursively add the contents of directories."),
2598.1.10 by Martin Pool
Clean up options that are registered globally and used once or not at all.
421
        Option('dry-run',
422
               help="Show what would be done, but don't actually do anything."),
423
        'verbose',
424
        Option('file-ids-from',
425
               type=unicode,
426
               help='Lookup file ids from this tree.'),
427
        ]
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()
428
    encoding_type = 'replace'
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
429
    _see_also = ['remove']
1185.53.1 by Michael Ellerman
Add support for bzr add --dry-run
430
1911.3.2 by John Arbash Meinel
Adding the AddFromBaseAction, which tries to reuse file ids from another tree
431
    def run(self, file_list, no_recurse=False, dry_run=False, verbose=False,
432
            file_ids_from=None):
1185.53.1 by Michael Ellerman
Add support for bzr add --dry-run
433
        import bzrlib.add
434
2255.7.69 by Robert Collins
Fix all blackbox add tests, and the add --from-ids case in the UI.
435
        base_tree = None
1911.3.2 by John Arbash Meinel
Adding the AddFromBaseAction, which tries to reuse file ids from another tree
436
        if file_ids_from is not None:
437
            try:
438
                base_tree, base_path = WorkingTree.open_containing(
439
                                            file_ids_from)
440
            except errors.NoWorkingTree:
1996.3.1 by John Arbash Meinel
Demandloading builtins.py drops our load time from 350ms to 291ms
441
                base_branch, base_path = Branch.open_containing(
1911.3.2 by John Arbash Meinel
Adding the AddFromBaseAction, which tries to reuse file ids from another tree
442
                                            file_ids_from)
443
                base_tree = base_branch.basis_tree()
444
445
            action = bzrlib.add.AddFromBaseAction(base_tree, base_path,
446
                          to_file=self.outf, should_print=(not is_quiet()))
447
        else:
448
            action = bzrlib.add.AddAction(to_file=self.outf,
449
                should_print=(not is_quiet()))
450
2255.7.69 by Robert Collins
Fix all blackbox add tests, and the add --from-ids case in the UI.
451
        if base_tree:
452
            base_tree.lock_read()
453
        try:
2568.2.6 by Robert Collins
Review feedback.
454
            file_list = self._maybe_expand_globs(file_list)
2568.2.2 by Robert Collins
* New method ``_glob_expand_file_list_if_needed`` on the ``Command`` class
455
            if file_list:
456
                tree = WorkingTree.open_containing(file_list[0])[0]
457
            else:
458
                tree = WorkingTree.open_containing(u'.')[0]
2568.2.8 by Robert Collins
Really really change the command to use the new API.
459
            added, ignored = tree.smart_add(file_list, not
2568.2.2 by Robert Collins
* New method ``_glob_expand_file_list_if_needed`` on the ``Command`` class
460
                no_recurse, action=action, save=not dry_run)
2255.7.69 by Robert Collins
Fix all blackbox add tests, and the add --from-ids case in the UI.
461
        finally:
462
            if base_tree is not None:
463
                base_tree.unlock()
1185.46.8 by Aaron Bentley
bzr add reports ignored patterns.
464
        if len(ignored) > 0:
1711.1.2 by Robert Collins
'bzr add' is now less verbose in telling you what ignore globs were
465
            if verbose:
466
                for glob in sorted(ignored.keys()):
1185.46.9 by Aaron Bentley
Added verbose option to bzr add, to list all ignored files.
467
                    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()
468
                        self.outf.write("ignored %s matching \"%s\"\n" 
469
                                        % (path, glob))
1711.1.2 by Robert Collins
'bzr add' is now less verbose in telling you what ignore globs were
470
            else:
471
                match_len = 0
472
                for glob, paths in ignored.items():
473
                    match_len += len(paths)
1685.1.69 by Wouter van Heyst
merge bzr.dev 1740
474
                self.outf.write("ignored %d file(s).\n" % match_len)
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()
475
            self.outf.write("If you wish to add some of these files,"
476
                            " please add them by name.\n")
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
477
478
479
class cmd_mkdir(Command):
480
    """Create a new versioned directory.
481
482
    This is equivalent to creating the directory and then adding it.
483
    """
1685.1.80 by Wouter van Heyst
more code cleanup
484
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
485
    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()
486
    encoding_type = 'replace'
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
487
488
    def run(self, dir_list):
489
        for d in dir_list:
490
            os.mkdir(d)
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
491
            wt, dd = WorkingTree.open_containing(d)
1508.1.5 by Robert Collins
Move add from Branch to WorkingTree.
492
            wt.add([dd])
1685.1.80 by Wouter van Heyst
more code cleanup
493
            self.outf.write('added %s\n' % d)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
494
495
496
class cmd_relpath(Command):
497
    """Show path of a file relative to root"""
1685.1.80 by Wouter van Heyst
more code cleanup
498
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
499
    takes_args = ['filename']
500
    hidden = True
501
    
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
502
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
503
    def run(self, filename):
1185.85.19 by John Arbash Meinel
Updated bzr relpath
504
        # TODO: jam 20050106 Can relpath return a munged path if
505
        #       sys.stdout encoding cannot represent it?
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
506
        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()
507
        self.outf.write(relpath)
508
        self.outf.write('\n')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
509
510
511
class cmd_inventory(Command):
1185.33.33 by Martin Pool
[patch] add 'bzr inventory --kind directory'; remove 'bzr directories'
512
    """Show inventory of the current working copy or a revision.
513
514
    It is possible to limit the output to a particular entry
2027.4.2 by John Arbash Meinel
Fix bug #3631, allow 'bzr inventory filename'
515
    type using the --kind option.  For example: --kind file.
516
517
    It is also possible to restrict the list of files to a specific
518
    set. For example: bzr inventory --show-ids this/file
1185.33.33 by Martin Pool
[patch] add 'bzr inventory --kind directory'; remove 'bzr directories'
519
    """
1685.1.80 by Wouter van Heyst
more code cleanup
520
1551.10.13 by Aaron Bentley
Hide 'unknowns', document alterntatives to hidden commands
521
    hidden = True
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
522
    _see_also = ['ls']
2598.1.11 by Martin Pool
Insist that all options have a help string and fix those that don't.
523
    takes_options = [
524
        'revision',
525
        'show-ids',
526
        Option('kind',
2598.1.12 by Martin Pool
Fix up --kind options
527
               help='List entries of a particular kind: file, directory, symlink.',
528
               type=unicode),
2598.1.11 by Martin Pool
Insist that all options have a help string and fix those that don't.
529
        ]
2027.4.2 by John Arbash Meinel
Fix bug #3631, allow 'bzr inventory filename'
530
    takes_args = ['file*']
531
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
532
    @display_command
2027.4.2 by John Arbash Meinel
Fix bug #3631, allow 'bzr inventory filename'
533
    def run(self, revision=None, show_ids=False, kind=None, file_list=None):
1185.33.33 by Martin Pool
[patch] add 'bzr inventory --kind directory'; remove 'bzr directories'
534
        if kind and kind not in ['file', 'directory', 'symlink']:
2598.1.12 by Martin Pool
Fix up --kind options
535
            raise errors.BzrCommandError('invalid kind %r specified' % (kind,))
2027.4.3 by John Arbash Meinel
Change how 'bzr inventory' finds paths
536
537
        work_tree, file_list = tree_files(file_list)
2255.7.24 by John Arbash Meinel
Rework cmd_inventory so that it uses paths2ids and locks the trees for read.
538
        work_tree.lock_read()
539
        try:
540
            if revision is not None:
541
                if len(revision) > 1:
542
                    raise errors.BzrCommandError(
543
                        'bzr inventory --revision takes exactly one revision'
544
                        ' identifier')
3655.3.1 by Lukáš Lalinský
Fix `bzr st -rbranch:PATH_TO_BRANCH`
545
                tree = revision[0].as_tree(work_tree.branch)
2255.7.24 by John Arbash Meinel
Rework cmd_inventory so that it uses paths2ids and locks the trees for read.
546
547
                extra_trees = [work_tree]
548
                tree.lock_read()
549
            else:
550
                tree = work_tree
551
                extra_trees = []
552
553
            if file_list is not None:
554
                file_ids = tree.paths2ids(file_list, trees=extra_trees,
555
                                          require_versioned=True)
556
                # find_ids_across_trees may include some paths that don't
557
                # exist in 'tree'.
558
                entries = sorted((tree.id2path(file_id), tree.inventory[file_id])
559
                                 for file_id in file_ids if file_id in tree)
560
            else:
561
                entries = tree.inventory.entries()
562
        finally:
563
            tree.unlock()
564
            if tree is not work_tree:
565
                work_tree.unlock()
2027.4.2 by John Arbash Meinel
Fix bug #3631, allow 'bzr inventory filename'
566
567
        for path, entry in entries:
1185.33.33 by Martin Pool
[patch] add 'bzr inventory --kind directory'; remove 'bzr directories'
568
            if kind and kind != entry.kind:
569
                continue
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
570
            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()
571
                self.outf.write('%-50s %s\n' % (path, entry.file_id))
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
572
            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()
573
                self.outf.write(path)
574
                self.outf.write('\n')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
575
576
577
class cmd_mv(Command):
578
    """Move or rename a file.
579
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
580
    :Usage:
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
581
        bzr mv OLDNAME NEWNAME
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
582
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
583
        bzr mv SOURCE... DESTINATION
584
585
    If the last argument is a versioned directory, all the other names
586
    are moved into it.  Otherwise, there must be exactly two arguments
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
587
    and the file is changed to a new name.
588
589
    If OLDNAME does not exist on the filesystem but is versioned and
590
    NEWNAME does exist on the filesystem but is not versioned, mv
591
    assumes that the file has been manually moved and only updates
592
    its internal inventory to reflect that change.
593
    The same is valid when moving many SOURCE files to a DESTINATION.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
594
595
    Files cannot be moved between branches.
596
    """
1685.1.80 by Wouter van Heyst
more code cleanup
597
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
598
    takes_args = ['names*']
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
599
    takes_options = [Option("after", help="Move only the bzr identifier"
600
        " of the file, because the file has already been moved."),
601
        ]
1616.1.8 by Martin Pool
Unify 'mv', 'move', 'rename'. (#5379, Matthew Fuller)
602
    aliases = ['move', 'rename']
1185.85.26 by John Arbash Meinel
bzr mv should succeed even if it can't display the paths.
603
    encoding_type = 'replace'
604
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
605
    def run(self, names_list, after=False):
1846.1.1 by Wouter van Heyst
Don't fail on 'bzr mv', extract move tests from OldTests.
606
        if names_list is None:
607
            names_list = []
608
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
609
        if len(names_list) < 2:
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
610
            raise errors.BzrCommandError("missing file argument")
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
611
        tree, rel_names = tree_files(names_list)
3201.2.1 by Lukáš Lalinský
Make 'mv a b' work for already renamed directories, like it does for files
612
        tree.lock_write()
613
        try:
614
            self._run(tree, names_list, rel_names, after)
615
        finally:
616
            tree.unlock()
3246.1.1 by Alexander Belchenko
Allow rename (change case of name) directory on case-insensitive filesystem.
617
3201.2.1 by Lukáš Lalinský
Make 'mv a b' work for already renamed directories, like it does for files
618
    def _run(self, tree, names_list, rel_names, after):
619
        into_existing = osutils.isdir(names_list[-1])
620
        if into_existing and len(names_list) == 2:
3249.4.1 by Alexander Belchenko
merge Lukas' patch and update it with case-insensitive rename check.
621
            # special cases:
622
            # a. case-insensitive filesystem and change case of dir
623
            # b. move directory after the fact (if the source used to be
624
            #    a directory, but now doesn't exist in the working tree
625
            #    and the target is an existing directory, just rename it)
626
            if (not tree.case_sensitive
627
                and rel_names[0].lower() == rel_names[1].lower()):
3201.2.1 by Lukáš Lalinský
Make 'mv a b' work for already renamed directories, like it does for files
628
                into_existing = False
3249.4.1 by Alexander Belchenko
merge Lukas' patch and update it with case-insensitive rename check.
629
            else:
630
                inv = tree.inventory
631
                from_id = tree.path2id(rel_names[0])
632
                if (not osutils.lexists(names_list[0]) and
633
                    from_id and inv.get_file_kind(from_id) == "directory"):
634
                    into_existing = False
635
        # move/rename
3201.2.1 by Lukáš Lalinský
Make 'mv a b' work for already renamed directories, like it does for files
636
        if into_existing:
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
637
            # move into existing directory
2123.3.5 by Steffen Eichenberg
specifying named parameters
638
            for pair in tree.move(rel_names[:-1], rel_names[-1], after=after):
1185.85.25 by John Arbash Meinel
updated 'bzr mv'
639
                self.outf.write("%s => %s\n" % pair)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
640
        else:
641
            if len(names_list) != 2:
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
642
                raise errors.BzrCommandError('to mv multiple files the'
643
                                             ' destination must be a versioned'
644
                                             ' directory')
2123.3.5 by Steffen Eichenberg
specifying named parameters
645
            tree.rename_one(rel_names[0], rel_names[1], after=after)
1185.85.25 by John Arbash Meinel
updated 'bzr mv'
646
            self.outf.write("%s => %s\n" % (rel_names[0], rel_names[1]))
3246.1.1 by Alexander Belchenko
Allow rename (change case of name) directory on case-insensitive filesystem.
647
648
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
649
class cmd_pull(Command):
1649.1.1 by Robert Collins
* 'pull' and 'push' now normalise the revision history, so that any two
650
    """Turn this branch into a mirror of another branch.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
651
652
    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
653
    considered diverged if the destination branch's most recent commit is one
654
    that has not been merged (directly or indirectly) into the parent.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
655
1661.1.1 by Martin Pool
[merge] olaf's --remember changes
656
    If branches have diverged, you can use 'bzr merge' to integrate the changes
657
    from one into the other.  Once one branch has merged, the other should
658
    be able to pull it again.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
659
1185.12.92 by Aaron Bentley
Fixed pull help, renamed clobber to overwrite
660
    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
661
    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
662
663
    If there is no default location set, the first pull will set it.  After
664
    that, you can omit the location to use the default.  To change the
1785.1.4 by John Arbash Meinel
Update help for the new --remember semantics.
665
    default, use --remember. The value will only be saved if the remote
666
    location can be accessed.
3313.1.1 by Ian Clatworthy
Improve doc on send/merge relationship (Peter Schuller)
667
668
    Note: The location can be specified either in the form of a branch,
669
    or in the form of a path to a file containing a merge directive generated
670
    with bzr send.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
671
    """
1685.1.80 by Wouter van Heyst
more code cleanup
672
2520.1.6 by Daniel Watkins
Fixed 'pull' help.
673
    _see_also = ['push', 'update', 'status-flags']
1551.17.4 by Aaron Bentley
Make pull -v description more specific
674
    takes_options = ['remember', 'overwrite', 'revision',
2768.1.5 by Ian Clatworthy
Wrap new std verbose option with new help instead of declaring a new one
675
        custom_help('verbose',
1551.17.4 by Aaron Bentley
Make pull -v description more specific
676
            help='Show logs of pulled revisions.'),
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
677
        Option('directory',
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
678
            help='Branch to pull into, '
679
                 'rather than the one containing the working directory.',
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
680
            short_name='d',
681
            type=unicode,
682
            ),
683
        ]
2520.1.6 by Daniel Watkins
Fixed 'pull' help.
684
    takes_args = ['location?']
1185.85.27 by John Arbash Meinel
Updated bzr branch and bzr pull
685
    encoding_type = 'replace'
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
686
1551.11.10 by Aaron Bentley
Add change reporting to pull
687
    def run(self, location=None, remember=False, overwrite=False,
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
688
            revision=None, verbose=False,
689
            directory=None):
1558.5.6 by Aaron Bentley
Renamed make-repo init-repo
690
        # FIXME: too much stuff is in the command class
1551.14.11 by Aaron Bentley
rename rev_id and other_rev_id
691
        revision_id = None
1551.14.7 by Aaron Bentley
test suite fixes
692
        mergeable = None
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
693
        if directory is None:
694
            directory = u'.'
1558.5.6 by Aaron Bentley
Renamed make-repo init-repo
695
        try:
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
696
            tree_to = WorkingTree.open_containing(directory)[0]
1558.5.6 by Aaron Bentley
Renamed make-repo init-repo
697
            branch_to = tree_to.branch
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
698
        except errors.NoWorkingTree:
1558.5.6 by Aaron Bentley
Renamed make-repo init-repo
699
            tree_to = None
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
700
            branch_to = Branch.open_containing(directory)[0]
1711.3.3 by John Arbash Meinel
Allow pull to use a bundle as a target,
701
2817.4.3 by Vincent Ladeuil
Add tests for commit, reuse master branch transport.
702
        possible_transports = []
1711.3.3 by John Arbash Meinel
Allow pull to use a bundle as a target,
703
        if location is not None:
3251.4.10 by Aaron Bentley
Pull of launchpad locations works (abentley, #181945)
704
            try:
705
                mergeable = bundle.read_mergeable_from_url(location,
706
                    possible_transports=possible_transports)
707
            except errors.NotABundle:
708
                mergeable = None
1711.3.3 by John Arbash Meinel
Allow pull to use a bundle as a target,
709
1558.5.6 by Aaron Bentley
Renamed make-repo init-repo
710
        stored_loc = branch_to.get_parent()
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
711
        if location is None:
712
            if stored_loc is None:
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
713
                raise errors.BzrCommandError("No pull location known or"
714
                                             " specified.")
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
715
            else:
1685.1.58 by Martin Pool
urlutils.unescape_for_display should return Unicode
716
                display_url = urlutils.unescape_for_display(stored_loc,
717
                        self.outf.encoding)
3200.1.1 by James Westby
Make pull --quiet more quiet. Fixes #185907.
718
                if not is_quiet():
3596.3.1 by James Westby
Give the user a bit more information about which saved location is being used.
719
                    self.outf.write("Using saved parent location: %s\n" % display_url)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
720
                location = stored_loc
1185.56.1 by Michael Ellerman
Simplify handling of DivergedBranches in cmd_pull()
721
1551.14.4 by Aaron Bentley
Change bundle reader and merge directive to both be 'mergeables'
722
        if mergeable is not None:
723
            if revision is not None:
724
                raise errors.BzrCommandError(
725
                    'Cannot use -r with merge directives or bundles')
2520.4.109 by Aaron Bentley
start work on directive cherry-picking
726
            mergeable.install_revisions(branch_to.repository)
727
            base_revision_id, revision_id, verified = \
728
                mergeable.get_merge_request(branch_to.repository)
1711.3.3 by John Arbash Meinel
Allow pull to use a bundle as a target,
729
            branch_from = branch_to
730
        else:
3251.4.10 by Aaron Bentley
Pull of launchpad locations works (abentley, #181945)
731
            branch_from = Branch.open(location,
732
                possible_transports=possible_transports)
1711.3.3 by John Arbash Meinel
Allow pull to use a bundle as a target,
733
734
            if branch_to.get_parent() is None or remember:
735
                branch_to.set_parent(branch_from.base)
736
1551.14.4 by Aaron Bentley
Change bundle reader and merge directive to both be 'mergeables'
737
        if revision is not None:
738
            if len(revision) == 1:
3298.2.8 by John Arbash Meinel
Get rid of .in_branch(need_revno=False) in favor of simpler .as_revision_id()
739
                revision_id = revision[0].as_revision_id(branch_from)
1551.14.4 by Aaron Bentley
Change bundle reader and merge directive to both be 'mergeables'
740
            else:
741
                raise errors.BzrCommandError(
742
                    'bzr pull --revision takes one value.')
1185.76.1 by Erik Bågfors
Support for --revision in pull
743
1551.19.42 by Aaron Bentley
Add lock around branch pull
744
        branch_to.lock_write()
745
        try:
746
            if tree_to is not None:
747
                change_reporter = delta._ChangeReporter(
748
                    unversioned_filter=tree_to.is_ignored)
749
                result = tree_to.pull(branch_from, overwrite, revision_id,
750
                                      change_reporter,
751
                                      possible_transports=possible_transports)
752
            else:
753
                result = branch_to.pull(branch_from, overwrite, revision_id)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
754
1551.19.42 by Aaron Bentley
Add lock around branch pull
755
            result.report(self.outf)
756
            if verbose and result.old_revid != result.new_revid:
757
                old_rh = list(
758
                    branch_to.repository.iter_reverse_revision_history(
759
                    result.old_revid))
760
                old_rh.reverse()
761
                new_rh = branch_to.revision_history()
762
                log.show_changed_revisions(branch_to, old_rh, new_rh,
763
                                           to_file=self.outf)
764
        finally:
765
            branch_to.unlock()
1185.31.5 by John Arbash Meinel
Merged pull --verbose changes
766
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
767
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
768
class cmd_push(Command):
1649.1.1 by Robert Collins
* 'pull' and 'push' now normalise the revision history, so that any two
769
    """Update a mirror of this branch.
770
    
771
    The target branch will not have its working tree populated because this
772
    is both expensive, and is not supported on remote file systems.
773
    
774
    Some smart servers or protocols *may* put the working tree in place in
775
    the future.
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
776
777
    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
778
    considered diverged if the destination branch's most recent commit is one
779
    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.
780
781
    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
782
    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.
783
    
784
    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
785
    do a merge (see bzr help merge) from the other branch, and commit that.
786
    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
787
788
    If there is no default push location set, the first push will set it.
789
    After that, you can omit the location to use the default.  To change the
1785.1.4 by John Arbash Meinel
Update help for the new --remember semantics.
790
    default, use --remember. The value will only be saved if the remote
791
    location can be accessed.
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
792
    """
1685.1.80 by Wouter van Heyst
more code cleanup
793
2485.1.2 by James Westby
Update with comments from review, thanks to John and Aaron.
794
    _see_also = ['pull', 'update', 'working-trees']
3256.1.2 by Daniel Watkins
Added revision argument to push.
795
    takes_options = ['remember', 'overwrite', 'verbose', 'revision',
2279.3.1 by mbp at sourcefrog
Add a -d option to push, pull, merge (ported from tags branch)
796
        Option('create-prefix',
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
797
               help='Create the path leading up to the branch '
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
798
                    'if it does not already exist.'),
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
799
        Option('directory',
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
800
            help='Branch to push from, '
801
                 'rather than the one containing the working directory.',
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
802
            short_name='d',
803
            type=unicode,
804
            ),
2279.3.1 by mbp at sourcefrog
Add a -d option to push, pull, merge (ported from tags branch)
805
        Option('use-existing-dir',
806
               help='By default push will fail if the target'
807
                    ' directory exists, but does not already'
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
808
                    ' have a control directory.  This flag will'
2279.3.1 by mbp at sourcefrog
Add a -d option to push, pull, merge (ported from tags branch)
809
                    ' allow push to proceed.'),
3549.1.1 by Martin Pool
rename push --reference to --stacked-on
810
        Option('stacked',
811
            help='Create a stacked branch that references the public location '
812
                'of the parent branch.'),
813
        Option('stacked-on',
3221.19.4 by Ian Clatworthy
shallow -> stacked
814
            help='Create a stacked branch that refers to another branch '
3221.19.2 by Ian Clatworthy
tweaks to ui during review by igc
815
                'for the commit history. Only the work not present in the '
816
                'referenced branch is included in the branch created.',
3221.11.12 by Robert Collins
Basic push --reference support, requires url, slow.
817
            type=unicode),
2279.3.1 by mbp at sourcefrog
Add a -d option to push, pull, merge (ported from tags branch)
818
        ]
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
819
    takes_args = ['location?']
1185.85.31 by John Arbash Meinel
Updated bzr push, including bringing in the unused --verbose flag.
820
    encoding_type = 'replace'
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
821
1495 by Robert Collins
Add a --create-prefix to the new push command.
822
    def run(self, location=None, remember=False, overwrite=False,
3221.14.3 by Ian Clatworthy
Merge bzr.dev r3466
823
        create_prefix=False, verbose=False, revision=None,
3549.1.1 by Martin Pool
rename push --reference to --stacked-on
824
        use_existing_dir=False, directory=None, stacked_on=None,
825
        stacked=False):
3221.19.1 by Ian Clatworthy
refactor cmd_push to use a helper function
826
        from bzrlib.push import _show_push_branch
827
828
        # Get the source branch and revision_id
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
829
        if directory is None:
830
            directory = '.'
3221.11.13 by Robert Collins
Allow push --shallow to just work, and fix the testing HTTPServer to not be affected by chdir() calls.
831
        br_from = Branch.open_containing(directory)[0]
3221.19.1 by Ian Clatworthy
refactor cmd_push to use a helper function
832
        if revision is not None:
833
            if len(revision) == 1:
834
                revision_id = revision[0].in_history(br_from).rev_id
835
            else:
836
                raise errors.BzrCommandError(
837
                    'bzr push --revision takes one value.')
838
        else:
839
            revision_id = br_from.last_revision()
840
3549.1.1 by Martin Pool
rename push --reference to --stacked-on
841
        # Get the stacked_on branch, if any
842
        if stacked_on is not None:
843
            stacked_on = urlutils.normalize_url(stacked_on)
3221.19.4 by Ian Clatworthy
shallow -> stacked
844
        elif stacked:
3221.11.15 by Robert Collins
no parent branch causes an error on push --shallow.
845
            parent_url = br_from.get_parent()
846
            if parent_url:
847
                parent = Branch.open(parent_url)
3549.1.1 by Martin Pool
rename push --reference to --stacked-on
848
                stacked_on = parent.get_public_branch()
849
                if not stacked_on:
3221.11.17 by Robert Collins
no public location causes the parent to be used directly with push --shallow.
850
                    # I considered excluding non-http url's here, thus forcing
851
                    # 'public' branches only, but that only works for some
3221.14.3 by Ian Clatworthy
Merge bzr.dev r3466
852
                    # users, so it's best to just depend on the user spotting an
3221.11.17 by Robert Collins
no public location causes the parent to be used directly with push --shallow.
853
                    # error by the feedback given to them. RBC 20080227.
3549.1.1 by Martin Pool
rename push --reference to --stacked-on
854
                    stacked_on = parent_url
855
            if not stacked_on:
3221.11.15 by Robert Collins
no parent branch causes an error on push --shallow.
856
                raise errors.BzrCommandError(
857
                    "Could not determine branch to refer to.")
3221.19.1 by Ian Clatworthy
refactor cmd_push to use a helper function
858
859
        # Get the destination location
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
860
        if location is None:
3221.19.1 by Ian Clatworthy
refactor cmd_push to use a helper function
861
            stored_loc = br_from.get_push_location()
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
862
            if stored_loc is None:
3221.19.1 by Ian Clatworthy
refactor cmd_push to use a helper function
863
                raise errors.BzrCommandError(
864
                    "No push location known or specified.")
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
865
            else:
1685.1.59 by Martin Pool
[broken] Fix up & refactor display of remembered urls to unescape properly
866
                display_url = urlutils.unescape_for_display(stored_loc,
867
                        self.outf.encoding)
3596.3.1 by James Westby
Give the user a bit more information about which saved location is being used.
868
                self.outf.write("Using saved push location: %s\n" % display_url)
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
869
                location = stored_loc
1685.1.22 by John Arbash Meinel
cmd_push was passing the location directly to relpath, rather than a URL
870
3221.19.1 by Ian Clatworthy
refactor cmd_push to use a helper function
871
        _show_push_branch(br_from, revision_id, location, self.outf,
872
            verbose=verbose, overwrite=overwrite, remember=remember,
3549.1.1 by Martin Pool
rename push --reference to --stacked-on
873
            stacked_on=stacked_on, create_prefix=create_prefix,
3221.19.1 by Ian Clatworthy
refactor cmd_push to use a helper function
874
            use_existing_dir=use_existing_dir)
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
875
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
876
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
877
class cmd_branch(Command):
878
    """Create a new copy of a branch.
879
880
    If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
881
    be used.  In other words, "branch ../foo/bar" will attempt to create ./bar.
2512.4.1 by Ian Clatworthy
Fixes #115491 - 'branch lp:projname' now creates ./projname as exected
882
    If the FROM_LOCATION has no / or path separator embedded, the TO_LOCATION
883
    is derived from the FROM_LOCATION by stripping a leading scheme or drive
884
    identifier, if any. For example, "branch lp:foo-bar" will attempt to
885
    create ./foo-bar.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
886
887
    To retrieve the branch as of a particular revision, supply the --revision
888
    parameter, as in "branch foo/bar -r 5".
889
    """
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
890
891
    _see_also = ['checkout']
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
892
    takes_args = ['from_location', 'to_location?']
3136.1.3 by Aaron Bentley
Implement hard-link support for branch and checkout
893
    takes_options = ['revision', Option('hardlink',
3221.11.20 by Robert Collins
Support --shallow on branch.
894
        help='Hard-link working tree files where possible.'),
3221.20.3 by Ian Clatworthy
shallow -> stacked
895
        Option('stacked',
896
            help='Create a stacked branch referring to the source branch. '
3221.11.20 by Robert Collins
Support --shallow on branch.
897
                'The new branch will depend on the availability of the source '
898
                'branch for all operations.'),
3696.2.3 by Daniel Watkins
Added --standalone option to branch.
899
        Option('standalone',
900
               help='Do not use a shared repository, even if available.'),
3221.11.20 by Robert Collins
Support --shallow on branch.
901
        ]
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
902
    aliases = ['get', 'clone']
903
3136.1.3 by Aaron Bentley
Implement hard-link support for branch and checkout
904
    def run(self, from_location, to_location=None, revision=None,
3696.2.3 by Daniel Watkins
Added --standalone option to branch.
905
            hardlink=False, stacked=False, standalone=False):
2220.2.30 by Martin Pool
split out tag-merging code and add some tests
906
        from bzrlib.tag import _merge_tags_if_possible
1185.17.3 by Martin Pool
[pick] larger read lock scope for branch command
907
        if revision is None:
908
            revision = [None]
909
        elif len(revision) > 1:
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
910
            raise errors.BzrCommandError(
1185.17.3 by Martin Pool
[pick] larger read lock scope for branch command
911
                'bzr branch --revision takes exactly 1 revision value')
2283.1.1 by John Arbash Meinel
(John Arbash Meinel) (trivial) remove unused and incorrect code.
912
3123.5.11 by Aaron Bentley
Accelerate branching from a lightweight checkout
913
        accelerator_tree, br_from = bzrdir.BzrDir.open_tree_or_branch(
914
            from_location)
1185.17.3 by Martin Pool
[pick] larger read lock scope for branch command
915
        br_from.lock_read()
916
        try:
1185.8.4 by Aaron Bentley
Fixed branch -r
917
            if len(revision) == 1 and revision[0] is not None:
3298.2.8 by John Arbash Meinel
Get rid of .in_branch(need_revno=False) in favor of simpler .as_revision_id()
918
                revision_id = revision[0].as_revision_id(br_from)
1185.8.4 by Aaron Bentley
Fixed branch -r
919
            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.
920
                # FIXME - wt.last_revision, fallback to branch, fall back to
921
                # None or perhaps NULL_REVISION to mean copy nothing
922
                # RBC 20060209
923
                revision_id = br_from.last_revision()
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
924
            if to_location is None:
2512.4.1 by Ian Clatworthy
Fixes #115491 - 'branch lp:projname' now creates ./projname as exected
925
                to_location = urlutils.derive_to_location(from_location)
1830.4.7 by Wouter van Heyst
review fixes, rename transport variable to to_transport
926
            to_transport = transport.get_transport(to_location)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
927
            try:
1685.1.20 by John Arbash Meinel
More changes to get 'bzr branch' and 'bzr pull' to work
928
                to_transport.mkdir('.')
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
929
            except errors.FileExists:
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
930
                raise errors.BzrCommandError('Target directory "%s" already'
931
                                             ' exists.' % to_location)
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
932
            except errors.NoSuchFile:
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
933
                raise errors.BzrCommandError('Parent of "%s" does not exist.'
934
                                             % to_location)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
935
            try:
1587.1.14 by Robert Collins
Make bound branch creation happen via 'checkout'
936
                # preserve whatever source format we have.
2485.8.56 by Vincent Ladeuil
Fix bug #112173 and bzr branch multiple connections.
937
                dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
3123.5.8 by Aaron Bentley
Work around double-opening lock issue
938
                                            possible_transports=[to_transport],
3136.1.3 by Aaron Bentley
Implement hard-link support for branch and checkout
939
                                            accelerator_tree=accelerator_tree,
3696.2.3 by Daniel Watkins
Added --standalone option to branch.
940
                                            hardlink=hardlink, stacked=stacked,
941
                                            force_new_repo=standalone)
1587.1.14 by Robert Collins
Make bound branch creation happen via 'checkout'
942
                branch = dir.open_branch()
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
943
            except errors.NoSuchRevision:
1685.1.80 by Wouter van Heyst
more code cleanup
944
                to_transport.delete_tree('.')
3221.20.1 by Ian Clatworthy
tweaks by igc during review
945
                msg = "The branch %s has no revision %s." % (from_location,
946
                    revision[0])
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
947
                raise errors.BzrCommandError(msg)
2220.2.30 by Martin Pool
split out tag-merging code and add some tests
948
            _merge_tags_if_possible(br_from, branch)
3221.20.3 by Ian Clatworthy
shallow -> stacked
949
            # If the source branch is stacked, the new branch may
950
            # be stacked whether we asked for that explicitly or not.
951
            # We therefore need a try/except here and not just 'if stacked:'
3221.11.19 by Robert Collins
Branching a shallow branch gets a shallow branch.
952
            try:
3221.20.3 by Ian Clatworthy
shallow -> stacked
953
                note('Created new stacked branch referring to %s.' %
3537.3.1 by Martin Pool
Rename branch.get_stacked_on to get_stacked_on_url
954
                    branch.get_stacked_on_url())
3221.11.19 by Robert Collins
Branching a shallow branch gets a shallow branch.
955
            except (errors.NotStacked, errors.UnstackableBranchFormat,
3221.11.20 by Robert Collins
Support --shallow on branch.
956
                errors.UnstackableRepositoryFormat), e:
3221.11.19 by Robert Collins
Branching a shallow branch gets a shallow branch.
957
                note('Branched %d revision(s).' % branch.revno())
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
958
        finally:
1185.17.3 by Martin Pool
[pick] larger read lock scope for branch command
959
            br_from.unlock()
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
960
961
1508.1.20 by Robert Collins
Create a checkout command.
962
class cmd_checkout(Command):
963
    """Create a new checkout of an existing branch.
964
1508.1.28 by Robert Collins
Test using bzr checkout to reconstitute working trees.
965
    If BRANCH_LOCATION is omitted, checkout will reconstitute a working tree for
966
    the branch found in '.'. This is useful if you have removed the working tree
967
    or if it was never created - i.e. if you pushed the branch to its current
968
    location using SFTP.
969
    
1508.1.20 by Robert Collins
Create a checkout command.
970
    If the TO_LOCATION is omitted, the last component of the BRANCH_LOCATION will
971
    be used.  In other words, "checkout ../foo/bar" will attempt to create ./bar.
2512.4.1 by Ian Clatworthy
Fixes #115491 - 'branch lp:projname' now creates ./projname as exected
972
    If the BRANCH_LOCATION has no / or path separator embedded, the TO_LOCATION
973
    is derived from the BRANCH_LOCATION by stripping a leading scheme or drive
974
    identifier, if any. For example, "checkout lp:foo-bar" will attempt to
975
    create ./foo-bar.
1508.1.20 by Robert Collins
Create a checkout command.
976
977
    To retrieve the branch as of a particular revision, supply the --revision
978
    parameter, as in "checkout foo/bar -r 5". Note that this will be immediately
979
    out of date [so you cannot commit] but it may be useful (i.e. to examine old
980
    code.)
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
981
    """
1508.1.20 by Robert Collins
Create a checkout command.
982
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
983
    _see_also = ['checkouts', 'branch']
1508.1.28 by Robert Collins
Test using bzr checkout to reconstitute working trees.
984
    takes_args = ['branch_location?', 'to_location?']
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
985
    takes_options = ['revision',
1587.1.14 by Robert Collins
Make bound branch creation happen via 'checkout'
986
                     Option('lightweight',
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
987
                            help="Perform a lightweight checkout.  Lightweight "
1587.1.14 by Robert Collins
Make bound branch creation happen via 'checkout'
988
                                 "checkouts depend on access to the branch for "
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
989
                                 "every operation.  Normal checkouts can perform "
1587.1.14 by Robert Collins
Make bound branch creation happen via 'checkout'
990
                                 "common operations like diff and status without "
991
                                 "such access, and also support local commits."
992
                            ),
3136.1.3 by Aaron Bentley
Implement hard-link support for branch and checkout
993
                     Option('files-from', type=str,
994
                            help="Get file contents from this tree."),
995
                     Option('hardlink',
996
                            help='Hard-link working tree files where possible.'
997
                            ),
1587.1.14 by Robert Collins
Make bound branch creation happen via 'checkout'
998
                     ]
1733.2.8 by Michael Ellerman
Add CVS compatible aliases for checkout and annotate, from fullermd.
999
    aliases = ['co']
1508.1.20 by Robert Collins
Create a checkout command.
1000
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
1001
    def run(self, branch_location=None, to_location=None, revision=None,
3136.1.3 by Aaron Bentley
Implement hard-link support for branch and checkout
1002
            lightweight=False, files_from=None, hardlink=False):
1508.1.20 by Robert Collins
Create a checkout command.
1003
        if revision is None:
1004
            revision = [None]
1005
        elif len(revision) > 1:
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
1006
            raise errors.BzrCommandError(
1508.1.20 by Robert Collins
Create a checkout command.
1007
                'bzr checkout --revision takes exactly 1 revision value')
1508.1.28 by Robert Collins
Test using bzr checkout to reconstitute working trees.
1008
        if branch_location is None:
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
1009
            branch_location = osutils.getcwd()
1508.1.28 by Robert Collins
Test using bzr checkout to reconstitute working trees.
1010
            to_location = branch_location
3123.5.20 by Aaron Bentley
Checkout uses branch tree as a fallback accelerator
1011
        accelerator_tree, source = bzrdir.BzrDir.open_tree_or_branch(
1012
            branch_location)
1013
        if files_from is not None:
1014
            accelerator_tree = WorkingTree.open(files_from)
1508.1.20 by Robert Collins
Create a checkout command.
1015
        if len(revision) == 1 and revision[0] is not None:
3298.2.8 by John Arbash Meinel
Get rid of .in_branch(need_revno=False) in favor of simpler .as_revision_id()
1016
            revision_id = revision[0].as_revision_id(source)
1508.1.20 by Robert Collins
Create a checkout command.
1017
        else:
1018
            revision_id = None
1019
        if to_location is None:
2512.4.1 by Ian Clatworthy
Fixes #115491 - 'branch lp:projname' now creates ./projname as exected
1020
            to_location = urlutils.derive_to_location(branch_location)
1508.1.28 by Robert Collins
Test using bzr checkout to reconstitute working trees.
1021
        # if the source and to_location are the same, 
1022
        # and there is no working tree,
1023
        # then reconstitute a branch
1997.1.4 by Robert Collins
``bzr checkout --lightweight`` now operates on readonly branches as well
1024
        if (osutils.abspath(to_location) ==
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
1025
            osutils.abspath(branch_location)):
1508.1.28 by Robert Collins
Test using bzr checkout to reconstitute working trees.
1026
            try:
1027
                source.bzrdir.open_workingtree()
1028
            except errors.NoWorkingTree:
1551.15.60 by Aaron Bentley
bzr checkout -r always works, even with -r0 (#127708)
1029
                source.bzrdir.create_workingtree(revision_id)
1508.1.28 by Robert Collins
Test using bzr checkout to reconstitute working trees.
1030
                return
3123.5.2 by Aaron Bentley
Allow checkout --files_from
1031
        source.create_checkout(to_location, revision_id, lightweight,
3136.1.3 by Aaron Bentley
Implement hard-link support for branch and checkout
1032
                               accelerator_tree, hardlink)
1508.1.20 by Robert Collins
Create a checkout command.
1033
1034
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1035
class cmd_renames(Command):
1036
    """Show list of renamed files.
1037
    """
1185.16.3 by Martin Pool
- remove all TODOs from bzr help messages
1038
    # TODO: Option to show renames between two historical versions.
1039
1040
    # TODO: Only show renames under dir, rather than in the whole branch.
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
1041
    _see_also = ['status']
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1042
    takes_args = ['dir?']
1043
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1044
    @display_command
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
1045
    def run(self, dir=u'.'):
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
1046
        tree = WorkingTree.open_containing(dir)[0]
2255.7.63 by Robert Collins
Fix cmd_renames to lock around inventory access.
1047
        tree.lock_read()
1048
        try:
1049
            new_inv = tree.inventory
1050
            old_tree = tree.basis_tree()
1051
            old_tree.lock_read()
1052
            try:
1053
                old_inv = old_tree.inventory
1054
                renames = list(_mod_tree.find_renames(old_inv, new_inv))
1055
                renames.sort()
1056
                for old_name, new_name in renames:
1057
                    self.outf.write("%s => %s\n" % (old_name, new_name))
1058
            finally:
1059
                old_tree.unlock()
1060
        finally:
1061
            tree.unlock()
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1062
1063
1508.1.24 by Robert Collins
Add update command for use with checkouts.
1064
class cmd_update(Command):
1065
    """Update a tree to have the latest code committed to its branch.
1066
    
1067
    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.
1068
    conflicts. If you have any local changes, you will still 
1069
    need to commit them after the update for the update to be complete.
1070
    
1071
    If you want to discard your local changes, you can just do a 
1072
    'bzr revert' instead of 'bzr commit' after the update.
1508.1.24 by Robert Collins
Add update command for use with checkouts.
1073
    """
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
1074
2625.5.1 by Daniel Watkins
'bzr update's help now includes a see also reference to 'help status-flags'.
1075
    _see_also = ['pull', 'working-trees', 'status-flags']
1508.1.24 by Robert Collins
Add update command for use with checkouts.
1076
    takes_args = ['dir?']
1815.3.1 by Stefan (metze) Metzmacher
add 'up' as alias for 'update'
1077
    aliases = ['up']
1508.1.24 by Robert Collins
Add update command for use with checkouts.
1078
1079
    def run(self, dir='.'):
1080
        tree = WorkingTree.open_containing(dir)[0]
2806.2.2 by Vincent Ladeuil
Fix #128076 and #131396 by reusing bound branch transport.
1081
        possible_transports = []
1082
        master = tree.branch.get_master_branch(
1083
            possible_transports=possible_transports)
2084.2.1 by Aaron Bentley
Support updating lightweight checkouts of readonly branches
1084
        if master is not None:
1085
            tree.lock_write()
1086
        else:
1087
            tree.lock_tree_write()
1508.1.24 by Robert Collins
Add update command for use with checkouts.
1088
        try:
2014.1.1 by John Arbash Meinel
Stop using pending_merges() in 'bzr update'
1089
            existing_pending_merges = tree.get_parent_ids()[1:]
2598.5.4 by Aaron Bentley
Restore original Branch.last_revision behavior, fix bits that care
1090
            last_rev = _mod_revision.ensure_null(tree.last_revision())
1091
            if last_rev == _mod_revision.ensure_null(
1092
                tree.branch.last_revision()):
1587.1.11 by Robert Collins
Local commits appear to be working properly.
1093
                # may be up to date, check master too.
2598.5.4 by Aaron Bentley
Restore original Branch.last_revision behavior, fix bits that care
1094
                if master is None or last_rev == _mod_revision.ensure_null(
1095
                    master.last_revision()):
1830.1.1 by John Arbash Meinel
Print up to date even if bound, also always print out current revno.
1096
                    revno = tree.branch.revision_id_to_revno(last_rev)
1097
                    note("Tree is up to date at revision %d." % (revno,))
1098
                    return 0
2806.2.2 by Vincent Ladeuil
Fix #128076 and #131396 by reusing bound branch transport.
1099
            conflicts = tree.update(
1100
                delta._ChangeReporter(unversioned_filter=tree.is_ignored),
1101
                possible_transports=possible_transports)
2598.5.4 by Aaron Bentley
Restore original Branch.last_revision behavior, fix bits that care
1102
            revno = tree.branch.revision_id_to_revno(
1103
                _mod_revision.ensure_null(tree.last_revision()))
1830.1.1 by John Arbash Meinel
Print up to date even if bound, also always print out current revno.
1104
            note('Updated to revision %d.' % (revno,))
2014.1.1 by John Arbash Meinel
Stop using pending_merges() in 'bzr update'
1105
            if tree.get_parent_ids()[1:] != existing_pending_merges:
1711.2.108 by John Arbash Meinel
Assert that update informs the user about where their local commits went.
1106
                note('Your local commits will now show as pending merges with '
1878.3.2 by Adeodato Simó
Update with suggestions from John Arbash Meinel.
1107
                     "'bzr status', and can be committed with 'bzr commit'.")
1508.1.24 by Robert Collins
Add update command for use with checkouts.
1108
            if conflicts != 0:
1109
                return 1
1110
            else:
1111
                return 0
1112
        finally:
1113
            tree.unlock()
1114
1115
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1116
class cmd_info(Command):
1694.2.6 by Martin Pool
[merge] bzr.dev
1117
    """Show information about a working tree, branch or repository.
1118
1119
    This command will show all known locations and formats associated to the
1120
    tree, branch or repository.  Statistical information is included with
1121
    each report.
1122
1123
    Branches and working trees will also report any missing revisions.
1124
    """
2485.1.2 by James Westby
Update with comments from review, thanks to John and Aaron.
1125
    _see_also = ['revno', 'working-trees', 'repositories']
1694.2.6 by Martin Pool
[merge] bzr.dev
1126
    takes_args = ['location?']
1624.3.21 by Olaf Conradi
Make bzr info command work on both local and remote locations. Support
1127
    takes_options = ['verbose']
2904.3.1 by Lukáš Lalinský
Unicode-safe output from ``bzr info``.
1128
    encoding_type = 'replace'
1694.2.6 by Martin Pool
[merge] bzr.dev
1129
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1130
    @display_command
2768.1.8 by Ian Clatworthy
Get test suite fully working again
1131
    def run(self, location=None, verbose=False):
1132
        if verbose:
1133
            noise_level = 2
1134
        else:
1135
            noise_level = 0
1694.2.6 by Martin Pool
[merge] bzr.dev
1136
        from bzrlib.info import show_bzrdir_info
1137
        show_bzrdir_info(bzrdir.BzrDir.open_containing(location)[0],
2904.3.1 by Lukáš Lalinský
Unicode-safe output from ``bzr info``.
1138
                         verbose=noise_level, outfile=self.outf)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1139
1140
2292.1.13 by Marius Kruger
* merge the unversion command back into the remove command,
1141
class cmd_remove(Command):
2292.1.24 by Marius Kruger
minor text cleanups
1142
    """Remove files or directories.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1143
3619.5.3 by Robert Collins
Review feedback.
1144
    This makes bzr stop tracking changes to the specified files. bzr will delete
1145
    them if they can easily be recovered using revert. If no options or
1146
    parameters are given bzr will scan for files that are being tracked by bzr
1147
    but missing in your tree and stop tracking them for you.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1148
    """
1551.6.26 by Aaron Bentley
Add support for remove --new
1149
    takes_args = ['file*']
2292.1.30 by Marius Kruger
* Minor text fixes.
1150
    takes_options = ['verbose',
3619.5.1 by Robert Collins
* ``bzr rm`` will now scan for files that are missing and remove just
1151
        Option('new', help='Only remove files that have never been committed.'),
2292.1.28 by Marius Kruger
* NEWS
1152
        RegistryOption.from_kwargs('file-deletion-strategy',
2681.1.7 by Aaron Bentley
Fix option grammar
1153
            'The file deletion mode to be used.',
2292.1.28 by Marius Kruger
* NEWS
1154
            title='Deletion Strategy', value_switches=True, enum_switch=False,
2292.1.30 by Marius Kruger
* Minor text fixes.
1155
            safe='Only delete files if they can be'
1156
                 ' safely recovered (default).',
2292.1.28 by Marius Kruger
* NEWS
1157
            keep="Don't delete any files.",
1158
            force='Delete all the specified files, even if they can not be '
1159
                'recovered and even if they are non-empty directories.')]
3619.5.2 by Robert Collins
* ``bzr rm`` is now aliased to ``bzr del`` for the convenience of svn
1160
    aliases = ['rm', 'del']
1685.1.77 by Wouter van Heyst
WorkingTree.remove takes an optional output file
1161
    encoding_type = 'replace'
2292.1.1 by Marius Kruger
"bzr remove" and "bzr rm" will now remove the working file.
1162
2292.1.30 by Marius Kruger
* Minor text fixes.
1163
    def run(self, file_list, verbose=False, new=False,
2292.1.28 by Marius Kruger
* NEWS
1164
        file_deletion_strategy='safe'):
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
1165
        tree, file_list = tree_files(file_list)
2292.1.1 by Marius Kruger
"bzr remove" and "bzr rm" will now remove the working file.
1166
1167
        if file_list is not None:
2748.3.2 by Aaron Bentley
Fix revert, remove-tree, and various tests to use None for 'no files specified'
1168
            file_list = [f for f in file_list]
2292.1.1 by Marius Kruger
"bzr remove" and "bzr rm" will now remove the working file.
1169
3619.5.1 by Robert Collins
* ``bzr rm`` will now scan for files that are missing and remove just
1170
        tree.lock_write()
1171
        try:
1172
            # Heuristics should probably all move into tree.remove_smart or
1173
            # some such?
1174
            if new:
1175
                added = tree.changes_from(tree.basis_tree(),
1176
                    specific_files=file_list).added
1177
                file_list = sorted([f[0] for f in added], reverse=True)
1178
                if len(file_list) == 0:
1179
                    raise errors.BzrCommandError('No matching files.')
1180
            elif file_list is None:
1181
                # missing files show up in iter_changes(basis) as
1182
                # versioned-with-no-kind.
1183
                missing = []
1184
                for change in tree.iter_changes(tree.basis_tree()):
3619.5.3 by Robert Collins
Review feedback.
1185
                    # Find paths in the working tree that have no kind:
1186
                    if change[1][1] is not None and change[6][1] is None:
3619.5.1 by Robert Collins
* ``bzr rm`` will now scan for files that are missing and remove just
1187
                        missing.append(change[1][1])
1188
                file_list = sorted(missing, reverse=True)
1189
                file_deletion_strategy = 'keep'
1190
            tree.remove(file_list, verbose=verbose, to_file=self.outf,
1191
                keep_files=file_deletion_strategy=='keep',
1192
                force=file_deletion_strategy=='force')
1193
        finally:
1194
            tree.unlock()
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1195
1196
1197
class cmd_file_id(Command):
1198
    """Print file_id of a particular file or directory.
1199
1200
    The file_id is assigned when the file is first added and remains the
1201
    same through all revisions where the file exists, even when it is
1202
    moved or renamed.
1203
    """
1685.1.80 by Wouter van Heyst
more code cleanup
1204
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1205
    hidden = True
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
1206
    _see_also = ['inventory', 'ls']
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1207
    takes_args = ['filename']
1185.85.35 by John Arbash Meinel
Updated file-path
1208
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1209
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1210
    def run(self, filename):
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
1211
        tree, relpath = WorkingTree.open_containing(filename)
2255.7.39 by Robert Collins
Remove gratuitous references to inventory.path2id from builtins.py, allowing more commands to work on dirstate trees.
1212
        i = tree.path2id(relpath)
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
1213
        if i is None:
2067.3.1 by Martin Pool
Clean up BzrNewError, other exception classes and users.
1214
            raise errors.NotVersionedError(filename)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1215
        else:
1685.1.80 by Wouter van Heyst
more code cleanup
1216
            self.outf.write(i + '\n')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1217
1218
1219
class cmd_file_path(Command):
1220
    """Print path of file_ids to a file or directory.
1221
1222
    This prints one line for each directory down to the target,
1185.85.35 by John Arbash Meinel
Updated file-path
1223
    starting at the branch root.
1224
    """
1685.1.80 by Wouter van Heyst
more code cleanup
1225
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1226
    hidden = True
1227
    takes_args = ['filename']
1185.85.35 by John Arbash Meinel
Updated file-path
1228
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1229
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1230
    def run(self, filename):
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
1231
        tree, relpath = WorkingTree.open_containing(filename)
2255.7.39 by Robert Collins
Remove gratuitous references to inventory.path2id from builtins.py, allowing more commands to work on dirstate trees.
1232
        fid = tree.path2id(relpath)
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
1233
        if fid is None:
2067.3.1 by Martin Pool
Clean up BzrNewError, other exception classes and users.
1234
            raise errors.NotVersionedError(filename)
2255.7.39 by Robert Collins
Remove gratuitous references to inventory.path2id from builtins.py, allowing more commands to work on dirstate trees.
1235
        segments = osutils.splitpath(relpath)
1236
        for pos in range(1, len(segments) + 1):
1237
            path = osutils.joinpath(segments[:pos])
1238
            self.outf.write("%s\n" % tree.path2id(path))
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1239
1240
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
1241
class cmd_reconcile(Command):
1242
    """Reconcile bzr metadata in a branch.
1243
1244
    This can correct data mismatches that may have been caused by
1245
    previous ghost operations or bzr upgrades. You should only
1246
    need to run this command if 'bzr check' or a bzr developer 
1247
    advises you to run it.
1248
1249
    If a second branch is provided, cross-branch reconciliation is
1250
    also attempted, which will check that data like the tree root
1251
    id which was not present in very early bzr versions is represented
1252
    correctly in both branches.
1253
1254
    At the same time it is run it may recompress data resulting in 
1255
    a potential saving in disk space or performance gain.
1256
1257
    The branch *MUST* be on a listable system such as local disk or sftp.
1258
    """
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
1259
1260
    _see_also = ['check']
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
1261
    takes_args = ['branch?']
1262
1263
    def run(self, branch="."):
1264
        from bzrlib.reconcile import reconcile
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
1265
        dir = bzrdir.BzrDir.open(branch)
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
1266
        reconcile(dir)
1267
1268
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1269
class cmd_revision_history(Command):
1733.2.1 by Michael Ellerman
Add an optional location parameter to the 'revision-history' command.
1270
    """Display the list of revision ids on a branch."""
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
1271
1272
    _see_also = ['log']
1733.2.1 by Michael Ellerman
Add an optional location parameter to the 'revision-history' command.
1273
    takes_args = ['location?']
1274
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1275
    hidden = True
1185.85.36 by John Arbash Meinel
Working on tests for revision-history, ancestry, and diff
1276
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1277
    @display_command
1733.2.1 by Michael Ellerman
Add an optional location parameter to the 'revision-history' command.
1278
    def run(self, location="."):
1279
        branch = Branch.open_containing(location)[0]
1280
        for revid in branch.revision_history():
1733.2.4 by Michael Ellerman
Merge bzr.dev, fix minor conflict in cmd_revision_history().
1281
            self.outf.write(revid)
1185.85.36 by John Arbash Meinel
Working on tests for revision-history, ancestry, and diff
1282
            self.outf.write('\n')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1283
1284
1225 by Martin Pool
- branch now tracks ancestry - all merged revisions
1285
class cmd_ancestry(Command):
1286
    """List all revisions merged into this branch."""
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
1287
1288
    _see_also = ['log', 'revision-history']
1733.2.2 by Michael Ellerman
Add optional location to ancestry and fix behaviour for checkouts.
1289
    takes_args = ['location?']
1290
1225 by Martin Pool
- branch now tracks ancestry - all merged revisions
1291
    hidden = True
1185.85.36 by John Arbash Meinel
Working on tests for revision-history, ancestry, and diff
1292
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1293
    @display_command
1733.2.2 by Michael Ellerman
Add optional location to ancestry and fix behaviour for checkouts.
1294
    def run(self, location="."):
1295
        try:
1296
            wt = WorkingTree.open_containing(location)[0]
1297
        except errors.NoWorkingTree:
1298
            b = Branch.open(location)
1299
            last_revision = b.last_revision()
1300
        else:
1301
            b = wt.branch
1302
            last_revision = wt.last_revision()
1303
1304
        revision_ids = b.repository.get_ancestry(last_revision)
1668.1.14 by Martin Pool
merge olaf - InvalidRevisionId fixes
1305
        revision_ids.pop(0)
1306
        for revision_id in revision_ids:
1685.1.69 by Wouter van Heyst
merge bzr.dev 1740
1307
            self.outf.write(revision_id + '\n')
1225 by Martin Pool
- branch now tracks ancestry - all merged revisions
1308
1309
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1310
class cmd_init(Command):
1311
    """Make a directory into a versioned branch.
1312
1313
    Use this to create an empty branch, or before importing an
1314
    existing project.
1315
1662.1.19 by Martin Pool
Better error message when initting existing tree
1316
    If there is a repository in a parent directory of the location, then 
1317
    the history of the branch will be stored in the repository.  Otherwise
2374.1.2 by Ian Clatworthy
Improved after feedback from reviewers
1318
    init creates a standalone branch which carries its own history
1319
    in the .bzr directory.
1662.1.19 by Martin Pool
Better error message when initting existing tree
1320
1321
    If there is already a branch at the location but it has no working tree,
1322
    the tree can be populated with 'bzr checkout'.
1323
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
1324
    Recipe for importing a tree of files::
1325
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1326
        cd ~/project
1327
        bzr init
1185.12.93 by Aaron Bentley
Fixed obsolete help
1328
        bzr add .
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1329
        bzr status
3035.1.1 by John Arbash Meinel
Address bug #59302 and fix documentation that uses single quotes.
1330
        bzr commit -m "imported project"
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1331
    """
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
1332
2677.1.2 by Alexander Belchenko
bzr_man: see also topics as cross-reference links
1333
    _see_also = ['init-repository', 'branch', 'checkout']
1185.16.138 by Martin Pool
[patch] 'bzr init DIR' (John)
1334
    takes_args = ['location?']
1857.1.20 by Aaron Bentley
Strip out all the EnumOption stuff
1335
    takes_options = [
2524.1.1 by Aaron Bentley
Revert broken changes
1336
        Option('create-prefix',
1337
               help='Create the path leading up to the branch '
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
1338
                    'if it does not already exist.'),
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
1339
         RegistryOption('format',
1340
                help='Specify a format for this branch. '
1341
                'See "help formats".',
3224.5.2 by Andrew Bennetts
Avoid importing bzrlib.bzrdir unnecessarily.
1342
                lazy_registry=('bzrlib.bzrdir', 'format_registry'),
1343
                converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
2241.1.19 by mbp at sourcefrog
(merge) trunk
1344
                value_switches=True,
1345
                title="Branch Format",
1346
                ),
2230.3.42 by Aaron Bentley
add --append-revisions-only option to init
1347
         Option('append-revisions-only',
1348
                help='Never change revnos or the existing log.'
1349
                '  Append revisions to it only.')
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
1350
         ]
2524.1.1 by Aaron Bentley
Revert broken changes
1351
    def run(self, location=None, format=None, append_revisions_only=False,
1352
            create_prefix=False):
1857.1.20 by Aaron Bentley
Strip out all the EnumOption stuff
1353
        if format is None:
2204.5.5 by Aaron Bentley
Remove RepositoryFormat.set_default_format, deprecate get_format_type
1354
            format = bzrdir.format_registry.make_bzrdir('default')
1185.16.138 by Martin Pool
[patch] 'bzr init DIR' (John)
1355
        if location is None:
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
1356
            location = u'.'
1830.4.5 by Wouter van Heyst
cleanup
1357
1830.4.7 by Wouter van Heyst
review fixes, rename transport variable to to_transport
1358
        to_transport = transport.get_transport(location)
1830.4.5 by Wouter van Heyst
cleanup
1359
1360
        # The path has to exist to initialize a
1361
        # branch inside of it.
1362
        # Just using os.mkdir, since I don't
1363
        # believe that we want to create a bunch of
1364
        # locations if the user supplies an extended path
2524.1.1 by Aaron Bentley
Revert broken changes
1365
        try:
1366
            to_transport.ensure_base()
1367
        except errors.NoSuchFile:
1368
            if not create_prefix:
1369
                raise errors.BzrCommandError("Parent directory of %s"
1370
                    " does not exist."
1371
                    "\nYou may supply --create-prefix to create all"
1372
                    " leading parent directories."
1373
                    % location)
1374
            _create_prefix(to_transport)
2504.1.3 by Daniel Watkins
Implemented --create-prefix for 'init'.
1375
1654.1.4 by Robert Collins
Teach `bzr init` how to init at the root of a repository.
1376
        try:
3697.5.4 by John Arbash Meinel
Merge vila's init[-repo] changes and add a NEWS entry.
1377
            a_bzrdir = bzrdir.BzrDir.open_from_transport(to_transport)
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
1378
        except errors.NotBranchError:
1662.1.19 by Martin Pool
Better error message when initting existing tree
1379
            # really a NotBzrDir error...
2476.3.11 by Vincent Ladeuil
Cosmetic changes.
1380
            create_branch = bzrdir.BzrDir.create_branch_convenience
2476.3.6 by Vincent Ladeuil
Fix the 'init connects multiple times' in a different way.
1381
            branch = create_branch(to_transport.base, format=format,
2476.3.8 by Vincent Ladeuil
Mark transports that need to be instrumented or refactored to check
1382
                                   possible_transports=[to_transport])
3697.5.4 by John Arbash Meinel
Merge vila's init[-repo] changes and add a NEWS entry.
1383
            a_bzrdir = branch.bzrdir
1654.1.4 by Robert Collins
Teach `bzr init` how to init at the root of a repository.
1384
        else:
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
1385
            from bzrlib.transport.local import LocalTransport
3697.5.4 by John Arbash Meinel
Merge vila's init[-repo] changes and add a NEWS entry.
1386
            if a_bzrdir.has_branch():
1830.4.8 by Wouter van Heyst
clean up imports (and get if collapsing right)
1387
                if (isinstance(to_transport, LocalTransport)
3697.5.4 by John Arbash Meinel
Merge vila's init[-repo] changes and add a NEWS entry.
1388
                    and not a_bzrdir.has_workingtree()):
1830.4.1 by Wouter van Heyst
Allow bzr init to create remote branches
1389
                        raise errors.BranchExistsWithoutWorkingTree(location)
1390
                raise errors.AlreadyBranchError(location)
3697.5.4 by John Arbash Meinel
Merge vila's init[-repo] changes and add a NEWS entry.
1391
            branch = a_bzrdir.create_branch()
1392
            a_bzrdir.create_workingtree()
2230.3.42 by Aaron Bentley
add --append-revisions-only option to init
1393
        if append_revisions_only:
1394
            try:
1395
                branch.set_append_revisions_only(True)
1396
            except errors.UpgradeRequired:
1397
                raise errors.BzrCommandError('This branch format cannot be set'
1398
                    ' to append-revisions-only.  Try --experimental-branch6')
3535.9.1 by Marius Kruger
print info after init and init-repo
1399
        if not is_quiet():
1400
            from bzrlib.info import show_bzrdir_info
3697.5.4 by John Arbash Meinel
Merge vila's init[-repo] changes and add a NEWS entry.
1401
            show_bzrdir_info(a_bzrdir, verbose=0, outfile=self.outf)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1402
1403
1558.5.6 by Aaron Bentley
Renamed make-repo init-repo
1404
class cmd_init_repository(Command):
1658.1.6 by Martin Pool
init-repo shouldn't insist on creating a new directory (Malone #38331)
1405
    """Create a shared repository to hold branches.
1406
2485.1.2 by James Westby
Update with comments from review, thanks to John and Aaron.
1407
    New branches created under the repository directory will store their
1408
    revisions in the repository, not in the branch directory.
1409
1410
    If the --no-trees option is used then the branches in the repository
1411
    will not have working trees by default.
1658.1.6 by Martin Pool
init-repo shouldn't insist on creating a new directory (Malone #38331)
1412
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
1413
    :Examples:
1414
        Create a shared repositories holding just branches::
1415
1416
            bzr init-repo --no-trees repo
1417
            bzr init repo/trunk
1418
1419
        Make a lightweight checkout elsewhere::
1420
1421
            bzr checkout --lightweight repo/trunk trunk-checkout
1422
            cd trunk-checkout
1423
            (add files here)
1658.1.6 by Martin Pool
init-repo shouldn't insist on creating a new directory (Malone #38331)
1424
    """
2353.2.1 by John Arbash Meinel
(Wouter van Heyst) switch 'bzr init-repo' to default to '--no-trees'
1425
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
1426
    _see_also = ['init', 'branch', 'checkout', 'repositories']
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
1427
    takes_args = ["location"]
2221.4.9 by Aaron Bentley
Zap trailing whitespace
1428
    takes_options = [RegistryOption('format',
2221.4.12 by Aaron Bentley
Add option grouping to RegistryOption and clean up format options
1429
                            help='Specify a format for this repository. See'
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
1430
                                 ' "bzr help formats" for details.',
3224.5.2 by Andrew Bennetts
Avoid importing bzrlib.bzrdir unnecessarily.
1431
                            lazy_registry=('bzrlib.bzrdir', 'format_registry'),
1432
                            converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
2221.4.12 by Aaron Bentley
Add option grouping to RegistryOption and clean up format options
1433
                            value_switches=True, title='Repository format'),
2257.2.1 by Wouter van Heyst
Change the ui level default for init-repo to --trees.
1434
                     Option('no-trees',
2353.2.1 by John Arbash Meinel
(Wouter van Heyst) switch 'bzr init-repo' to default to '--no-trees'
1435
                             help='Branches in the repository will default to'
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
1436
                                  ' not having a working tree.'),
2353.2.1 by John Arbash Meinel
(Wouter van Heyst) switch 'bzr init-repo' to default to '--no-trees'
1437
                    ]
1558.5.6 by Aaron Bentley
Renamed make-repo init-repo
1438
    aliases = ["init-repo"]
2353.2.1 by John Arbash Meinel
(Wouter van Heyst) switch 'bzr init-repo' to default to '--no-trees'
1439
2257.2.2 by Wouter van Heyst
Actually test that `bzr init-repo --{no,}-trees` still works
1440
    def run(self, location, format=None, no_trees=False):
1857.1.20 by Aaron Bentley
Strip out all the EnumOption stuff
1441
        if format is None:
2204.5.5 by Aaron Bentley
Remove RepositoryFormat.set_default_format, deprecate get_format_type
1442
            format = bzrdir.format_registry.make_bzrdir('default')
1857.1.20 by Aaron Bentley
Strip out all the EnumOption stuff
1443
1444
        if location is None:
1445
            location = '.'
1446
1830.4.7 by Wouter van Heyst
review fixes, rename transport variable to to_transport
1447
        to_transport = transport.get_transport(location)
2475.3.3 by John Arbash Meinel
Change calls to try/mkdir('.')/except FileExists to ensure_base()
1448
        to_transport.ensure_base()
1830.4.5 by Wouter van Heyst
cleanup
1449
1857.1.20 by Aaron Bentley
Strip out all the EnumOption stuff
1450
        newdir = format.initialize_on_transport(to_transport)
1558.5.2 by Aaron Bentley
Created *shared* repositories...
1451
        repo = newdir.create_repository(shared=True)
2257.2.2 by Wouter van Heyst
Actually test that `bzr init-repo --{no,}-trees` still works
1452
        repo.set_make_working_trees(not no_trees)
3535.9.1 by Marius Kruger
print info after init and init-repo
1453
        if not is_quiet():
1454
            from bzrlib.info import show_bzrdir_info
3697.5.4 by John Arbash Meinel
Merge vila's init[-repo] changes and add a NEWS entry.
1455
            show_bzrdir_info(repo.bzrdir, verbose=0, outfile=self.outf)
1558.5.1 by Aaron Bentley
Added make-repository command
1456
1457
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1458
class cmd_diff(Command):
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
1459
    """Show differences in the working tree, between revisions or branches.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1460
    
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
1461
    If no arguments are given, all changes for the current tree are listed.
1462
    If files are given, only the changes in those files are listed.
1463
    Remote and multiple branches can be compared by using the --old and
1464
    --new options. If not provided, the default for both is derived from
1465
    the first argument, if any, or the current tree if no arguments are
1466
    given.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1467
1694.2.3 by Martin Pool
Add -p0, -p1 options for diff.
1468
    "bzr diff -p1" is equivalent to "bzr diff --prefix old/:new/", and
1469
    produces patches suitable for "patch -p1".
1470
2961.2.1 by Guillermo Gonzalez
* fix Bug #147938 (add exit values reference for cmd_diff help)
1471
    :Exit values:
1472
        1 - changed
1473
        2 - unrepresentable changes
1474
        3 - error
1475
        0 - no change
1476
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
1477
    :Examples:
1478
        Shows the difference in the working tree versus the last commit::
1479
1480
            bzr diff
1481
1482
        Difference between the working tree and revision 1::
1483
1484
            bzr diff -r1
1485
1486
        Difference between revision 2 and revision 1::
1487
1488
            bzr diff -r1..2
1489
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
1490
        Difference between revision 2 and revision 1 for branch xxx::
1491
1492
            bzr diff -r1..2 xxx
1493
1494
        Show just the differences for file NEWS::
1495
1496
            bzr diff NEWS
1497
1498
        Show the differences in working tree xxx for file NEWS::
1499
1500
            bzr diff xxx/NEWS
1501
1502
        Show the differences from branch xxx to this working tree:
1503
1504
            bzr diff --old xxx
1505
1506
        Show the differences between two branches for file NEWS::
1507
3072.1.4 by Ian Clatworthy
Tweak help
1508
            bzr diff --old xxx --new yyy NEWS
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
1509
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
1510
        Same as 'bzr diff' but prefix paths with old/ and new/::
1511
1512
            bzr diff --prefix old/:new/
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1513
    """
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
1514
    _see_also = ['status']
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1515
    takes_args = ['file*']
2598.1.10 by Martin Pool
Clean up options that are registered globally and used once or not at all.
1516
    takes_options = [
2598.1.11 by Martin Pool
Insist that all options have a help string and fix those that don't.
1517
        Option('diff-options', type=str,
1518
               help='Pass these options to the external diff program.'),
2193.3.1 by Martin Pool
Finish removal of global short-option table
1519
        Option('prefix', type=str,
1520
               short_name='p',
2852.1.1 by Vincent Ladeuil
Fix typo.
1521
               help='Set prefixes added to old and new filenames, as '
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
1522
                    'two values separated by a colon. (eg "old/:new/").'),
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
1523
        Option('old',
3118.1.2 by Ian Clatworthy
diff on branches without working trees (Ian Clatworthy, #6700)
1524
            help='Branch/tree to compare from.',
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
1525
            type=unicode,
1526
            ),
1527
        Option('new',
3118.1.2 by Ian Clatworthy
diff on branches without working trees (Ian Clatworthy, #6700)
1528
            help='Branch/tree to compare to.',
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
1529
            type=unicode,
1530
            ),
2598.1.11 by Martin Pool
Insist that all options have a help string and fix those that don't.
1531
        'revision',
2745.4.1 by Lukáš Lalinsky
New option -C/--change for diff and status to show changes in one revision. (#56299)
1532
        'change',
3123.6.2 by Aaron Bentley
Implement diff --using natively
1533
        Option('using',
1534
            help='Use this command to compare files.',
1535
            type=unicode,
1536
            ),
2190.2.1 by Martin Pool
remove global registration of short options
1537
        ]
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1538
    aliases = ['di', 'dif']
1185.85.36 by John Arbash Meinel
Working on tests for revision-history, ancestry, and diff
1539
    encoding_type = 'exact'
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1540
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1541
    @display_command
1684.1.6 by Martin Pool
(patch) --diff-prefix option (goffredo, alexander)
1542
    def run(self, revision=None, file_list=None, diff_options=None,
3123.6.2 by Aaron Bentley
Implement diff --using natively
1543
            prefix=None, old=None, new=None, using=None):
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
1544
        from bzrlib.diff import _get_trees_to_diff, show_diff_trees
1684.1.6 by Martin Pool
(patch) --diff-prefix option (goffredo, alexander)
1545
1694.2.3 by Martin Pool
Add -p0, -p1 options for diff.
1546
        if (prefix is None) or (prefix == '0'):
1547
            # diff -p0 format
1694.2.1 by Martin Pool
Remove 'a/', 'b/' default prefixes on diff output.
1548
            old_label = ''
1549
            new_label = ''
1694.2.3 by Martin Pool
Add -p0, -p1 options for diff.
1550
        elif prefix == '1':
1551
            old_label = 'old/'
1552
            new_label = 'new/'
2197.2.1 by Martin Pool
Refactor cmd_diff
1553
        elif ':' in prefix:
1694.2.3 by Martin Pool
Add -p0, -p1 options for diff.
1554
            old_label, new_label = prefix.split(":")
2197.2.1 by Martin Pool
Refactor cmd_diff
1555
        else:
2324.1.1 by Dmitry Vasiliev
Small fixes for bzr diff
1556
            raise errors.BzrCommandError(
2325.1.2 by John Arbash Meinel
Add (eg "old/:new/") to errors to make it a little clearer.
1557
                '--prefix expects two values separated by a colon'
1558
                ' (eg "old/:new/")')
2197.2.1 by Martin Pool
Refactor cmd_diff
1559
2745.4.2 by Lukáš Lalinsky
Allow options to be stored in attributes that differ from their 'name' and use this to let '--change' and '--revision' to override each other.
1560
        if revision and len(revision) > 2:
1561
            raise errors.BzrCommandError('bzr diff --revision takes exactly'
1562
                                         ' one or two revision specifiers')
2325.1.2 by John Arbash Meinel
Add (eg "old/:new/") to errors to make it a little clearer.
1563
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
1564
        old_tree, new_tree, specific_files, extra_trees = \
1565
                _get_trees_to_diff(file_list, revision, old, new)
1566
        return show_diff_trees(old_tree, new_tree, sys.stdout, 
1567
                               specific_files=specific_files,
1568
                               external_diff_options=diff_options,
1569
                               old_label=old_label, new_label=new_label,
3123.6.2 by Aaron Bentley
Implement diff --using natively
1570
                               extra_trees=extra_trees, using=using)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1571
1572
1573
class cmd_deleted(Command):
1574
    """List files deleted in the working tree.
1575
    """
1185.16.3 by Martin Pool
- remove all TODOs from bzr help messages
1576
    # TODO: Show files deleted since a previous revision, or
1577
    # between two revisions.
1578
    # TODO: Much more efficient way to do this: read in new
1579
    # directories with readdir, rather than stating each one.  Same
1580
    # level of effort but possibly much less IO.  (Or possibly not,
1581
    # if the directories are very large...)
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
1582
    _see_also = ['status', 'ls']
1185.85.49 by John Arbash Meinel
Updated cmd_deleted, including adding --show-ids option.
1583
    takes_options = ['show-ids']
1584
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1585
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1586
    def run(self, show_ids=False):
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
1587
        tree = WorkingTree.open_containing(u'.')[0]
2255.7.72 by Robert Collins
Update cmd_deleted to lock around inventory access.
1588
        tree.lock_read()
1589
        try:
1590
            old = tree.basis_tree()
1591
            old.lock_read()
1592
            try:
1593
                for path, ie in old.inventory.iter_entries():
1594
                    if not tree.has_id(ie.file_id):
1595
                        self.outf.write(path)
1596
                        if show_ids:
1597
                            self.outf.write(' ')
1598
                            self.outf.write(ie.file_id)
1599
                        self.outf.write('\n')
1600
            finally:
1601
                old.unlock()
1602
        finally:
1603
            tree.unlock()
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1604
1605
1606
class cmd_modified(Command):
1551.10.13 by Aaron Bentley
Hide 'unknowns', document alterntatives to hidden commands
1607
    """List files modified in working tree.
1608
    """
1551.10.14 by Aaron Bentley
Add some blank lines
1609
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1610
    hidden = True
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
1611
    _see_also = ['status', 'ls']
3251.6.2 by Adrian Wilkins
Added null separation option for bzr modified and bzr added
1612
    takes_options = [
1613
            Option('null',
1614
                   help='Write an ascii NUL (\\0) separator '
1615
                   'between files rather than a newline.')
1616
            ]
1551.10.14 by Aaron Bentley
Add some blank lines
1617
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1618
    @display_command
3251.6.2 by Adrian Wilkins
Added null separation option for bzr modified and bzr added
1619
    def run(self, null=False):
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
1620
        tree = WorkingTree.open_containing(u'.')[0]
1852.10.3 by Robert Collins
Remove all uses of compare_trees and replace with Tree.changes_from throughout bzrlib.
1621
        td = tree.changes_from(tree.basis_tree())
1398 by Robert Collins
integrate in Gustavos x-bit patch
1622
        for path, id, kind, text_modified, meta_modified in td.modified:
3251.6.2 by Adrian Wilkins
Added null separation option for bzr modified and bzr added
1623
            if null:
1624
                self.outf.write(path + '\0')
1625
            else:
1626
                self.outf.write(osutils.quotefn(path) + '\n')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1627
1628
1629
class cmd_added(Command):
1551.10.13 by Aaron Bentley
Hide 'unknowns', document alterntatives to hidden commands
1630
    """List files added in working tree.
1631
    """
1551.10.14 by Aaron Bentley
Add some blank lines
1632
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1633
    hidden = True
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
1634
    _see_also = ['status', 'ls']
3251.6.2 by Adrian Wilkins
Added null separation option for bzr modified and bzr added
1635
    takes_options = [
1636
            Option('null',
1637
                   help='Write an ascii NUL (\\0) separator '
1638
                   'between files rather than a newline.')
1639
            ]
1551.10.14 by Aaron Bentley
Add some blank lines
1640
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1641
    @display_command
3251.6.2 by Adrian Wilkins
Added null separation option for bzr modified and bzr added
1642
    def run(self, null=False):
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
1643
        wt = WorkingTree.open_containing(u'.')[0]
2255.7.69 by Robert Collins
Fix all blackbox add tests, and the add --from-ids case in the UI.
1644
        wt.lock_read()
1645
        try:
1646
            basis = wt.basis_tree()
1647
            basis.lock_read()
1648
            try:
1649
                basis_inv = basis.inventory
1650
                inv = wt.inventory
1651
                for file_id in inv:
1652
                    if file_id in basis_inv:
1653
                        continue
1654
                    if inv.is_root(file_id) and len(basis_inv) == 0:
1655
                        continue
1656
                    path = inv.id2path(file_id)
1657
                    if not os.access(osutils.abspath(path), os.F_OK):
1658
                        continue
3251.6.2 by Adrian Wilkins
Added null separation option for bzr modified and bzr added
1659
                    if null:
1660
                        self.outf.write(path + '\0')
1661
                    else:
1662
                        self.outf.write(osutils.quotefn(path) + '\n')
2255.7.69 by Robert Collins
Fix all blackbox add tests, and the add --from-ids case in the UI.
1663
            finally:
1664
                basis.unlock()
1665
        finally:
1666
            wt.unlock()
1185.85.53 by John Arbash Meinel
Updated cmd_root
1667
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1668
1669
class cmd_root(Command):
1670
    """Show the tree root directory.
1671
1672
    The root is the nearest enclosing directory with a .bzr control
1673
    directory."""
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
1674
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1675
    takes_args = ['filename?']
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1676
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1677
    def run(self, filename=None):
1678
        """Print the branch root."""
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
1679
        tree = WorkingTree.open_containing(filename)[0]
1685.1.80 by Wouter van Heyst
more code cleanup
1680
        self.outf.write(tree.basedir + '\n')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1681
1682
2466.9.1 by Kent Gibson
add bzr log --limit
1683
def _parse_limit(limitstring):
1684
    try:
1685
        return int(limitstring)
1686
    except ValueError:
1687
        msg = "The limit argument must be an integer."
1688
        raise errors.BzrCommandError(msg)
1689
1690
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1691
class cmd_log(Command):
1626.1.2 by Martin Pool
Better help message for log command.
1692
    """Show log of a branch, file, or directory.
1693
1694
    By default show the log of the branch containing the working directory.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1695
1185.16.153 by Martin Pool
[patch] fix help for bzr log (Matthieu)
1696
    To request a range of logs, you can use the command -r begin..end
1697
    -r revision requests a specific revision, -r ..end or -r begin.. are
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1698
    also valid.
1626.1.2 by Martin Pool
Better help message for log command.
1699
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
1700
    :Examples:
1701
        Log the current branch::
1702
1703
            bzr log
1704
1705
        Log a file::
1706
1707
            bzr log foo.c
1708
1709
        Log the last 10 revisions of a branch::
1710
1711
            bzr log -r -10.. http://server/branch
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1712
    """
1713
1393.1.55 by Martin Pool
doc
1714
    # TODO: Make --revision support uuid: and hash: [future tag:] notation.
1715
1626.1.2 by Martin Pool
Better help message for log command.
1716
    takes_args = ['location?']
2598.1.3 by Martin Pool
Option help improvements (thanks jamesw)
1717
    takes_options = [
1718
            Option('forward',
1719
                   help='Show from oldest to newest.'),
3755.1.1 by Vincent Ladeuil
Fix --verbose leaking into blackbox tests.
1720
            'timezone',
2768.1.5 by Ian Clatworthy
Wrap new std verbose option with new help instead of declaring a new one
1721
            custom_help('verbose',
2598.1.3 by Martin Pool
Option help improvements (thanks jamesw)
1722
                   help='Show files changed in each revision.'),
1723
            'show-ids',
1724
            'revision',
3734.1.1 by Vincent Ladeuil
Fix bug #248427 by adding a --change option to log.
1725
            Option('change',
1726
                   type=bzrlib.option._parse_revision_str,
1727
                   short_name='c',
1728
                   help='Show just the specified revision.'
1729
                   ' See also "help revisionspec".'),
2598.1.3 by Martin Pool
Option help improvements (thanks jamesw)
1730
            'log-format',
1731
            Option('message',
1732
                   short_name='m',
1733
                   help='Show revisions whose message matches this '
1734
                        'regular expression.',
1735
                   type=str),
1736
            Option('limit',
3108.1.1 by Matt Nordhoff
bzr log: Add -l short name for the --limit argument.
1737
                   short_name='l',
2598.1.3 by Martin Pool
Option help improvements (thanks jamesw)
1738
                   help='Limit the output to the first N revisions.',
1739
                   argname='N',
1740
                   type=_parse_limit),
1741
            ]
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()
1742
    encoding_type = 'replace'
1743
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1744
    @display_command
1626.1.2 by Martin Pool
Better help message for log command.
1745
    def run(self, location=None, timezone='original',
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1746
            verbose=False,
1747
            show_ids=False,
1748
            forward=False,
1749
            revision=None,
3734.1.1 by Vincent Ladeuil
Fix bug #248427 by adding a --change option to log.
1750
            change=None,
1553.2.1 by Erik Bågfors
Support for plugins to register log formatters and set default formatter
1751
            log_format=None,
2466.9.1 by Kent Gibson
add bzr log --limit
1752
            message=None,
1753
            limit=None):
2221.4.10 by Aaron Bentley
Implement log options using RegistryOption
1754
        from bzrlib.log import show_log
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1755
        direction = (forward and 'forward') or 'reverse'
3734.1.1 by Vincent Ladeuil
Fix bug #248427 by adding a --change option to log.
1756
1757
        if change is not None:
1758
            if len(change) > 1:
1759
                raise errors.RangeInChangeOption()
1760
            if revision is not None:
1761
                raise errors.BzrCommandError(
1762
                    '--revision and --change are mutually exclusive')
1763
            else:
1764
                revision = change
1765
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1766
        # log everything
1767
        file_id = None
1626.1.2 by Martin Pool
Better help message for log command.
1768
        if location:
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1769
            # find the file id to log:
1770
1551.10.18 by Aaron Bentley
Log works in local treeless branches (#84247)
1771
            tree, b, fp = bzrdir.BzrDir.open_containing_tree_or_branch(
1772
                location)
1442.1.64 by Robert Collins
Branch.open_containing now returns a tuple (Branch, relative-path).
1773
            if fp != '':
1551.10.18 by Aaron Bentley
Log works in local treeless branches (#84247)
1774
                if tree is None:
1775
                    tree = b.basis_tree()
2255.7.39 by Robert Collins
Remove gratuitous references to inventory.path2id from builtins.py, allowing more commands to work on dirstate trees.
1776
                file_id = tree.path2id(fp)
2100.1.1 by wang
Running ``bzr log`` on nonexistent file gives an error instead of the
1777
                if file_id is None:
1778
                    raise errors.BzrCommandError(
1779
                        "Path does not have any revision history: %s" %
1780
                        location)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1781
        else:
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1782
            # local dir only
1783
            # FIXME ? log the current subdir only RBC 20060203 
1907.4.10 by Matthieu Moy
Cut long lines, prevent "path" component from being used in revno:branch/path.
1784
            if revision is not None \
1785
                    and len(revision) > 0 and revision[0].get_branch():
1907.4.2 by Matthieu Moy
Make log work nicely with revno:N:path too.
1786
                location = revision[0].get_branch()
1787
            else:
1788
                location = '.'
1789
            dir, relpath = bzrdir.BzrDir.open_containing(location)
1534.4.46 by Robert Collins
Nearly complete .bzr/checkout splitout.
1790
            b = dir.open_branch()
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1791
2230.4.1 by Aaron Bentley
Get log as fast branch5
1792
        b.lock_read()
1793
        try:
1794
            if revision is None:
1795
                rev1 = None
1796
                rev2 = None
1797
            elif len(revision) == 1:
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
1798
                rev1 = rev2 = revision[0].in_history(b)
2230.4.1 by Aaron Bentley
Get log as fast branch5
1799
            elif len(revision) == 2:
1800
                if revision[1].get_branch() != revision[0].get_branch():
1801
                    # b is taken from revision[0].get_branch(), and
1802
                    # show_log will use its revision_history. Having
1803
                    # different branches will lead to weird behaviors.
1804
                    raise errors.BzrCommandError(
1805
                        "Log doesn't accept two revisions in different"
1806
                        " branches.")
2466.12.1 by Kent Gibson
Fix ``bzr log -r`` to support selecting merge revisions.
1807
                rev1 = revision[0].in_history(b)
1808
                rev2 = revision[1].in_history(b)
2230.4.1 by Aaron Bentley
Get log as fast branch5
1809
            else:
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
1810
                raise errors.BzrCommandError(
2230.4.1 by Aaron Bentley
Get log as fast branch5
1811
                    'bzr log --revision takes one or two values.')
1812
1813
            if log_format is None:
1814
                log_format = log.log_formatter_registry.get_default(b)
2388.1.8 by Erik Bagfors
Redo based on input from Alexander
1815
2230.4.1 by Aaron Bentley
Get log as fast branch5
1816
            lf = log_format(show_ids=show_ids, to_file=self.outf,
2388.1.8 by Erik Bagfors
Redo based on input from Alexander
1817
                            show_timezone=timezone)
2230.4.1 by Aaron Bentley
Get log as fast branch5
1818
1819
            show_log(b,
1820
                     lf,
1821
                     file_id,
1822
                     verbose=verbose,
1823
                     direction=direction,
1824
                     start_revision=rev1,
1825
                     end_revision=rev2,
2466.9.1 by Kent Gibson
add bzr log --limit
1826
                     search=message,
1827
                     limit=limit)
2230.4.1 by Aaron Bentley
Get log as fast branch5
1828
        finally:
1829
            b.unlock()
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1830
1185.85.4 by John Arbash Meinel
currently broken, trying to fix things up.
1831
1857.1.20 by Aaron Bentley
Strip out all the EnumOption stuff
1832
def get_log_format(long=False, short=False, line=False, default='long'):
1833
    log_format = default
1834
    if long:
1835
        log_format = 'long'
1836
    if short:
1837
        log_format = 'short'
1838
    if line:
1839
        log_format = 'line'
1840
    return log_format
1841
1842
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1843
class cmd_touching_revisions(Command):
1844
    """Return revision-ids which affected a particular file.
1845
1685.1.80 by Wouter van Heyst
more code cleanup
1846
    A more user-friendly interface is "bzr log FILE".
1847
    """
1848
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1849
    hidden = True
1850
    takes_args = ["filename"]
1185.85.55 by John Arbash Meinel
Updated cmd_touching_revisions
1851
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1852
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1853
    def run(self, filename):
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
1854
        tree, relpath = WorkingTree.open_containing(filename)
1855
        b = tree.branch
2255.7.39 by Robert Collins
Remove gratuitous references to inventory.path2id from builtins.py, allowing more commands to work on dirstate trees.
1856
        file_id = tree.path2id(relpath)
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
1857
        for revno, revision_id, what in log.find_touching_revisions(b, file_id):
1185.85.55 by John Arbash Meinel
Updated cmd_touching_revisions
1858
            self.outf.write("%6d %s\n" % (revno, what))
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1859
1860
1861
class cmd_ls(Command):
1862
    """List files in a tree.
1863
    """
1551.9.24 by Aaron Bentley
Unhide ls, add kind flag
1864
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
1865
    _see_also = ['status', 'cat']
2215.3.1 by Aaron Bentley
Allow ls to take a PATH
1866
    takes_args = ['path?']
1185.16.3 by Martin Pool
- remove all TODOs from bzr help messages
1867
    # TODO: Take a revision or remote path and list that tree instead.
2598.1.2 by Martin Pool
Also check that option help ends in a period, and fix those that don't
1868
    takes_options = [
1869
            'verbose',
1870
            'revision',
1871
            Option('non-recursive',
1872
                   help='Don\'t recurse into subdirectories.'),
1873
            Option('from-root',
2598.1.3 by Martin Pool
Option help improvements (thanks jamesw)
1874
                   help='Print paths relative to the root of the branch.'),
2598.1.2 by Martin Pool
Also check that option help ends in a period, and fix those that don't
1875
            Option('unknown', help='Print unknown files.'),
3382.2.1 by Jerad Cramp
Fixed bug #165086. Command 'bzr ls' now accepts '-V' as an alias for '--versioned'.
1876
            Option('versioned', help='Print versioned files.',
1877
                   short_name='V'),
2598.1.2 by Martin Pool
Also check that option help ends in a period, and fix those that don't
1878
            Option('ignored', help='Print ignored files.'),
1879
            Option('null',
1880
                   help='Write an ascii NUL (\\0) separator '
1881
                   'between files rather than a newline.'),
2598.1.11 by Martin Pool
Insist that all options have a help string and fix those that don't.
1882
            Option('kind',
2598.1.12 by Martin Pool
Fix up --kind options
1883
                   help='List entries of a particular kind: file, directory, symlink.',
1884
                   type=unicode),
2598.1.2 by Martin Pool
Also check that option help ends in a period, and fix those that don't
1885
            'show-ids',
1886
            ]
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1887
    @display_command
2598.1.12 by Martin Pool
Fix up --kind options
1888
    def run(self, revision=None, verbose=False,
1185.26.1 by John Arbash Meinel
Made ls work again, and take extra arguments.
1889
            non_recursive=False, from_root=False,
1890
            unknown=False, versioned=False, ignored=False,
2215.3.1 by Aaron Bentley
Allow ls to take a PATH
1891
            null=False, kind=None, show_ids=False, path=None):
1551.9.24 by Aaron Bentley
Unhide ls, add kind flag
1892
1893
        if kind and kind not in ('file', 'directory', 'symlink'):
1894
            raise errors.BzrCommandError('invalid kind specified')
1185.26.1 by John Arbash Meinel
Made ls work again, and take extra arguments.
1895
1896
        if verbose and null:
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
1897
            raise errors.BzrCommandError('Cannot set both --verbose and --null')
1551.6.36 by Aaron Bentley
Revert --debris/--detritus changes
1898
        all = not (unknown or versioned or ignored)
1185.26.1 by John Arbash Meinel
Made ls work again, and take extra arguments.
1899
1551.6.36 by Aaron Bentley
Revert --debris/--detritus changes
1900
        selection = {'I':ignored, '?':unknown, 'V':versioned}
1185.26.1 by John Arbash Meinel
Made ls work again, and take extra arguments.
1901
2215.3.1 by Aaron Bentley
Allow ls to take a PATH
1902
        if path is None:
1903
            fs_path = '.'
1904
            prefix = ''
1905
        else:
1906
            if from_root:
1907
                raise errors.BzrCommandError('cannot specify both --from-root'
1908
                                             ' and PATH')
1909
            fs_path = path
1910
            prefix = path
2215.3.3 by Aaron Bentley
Get ls working on branches
1911
        tree, branch, relpath = bzrdir.BzrDir.open_containing_tree_or_branch(
1912
            fs_path)
1185.26.1 by John Arbash Meinel
Made ls work again, and take extra arguments.
1913
        if from_root:
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
1914
            relpath = u''
1185.26.1 by John Arbash Meinel
Made ls work again, and take extra arguments.
1915
        elif relpath:
1916
            relpath += '/'
3655.3.1 by Lukáš Lalinský
Fix `bzr st -rbranch:PATH_TO_BRANCH`
1917
        if revision is not None or tree is None:
3732.1.1 by Ian Clatworthy
fix bzr st -rbranch:path-to-branch (Lukas Lalinsky)
1918
            tree = _get_one_revision_tree('ls', revision, branch=branch)
1551.6.36 by Aaron Bentley
Revert --debris/--detritus changes
1919
2255.2.61 by John Arbash Meinel
Find callers of list_files() and make sure the tree is always locked.
1920
        tree.lock_read()
1921
        try:
1922
            for fp, fc, fkind, fid, entry in tree.list_files(include_root=False):
1923
                if fp.startswith(relpath):
1924
                    fp = osutils.pathjoin(prefix, fp[len(relpath):])
1925
                    if non_recursive and '/' in fp:
1926
                        continue
1927
                    if not all and not selection[fc]:
1928
                        continue
1929
                    if kind is not None and fkind != kind:
1930
                        continue
1931
                    if verbose:
1932
                        kindch = entry.kind_character()
1933
                        outstring = '%-8s %s%s' % (fc, fp, kindch)
1934
                        if show_ids and fid is not None:
1935
                            outstring = "%-50s %s" % (outstring, fid)
1936
                        self.outf.write(outstring + '\n')
1937
                    elif null:
1938
                        self.outf.write(fp + '\0')
1939
                        if show_ids:
1940
                            if fid is not None:
1941
                                self.outf.write(fid)
1942
                            self.outf.write('\0')
1943
                        self.outf.flush()
1944
                    else:
1551.9.27 by Aaron Bentley
Implement show-ids for all output formats
1945
                        if fid is not None:
2255.2.61 by John Arbash Meinel
Find callers of list_files() and make sure the tree is always locked.
1946
                            my_id = fid
1947
                        else:
1948
                            my_id = ''
1949
                        if show_ids:
1950
                            self.outf.write('%-50s %s\n' % (fp, my_id))
1951
                        else:
1952
                            self.outf.write(fp + '\n')
1953
        finally:
1954
            tree.unlock()
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1955
1956
1957
class cmd_unknowns(Command):
1551.10.13 by Aaron Bentley
Hide 'unknowns', document alterntatives to hidden commands
1958
    """List unknown files.
1959
    """
1551.10.14 by Aaron Bentley
Add some blank lines
1960
1551.10.13 by Aaron Bentley
Hide 'unknowns', document alterntatives to hidden commands
1961
    hidden = True
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
1962
    _see_also = ['ls']
1551.10.14 by Aaron Bentley
Add some blank lines
1963
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1964
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1965
    def run(self):
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
1966
        for f in WorkingTree.open_containing(u'.')[0].unknowns():
1773.4.2 by Martin Pool
Cleanup of imports; undeprecate all_revision_ids()
1967
            self.outf.write(osutils.quotefn(f) + '\n')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1968
1969
1970
class cmd_ignore(Command):
2063.5.1 by wang
"bzr ignore" takes multiple arguments. Fixes bug 29488.
1971
    """Ignore specified files or patterns.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1972
3398.1.26 by Ian Clatworthy
jam feedback - make patterns a separate help topic
1973
    See ``bzr help patterns`` for details on the syntax of patterns.
1974
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1975
    To remove patterns from the ignore list, edit the .bzrignore file.
3398.1.26 by Ian Clatworthy
jam feedback - make patterns a separate help topic
1976
    After adding, editing or deleting that file either indirectly by
1977
    using this command or directly by using an editor, be sure to commit
1978
    it.
2135.2.2 by Kent Gibson
Ignore pattern matcher (glob.py) patches:
1979
1980
    Note: ignore patterns containing shell wildcards must be quoted from 
1981
    the shell on Unix.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1982
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
1983
    :Examples:
1984
        Ignore the top level Makefile::
1985
1986
            bzr ignore ./Makefile
1987
1988
        Ignore class files in all directories::
1989
3035.1.1 by John Arbash Meinel
Address bug #59302 and fix documentation that uses single quotes.
1990
            bzr ignore "*.class"
1991
1992
        Ignore .o files under the lib directory::
1993
1994
            bzr ignore "lib/**/*.o"
1995
1996
        Ignore .o files under the lib directory::
1997
1998
            bzr ignore "RE:lib/.*\.o"
3257.1.1 by Adeodato Simó
Add an example of some bzrignore cool stuff with Python regexes.
1999
2000
        Ignore everything but the "debian" toplevel directory::
2001
2002
            bzr ignore "RE:(?!debian/).*"
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2003
    """
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
2004
3398.1.26 by Ian Clatworthy
jam feedback - make patterns a separate help topic
2005
    _see_also = ['status', 'ignored', 'patterns']
2063.5.1 by wang
"bzr ignore" takes multiple arguments. Fixes bug 29488.
2006
    takes_args = ['name_pattern*']
1765.1.1 by Robert Collins
Remove the default ignores list from bzr, lowering the minimum overhead in bzr add.
2007
    takes_options = [
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
2008
        Option('old-default-rules',
2009
               help='Write out the ignore rules bzr < 0.9 always used.')
2010
        ]
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2011
    
2063.5.2 by wang
Don't use mutable values as default argument definitions.
2012
    def run(self, name_pattern_list=None, old_default_rules=None):
3528.2.1 by Jelmer Vernooij
Move functionality to add ignores to the ignore file into a separate function.
2013
        from bzrlib import ignores
1765.1.1 by Robert Collins
Remove the default ignores list from bzr, lowering the minimum overhead in bzr add.
2014
        if old_default_rules is not None:
2015
            # dump the rules and exit
1836.1.12 by John Arbash Meinel
Move ignores into a file of their own, make DEFAULT_IGNORE a deprecated list. Create deprecated_list in symbol versioning.
2016
            for pattern in ignores.OLD_DEFAULTS:
1765.1.1 by Robert Collins
Remove the default ignores list from bzr, lowering the minimum overhead in bzr add.
2017
                print pattern
2018
            return
2077.1.2 by Kent Gibson
Strip trailing slashes from ignore patterns (#4559).
2019
        if not name_pattern_list:
2063.5.5 by wang
resolve a conflict
2020
            raise errors.BzrCommandError("ignore requires at least one "
2063.5.4 by wang
Copy Kent Gibson's changes that incorporates John Arbash Meinel's
2021
                                  "NAME_PATTERN or --old-default-rules")
2298.8.4 by Kent Gibson
Fix whitespace and alignment.
2022
        name_pattern_list = [globbing.normalize_pattern(p) 
2023
                             for p in name_pattern_list]
2077.1.2 by Kent Gibson
Strip trailing slashes from ignore patterns (#4559).
2024
        for name_pattern in name_pattern_list:
2298.8.1 by Kent Gibson
Normalise ignore patterns to use '/' path separator.
2025
            if (name_pattern[0] == '/' or 
2026
                (len(name_pattern) > 1 and name_pattern[1] == ':')):
2077.1.2 by Kent Gibson
Strip trailing slashes from ignore patterns (#4559).
2027
                raise errors.BzrCommandError(
2028
                    "NAME_PATTERN should not be an absolute path")
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
2029
        tree, relpath = WorkingTree.open_containing(u'.')
3528.2.1 by Jelmer Vernooij
Move functionality to add ignores to the ignore file into a separate function.
2030
        ignores.tree_ignores_add_patterns(tree, name_pattern_list)
2747.5.1 by Daniel Watkins
'ignore' now outputs a list of versioned files that match the given pattern.
2031
        ignored = globbing.Globster(name_pattern_list)
2032
        matches = []
2033
        tree.lock_read()
2034
        for entry in tree.list_files():
2035
            id = entry[3]
2036
            if id is not None:
2037
                filename = entry[0]
2038
                if ignored.match(filename):
2747.5.3 by Daniel Watkins
Modified to avoid encoding issues.
2039
                    matches.append(filename.encode('utf-8'))
2747.5.1 by Daniel Watkins
'ignore' now outputs a list of versioned files that match the given pattern.
2040
        tree.unlock()
2041
        if len(matches) > 0:
2042
            print "Warning: the following files are version controlled and" \
2043
                  " match your ignore pattern:\n%s" % ("\n".join(matches),)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2044
3603.3.1 by Robert Collins
* The help for ``bzr ignored`` now sugests ``bzr ls --ignored`` for
2045
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2046
class cmd_ignored(Command):
2047
    """List ignored files and the patterns that matched them.
3603.3.1 by Robert Collins
* The help for ``bzr ignored`` now sugests ``bzr ls --ignored`` for
2048
2049
    List all the ignored files and the ignore pattern that caused the file to
2050
    be ignored.
2051
2052
    Alternatively, to list just the files::
2053
2054
        bzr ls --ignored
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
2055
    """
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2056
3123.2.1 by Lukáš Lalinský
Use self.outf instead of sys.stdout in cmd_ignored.
2057
    encoding_type = 'replace'
3603.3.1 by Robert Collins
* The help for ``bzr ignored`` now sugests ``bzr ls --ignored`` for
2058
    _see_also = ['ignore', 'ls']
3123.2.1 by Lukáš Lalinský
Use self.outf instead of sys.stdout in cmd_ignored.
2059
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
2060
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2061
    def run(self):
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
2062
        tree = WorkingTree.open_containing(u'.')[0]
2255.2.61 by John Arbash Meinel
Find callers of list_files() and make sure the tree is always locked.
2063
        tree.lock_read()
2064
        try:
2065
            for path, file_class, kind, file_id, entry in tree.list_files():
2066
                if file_class != 'I':
2067
                    continue
2068
                ## XXX: Slightly inefficient since this was already calculated
2069
                pat = tree.is_ignored(path)
3123.2.1 by Lukáš Lalinský
Use self.outf instead of sys.stdout in cmd_ignored.
2070
                self.outf.write('%-50s %s\n' % (path, pat))
2255.2.61 by John Arbash Meinel
Find callers of list_files() and make sure the tree is always locked.
2071
        finally:
2072
            tree.unlock()
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2073
2074
2075
class cmd_lookup_revision(Command):
2076
    """Lookup the revision-id from a revision-number
2077
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
2078
    :Examples:
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2079
        bzr lookup-revision 33
2080
    """
2081
    hidden = True
2082
    takes_args = ['revno']
2083
    
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
2084
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2085
    def run(self, revno):
2086
        try:
2087
            revno = int(revno)
2088
        except ValueError:
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
2089
            raise errors.BzrCommandError("not a valid revision-number: %r" % revno)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2090
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
2091
        print WorkingTree.open_containing(u'.')[0].branch.get_rev_id(revno)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2092
2093
2094
class cmd_export(Command):
2374.1.1 by Ian Clatworthy
Help and man page fixes
2095
    """Export current or past revision to a destination directory or archive.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2096
2097
    If no revision is specified this exports the last committed revision.
2098
2099
    Format may be an "exporter" name, such as tar, tgz, tbz2.  If none is
2100
    given, try to find the format with the extension. If no extension
2101
    is found exports to a directory (equivalent to --format=dir).
2102
2374.1.4 by Ian Clatworthy
Include feedback from mailing list.
2103
    If root is supplied, it will be used as the root directory inside
2104
    container formats (tar, zip, etc). If it is not supplied it will default
2105
    to the exported filename. The root option has no effect for 'dir' format.
1185.31.11 by John Arbash Meinel
Merging Alexander's zip export patch
2106
2374.1.2 by Ian Clatworthy
Improved after feedback from reviewers
2107
    If branch is omitted then the branch containing the current working
2108
    directory will be used.
2099.1.1 by Daniel Silverstone
Add source branch support to export command
2109
2374.1.3 by Ian Clatworthy
Minor man page fixes for add, commit, export
2110
    Note: Export of tree with non-ASCII filenames to zip is not supported.
1185.31.11 by John Arbash Meinel
Merging Alexander's zip export patch
2111
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
2112
      =================       =========================
2113
      Supported formats       Autodetected by extension
2114
      =================       =========================
2666.1.5 by Ian Clatworthy
Incorporate feedback from Alex B. & James W.
2115
         dir                         (none)
1185.31.11 by John Arbash Meinel
Merging Alexander's zip export patch
2116
         tar                          .tar
2117
         tbz2                    .tar.bz2, .tbz2
2118
         tgz                      .tar.gz, .tgz
2119
         zip                          .zip
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
2120
      =================       =========================
1185.31.11 by John Arbash Meinel
Merging Alexander's zip export patch
2121
    """
3613.2.1 by Robert Collins
Teach export how to export a subdirectory. (Robert Collins)
2122
    takes_args = ['dest', 'branch_or_subdir?']
2598.1.10 by Martin Pool
Clean up options that are registered globally and used once or not at all.
2123
    takes_options = [
2124
        Option('format',
2125
               help="Type of file to export to.",
2126
               type=unicode),
2127
        'revision',
2128
        Option('root',
2129
               type=str,
2130
               help="Name of the root directory inside the exported file."),
2131
        ]
3613.2.1 by Robert Collins
Teach export how to export a subdirectory. (Robert Collins)
2132
    def run(self, dest, branch_or_subdir=None, revision=None, format=None,
2133
        root=None):
1185.31.12 by John Arbash Meinel
Refactored the export code to make it easier to add new export formats.
2134
        from bzrlib.export import export
2099.1.1 by Daniel Silverstone
Add source branch support to export command
2135
3613.2.1 by Robert Collins
Teach export how to export a subdirectory. (Robert Collins)
2136
        if branch_or_subdir is None:
2099.1.1 by Daniel Silverstone
Add source branch support to export command
2137
            tree = WorkingTree.open_containing(u'.')[0]
2138
            b = tree.branch
3613.2.1 by Robert Collins
Teach export how to export a subdirectory. (Robert Collins)
2139
            subdir = None
2099.1.1 by Daniel Silverstone
Add source branch support to export command
2140
        else:
3613.2.1 by Robert Collins
Teach export how to export a subdirectory. (Robert Collins)
2141
            b, subdir = Branch.open_containing(branch_or_subdir)
3655.3.1 by Lukáš Lalinský
Fix `bzr st -rbranch:PATH_TO_BRANCH`
2142
            tree = None
2143
3732.1.1 by Ian Clatworthy
fix bzr st -rbranch:path-to-branch (Lukas Lalinsky)
2144
        rev_tree = _get_one_revision_tree('export', revision, branch=b, tree=tree)
1185.31.12 by John Arbash Meinel
Refactored the export code to make it easier to add new export formats.
2145
        try:
3655.3.1 by Lukáš Lalinský
Fix `bzr st -rbranch:PATH_TO_BRANCH`
2146
            export(rev_tree, dest, format, root, subdir)
1185.31.12 by John Arbash Meinel
Refactored the export code to make it easier to add new export formats.
2147
        except errors.NoSuchExportFormat, e:
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
2148
            raise errors.BzrCommandError('Unsupported export format: %s' % e.format)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2149
2150
2151
class cmd_cat(Command):
2374.1.1 by Ian Clatworthy
Help and man page fixes
2152
    """Write the contents of a file as of a given revision to standard output.
2153
2154
    If no revision is nominated, the last revision is used.
2155
2374.1.2 by Ian Clatworthy
Improved after feedback from reviewers
2156
    Note: Take care to redirect standard output when using this command on a
2157
    binary file. 
2374.1.1 by Ian Clatworthy
Help and man page fixes
2158
    """
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2159
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
2160
    _see_also = ['ls']
2598.1.10 by Martin Pool
Clean up options that are registered globally and used once or not at all.
2161
    takes_options = [
2162
        Option('name-from-revision', help='The path name in the old tree.'),
2163
        'revision',
2164
        ]
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2165
    takes_args = ['filename']
2178.4.4 by Alexander Belchenko
encoding_type = 'exact' force sys.stdout to be binary stream on win32
2166
    encoding_type = 'exact'
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2167
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
2168
    @display_command
2073.2.3 by wang
Change option name to --name-from-revision. Always make new tree the
2169
    def run(self, filename, revision=None, name_from_revision=False):
1185.50.9 by John Arbash Meinel
[bug 3632] Matthieu Moy- bzr cat should default to last revision
2170
        if revision is not None and len(revision) != 1:
2073.2.1 by wang
``bzr cat`` can look up contents of removed or renamed files. If the
2171
            raise errors.BzrCommandError("bzr cat --revision takes exactly"
3063.4.1 by Lukáš Lalinský
Fix UnboundLocalError in cmd_cat.
2172
                                         " one revision specifier")
2173
        tree, branch, relpath = \
2174
            bzrdir.BzrDir.open_containing_tree_or_branch(filename)
2175
        branch.lock_read()
2176
        try:
2177
            return self._run(tree, branch, relpath, filename, revision,
2178
                             name_from_revision)
3010.1.17 by Robert Collins
Lock correctness and commit_group management for re-sign, in builtins.
2179
        finally:
3063.4.1 by Lukáš Lalinský
Fix UnboundLocalError in cmd_cat.
2180
            branch.unlock()
3010.1.17 by Robert Collins
Lock correctness and commit_group management for re-sign, in builtins.
2181
2182
    def _run(self, tree, b, relpath, filename, revision, name_from_revision):
1907.4.5 by Matthieu Moy
Make bzr cat -r revno:N:foo consistant with bzr cat -r branch:foo.
2183
        if tree is None:
2158.1.1 by Wouter van Heyst
Fix #73500 mostly by catching a NotLocalUrl exception in cmd_cat.
2184
            tree = b.basis_tree()
3732.1.1 by Ian Clatworthy
fix bzr st -rbranch:path-to-branch (Lukas Lalinsky)
2185
        rev_tree = _get_one_revision_tree('cat', revision, branch=b)
2073.2.1 by wang
``bzr cat`` can look up contents of removed or renamed files. If the
2186
2187
        cur_file_id = tree.path2id(relpath)
2188
        old_file_id = rev_tree.path2id(relpath)
3655.3.1 by Lukáš Lalinský
Fix `bzr st -rbranch:PATH_TO_BRANCH`
2189
2073.2.3 by wang
Change option name to --name-from-revision. Always make new tree the
2190
        if name_from_revision:
2073.2.1 by wang
``bzr cat`` can look up contents of removed or renamed files. If the
2191
            if old_file_id is None:
3655.3.1 by Lukáš Lalinský
Fix `bzr st -rbranch:PATH_TO_BRANCH`
2192
                raise errors.BzrCommandError(
2193
                    "%r is not present in revision %s" % (
2194
                        filename, rev_tree.get_revision_id()))
2073.2.1 by wang
``bzr cat`` can look up contents of removed or renamed files. If the
2195
            else:
3341.2.1 by Alexander Belchenko
`bzr cat` no more internally used Tree.print_file().
2196
                content = rev_tree.get_file_text(old_file_id)
2073.2.2 by wang
Make the decision tree a little clearer. Add more tests for exceptions.
2197
        elif cur_file_id is not None:
3341.2.1 by Alexander Belchenko
`bzr cat` no more internally used Tree.print_file().
2198
            content = rev_tree.get_file_text(cur_file_id)
2073.2.1 by wang
``bzr cat`` can look up contents of removed or renamed files. If the
2199
        elif old_file_id is not None:
3341.2.1 by Alexander Belchenko
`bzr cat` no more internally used Tree.print_file().
2200
            content = rev_tree.get_file_text(old_file_id)
2073.2.1 by wang
``bzr cat`` can look up contents of removed or renamed files. If the
2201
        else:
3655.3.1 by Lukáš Lalinský
Fix `bzr st -rbranch:PATH_TO_BRANCH`
2202
            raise errors.BzrCommandError(
2203
                "%r is not present in revision %s" % (
2204
                    filename, rev_tree.get_revision_id()))
3341.2.1 by Alexander Belchenko
`bzr cat` no more internally used Tree.print_file().
2205
        self.outf.write(content)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2206
2207
2208
class cmd_local_time_offset(Command):
2209
    """Show the offset in seconds from GMT to local time."""
2210
    hidden = True    
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
2211
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2212
    def run(self):
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
2213
        print osutils.local_time_offset()
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2214
2215
2216
2217
class cmd_commit(Command):
2218
    """Commit changes into a new revision.
2219
    
2220
    If no arguments are given, the entire tree is committed.
2221
2222
    If selected files are specified, only changes to those files are
2223
    committed.  If a directory is specified then the directory and everything 
2224
    within it is committed.
2225
3602.1.1 by Robert Collins
Add support for -x or --exclude to bzr commit, fixing bug 3117. (Robert Collins)
2226
    When excludes are given, they take precedence over selected files.
2227
    For example, too commit only changes within foo, but not changes within
2228
    foo/bar::
2229
2230
      bzr commit foo -x foo/bar
2231
2671.2.2 by Lukáš Lalinský
Move setting of the author revision property to MutableTree.commit. Don't use try/except KeyError in LongLogFormatter to display authors and branch-nicks. Removed warning about missing e-mail in the authors name.
2232
    If author of the change is not the same person as the committer, you can
2233
    specify the author's name using the --author option. The name should be
2234
    in the same format as a committer-id, e.g. "John Doe <jdoe@example.com>".
2671.2.1 by Lukáš Lalinský
Add --author option to 'bzr commit' to record the author's name, if it's different from the committer.
2235
2374.1.5 by Ian Clatworthy
explained selected fail commit failure by design
2236
    A selected-file commit may fail in some cases where the committed
2237
    tree would be invalid. Consider::
2238
2239
      bzr init foo
2240
      mkdir foo/bar
2241
      bzr add foo/bar
2242
      bzr commit foo -m "committing foo"
2374.1.6 by Ian Clatworthy
explained selected fail commit failure by design
2243
      bzr mv foo/bar foo/baz
2374.1.5 by Ian Clatworthy
explained selected fail commit failure by design
2244
      mkdir foo/bar
2245
      bzr add foo/bar
2374.1.6 by Ian Clatworthy
explained selected fail commit failure by design
2246
      bzr commit foo/bar -m "committing bar but not baz"
2374.1.5 by Ian Clatworthy
explained selected fail commit failure by design
2247
2248
    In the example above, the last commit will fail by design. This gives
2249
    the user the opportunity to decide whether they want to commit the
2250
    rename at the same time, separately first, or not at all. (As a general
2251
    rule, when in doubt, Bazaar has a policy of Doing the Safe Thing.)
2252
2374.1.3 by Ian Clatworthy
Minor man page fixes for add, commit, export
2253
    Note: A selected-file commit after a merge is not yet supported.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2254
    """
1185.16.3 by Martin Pool
- remove all TODOs from bzr help messages
2255
    # TODO: Run hooks on tree to-be-committed, and after commit.
2256
1185.16.65 by mbp at sourcefrog
- new commit --strict option
2257
    # TODO: Strict commit that fails if there are deleted files.
2258
    #       (what does "deleted files" mean ??)
2259
1185.16.3 by Martin Pool
- remove all TODOs from bzr help messages
2260
    # TODO: Give better message for -s, --summary, used by tla people
2261
2262
    # XXX: verbose currently does nothing
2263
2376.4.36 by Jonathan Lange
Provide really basic help topic for our bug tracker support.
2264
    _see_also = ['bugs', 'uncommit']
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2265
    takes_args = ['selected*']
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
2266
    takes_options = [
3602.1.1 by Robert Collins
Add support for -x or --exclude to bzr commit, fixing bug 3117. (Robert Collins)
2267
            ListOption('exclude', type=str, short_name='x',
2268
                help="Do not consider changes made to a given path."),
2598.1.10 by Martin Pool
Clean up options that are registered globally and used once or not at all.
2269
            Option('message', type=unicode,
2270
                   short_name='m',
2271
                   help="Description of the new revision."),
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
2272
            'verbose',
2273
             Option('unchanged',
2274
                    help='Commit even if nothing has changed.'),
2275
             Option('file', type=str,
2276
                    short_name='F',
2277
                    argname='msgfile',
2278
                    help='Take commit message from this file.'),
2279
             Option('strict',
2280
                    help="Refuse to commit if there are unknown "
2281
                    "files in the working tree."),
2282
             ListOption('fixes', type=str,
2283
                    help="Mark a bug as being fixed by this revision."),
3099.2.1 by John Arbash Meinel
Allow 'bzr commit --author' to take a unicode string.
2284
             Option('author', type=unicode,
2671.2.1 by Lukáš Lalinský
Add --author option to 'bzr commit' to record the author's name, if it's different from the committer.
2285
                    help="Set the author's name, if it's different "
2286
                         "from the committer."),
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
2287
             Option('local',
2288
                    help="Perform a local commit in a bound "
2289
                         "branch.  Local commits are not pushed to "
2290
                         "the master branch until a normal commit "
2291
                         "is performed."
2292
                    ),
2598.6.10 by ghigo
In the commit dialog, the diff is stored as 8-bit raw data
2293
              Option('show-diff',
2294
                     help='When no message is supplied, show the diff along'
2295
                     ' with the status summary in the message editor.'),
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
2296
             ]
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2297
    aliases = ['ci', 'checkin']
2298
2376.4.7 by jml at canonical
- Add docstrings to tests.
2299
    def _get_bug_fix_properties(self, fixes, branch):
2376.4.18 by Jonathan Lange
Store all bug fix URLs in a single property.
2300
        properties = []
2376.4.7 by jml at canonical
- Add docstrings to tests.
2301
        # Configure the properties for bug fixing attributes.
2302
        for fixed_bug in fixes:
2303
            tokens = fixed_bug.split(':')
2304
            if len(tokens) != 2:
2305
                raise errors.BzrCommandError(
2306
                    "Invalid bug %s. Must be in the form of 'tag:id'. "
2307
                    "Commit refused." % fixed_bug)
2308
            tag, bug_id = tokens
2309
            try:
2376.4.22 by Jonathan Lange
Variety of whitespace cleanups, tightening of tests and docstring changes in
2310
                bug_url = bugtracker.get_bug_url(tag, branch, bug_id)
2376.4.26 by Jonathan Lange
Tests for MalformedBugIdentifier and new error UnknownBugTrackerAbbreviation.
2311
            except errors.UnknownBugTrackerAbbreviation:
2376.4.7 by jml at canonical
- Add docstrings to tests.
2312
                raise errors.BzrCommandError(
2313
                    'Unrecognized bug %s. Commit refused.' % fixed_bug)
2314
            except errors.MalformedBugIdentifier:
2315
                raise errors.BzrCommandError(
2316
                    "Invalid bug identifier for %s. Commit refused."
2317
                    % fixed_bug)
2376.4.18 by Jonathan Lange
Store all bug fix URLs in a single property.
2318
            properties.append('%s fixed' % bug_url)
2376.4.21 by Jonathan Lange
Change the bugs separator to \n from ,
2319
        return '\n'.join(properties)
2376.4.7 by jml at canonical
- Add docstrings to tests.
2320
2768.1.5 by Ian Clatworthy
Wrap new std verbose option with new help instead of declaring a new one
2321
    def run(self, message=None, file=None, verbose=False, selected_list=None,
2817.4.4 by Vincent Ladeuil
Redo the lost modification.
2322
            unchanged=False, strict=False, local=False, fixes=None,
3602.1.1 by Robert Collins
Add support for -x or --exclude to bzr commit, fixing bug 3117. (Robert Collins)
2323
            author=None, show_diff=False, exclude=None):
2598.6.30 by ghigo
- Updated the identation on the basis of Aaron suggestions
2324
        from bzrlib.errors import (
2325
            PointlessCommit,
2326
            ConflictsInTree,
2327
            StrictCommitFailed
2328
        )
2329
        from bzrlib.msgeditor import (
2330
            edit_commit_message_encoded,
2331
            make_commit_message_template_encoded
2332
        )
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2333
1185.33.77 by Martin Pool
doc
2334
        # TODO: Need a blackbox test for invoking the external editor; may be
2335
        # slightly problematic to run this cross-platform.
2336
1185.33.72 by Martin Pool
Fix commit message template for non-ascii files, and add test for handling of
2337
        # TODO: do more checks that the commit will succeed before 
2338
        # spending the user's valuable time typing a commit message.
2376.4.2 by jml at canonical
More sophisticated error handling for --fixes option
2339
2340
        properties = {}
2341
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
2342
        tree, selected_list = tree_files(selected_list)
1704.2.11 by Martin Pool
Handle 'bzr commit DIR' when dir contains pending merges.
2343
        if selected_list == ['']:
2344
            # workaround - commit of root of tree should be exactly the same
2345
            # as just default commit in that tree, and succeed even though
2346
            # selected-file merge commit is not done yet
2347
            selected_list = []
2348
2817.4.4 by Vincent Ladeuil
Redo the lost modification.
2349
        if fixes is None:
2350
            fixes = []
2453.2.1 by Martin Pool
Don't set the bugs property unless bugs are actually set
2351
        bug_property = self._get_bug_fix_properties(fixes, tree.branch)
2352
        if bug_property:
2353
            properties['bugs'] = bug_property
2376.4.7 by jml at canonical
- Add docstrings to tests.
2354
1587.1.8 by Robert Collins
Local commits on unbound branches fail.
2355
        if local and not tree.branch.get_bound_location():
2356
            raise errors.LocalRequiresBoundBranch()
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2357
2149.1.4 by Aaron Bentley
Add additional test that callback is called with a Commit instance
2358
        def get_message(commit_obj):
2149.1.2 by Aaron Bentley
Defer getting the commit message until the revision is almost-committed
2359
            """Callback to get commit message"""
2360
            my_message = message
2361
            if my_message is None and not file:
2598.6.24 by ghigo
update on the basis of Aaron suggestions
2362
                t = make_commit_message_template_encoded(tree,
2598.6.30 by ghigo
- Updated the identation on the basis of Aaron suggestions
2363
                        selected_list, diff=show_diff,
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
2364
                        output_encoding=osutils.get_user_encoding())
2598.6.24 by ghigo
update on the basis of Aaron suggestions
2365
                my_message = edit_commit_message_encoded(t)
2149.1.2 by Aaron Bentley
Defer getting the commit message until the revision is almost-committed
2366
                if my_message is None:
2367
                    raise errors.BzrCommandError("please specify a commit"
2368
                        " message with either --message or --file")
2598.6.29 by ghigo
Removed the check on the switch "--show-diff" in order to allow the
2369
            elif my_message and file:
2149.1.2 by Aaron Bentley
Defer getting the commit message until the revision is almost-committed
2370
                raise errors.BzrCommandError(
2598.6.29 by ghigo
Removed the check on the switch "--show-diff" in order to allow the
2371
                    "please specify either --message or --file")
2149.1.2 by Aaron Bentley
Defer getting the commit message until the revision is almost-committed
2372
            if file:
3602.1.1 by Robert Collins
Add support for -x or --exclude to bzr commit, fixing bug 3117. (Robert Collins)
2373
                my_message = codecs.open(file, 'rt',
3224.5.4 by Andrew Bennetts
Fix test suite, mainly weeding out uses of bzrlib.user_encoding.
2374
                                         osutils.get_user_encoding()).read()
2149.1.2 by Aaron Bentley
Defer getting the commit message until the revision is almost-committed
2375
            if my_message == "":
2376
                raise errors.BzrCommandError("empty commit message specified")
2377
            return my_message
2376.4.2 by jml at canonical
More sophisticated error handling for --fixes option
2378
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2379
        try:
2149.1.2 by Aaron Bentley
Defer getting the commit message until the revision is almost-committed
2380
            tree.commit(message_callback=get_message,
2381
                        specific_files=selected_list,
1607.1.5 by Robert Collins
Make commit verbose mode work!.
2382
                        allow_pointless=unchanged, strict=strict, local=local,
2789.2.1 by Ian Clatworthy
Make commit less verbose by default
2383
                        reporter=None, verbose=verbose, revprops=properties,
3602.1.1 by Robert Collins
Add support for -x or --exclude to bzr commit, fixing bug 3117. (Robert Collins)
2384
                        author=author,
2385
                        exclude=safe_relpath_files(tree, exclude))
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2386
        except PointlessCommit:
2387
            # FIXME: This should really happen before the file is read in;
2388
            # perhaps prepare the commit; get the message; then actually commit
1551.9.5 by Aaron Bentley
Revert broken save-commit-message code
2389
            raise errors.BzrCommandError("no changes to commit."
2390
                              " use --unchanged to commit anyhow")
1185.14.10 by Aaron Bentley
Commit aborts with conflicts in the tree.
2391
        except ConflictsInTree:
1551.9.5 by Aaron Bentley
Revert broken save-commit-message code
2392
            raise errors.BzrCommandError('Conflicts detected in working '
2393
                'tree.  Use "bzr conflicts" to list, "bzr resolve FILE" to'
2394
                ' resolve.')
1185.16.65 by mbp at sourcefrog
- new commit --strict option
2395
        except StrictCommitFailed:
1551.9.5 by Aaron Bentley
Revert broken save-commit-message code
2396
            raise errors.BzrCommandError("Commit refused because there are"
2397
                              " unknown 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
2398
        except errors.BoundBranchOutOfDate, e:
1551.9.5 by Aaron Bentley
Revert broken save-commit-message code
2399
            raise errors.BzrCommandError(str(e) + "\n"
2400
            'To commit to master branch, run update and then commit.\n'
2401
            'You can also pass --local to commit to continue working '
2402
            'disconnected.')
2111.1.1 by Martin Pool
Fix #32054, save message if commit fails.
2403
2404
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2405
class cmd_check(Command):
3015.4.20 by Daniel Watkins
Fixed summary.
2406
    """Validate working tree structure, branch consistency and repository history.
3015.3.25 by Daniel Watkins
Updated help.
2407
2408
    This command checks various invariants about branch and repository storage
2409
    to detect data corruption or bzr bugs.
2410
2411
    The working tree and branch checks will only give output if a problem is
2412
    detected. The output fields of the repository check are:
2745.6.8 by Aaron Bentley
Clean up text
2413
2414
        revisions: This is just the number of revisions checked.  It doesn't
2415
            indicate a problem.
2416
        versionedfiles: This is just the number of versionedfiles checked.  It
2417
            doesn't indicate a problem.
2418
        unreferenced ancestors: Texts that are ancestors of other texts, but
2419
            are not properly referenced by the revision ancestry.  This is a
2420
            subtle problem that Bazaar can work around.
2421
        unique file texts: This is the total number of unique file contents
2422
            seen in the checked revisions.  It does not indicate a problem.
2423
        repeated file texts: This is the total number of repeated texts seen
2424
            in the checked revisions.  Texts can be repeated when their file
2425
            entries are modified, but the file contents are not.  It does not
2426
            indicate a problem.
3015.4.14 by Daniel Watkins
Updated check help to explain what happens when no options are given.
2427
3015.4.19 by Daniel Watkins
Improved check docs.
2428
    If no restrictions are specified, all Bazaar data that is found at the given
2429
    location will be checked.
2430
2431
    :Examples:
2432
2433
        Check the tree and branch at 'foo'::
2434
2435
            bzr check --tree --branch foo
2436
2437
        Check only the repository at 'bar'::
2438
2439
            bzr check --repo bar
2440
2441
        Check everything at 'baz'::
2442
2443
            bzr check baz
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2444
    """
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
2445
2446
    _see_also = ['reconcile']
3015.3.2 by Daniel Watkins
Check.check now takes a path rather than a branch.
2447
    takes_args = ['path?']
3015.4.2 by Daniel Watkins
Made UI changes to include CLI options.
2448
    takes_options = ['verbose',
2449
                     Option('branch', help="Check the branch related to the"
2450
                                           " current directory."),
2451
                     Option('repo', help="Check the repository related to the"
2452
                                         " current directory."),
2453
                     Option('tree', help="Check the working tree related to"
2454
                                         " the current directory.")]
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2455
3015.4.5 by Daniel Watkins
Each option selects only the specific thing to be checked.
2456
    def run(self, path=None, verbose=False, branch=False, repo=False,
2457
            tree=False):
3015.3.22 by Daniel Watkins
Changed 'check' to 'check_dwim'.
2458
        from bzrlib.check import check_dwim
3015.3.2 by Daniel Watkins
Check.check now takes a path rather than a branch.
2459
        if path is None:
2460
            path = '.'
3015.4.7 by Daniel Watkins
Vanilla 'bzr check' checks all items.
2461
        if not branch and not repo and not tree:
2462
            branch = repo = tree = True
3015.4.2 by Daniel Watkins
Made UI changes to include CLI options.
2463
        check_dwim(path, verbose, do_branch=branch, do_repo=repo, do_tree=tree)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2464
2465
2466
class cmd_upgrade(Command):
2467
    """Upgrade branch storage to current format.
2468
2469
    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.
2470
    this command. When the default format has changed you may also be warned
2471
    during other operations to upgrade.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2472
    """
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
2473
2474
    _see_also = ['check']
1534.4.13 by Robert Collins
Give a reasonable warning on attempts to upgrade a readonly url.
2475
    takes_args = ['url?']
1857.1.20 by Aaron Bentley
Strip out all the EnumOption stuff
2476
    takes_options = [
2221.4.9 by Aaron Bentley
Zap trailing whitespace
2477
                    RegistryOption('format',
2221.4.12 by Aaron Bentley
Add option grouping to RegistryOption and clean up format options
2478
                        help='Upgrade to a specific format.  See "bzr help'
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
2479
                             ' formats" for details.',
3224.5.2 by Andrew Bennetts
Avoid importing bzrlib.bzrdir unnecessarily.
2480
                        lazy_registry=('bzrlib.bzrdir', 'format_registry'),
2481
                        converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
2221.4.12 by Aaron Bentley
Add option grouping to RegistryOption and clean up format options
2482
                        value_switches=True, title='Branch format'),
1857.1.20 by Aaron Bentley
Strip out all the EnumOption stuff
2483
                    ]
2484
2485
    def run(self, url='.', format=None):
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2486
        from bzrlib.upgrade import upgrade
1857.1.20 by Aaron Bentley
Strip out all the EnumOption stuff
2487
        if format is None:
2204.5.5 by Aaron Bentley
Remove RepositoryFormat.set_default_format, deprecate get_format_type
2488
            format = bzrdir.format_registry.make_bzrdir('default')
1857.1.20 by Aaron Bentley
Strip out all the EnumOption stuff
2489
        upgrade(url, format)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2490
2491
2492
class cmd_whoami(Command):
1816.2.4 by Robey Pointer
flesh out 'whoami' docs a little, and don't display the identity after setting it
2493
    """Show or set bzr user id.
2494
    
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
2495
    :Examples:
2496
        Show the email of the current user::
2497
2498
            bzr whoami --email
2499
2500
        Set the current user::
2501
3035.1.1 by John Arbash Meinel
Address bug #59302 and fix documentation that uses single quotes.
2502
            bzr whoami "Frank Chu <fchu@example.com>"
1816.2.4 by Robey Pointer
flesh out 'whoami' docs a little, and don't display the identity after setting it
2503
    """
1816.2.2 by Robey Pointer
fix 'whoami' to use encodings and allow setting the global or branch identity
2504
    takes_options = [ Option('email',
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
2505
                             help='Display email address only.'),
1816.2.2 by Robey Pointer
fix 'whoami' to use encodings and allow setting the global or branch identity
2506
                      Option('branch',
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
2507
                             help='Set identity for the current branch instead of '
2508
                                  'globally.'),
1816.2.2 by Robey Pointer
fix 'whoami' to use encodings and allow setting the global or branch identity
2509
                    ]
2510
    takes_args = ['name?']
2511
    encoding_type = 'replace'
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2512
    
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
2513
    @display_command
1816.2.2 by Robey Pointer
fix 'whoami' to use encodings and allow setting the global or branch identity
2514
    def run(self, email=False, branch=False, name=None):
2515
        if name is None:
2516
            # use branch if we're inside one; otherwise global config
2517
            try:
1816.2.10 by Robey Pointer
code style changes
2518
                c = Branch.open_containing('.')[0].get_config()
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
2519
            except errors.NotBranchError:
1816.2.2 by Robey Pointer
fix 'whoami' to use encodings and allow setting the global or branch identity
2520
                c = config.GlobalConfig()
1816.2.4 by Robey Pointer
flesh out 'whoami' docs a little, and don't display the identity after setting it
2521
            if email:
1816.2.10 by Robey Pointer
code style changes
2522
                self.outf.write(c.user_email() + '\n')
1816.2.2 by Robey Pointer
fix 'whoami' to use encodings and allow setting the global or branch identity
2523
            else:
1816.2.10 by Robey Pointer
code style changes
2524
                self.outf.write(c.username() + '\n')
1816.2.4 by Robey Pointer
flesh out 'whoami' docs a little, and don't display the identity after setting it
2525
            return
1816.2.2 by Robey Pointer
fix 'whoami' to use encodings and allow setting the global or branch identity
2526
1840.1.2 by Robey Pointer
instead of raising an error, just display an exception if 'whoami' is given a name that doesn't look like it contains an email address
2527
        # display a warning if an email address isn't included in the given name.
2528
        try:
2529
            config.extract_email_address(name)
2055.2.2 by John Arbash Meinel
Switch extract_email_address() to use a more specific exception
2530
        except errors.NoEmailInUsername, e:
1840.1.5 by Robey Pointer
change the warning message for a 'whoami' with no email address, on jam's recommendation
2531
            warning('"%s" does not seem to contain an email address.  '
2532
                    'This is allowed, but not recommended.', name)
1840.1.1 by Robey Pointer
raise an exception if 'whoami' is given a name without a decodable email address
2533
        
1816.2.4 by Robey Pointer
flesh out 'whoami' docs a little, and don't display the identity after setting it
2534
        # use global config unless --branch given
2535
        if branch:
1816.2.10 by Robey Pointer
code style changes
2536
            c = Branch.open_containing('.')[0].get_config()
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2537
        else:
1816.2.4 by Robey Pointer
flesh out 'whoami' docs a little, and don't display the identity after setting it
2538
            c = config.GlobalConfig()
2539
        c.set_user_option('email', name)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2540
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.
2541
1185.35.14 by Aaron Bentley
Implemented nick command
2542
class cmd_nick(Command):
1551.3.11 by Aaron Bentley
Merge from Robert
2543
    """Print or set the branch nickname.  
2544
1185.35.14 by Aaron Bentley
Implemented nick command
2545
    If unset, the tree root directory name is used as the nickname
2546
    To print the current nickname, execute with no argument.  
2547
    """
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
2548
2549
    _see_also = ['info']
1185.35.14 by Aaron Bentley
Implemented nick command
2550
    takes_args = ['nickname?']
2551
    def run(self, nickname=None):
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
2552
        branch = Branch.open_containing(u'.')[0]
1185.35.14 by Aaron Bentley
Implemented nick command
2553
        if nickname is None:
2554
            self.printme(branch)
2555
        else:
2556
            branch.nick = nickname
2557
2558
    @display_command
2559
    def printme(self, branch):
2367.1.8 by Robert Collins
Whitespace.
2560
        print branch.nick
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2561
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.
2562
2900.3.2 by Tim Penhey
A working alias command.
2563
class cmd_alias(Command):
2900.3.7 by Tim Penhey
Updates from Aaron's review.
2564
    """Set/unset and display aliases.
2900.3.2 by Tim Penhey
A working alias command.
2565
2566
    :Examples:
2567
        Show the current aliases::
2568
2569
            bzr alias
2570
2571
        Show the alias specified for 'll'::
2572
2573
            bzr alias ll
2574
2575
        Set an alias for 'll'::
2576
2900.3.10 by Tim Penhey
Show examples, and change text to use double rather than single quotes.
2577
            bzr alias ll="log --line -r-10..-1"
2900.3.2 by Tim Penhey
A working alias command.
2578
2900.3.4 by Tim Penhey
Removed the unalais separate command.
2579
        To remove an alias for 'll'::
2580
2581
            bzr alias --remove ll
2582
2900.3.2 by Tim Penhey
A working alias command.
2583
    """
2584
    takes_args = ['name?']
2900.3.4 by Tim Penhey
Removed the unalais separate command.
2585
    takes_options = [
2586
        Option('remove', help='Remove the alias.'),
2587
        ]
2900.3.2 by Tim Penhey
A working alias command.
2588
2900.3.4 by Tim Penhey
Removed the unalais separate command.
2589
    def run(self, name=None, remove=False):
2590
        if remove:
2591
            self.remove_alias(name)
2592
        elif name is None:
2900.3.2 by Tim Penhey
A working alias command.
2593
            self.print_aliases()
2594
        else:
2595
            equal_pos = name.find('=')
2596
            if equal_pos == -1:
2597
                self.print_alias(name)
2598
            else:
2599
                self.set_alias(name[:equal_pos], name[equal_pos+1:])
2600
2900.3.4 by Tim Penhey
Removed the unalais separate command.
2601
    def remove_alias(self, alias_name):
2602
        if alias_name is None:
2603
            raise errors.BzrCommandError(
2604
                'bzr alias --remove expects an alias to remove.')
2605
        # If alias is not found, print something like:
2606
        # unalias: foo: not found
2900.3.8 by Tim Penhey
Use the exception text for unalias not found.
2607
        c = config.GlobalConfig()
2608
        c.unset_alias(alias_name)
2900.3.4 by Tim Penhey
Removed the unalais separate command.
2609
2610
    @display_command
2900.3.2 by Tim Penhey
A working alias command.
2611
    def print_aliases(self):
2612
        """Print out the defined aliases in a similar format to bash."""
2613
        aliases = config.GlobalConfig().get_aliases()
2900.3.7 by Tim Penhey
Updates from Aaron's review.
2614
        for key, value in sorted(aliases.iteritems()):
2900.3.10 by Tim Penhey
Show examples, and change text to use double rather than single quotes.
2615
            self.outf.write('bzr alias %s="%s"\n' % (key, value))
2900.3.2 by Tim Penhey
A working alias command.
2616
2617
    @display_command
2618
    def print_alias(self, alias_name):
2619
        from bzrlib.commands import get_alias
2620
        alias = get_alias(alias_name)
2621
        if alias is None:
2900.3.7 by Tim Penhey
Updates from Aaron's review.
2622
            self.outf.write("bzr alias: %s: not found\n" % alias_name)
2900.3.2 by Tim Penhey
A working alias command.
2623
        else:
2900.3.7 by Tim Penhey
Updates from Aaron's review.
2624
            self.outf.write(
2900.3.11 by Tim Penhey
Fixed the output in the tests.
2625
                'bzr alias %s="%s"\n' % (alias_name, ' '.join(alias)))
2900.3.2 by Tim Penhey
A working alias command.
2626
2900.3.12 by Tim Penhey
Final review comments.
2627
    def set_alias(self, alias_name, alias_command):
2900.3.2 by Tim Penhey
A working alias command.
2628
        """Save the alias in the global config."""
2629
        c = config.GlobalConfig()
2900.3.12 by Tim Penhey
Final review comments.
2630
        c.set_alias(alias_name, alias_command)
2900.3.2 by Tim Penhey
A working alias command.
2631
2632
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2633
class cmd_selftest(Command):
1393.1.46 by Martin Pool
- bzr selftest arguments can be partial ids of tests to run
2634
    """Run internal test suite.
2635
    
2213.2.1 by Martin Pool
Add selftest --first flag
2636
    If arguments are given, they are regular expressions that say which tests
2637
    should run.  Tests matching any expression are run, and other tests are
2638
    not run.
2639
2640
    Alternatively if --first is given, matching tests are run first and then
2641
    all other tests are run.  This is useful if you have been working in a
2642
    particular area, but want to make sure nothing else was broken.
1552 by Martin Pool
Improved help text for bzr selftest
2643
2394.2.2 by Ian Clatworthy
Add --randomize and update help
2644
    If --exclude is given, tests that match that regular expression are
2394.2.9 by Ian Clatworthy
update NEWS and help to reflect removal of comma support
2645
    excluded, regardless of whether they match --first or not.
2394.2.2 by Ian Clatworthy
Add --randomize and update help
2646
2647
    To help catch accidential dependencies between tests, the --randomize
2648
    option is useful. In most cases, the argument used is the word 'now'.
2649
    Note that the seed used for the random number generator is displayed
2650
    when this option is used. The seed can be explicitly passed as the
2651
    argument to this option if required. This enables reproduction of the
2652
    actual ordering used if and when an order sensitive problem is encountered.
2653
2654
    If --list-only is given, the tests that would be run are listed. This is
2655
    useful when combined with --first, --exclude and/or --randomize to
2656
    understand their impact. The test harness reports "Listed nn tests in ..."
2657
    instead of "Ran nn tests in ..." when list mode is enabled.
2658
1552 by Martin Pool
Improved help text for bzr selftest
2659
    If the global option '--no-plugins' is given, plugins are not loaded
2660
    before running the selftests.  This has two effects: features provided or
2661
    modified by plugins will not be tested, and tests provided by plugins will
2662
    not be run.
2663
2598.4.1 by Martin Pool
Remove obsolete --clean-output, --keep-output, --numbered-dirs selftest options (thanks Alexander)
2664
    Tests that need working space on disk use a common temporary directory, 
2665
    typically inside $TMPDIR or /tmp.
2666
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
2667
    :Examples:
2668
        Run only tests relating to 'ignore'::
2669
2670
            bzr selftest ignore
2671
2672
        Disable plugins and list tests as they're run::
2673
2674
            bzr --no-plugins selftest -v
1185.16.58 by mbp at sourcefrog
- run all selftests by default
2675
    """
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.
2676
    # NB: this is used from the class without creating an instance, which is
2677
    # why it does not have a self parameter.
2678
    def get_transport_type(typestring):
2679
        """Parse and return a transport specifier."""
2680
        if typestring == "sftp":
2681
            from bzrlib.transport.sftp import SFTPAbsoluteServer
2682
            return SFTPAbsoluteServer
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
2683
        if typestring == "memory":
2684
            from bzrlib.transport.memory import MemoryServer
2685
            return MemoryServer
1558.10.1 by Aaron Bentley
Handle lockdirs over NFS properly
2686
        if typestring == "fakenfs":
1558.10.2 by Robert Collins
Refactor the FakeNFS support into a TransportDecorator.
2687
            from bzrlib.transport.fakenfs import FakeNFSServer
1558.10.1 by Aaron Bentley
Handle lockdirs over NFS properly
2688
            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.
2689
        msg = "No known transport type %s. Supported types are: sftp\n" %\
2690
            (typestring)
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
2691
        raise errors.BzrCommandError(msg)
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.
2692
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2693
    hidden = True
1185.1.57 by Robert Collins
nuke --pattern to selftest, replace with regexp.search calls.
2694
    takes_args = ['testspecs*']
1552 by Martin Pool
Improved help text for bzr selftest
2695
    takes_options = ['verbose',
2418.2.2 by Martin Pool
Add -1 option to selftest
2696
                     Option('one',
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
2697
                             help='Stop when one test fails.',
2418.2.2 by Martin Pool
Add -1 option to selftest
2698
                             short_name='1',
2699
                             ),
2333.1.1 by Dmitry Vasiliev
Fixed typo and removed some trailing whitespaces
2700
                     Option('transport',
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.
2701
                            help='Use a different transport by default '
2702
                                 'throughout the test suite.',
2703
                            type=get_transport_type),
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
2704
                     Option('benchmark',
2705
                            help='Run the benchmarks rather than selftests.'),
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
2706
                     Option('lsprof-timed',
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
2707
                            help='Generate lsprof output for benchmarked'
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
2708
                                 ' sections of code.'),
1908.2.4 by John Arbash Meinel
Add the ability to specify a benchmark cache directory.
2709
                     Option('cache-dir', type=str,
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
2710
                            help='Cache intermediate benchmark output in this '
2711
                                 'directory.'),
2213.2.1 by Martin Pool
Add selftest --first flag
2712
                     Option('first',
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
2713
                            help='Run all tests, but run specified tests first.',
2418.2.1 by Martin Pool
Add -f alias for selftest --first
2714
                            short_name='f',
2321.2.1 by Alexander Belchenko
`bzr selftest --numbered-dirs` use numbered dirs for TestCaseInTempDir
2715
                            ),
2394.2.1 by Ian Clatworthy
--list and --exclude first cut
2716
                     Option('list-only',
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
2717
                            help='List the tests instead of running them.'),
2394.2.2 by Ian Clatworthy
Add --randomize and update help
2718
                     Option('randomize', type=str, argname="SEED",
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
2719
                            help='Randomize the order of tests using the given'
2720
                                 ' seed or "now" for the current time.'),
2394.2.2 by Ian Clatworthy
Add --randomize and update help
2721
                     Option('exclude', type=str, argname="PATTERN",
2394.2.6 by Ian Clatworthy
completed blackbox tests
2722
                            short_name='x',
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
2723
                            help='Exclude tests that match this regular'
2724
                                 ' expression.'),
2658.3.3 by Daniel Watkins
Added UI support for bzr selftest --strict.
2725
                     Option('strict', help='Fail on missing dependencies or '
2726
                            'known failures.'),
3193.1.8 by Vincent Ladeuil
Add '--load-list' option to selftest.
2727
                     Option('load-list', type=str, argname='TESTLISTFILE',
2728
                            help='Load a test id list from a text file.'),
3390.1.1 by Andrew Bennetts
Add --debugflags/-E option to selftest.
2729
                     ListOption('debugflag', type=str, short_name='E',
2730
                                help='Turn on a selftest debug flag.'),
3649.6.4 by Vincent Ladeuil
selftest --starting-with now accepts multiple values.
2731
                     ListOption('starting-with', type=str, argname='TESTID',
2732
                                param_name='starting_with', short_name='s',
2733
                                help=
2734
                                'Load only the tests starting with TESTID.'),
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
2735
                     ]
2204.3.4 by Alexander Belchenko
Command 'selftest' use 'replace' encoding_type to prevent sudden traceback
2736
    encoding_type = 'replace'
1185.16.58 by mbp at sourcefrog
- run all selftests by default
2737
2805.1.1 by Ian Clatworthy
Fix selftest --benchmark so verbose by default again
2738
    def run(self, testspecs_list=None, verbose=False, one=False,
2598.4.1 by Martin Pool
Remove obsolete --clean-output, --keep-output, --numbered-dirs selftest options (thanks Alexander)
2739
            transport=None, benchmark=None,
2740
            lsprof_timed=None, cache_dir=None,
2741
            first=False, list_only=False,
3198.1.1 by Vincent Ladeuil
Add --load-list option to selftest
2742
            randomize=None, exclude=None, strict=False,
3302.11.7 by Vincent Ladeuil
merge bzr.dev, fixing simple conflicts
2743
            load_list=None, debugflag=None, starting_with=None):
1707.2.2 by Robert Collins
Start on bench_add, an add benchtest.
2744
        from bzrlib.tests import selftest
2745
        import bzrlib.benchmarks as benchmarks
1908.2.16 by John Arbash Meinel
Move all the new TreeCreator classes into separate files.
2746
        from bzrlib.benchmarks import tree_creator
2321.2.1 by Alexander Belchenko
`bzr selftest --numbered-dirs` use numbered dirs for TestCaseInTempDir
2747
3427.5.3 by John Arbash Meinel
Update the activate_deprecation_warnings so it can be skipped if there is already an error set.
2748
        # Make deprecation warnings visible, unless -Werror is set
3427.5.7 by John Arbash Meinel
Bring back always in the form of 'override'.
2749
        symbol_versioning.activate_deprecation_warnings(override=False)
3427.5.3 by John Arbash Meinel
Update the activate_deprecation_warnings so it can be skipped if there is already an error set.
2750
1908.2.4 by John Arbash Meinel
Add the ability to specify a benchmark cache directory.
2751
        if cache_dir is not None:
1908.2.16 by John Arbash Meinel
Move all the new TreeCreator classes into separate files.
2752
            tree_creator.TreeCreator.CACHE_ROOT = osutils.abspath(cache_dir)
2606.1.3 by Martin Pool
Update tests for new version display
2753
        if not list_only:
2687.3.1 by Martin Pool
Revert selftest header to just two lines, but still show the bzrlib and python versions
2754
            print 'testing: %s' % (osutils.realpath(sys.argv[0]),)
2755
            print '   %s (%s python%s)' % (
2756
                    bzrlib.__path__[0],
2757
                    bzrlib.version_string,
3293.2.2 by Martin Pool
Fix formatting of other occurrences of Python version
2758
                    bzrlib._format_version_tuple(sys.version_info),
2687.3.1 by Martin Pool
Revert selftest header to just two lines, but still show the bzrlib and python versions
2759
                    )
1707.2.1 by Robert Collins
'bzr selftest --benchmark' will run a new benchmarking selftest.
2760
        print
2095.4.1 by Martin Pool
Better progress bars during tests
2761
        if testspecs_list is not None:
2762
            pattern = '|'.join(testspecs_list)
2763
        else:
2764
            pattern = ".*"
2765
        if benchmark:
2766
            test_suite_factory = benchmarks.test_suite
2805.1.1 by Ian Clatworthy
Fix selftest --benchmark so verbose by default again
2767
            # Unless user explicitly asks for quiet, be verbose in benchmarks
2768
            verbose = not is_quiet()
2095.4.1 by Martin Pool
Better progress bars during tests
2769
            # TODO: should possibly lock the history file...
2197.1.1 by Martin Pool
Use line buffering to write .perf_history
2770
            benchfile = open(".perf_history", "at", buffering=1)
2095.4.1 by Martin Pool
Better progress bars during tests
2771
        else:
2772
            test_suite_factory = None
2773
            benchfile = None
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2774
        try:
2598.4.1 by Martin Pool
Remove obsolete --clean-output, --keep-output, --numbered-dirs selftest options (thanks Alexander)
2775
            result = selftest(verbose=verbose,
2095.4.1 by Martin Pool
Better progress bars during tests
2776
                              pattern=pattern,
2598.4.1 by Martin Pool
Remove obsolete --clean-output, --keep-output, --numbered-dirs selftest options (thanks Alexander)
2777
                              stop_on_failure=one,
2095.4.1 by Martin Pool
Better progress bars during tests
2778
                              transport=transport,
2779
                              test_suite_factory=test_suite_factory,
2780
                              lsprof_timed=lsprof_timed,
2213.2.1 by Martin Pool
Add selftest --first flag
2781
                              bench_history=benchfile,
2782
                              matching_tests_first=first,
2394.2.1 by Ian Clatworthy
--list and --exclude first cut
2783
                              list_only=list_only,
2394.2.2 by Ian Clatworthy
Add --randomize and update help
2784
                              random_seed=randomize,
2658.3.3 by Daniel Watkins
Added UI support for bzr selftest --strict.
2785
                              exclude_pattern=exclude,
2786
                              strict=strict,
3193.1.8 by Vincent Ladeuil
Add '--load-list' option to selftest.
2787
                              load_list=load_list,
3390.1.1 by Andrew Bennetts
Add --debugflags/-E option to selftest.
2788
                              debug_flags=debugflag,
3302.11.2 by Vincent Ladeuil
selftest now accepts --starting-ith <id> to load and execute only a module|class|test* reduced suite.
2789
                              starting_with=starting_with,
2213.2.1 by Martin Pool
Add selftest --first flag
2790
                              )
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2791
        finally:
2095.4.1 by Martin Pool
Better progress bars during tests
2792
            if benchfile is not None:
2793
                benchfile.close()
2794
        if result:
3221.5.1 by Vincent Ladeuil
Fix bug #137823 by raising UnavailableFeature *after* the fake ftp server
2795
            note('tests passed')
2095.4.1 by Martin Pool
Better progress bars during tests
2796
        else:
3221.5.1 by Vincent Ladeuil
Fix bug #137823 by raising UnavailableFeature *after* the fake ftp server
2797
            note('tests failed')
2095.4.1 by Martin Pool
Better progress bars during tests
2798
        return int(not result)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2799
2800
2801
class cmd_version(Command):
2802
    """Show version of bzr."""
1871.1.1 by Robert Collins
Relocate bzrlib selftest external output tests to bzrlib/tests/blackbox/test_selftest.py.
2803
2785.1.2 by bialix at ukr
bugfix for #131100
2804
    encoding_type = 'replace'
3346.2.1 by Martin Pool
Add version --short option
2805
    takes_options = [
2806
        Option("short", help="Print just the version number."),
2807
        ]
2785.1.2 by bialix at ukr
bugfix for #131100
2808
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
2809
    @display_command
3346.2.1 by Martin Pool
Add version --short option
2810
    def run(self, short=False):
1819.1.8 by Martin Pool
Improved reporting of bzrlib revision_id
2811
        from bzrlib.version import show_version
3346.2.1 by Martin Pool
Add version --short option
2812
        if short:
3346.2.7 by Martin Pool
Commands should use self.outf not print
2813
            self.outf.write(bzrlib.version_string + '\n')
3346.2.1 by Martin Pool
Add version --short option
2814
        else:
2815
            show_version(to_file=self.outf)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2816
1871.1.1 by Robert Collins
Relocate bzrlib selftest external output tests to bzrlib/tests/blackbox/test_selftest.py.
2817
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2818
class cmd_rocks(Command):
2819
    """Statement of optimism."""
1871.1.1 by Robert Collins
Relocate bzrlib selftest external output tests to bzrlib/tests/blackbox/test_selftest.py.
2820
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2821
    hidden = True
1871.1.1 by Robert Collins
Relocate bzrlib selftest external output tests to bzrlib/tests/blackbox/test_selftest.py.
2822
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
2823
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2824
    def run(self):
2227.4.1 by v.ladeuil+lp at free
Fix #78026.
2825
        print "It sure does!"
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2826
2827
2828
class cmd_find_merge_base(Command):
1871.1.1 by Robert Collins
Relocate bzrlib selftest external output tests to bzrlib/tests/blackbox/test_selftest.py.
2829
    """Find and print a base revision for merging two branches."""
1185.16.3 by Martin Pool
- remove all TODOs from bzr help messages
2830
    # TODO: Options to specify revisions on either side, as if
2831
    #       merging only part of the history.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2832
    takes_args = ['branch', 'other']
2833
    hidden = True
2834
    
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
2835
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2836
    def run(self, branch, other):
2872.2.1 by Andrew Bennetts
Remove unused imports in builtins.py revealed by pyflakes, and fix one undefined name.
2837
        from bzrlib.revision import ensure_null
1155 by Martin Pool
- update find-merge-base to use new common_ancestor code
2838
        
1442.1.64 by Robert Collins
Branch.open_containing now returns a tuple (Branch, relative-path).
2839
        branch1 = Branch.open_containing(branch)[0]
2840
        branch2 = Branch.open_containing(other)[0]
3010.1.17 by Robert Collins
Lock correctness and commit_group management for re-sign, in builtins.
2841
        branch1.lock_read()
2842
        try:
2843
            branch2.lock_read()
2844
            try:
2845
                last1 = ensure_null(branch1.last_revision())
2846
                last2 = ensure_null(branch2.last_revision())
2847
2848
                graph = branch1.repository.get_graph(branch2.repository)
2849
                base_rev_id = graph.find_unique_lca(last1, last2)
2850
2851
                print 'merge base is revision %s' % base_rev_id
2852
            finally:
2853
                branch2.unlock()
2854
        finally:
2855
            branch1.unlock()
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2856
2857
2858
class cmd_merge(Command):
2859
    """Perform a three-way merge.
2860
    
3277.1.1 by Peter Schuller
Document the relationship between bzr send and bzr merge. In
2861
    The source of the merge can be specified either in the form of a branch,
2862
    or in the form of a path to a file containing a merge directive generated
2863
    with bzr send. If neither is specified, the default is the upstream branch
3277.1.2 by Peter Schuller
As per feedback to previous attempt:
2864
    or the branch most recently merged using --remember.
3277.1.1 by Peter Schuller
Document the relationship between bzr send and bzr merge. In
2865
3277.1.2 by Peter Schuller
As per feedback to previous attempt:
2866
    When merging a branch, by default the tip will be merged. To pick a different
2867
    revision, pass --revision. If you specify two values, the first will be used as
3313.1.1 by Ian Clatworthy
Improve doc on send/merge relationship (Peter Schuller)
2868
    BASE and the second one as OTHER. Merging individual revisions, or a subset of
2869
    available revisions, like this is commonly referred to as "cherrypicking".
3277.1.3 by Peter Schuller
Identify by name the "cherrypicking" mode of operation of 'bzr merge'.
2870
2871
    Revision numbers are always relative to the branch being merged.
1172 by Martin Pool
- better explanation when merge fails with AmbiguousBase
2872
1551.2.19 by Aaron Bentley
Added See Conflicts to merge help
2873
    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
2874
    branch, automatically determining an appropriate base.  If this
2875
    fails, you may need to give an explicit base.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2876
    
1551.2.18 by Aaron Bentley
Updated docs to clarify conflict handling
2877
    Merge will do its best to combine the changes in two branches, but there
2878
    are some kinds of problems only a human can fix.  When it encounters those,
2879
    it will mark a conflict.  A conflict means that you need to fix something,
2880
    before you should commit.
2881
1551.2.19 by Aaron Bentley
Added See Conflicts to merge help
2882
    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
2883
1614.2.4 by Olaf Conradi
Renamed argument location in command merge back to branch.
2884
    If there is no default branch set, the first merge will set it. After
2885
    that, you can omit the branch to use the default.  To change the
1785.1.4 by John Arbash Meinel
Update help for the new --remember semantics.
2886
    default, use --remember. The value will only be saved if the remote
2887
    location can be accessed.
1614.2.2 by Olaf Conradi
Merge command:
2888
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
2889
    The results of the merge are placed into the destination working
2890
    directory, where they can be reviewed (with bzr diff), tested, and then
2891
    committed to record the result of the merge.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2892
    
2893
    merge refuses to run if there are any uncommitted changes, unless
2894
    --force is given.
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
2895
2896
    :Examples:
2897
        To merge the latest revision from bzr.dev::
2898
2899
            bzr merge ../bzr.dev
2900
2901
        To merge changes up to and including revision 82 from bzr.dev::
2902
2903
            bzr merge -r 82 ../bzr.dev
2904
2905
        To merge the changes introduced by 82, without previous changes::
2906
2907
            bzr merge -r 81..82 ../bzr.dev
3277.1.1 by Peter Schuller
Document the relationship between bzr send and bzr merge. In
2908
2909
        To apply a merge directive contained in in /tmp/merge:
2910
2911
            bzr merge /tmp/merge
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2912
    """
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
2913
3008.1.25 by Aaron Bentley
Set encoding exact on cmd_merge
2914
    encoding_type = 'exact'
2520.1.5 by Daniel Watkins
'help merge' now points to 'help status-flags'.
2915
    _see_also = ['update', 'remerge', 'status-flags']
3277.1.4 by Peter Schuller
As per further feedback, use LOCATION instead of MERGE_OR_MERGE_DIRECTIVE.
2916
    takes_args = ['location?']
2598.1.10 by Martin Pool
Clean up options that are registered globally and used once or not at all.
2917
    takes_options = [
2839.5.1 by Alexander Belchenko
add -c option to merge command
2918
        'change',
2598.1.10 by Martin Pool
Clean up options that are registered globally and used once or not at all.
2919
        'revision',
2920
        Option('force',
2921
               help='Merge even if the destination tree has uncommitted changes.'),
2922
        'merge-type',
2923
        'reprocess',
2924
        'remember',
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
2925
        Option('show-base', help="Show base revision text in "
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
2926
               "conflicts."),
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
2927
        Option('uncommitted', help='Apply uncommitted changes'
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
2928
               ' from a working copy, instead of branch changes.'),
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
2929
        Option('pull', help='If the destination is already'
2930
                ' completely merged into the source, pull from the'
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
2931
                ' source rather than merging.  When this happens,'
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
2932
                ' you do not need to commit the result.'),
2933
        Option('directory',
2598.1.10 by Martin Pool
Clean up options that are registered globally and used once or not at all.
2934
               help='Branch to merge into, '
2935
                    'rather than the one containing the working directory.',
2936
               short_name='d',
2937
               type=unicode,
2938
               ),
3008.1.24 by Aaron Bentley
Add merge --preview to show diff
2939
        Option('preview', help='Instead of merging, show a diff of the merge.')
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
2940
    ]
1551.6.22 by Aaron Bentley
Improved help for remerge and merge
2941
3277.1.4 by Peter Schuller
As per further feedback, use LOCATION instead of MERGE_OR_MERGE_DIRECTIVE.
2942
    def run(self, location=None, revision=None, force=False,
3744.2.1 by John Arbash Meinel
Change 'bzr merge' so that it uses --reprocess as long as --show-base is not given.
2943
            merge_type=None, show_base=False, reprocess=None, remember=False,
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
2944
            uncommitted=False, pull=False,
2945
            directory=None,
3008.1.24 by Aaron Bentley
Add merge --preview to show diff
2946
            preview=False,
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
2947
            ):
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2948
        if merge_type is None:
1996.3.5 by John Arbash Meinel
Cleanup, deprecated, and get the tests passing again.
2949
            merge_type = _mod_merge.Merge3Merger
1614.2.2 by Olaf Conradi
Merge command:
2950
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
2951
        if directory is None: directory = u'.'
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
2952
        possible_transports = []
2953
        merger = None
2954
        allow_pending = True
2955
        verified = 'inapplicable'
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
2956
        tree = WorkingTree.open_containing(directory)[0]
1551.10.25 by Aaron Bentley
Make ChangeReporter private
2957
        change_reporter = delta._ChangeReporter(
2255.7.98 by Robert Collins
Merge bzr.dev.
2958
            unversioned_filter=tree.is_ignored)
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
2959
        cleanups = []
2960
        try:
2961
            pb = ui.ui_factory.nested_progress_bar()
2962
            cleanups.append(pb.finished)
2963
            tree.lock_write()
2964
            cleanups.append(tree.unlock)
1551.15.74 by Aaron Bentley
Textual updates from review
2965
            if location is not None:
3251.4.10 by Aaron Bentley
Pull of launchpad locations works (abentley, #181945)
2966
                try:
2967
                    mergeable = bundle.read_mergeable_from_url(location,
2968
                        possible_transports=possible_transports)
2969
                except errors.NotABundle:
2970
                    mergeable = None
2971
                else:
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
2972
                    if uncommitted:
2973
                        raise errors.BzrCommandError('Cannot use --uncommitted'
2974
                            ' with bundles or merge directives.')
2975
2976
                    if revision is not None:
2977
                        raise errors.BzrCommandError(
2978
                            'Cannot use -r with merge directives or bundles')
2979
                    merger, verified = _mod_merge.Merger.from_mergeable(tree,
2980
                       mergeable, pb)
2981
2982
            if merger is None and uncommitted:
2983
                if revision is not None and len(revision) > 0:
2984
                    raise errors.BzrCommandError('Cannot use --uncommitted and'
2985
                        ' --revision at the same time.')
1551.15.74 by Aaron Bentley
Textual updates from review
2986
                location = self._select_branch_location(tree, location)[0]
2987
                other_tree, other_path = WorkingTree.open_containing(location)
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
2988
                merger = _mod_merge.Merger.from_uncommitted(tree, other_tree,
2989
                    pb)
2990
                allow_pending = False
3017.3.1 by Aaron Bentley
merge --uncommit can now specify single files (#136890)
2991
                if other_path != '':
2992
                    merger.interesting_files = [other_path]
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
2993
2994
            if merger is None:
1551.15.75 by Aaron Bentley
_merger_from_branch -> _get_merger_from_branch
2995
                merger, allow_pending = self._get_merger_from_branch(tree,
1551.15.74 by Aaron Bentley
Textual updates from review
2996
                    location, revision, remember, possible_transports, pb)
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
2997
2998
            merger.merge_type = merge_type
2999
            merger.reprocess = reprocess
3000
            merger.show_base = show_base
3001
            self.sanity_check_merger(merger)
3002
            if (merger.base_rev_id == merger.other_rev_id and
3376.2.11 by Martin Pool
Compare to None using is/is not not ==
3003
                merger.other_rev_id is not None):
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
3004
                note('Nothing to do.')
3005
                return 0
3006
            if pull:
3007
                if merger.interesting_files is not None:
2872.2.1 by Andrew Bennetts
Remove unused imports in builtins.py revealed by pyflakes, and fix one undefined name.
3008
                    raise errors.BzrCommandError('Cannot pull individual files')
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
3009
                if (merger.base_rev_id == tree.last_revision()):
3010
                    result = tree.pull(merger.other_branch, False,
3011
                                       merger.other_rev_id)
3012
                    result.report(self.outf)
3013
                    return 0
3014
            merger.check_basis(not force)
3008.1.24 by Aaron Bentley
Add merge --preview to show diff
3015
            if preview:
3016
                return self._do_preview(merger)
1551.15.66 by Aaron Bentley
Improve behavior with revision ids
3017
            else:
3008.1.24 by Aaron Bentley
Add merge --preview to show diff
3018
                return self._do_merge(merger, change_reporter, allow_pending,
3019
                                      verified)
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
3020
        finally:
3021
            for cleanup in reversed(cleanups):
3022
                cleanup()
3023
3008.1.24 by Aaron Bentley
Add merge --preview to show diff
3024
    def _do_preview(self, merger):
3025
        from bzrlib.diff import show_diff_trees
3026
        tree_merger = merger.make_merger()
3027
        tt = tree_merger.make_preview_transform()
3199.1.9 by Vincent Ladeuil
Aaron's review feedback.
3028
        try:
3029
            result_tree = tt.get_preview_tree()
3030
            show_diff_trees(merger.this_tree, result_tree, self.outf,
3031
                            old_label='', new_label='')
3032
        finally:
3033
            tt.finalize()
3008.1.24 by Aaron Bentley
Add merge --preview to show diff
3034
3035
    def _do_merge(self, merger, change_reporter, allow_pending, verified):
3036
        merger.change_reporter = change_reporter
3037
        conflict_count = merger.do_merge()
3038
        if allow_pending:
3039
            merger.set_pending()
3040
        if verified == 'failed':
3041
            warning('Preview patch does not match changes')
3042
        if conflict_count != 0:
3043
            return 1
3044
        else:
3045
            return 0
3046
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
3047
    def sanity_check_merger(self, merger):
3048
        if (merger.show_base and
3049
            not merger.merge_type is _mod_merge.Merge3Merger):
3050
            raise errors.BzrCommandError("Show-base is not supported for this"
2665.2.1 by Michael Hudson
test and fix for a NameError in merge --weave --show-base
3051
                                         " merge type. %s" % merger.merge_type)
3744.2.1 by John Arbash Meinel
Change 'bzr merge' so that it uses --reprocess as long as --show-base is not given.
3052
        if merger.reprocess is None:
3053
            if merger.show_base:
3054
                merger.reprocess = False
3055
            else:
3056
                # Use reprocess if the merger supports it
3057
                merger.reprocess = merger.merge_type.supports_reprocess
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
3058
        if merger.reprocess and not merger.merge_type.supports_reprocess:
3059
            raise errors.BzrCommandError("Conflict reduction is not supported"
2665.2.1 by Michael Hudson
test and fix for a NameError in merge --weave --show-base
3060
                                         " for merge type %s." %
3061
                                         merger.merge_type)
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
3062
        if merger.reprocess and merger.show_base:
3063
            raise errors.BzrCommandError("Cannot do conflict reduction and"
3064
                                         " show base.")
3065
1551.15.75 by Aaron Bentley
_merger_from_branch -> _get_merger_from_branch
3066
    def _get_merger_from_branch(self, tree, location, revision, remember,
3067
                                possible_transports, pb):
3068
        """Produce a merger from a location, assuming it refers to a branch."""
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
3069
        from bzrlib.tag import _merge_tags_if_possible
3070
        # find the branch locations
1551.20.2 by Aaron Bentley
Merge prefers submit branch, but falls back to parent branch
3071
        other_loc, user_location = self._select_branch_location(tree, location,
1551.15.74 by Aaron Bentley
Textual updates from review
3072
            revision, -1)
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
3073
        if revision is not None and len(revision) == 2:
1551.20.2 by Aaron Bentley
Merge prefers submit branch, but falls back to parent branch
3074
            base_loc, _unused = self._select_branch_location(tree,
3075
                location, revision, 0)
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
3076
        else:
3077
            base_loc = other_loc
3078
        # Open the branches
3079
        other_branch, other_path = Branch.open_containing(other_loc,
3080
            possible_transports)
3081
        if base_loc == other_loc:
3082
            base_branch = other_branch
3083
        else:
3084
            base_branch, base_path = Branch.open_containing(base_loc,
1551.15.66 by Aaron Bentley
Improve behavior with revision ids
3085
                possible_transports)
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
3086
        # Find the revision ids
3087
        if revision is None or len(revision) < 1 or revision[-1] is None:
3088
            other_revision_id = _mod_revision.ensure_null(
3089
                other_branch.last_revision())
3090
        else:
3298.2.8 by John Arbash Meinel
Get rid of .in_branch(need_revno=False) in favor of simpler .as_revision_id()
3091
            other_revision_id = revision[-1].as_revision_id(other_branch)
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
3092
        if (revision is not None and len(revision) == 2
3093
            and revision[0] is not None):
3298.2.8 by John Arbash Meinel
Get rid of .in_branch(need_revno=False) in favor of simpler .as_revision_id()
3094
            base_revision_id = revision[0].as_revision_id(base_branch)
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
3095
        else:
3096
            base_revision_id = None
2485.8.37 by Vincent Ladeuil
Fix merge multiple connections. Test suite *not* passing (sftp
3097
        # Remember where we merge from
1551.20.2 by Aaron Bentley
Merge prefers submit branch, but falls back to parent branch
3098
        if ((remember or tree.branch.get_submit_branch() is None) and
3099
             user_location is not None):
3100
            tree.branch.set_submit_branch(other_branch.base)
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
3101
        _merge_tags_if_possible(other_branch, tree.branch)
3102
        merger = _mod_merge.Merger.from_revision_ids(pb, tree,
3103
            other_revision_id, base_revision_id, other_branch, base_branch)
3104
        if other_path != '':
3105
            allow_pending = False
3106
            merger.interesting_files = [other_path]
1645.1.1 by Aaron Bentley
Implement single-file merge
3107
        else:
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
3108
            allow_pending = True
3109
        return merger, allow_pending
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3110
1551.20.2 by Aaron Bentley
Merge prefers submit branch, but falls back to parent branch
3111
    def _select_branch_location(self, tree, user_location, revision=None,
1551.15.74 by Aaron Bentley
Textual updates from review
3112
                                index=None):
3113
        """Select a branch location, according to possible inputs.
3114
3115
        If provided, branches from ``revision`` are preferred.  (Both
3116
        ``revision`` and ``index`` must be supplied.)
3117
3118
        Otherwise, the ``location`` parameter is used.  If it is None, then the
1551.20.2 by Aaron Bentley
Merge prefers submit branch, but falls back to parent branch
3119
        ``submit`` or ``parent`` location is used, and a note is printed.
1551.15.74 by Aaron Bentley
Textual updates from review
3120
3121
        :param tree: The working tree to select a branch for merging into
3122
        :param location: The location entered by the user
3123
        :param revision: The revision parameter to the command
3124
        :param index: The index to use for the revision parameter.  Negative
3125
            indices are permitted.
1551.20.2 by Aaron Bentley
Merge prefers submit branch, but falls back to parent branch
3126
        :return: (selected_location, user_location).  The default location
3127
            will be the user-entered location.
1551.15.74 by Aaron Bentley
Textual updates from review
3128
        """
1551.15.66 by Aaron Bentley
Improve behavior with revision ids
3129
        if (revision is not None and index is not None
3130
            and revision[index] is not None):
3131
            branch = revision[index].get_branch()
3132
            if branch is not None:
1551.20.2 by Aaron Bentley
Merge prefers submit branch, but falls back to parent branch
3133
                return branch, branch
3134
        if user_location is None:
3135
            location = self._get_remembered(tree, 'Merging from')
3136
        else:
3137
            location = user_location
3138
        return location, user_location
1551.15.66 by Aaron Bentley
Improve behavior with revision ids
3139
1551.20.2 by Aaron Bentley
Merge prefers submit branch, but falls back to parent branch
3140
    def _get_remembered(self, tree, verb_string):
1685.1.59 by Martin Pool
[broken] Fix up & refactor display of remembered urls to unescape properly
3141
        """Use tree.branch's parent if none was supplied.
3142
3143
        Report if the remembered location was used.
3144
        """
1551.20.2 by Aaron Bentley
Merge prefers submit branch, but falls back to parent branch
3145
        stored_location = tree.branch.get_submit_branch()
3596.3.1 by James Westby
Give the user a bit more information about which saved location is being used.
3146
        stored_location_type = "submit"
1551.20.2 by Aaron Bentley
Merge prefers submit branch, but falls back to parent branch
3147
        if stored_location is None:
3148
            stored_location = tree.branch.get_parent()
3596.3.1 by James Westby
Give the user a bit more information about which saved location is being used.
3149
            stored_location_type = "parent"
1685.1.71 by Wouter van Heyst
change branch.{get,set}_parent to store a relative path but return full urls
3150
        mutter("%s", stored_location)
1685.1.59 by Martin Pool
[broken] Fix up & refactor display of remembered urls to unescape properly
3151
        if stored_location is None:
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
3152
            raise errors.BzrCommandError("No location specified or remembered")
3249.1.1 by Ian Clatworthy
fix merge redirection when using a remembered location
3153
        display_url = urlutils.unescape_for_display(stored_location, 'utf-8')
3596.3.1 by James Westby
Give the user a bit more information about which saved location is being used.
3154
        note(u"%s remembered %s location %s", verb_string,
3155
                stored_location_type, display_url)
1685.1.59 by Martin Pool
[broken] Fix up & refactor display of remembered urls to unescape properly
3156
        return stored_location
3157
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3158
1185.35.4 by Aaron Bentley
Implemented remerge
3159
class cmd_remerge(Command):
3160
    """Redo a merge.
1551.6.22 by Aaron Bentley
Improved help for remerge and merge
3161
3162
    Use this if you want to try a different merge technique while resolving
3163
    conflicts.  Some merge techniques are better than others, and remerge 
3164
    lets you try different ones on different files.
3165
3166
    The options for remerge have the same meaning and defaults as the ones for
3167
    merge.  The difference is that remerge can (only) be run when there is a
3168
    pending merge, and it lets you specify particular files.
3169
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
3170
    :Examples:
1551.6.22 by Aaron Bentley
Improved help for remerge and merge
3171
        Re-do the merge of all conflicted files, and show the base text in
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
3172
        conflict regions, in addition to the usual THIS and OTHER texts::
3173
      
3174
            bzr remerge --show-base
1551.6.22 by Aaron Bentley
Improved help for remerge and merge
3175
3176
        Re-do the merge of "foobar", using the weave merge algorithm, with
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
3177
        additional processing to reduce the size of conflict regions::
3178
      
3179
            bzr remerge --merge-type weave --reprocess foobar
2374.1.1 by Ian Clatworthy
Help and man page fixes
3180
    """
1185.35.4 by Aaron Bentley
Implemented remerge
3181
    takes_args = ['file*']
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
3182
    takes_options = [
3183
            'merge-type',
3184
            'reprocess',
3185
            Option('show-base',
3186
                   help="Show base revision text in conflicts."),
3187
            ]
1185.35.4 by Aaron Bentley
Implemented remerge
3188
3189
    def run(self, file_list=None, merge_type=None, show_base=False,
3190
            reprocess=False):
3191
        if merge_type is None:
1996.3.5 by John Arbash Meinel
Cleanup, deprecated, and get the tests passing again.
3192
            merge_type = _mod_merge.Merge3Merger
1508.1.15 by Robert Collins
Merge from mpool.
3193
        tree, file_list = tree_files(file_list)
3194
        tree.lock_write()
1185.35.4 by Aaron Bentley
Implemented remerge
3195
        try:
1908.6.8 by Robert Collins
Remove remerges dependence on pending_merges, also makes it simpler.
3196
            parents = tree.get_parent_ids()
3197
            if len(parents) != 2:
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
3198
                raise errors.BzrCommandError("Sorry, remerge only works after normal"
3199
                                             " merges.  Not cherrypicking or"
3200
                                             " multi-merges.")
1185.67.2 by Aaron Bentley
Renamed Branch.storage to Branch.repository
3201
            repository = tree.branch.repository
1185.35.4 by Aaron Bentley
Implemented remerge
3202
            interesting_ids = None
1551.7.10 by Aaron Bentley
Remerge doesn't clear unrelated conflicts
3203
            new_conflicts = []
3204
            conflicts = tree.conflicts()
1185.35.4 by Aaron Bentley
Implemented remerge
3205
            if file_list is not None:
3206
                interesting_ids = set()
3207
                for filename in file_list:
1508.1.15 by Robert Collins
Merge from mpool.
3208
                    file_id = tree.path2id(filename)
1558.2.1 by Aaron Bentley
Ensure remerge errors when file-id is None
3209
                    if file_id is None:
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
3210
                        raise errors.NotVersionedError(filename)
1185.35.4 by Aaron Bentley
Implemented remerge
3211
                    interesting_ids.add(file_id)
1508.1.15 by Robert Collins
Merge from mpool.
3212
                    if tree.kind(file_id) != "directory":
1185.35.4 by Aaron Bentley
Implemented remerge
3213
                        continue
1185.35.13 by Aaron Bentley
Merged Martin
3214
                    
1508.1.15 by Robert Collins
Merge from mpool.
3215
                    for name, ie in tree.inventory.iter_entries(file_id):
1185.35.4 by Aaron Bentley
Implemented remerge
3216
                        interesting_ids.add(ie.file_id)
1551.7.10 by Aaron Bentley
Remerge doesn't clear unrelated conflicts
3217
                new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
2080.2.1 by John Arbash Meinel
Make 'bzr remerge' not use deprecated WorkingTree.iter_conflicts
3218
            else:
2080.2.3 by John Arbash Meinel
remerge only supports text or content conflicts
3219
                # Remerge only supports resolving contents conflicts
3220
                allowed_conflicts = ('text conflict', 'contents conflict')
3221
                restore_files = [c.path for c in conflicts
3222
                                 if c.typestring in allowed_conflicts]
1996.3.5 by John Arbash Meinel
Cleanup, deprecated, and get the tests passing again.
3223
            _mod_merge.transform_tree(tree, tree.basis_tree(), interesting_ids)
1551.7.10 by Aaron Bentley
Remerge doesn't clear unrelated conflicts
3224
            tree.set_conflicts(ConflictList(new_conflicts))
2080.2.1 by John Arbash Meinel
Make 'bzr remerge' not use deprecated WorkingTree.iter_conflicts
3225
            if file_list is not None:
1185.35.4 by Aaron Bentley
Implemented remerge
3226
                restore_files = file_list
3227
            for filename in restore_files:
3228
                try:
1508.1.15 by Robert Collins
Merge from mpool.
3229
                    restore(tree.abspath(filename))
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
3230
                except errors.NotConflicted:
1185.35.4 by Aaron Bentley
Implemented remerge
3231
                    pass
1551.15.52 by Aaron Bentley
Tweak from review comments
3232
            # Disable pending merges, because the file texts we are remerging
3233
            # have not had those merges performed.  If we use the wrong parents
3234
            # list, we imply that the working tree text has seen and rejected
3235
            # all the changes from the other tree, when in fact those changes
3236
            # have not yet been seen.
3062.2.8 by Aaron Bentley
Update remerge to use Merger.from_revision_ids
3237
            pb = ui.ui_factory.nested_progress_bar()
1551.15.53 by Aaron Bentley
Restore old method of adjusting partents
3238
            tree.set_parent_ids(parents[:1])
1551.15.47 by Aaron Bentley
Fix remerge --weave
3239
            try:
3062.2.8 by Aaron Bentley
Update remerge to use Merger.from_revision_ids
3240
                merger = _mod_merge.Merger.from_revision_ids(pb,
3241
                                                             tree, parents[1])
3242
                merger.interesting_ids = interesting_ids
3243
                merger.merge_type = merge_type
3244
                merger.show_base = show_base
3245
                merger.reprocess = reprocess
3246
                conflicts = merger.do_merge()
1551.15.47 by Aaron Bentley
Fix remerge --weave
3247
            finally:
1551.15.53 by Aaron Bentley
Restore old method of adjusting partents
3248
                tree.set_parent_ids(parents)
3062.2.8 by Aaron Bentley
Update remerge to use Merger.from_revision_ids
3249
                pb.finished()
1185.35.4 by Aaron Bentley
Implemented remerge
3250
        finally:
1508.1.15 by Robert Collins
Merge from mpool.
3251
            tree.unlock()
1185.35.4 by Aaron Bentley
Implemented remerge
3252
        if conflicts > 0:
3253
            return 1
3254
        else:
3255
            return 0
3256
2023.1.1 by ghigo
add topics help
3257
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3258
class cmd_revert(Command):
1551.8.27 by Aaron Bentley
Update docs again
3259
    """Revert files to a previous revision.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3260
1551.8.27 by Aaron Bentley
Update docs again
3261
    Giving a list of files will revert only those files.  Otherwise, all files
3262
    will be reverted.  If the revision is not specified with '--revision', the
3263
    last committed revision is used.
1551.8.26 by Aaron Bentley
Update revert help text
3264
3265
    To remove only some changes, without reverting to a prior version, use
3026.1.1 by Nicholas Allen
Fix small typo in command description for the revert command.
3266
    merge instead.  For example, "merge . --revision -2..-3" will remove the
3267
    changes introduced by -2, without affecting the changes introduced by -1.
3268
    Or to remove certain changes on a hunk-by-hunk basis, see the Shelf plugin.
1551.8.26 by Aaron Bentley
Update revert help text
3269
    
3270
    By default, any files that have been manually changed will be backed up
3271
    first.  (Files changed only by merge are not backed up.)  Backup files have
1551.8.27 by Aaron Bentley
Update docs again
3272
    '.~#~' appended to their name, where # is a number.
3273
3274
    When you provide files, you can use their current pathname or the pathname
3275
    from the target revision.  So you can use revert to "undelete" a file by
3276
    name.  If you name a directory, all the contents of that directory will be
3277
    reverted.
2614.1.1 by Martin Pool
Doc for revert, #87548
3278
3279
    Any files that have been newly added since that revision will be deleted,
3280
    with a backup kept if appropriate.  Directories containing unknown files
3281
    will not be deleted.
2911.2.1 by Martin Pool
Better help for revert
3282
3283
    The working tree contains a list of pending merged revisions, which will
3284
    be included as parents in the next commit.  Normally, revert clears that
3006.1.1 by Adeodato Simó
Fix typos in revert's help.
3285
    list as well as reverting the files.  If any files are specified, revert
3286
    leaves the pending merge list alone and reverts only the files.  Use "bzr
2911.2.1 by Martin Pool
Better help for revert
3287
    revert ." in the tree root to revert all files but keep the merge record,
3288
    and "bzr revert --forget-merges" to clear the pending merge list without
3289
    reverting any files.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3290
    """
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
3291
3292
    _see_also = ['cat', 'export']
2598.1.6 by Martin Pool
Add help for --no-backup
3293
    takes_options = [
2851.2.1 by Martin Pool
Add revert --forget-merges
3294
        'revision',
3295
        Option('no-backup', "Do not save backups of reverted files."),
3296
        Option('forget-merges',
3297
               'Remove pending merge marker, without changing any files.'),
3298
        ]
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3299
    takes_args = ['file*']
3300
2851.2.1 by Martin Pool
Add revert --forget-merges
3301
    def run(self, revision=None, no_backup=False, file_list=None,
3302
            forget_merges=None):
1185.50.53 by John Arbash Meinel
[patch] Aaron Bentley: make revert work in a subdirectory.
3303
        tree, file_list = tree_files(file_list)
3737.2.1 by John Arbash Meinel
Take out a write lock right away for 'bzr revert'
3304
        tree.lock_write()
3305
        try:
3306
            if forget_merges:
3307
                tree.set_parent_ids(tree.get_parent_ids()[:1])
3308
            else:
3309
                self._revert_tree_to_revision(tree, revision, file_list, no_backup)
3310
        finally:
3311
            tree.unlock()
2851.2.1 by Martin Pool
Add revert --forget-merges
3312
3313
    @staticmethod
3314
    def _revert_tree_to_revision(tree, revision, file_list, no_backup):
3732.1.1 by Ian Clatworthy
fix bzr st -rbranch:path-to-branch (Lukas Lalinsky)
3315
        rev_tree = _get_one_revision_tree('revert', revision, tree=tree)
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
3316
        pb = ui.ui_factory.nested_progress_bar()
1551.2.25 by Aaron Bentley
Stop using deprecated methods in merge and revert
3317
        try:
3655.3.1 by Lukáš Lalinský
Fix `bzr st -rbranch:PATH_TO_BRANCH`
3318
            tree.revert(file_list, rev_tree, not no_backup, pb,
3319
                report_changes=True)
1551.2.25 by Aaron Bentley
Stop using deprecated methods in merge and revert
3320
        finally:
3321
            pb.finished()
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3322
3323
3324
class cmd_assert_fail(Command):
3325
    """Test reporting of assertion failures"""
2090.2.1 by Martin Pool
Fix some code which relies on assertions and breaks under python -O
3326
    # intended just for use in testing
3327
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3328
    hidden = True
2090.2.1 by Martin Pool
Fix some code which relies on assertions and breaks under python -O
3329
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3330
    def run(self):
2090.2.1 by Martin Pool
Fix some code which relies on assertions and breaks under python -O
3331
        raise AssertionError("always fails")
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3332
3333
3334
class cmd_help(Command):
3335
    """Show help on a command or other topic.
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
3336
    """
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3337
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
3338
    _see_also = ['topics']
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
3339
    takes_options = [
3340
            Option('long', 'Show help on all commands.'),
3341
            ]
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3342
    takes_args = ['topic?']
1616.1.15 by Martin Pool
Handle 'bzr ?', etc.
3343
    aliases = ['?', '--help', '-?', '-h']
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3344
    
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
3345
    @display_command
1993.4.6 by John Arbash Meinel
Cleanup the cmd_help class
3346
    def run(self, topic=None, long=False):
2023.1.1 by ghigo
add topics help
3347
        import bzrlib.help
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3348
        if topic is None and long:
3349
            topic = "commands"
2023.1.1 by ghigo
add topics help
3350
        bzrlib.help.help(topic)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3351
3352
3353
class cmd_shell_complete(Command):
3354
    """Show appropriate completions for context.
3355
2023.1.1 by ghigo
add topics help
3356
    For a list of all available commands, say 'bzr shell-complete'.
3357
    """
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3358
    takes_args = ['context?']
3359
    aliases = ['s-c']
3360
    hidden = True
3361
    
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
3362
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3363
    def run(self, context=None):
3364
        import shellcomplete
3365
        shellcomplete.shellcomplete(context)
3366
3367
3368
class cmd_missing(Command):
1185.54.3 by Aaron Bentley
Factored out find_unmerged
3369
    """Show unmerged/unpulled revisions between two branches.
2528.1.1 by Martin Pool
Better option names for missing (elliot)
3370
    
2023.1.1 by ghigo
add topics help
3371
    OTHER_BRANCH may be local or remote.
3372
    """
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
3373
3374
    _see_also = ['merge', 'pull']
1185.54.1 by Aaron Bentley
Import Kinnison's plugin
3375
    takes_args = ['other_branch?']
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
3376
    takes_options = [
3377
            Option('reverse', 'Reverse the order of revisions.'),
3378
            Option('mine-only',
3379
                   'Display changes in the local branch only.'),
3380
            Option('this' , 'Same as --mine-only.'),
3381
            Option('theirs-only',
3382
                   'Display changes in the remote branch only.'),
3383
            Option('other', 'Same as --theirs-only.'),
3384
            'log-format',
3385
            'show-ids',
3677.1.1 by Vincent Ladeuil
Begin fixing bug #233817.
3386
            'verbose',
3387
            Option('include-merges', 'Show merged revisions.'),
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
3388
            ]
1816.1.2 by Alexander Belchenko
fix non-ascii messages handling in 'missing' command
3389
    encoding_type = 'replace'
1185.54.1 by Aaron Bentley
Import Kinnison's plugin
3390
1816.1.2 by Alexander Belchenko
fix non-ascii messages handling in 'missing' command
3391
    @display_command
1185.54.1 by Aaron Bentley
Import Kinnison's plugin
3392
    def run(self, other_branch=None, reverse=False, mine_only=False,
3677.1.1 by Vincent Ladeuil
Begin fixing bug #233817.
3393
            theirs_only=False,
3394
            log_format=None, long=False, short=False, line=False,
3395
            show_ids=False, verbose=False, this=False, other=False,
3396
            include_merges=False):
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
3397
        from bzrlib.missing import find_unmerged, iter_log_revisions
2528.1.1 by Martin Pool
Better option names for missing (elliot)
3398
3399
        if this:
3427.3.3 by John Arbash Meinel
Revert cmd_missing to use the original function, only now supply restrict
3400
            mine_only = this
2528.1.1 by Martin Pool
Better option names for missing (elliot)
3401
        if other:
3427.3.3 by John Arbash Meinel
Revert cmd_missing to use the original function, only now supply restrict
3402
            theirs_only = other
3403
        # TODO: We should probably check that we don't have mine-only and
3404
        #       theirs-only set, but it gets complicated because we also have
3405
        #       this and other which could be used.
3406
        restrict = 'all'
3407
        if mine_only:
3408
            restrict = 'local'
3409
        elif theirs_only:
3410
            restrict = 'remote'
2528.1.1 by Martin Pool
Better option names for missing (elliot)
3411
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
3412
        local_branch = Branch.open_containing(u".")[0]
1185.54.16 by Aaron Bentley
fixed location handling to match old missing
3413
        parent = local_branch.get_parent()
1185.54.1 by Aaron Bentley
Import Kinnison's plugin
3414
        if other_branch is None:
1185.54.16 by Aaron Bentley
fixed location handling to match old missing
3415
            other_branch = parent
3416
            if other_branch is None:
2485.8.11 by Vincent Ladeuil
Fix some display leaks in tests.
3417
                raise errors.BzrCommandError("No peer location known"
2485.8.17 by Vincent Ladeuil
Fix the fix.
3418
                                             " or specified.")
2193.4.1 by Alexander Belchenko
'bzr missing' without specifying location show remembered location unescaped
3419
            display_url = urlutils.unescape_for_display(parent,
3420
                                                        self.outf.encoding)
3596.3.1 by James Westby
Give the user a bit more information about which saved location is being used.
3421
            self.outf.write("Using saved parent location: "
3422
                    + display_url + "\n")
2193.4.1 by Alexander Belchenko
'bzr missing' without specifying location show remembered location unescaped
3423
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
3424
        remote_branch = Branch.open(other_branch)
1551.2.46 by abentley
Made bzr missing . work on win32
3425
        if remote_branch.base == local_branch.base:
3426
            remote_branch = local_branch
1666.1.5 by Robert Collins
Merge bound branch test performance improvements.
3427
        local_branch.lock_read()
1594.3.6 by Robert Collins
Take out appropriate locks for missing.
3428
        try:
1551.2.46 by abentley
Made bzr missing . work on win32
3429
            remote_branch.lock_read()
1594.3.6 by Robert Collins
Take out appropriate locks for missing.
3430
            try:
3427.3.3 by John Arbash Meinel
Revert cmd_missing to use the original function, only now supply restrict
3431
                local_extra, remote_extra = find_unmerged(
3677.1.1 by Vincent Ladeuil
Begin fixing bug #233817.
3432
                    local_branch, remote_branch, restrict,
3677.1.4 by Vincent Ladeuil
Replace 'reverse' by 'backward' when talking about revision order.
3433
                    backward=not reverse,
3677.1.1 by Vincent Ladeuil
Begin fixing bug #233817.
3434
                    include_merges=include_merges)
3427.3.1 by John Arbash Meinel
Add bzrlib.missing.find_unmerged_mainline_revisions
3435
2485.8.11 by Vincent Ladeuil
Fix some display leaks in tests.
3436
                if log_format is None:
3437
                    registry = log.log_formatter_registry
3438
                    log_format = registry.get_default(local_branch)
2221.4.10 by Aaron Bentley
Implement log options using RegistryOption
3439
                lf = log_format(to_file=self.outf,
3440
                                show_ids=show_ids,
3441
                                show_timezone='original')
3427.3.7 by John Arbash Meinel
Update how 'bzr missing' works when given --mine-only or --theirs-only
3442
3443
                status_code = 0
1594.3.6 by Robert Collins
Take out appropriate locks for missing.
3444
                if local_extra and not theirs_only:
2485.8.17 by Vincent Ladeuil
Fix the fix.
3445
                    self.outf.write("You have %d extra revision(s):\n" %
2485.8.11 by Vincent Ladeuil
Fix some display leaks in tests.
3446
                                    len(local_extra))
2485.8.13 by Vincent Ladeuil
merge bzr.dev@2495
3447
                    for revision in iter_log_revisions(local_extra,
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
3448
                                        local_branch.repository,
3449
                                        verbose):
3450
                        lf.log_revision(revision)
1594.3.6 by Robert Collins
Take out appropriate locks for missing.
3451
                    printed_local = True
3427.3.7 by John Arbash Meinel
Update how 'bzr missing' works when given --mine-only or --theirs-only
3452
                    status_code = 1
1594.3.6 by Robert Collins
Take out appropriate locks for missing.
3453
                else:
3454
                    printed_local = False
3427.3.7 by John Arbash Meinel
Update how 'bzr missing' works when given --mine-only or --theirs-only
3455
1594.3.6 by Robert Collins
Take out appropriate locks for missing.
3456
                if remote_extra and not mine_only:
3457
                    if printed_local is True:
2485.8.17 by Vincent Ladeuil
Fix the fix.
3458
                        self.outf.write("\n\n\n")
3459
                    self.outf.write("You are missing %d revision(s):\n" %
2485.8.11 by Vincent Ladeuil
Fix some display leaks in tests.
3460
                                    len(remote_extra))
2485.8.13 by Vincent Ladeuil
merge bzr.dev@2495
3461
                    for revision in iter_log_revisions(remote_extra,
3462
                                        remote_branch.repository,
2466.8.1 by Kent Gibson
Reworked LogFormatter API to simplify extending the attributes of the revision being logged. Added support for begin_log() and end_log() hooks in LogFormatters.
3463
                                        verbose):
3464
                        lf.log_revision(revision)
3427.3.7 by John Arbash Meinel
Update how 'bzr missing' works when given --mine-only or --theirs-only
3465
                    status_code = 1
3466
3467
                if mine_only and not local_extra:
3468
                    # We checked local, and found nothing extra
3427.3.8 by John Arbash Meinel
Change the output to 'This branch' and 'Other branch', and document the text in NEWS
3469
                    self.outf.write('This branch is up to date.\n')
3427.3.7 by John Arbash Meinel
Update how 'bzr missing' works when given --mine-only or --theirs-only
3470
                elif theirs_only and not remote_extra:
3471
                    # We checked remote, and found nothing extra
3427.3.8 by John Arbash Meinel
Change the output to 'This branch' and 'Other branch', and document the text in NEWS
3472
                    self.outf.write('Other branch is up to date.\n')
3427.3.7 by John Arbash Meinel
Update how 'bzr missing' works when given --mine-only or --theirs-only
3473
                elif not (mine_only or theirs_only or local_extra or
3474
                          remote_extra):
3475
                    # We checked both branches, and neither one had extra
3476
                    # revisions
2485.8.17 by Vincent Ladeuil
Fix the fix.
3477
                    self.outf.write("Branches are up to date.\n")
1594.3.6 by Robert Collins
Take out appropriate locks for missing.
3478
            finally:
1666.1.5 by Robert Collins
Merge bound branch test performance improvements.
3479
                remote_branch.unlock()
3480
        finally:
3481
            local_branch.unlock()
3482
        if not status_code and parent is None and other_branch is not None:
3483
            local_branch.lock_write()
3484
            try:
3485
                # handle race conditions - a parent might be set while we run.
3486
                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
3487
                    local_branch.set_parent(remote_branch.base)
1594.3.6 by Robert Collins
Take out appropriate locks for missing.
3488
            finally:
3489
                local_branch.unlock()
1666.1.5 by Robert Collins
Merge bound branch test performance improvements.
3490
        return status_code
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3491
3492
2604.2.1 by Robert Collins
(robertc) Introduce a pack command.
3493
class cmd_pack(Command):
3494
    """Compress the data within a repository."""
3495
3496
    _see_also = ['repositories']
3497
    takes_args = ['branch_or_repo?']
3498
3499
    def run(self, branch_or_repo='.'):
3500
        dir = bzrdir.BzrDir.open_containing(branch_or_repo)[0]
3501
        try:
3502
            branch = dir.open_branch()
3503
            repository = branch.repository
3504
        except errors.NotBranchError:
3505
            repository = dir.open_repository()
3506
        repository.pack()
3507
3508
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3509
class cmd_plugins(Command):
2617.3.1 by Ian Clatworthy
Make the plugins command public with better help
3510
    """List the installed plugins.
3511
    
3193.2.3 by Alexander Belchenko
another formatting variant suggested by John Meinel.
3512
    This command displays the list of installed plugins including
3513
    version of plugin and a short description of each.
3514
3515
    --verbose shows the path where each plugin is located.
2617.3.1 by Ian Clatworthy
Make the plugins command public with better help
3516
3517
    A plugin is an external component for Bazaar that extends the
3518
    revision control system, by adding or replacing code in Bazaar.
3519
    Plugins can do a variety of things, including overriding commands,
3520
    adding new commands, providing additional network transports and
3521
    customizing log output.
3522
3523
    See the Bazaar web site, http://bazaar-vcs.org, for further
3524
    information on plugins including where to find them and how to
3525
    install them. Instructions are also provided there on how to
3526
    write new plugins using the Python programming language.
3527
    """
3193.2.3 by Alexander Belchenko
another formatting variant suggested by John Meinel.
3528
    takes_options = ['verbose']
2629.1.1 by Ian Clatworthy
(Ian Clatworthy) Tweak the 'make plugins public' change following feedback from lifeless
3529
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
3530
    @display_command
3193.2.3 by Alexander Belchenko
another formatting variant suggested by John Meinel.
3531
    def run(self, verbose=False):
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3532
        import bzrlib.plugin
3533
        from inspect import getdoc
3193.2.2 by Alexander Belchenko
new formatting of `bzr plugins` output.
3534
        result = []
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
3535
        for name, plugin in bzrlib.plugin.plugins().items():
3193.2.2 by Alexander Belchenko
new formatting of `bzr plugins` output.
3536
            version = plugin.__version__
3537
            if version == 'unknown':
3538
                version = ''
3539
            name_ver = '%s %s' % (name, version)
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
3540
            d = getdoc(plugin.module)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3541
            if d:
3193.2.2 by Alexander Belchenko
new formatting of `bzr plugins` output.
3542
                doc = d.split('\n')[0]
3543
            else:
3544
                doc = '(no description)'
3545
            result.append((name_ver, doc, plugin.path()))
3193.2.3 by Alexander Belchenko
another formatting variant suggested by John Meinel.
3546
        for name_ver, doc, path in sorted(result):
3547
            print name_ver
3548
            print '   ', doc
3549
            if verbose:
3550
                print '   ', path
3551
            print
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3552
3553
1185.16.24 by Martin Pool
- add and test 'testament' builtin command
3554
class cmd_testament(Command):
3555
    """Show testament (signing-form) of a revision."""
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
3556
    takes_options = [
3557
            'revision',
3558
            Option('long', help='Produce long-format testament.'),
3559
            Option('strict',
3560
                   help='Produce a strict-format testament.')]
1185.16.24 by Martin Pool
- add and test 'testament' builtin command
3561
    takes_args = ['branch?']
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
3562
    @display_command
1551.7.1 by Aaron Bentley
Implement --strict at commandline, fix up strict format
3563
    def run(self, branch=u'.', revision=None, long=False, strict=False):
3564
        from bzrlib.testament import Testament, StrictTestament
3565
        if strict is True:
3566
            testament_class = StrictTestament
3567
        else:
3568
            testament_class = Testament
3530.2.1 by John Arbash Meinel
'bzr testament' should just open the branch
3569
        if branch == '.':
3570
            b = Branch.open_containing(branch)[0]
3571
        else:
3572
            b = Branch.open(branch)
1185.16.24 by Martin Pool
- add and test 'testament' builtin command
3573
        b.lock_read()
3574
        try:
3575
            if revision is None:
3576
                rev_id = b.last_revision()
3577
            else:
3298.2.8 by John Arbash Meinel
Get rid of .in_branch(need_revno=False) in favor of simpler .as_revision_id()
3578
                rev_id = revision[0].as_revision_id(b)
1551.7.1 by Aaron Bentley
Implement --strict at commandline, fix up strict format
3579
            t = testament_class.from_revision(b.repository, rev_id)
1185.16.24 by Martin Pool
- add and test 'testament' builtin command
3580
            if long:
3581
                sys.stdout.writelines(t.as_text_lines())
3582
            else:
3583
                sys.stdout.write(t.as_short_text())
3584
        finally:
3585
            b.unlock()
1185.16.32 by Martin Pool
- add a basic annotate built-in command
3586
3587
3588
class cmd_annotate(Command):
3589
    """Show the origin of each line in a file.
3590
1185.16.53 by Martin Pool
- annotate improvements from Goffreddo, with extra bug fixes and tests
3591
    This prints out the given file with an annotation on the left side
3592
    indicating which revision, author and date introduced the change.
3593
3594
    If the origin is the same for a run of consecutive lines, it is 
3595
    shown only at the top, unless the --all option is given.
1185.16.32 by Martin Pool
- add a basic annotate built-in command
3596
    """
3597
    # TODO: annotate directories; showing when each file was last changed
1185.16.53 by Martin Pool
- annotate improvements from Goffreddo, with extra bug fixes and tests
3598
    # TODO: if the working copy is modified, show annotations on that 
3599
    #       with new uncommitted lines marked
1733.2.8 by Michael Ellerman
Add CVS compatible aliases for checkout and annotate, from fullermd.
3600
    aliases = ['ann', 'blame', 'praise']
1185.16.32 by Martin Pool
- add a basic annotate built-in command
3601
    takes_args = ['filename']
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
3602
    takes_options = [Option('all', help='Show annotations on all lines.'),
3603
                     Option('long', help='Show commit date in annotations.'),
2182.3.1 by John Arbash Meinel
Annotate now shows dotted revnos instead of plain revnos.
3604
                     'revision',
3605
                     'show-ids',
1185.16.53 by Martin Pool
- annotate improvements from Goffreddo, with extra bug fixes and tests
3606
                     ]
2593.1.1 by Adeodato Simó
Improve annotate to prevent unicode exceptions in certain situations.
3607
    encoding_type = 'exact'
1185.16.32 by Martin Pool
- add a basic annotate built-in command
3608
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
3609
    @display_command
2182.3.1 by John Arbash Meinel
Annotate now shows dotted revnos instead of plain revnos.
3610
    def run(self, filename, all=False, long=False, revision=None,
3611
            show_ids=False):
3603.4.1 by Robert Collins
Implement lookups into the current working tree for bzr annotate, fixing bug 3439.
3612
        from bzrlib.annotate import annotate_file, annotate_file_tree
3146.2.1 by Lukáš Lalinský
Don't require a working tree in cmd_annotate.
3613
        wt, branch, relpath = \
3614
            bzrdir.BzrDir.open_containing_tree_or_branch(filename)
3615
        if wt is not None:
3616
            wt.lock_read()
3617
        else:
3618
            branch.lock_read()
1185.16.32 by Martin Pool
- add a basic annotate built-in command
3619
        try:
3732.1.1 by Ian Clatworthy
fix bzr st -rbranch:path-to-branch (Lukas Lalinsky)
3620
            tree = _get_one_revision_tree('annotate', revision, branch=branch)
3146.2.1 by Lukáš Lalinský
Don't require a working tree in cmd_annotate.
3621
            if wt is not None:
3622
                file_id = wt.path2id(relpath)
3623
            else:
3624
                file_id = tree.path2id(relpath)
2561.2.1 by James Westby
Display a useful error message when annotating a non-existant file (#122656)
3625
            if file_id is None:
2561.2.2 by James Westby
Fix up with comments from Aaron.
3626
                raise errors.NotVersionedError(filename)
1185.16.32 by Martin Pool
- add a basic annotate built-in command
3627
            file_version = tree.inventory[file_id].revision
3603.4.1 by Robert Collins
Implement lookups into the current working tree for bzr annotate, fixing bug 3439.
3628
            if wt is not None and revision is None:
3629
                # If there is a tree and we're not annotating historical
3630
                # versions, annotate the working tree's content.
3631
                annotate_file_tree(wt, file_id, self.outf, long, all,
3632
                    show_ids=show_ids)
3633
            else:
3634
                annotate_file(branch, file_version, file_id, long, all, self.outf,
3635
                              show_ids=show_ids)
1185.16.32 by Martin Pool
- add a basic annotate built-in command
3636
        finally:
3146.2.1 by Lukáš Lalinský
Don't require a working tree in cmd_annotate.
3637
            if wt is not None:
3638
                wt.unlock()
3639
            else:
3640
                branch.unlock()
1185.16.33 by Martin Pool
- move 'conflict' and 'resolved' from shipped plugin to regular builtins
3641
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
3642
3643
class cmd_re_sign(Command):
3644
    """Create a digital signature for an existing revision."""
3645
    # TODO be able to replace existing ones.
3646
3647
    hidden = True # is this right ?
1185.78.1 by John Arbash Meinel
Updating bzr re-sign to allow multiple arguments, and updating tests
3648
    takes_args = ['revision_id*']
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
3649
    takes_options = ['revision']
3650
    
1185.78.1 by John Arbash Meinel
Updating bzr re-sign to allow multiple arguments, and updating tests
3651
    def run(self, revision_id_list=None, revision=None):
3652
        if revision_id_list is not None and revision is not None:
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
3653
            raise errors.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
3654
        if revision_id_list is None and revision is None:
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
3655
            raise errors.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)
3656
        b = WorkingTree.open_containing(u'.')[0].branch
3010.1.17 by Robert Collins
Lock correctness and commit_group management for re-sign, in builtins.
3657
        b.lock_write()
3658
        try:
3659
            return self._run(b, revision_id_list, revision)
3660
        finally:
3661
            b.unlock()
3662
3663
    def _run(self, b, revision_id_list, revision):
3664
        import bzrlib.gpg as gpg
1770.2.9 by Aaron Bentley
Add Branch.get_config, update BranchConfig() callers
3665
        gpg_strategy = gpg.GPGStrategy(b.get_config())
1185.78.1 by John Arbash Meinel
Updating bzr re-sign to allow multiple arguments, and updating tests
3666
        if revision_id_list is not None:
3010.1.17 by Robert Collins
Lock correctness and commit_group management for re-sign, in builtins.
3667
            b.repository.start_write_group()
3668
            try:
3669
                for revision_id in revision_id_list:
3670
                    b.repository.sign_revision(revision_id, gpg_strategy)
3671
            except:
3672
                b.repository.abort_write_group()
3673
                raise
3674
            else:
3675
                b.repository.commit_write_group()
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
3676
        elif revision is not None:
1483 by Robert Collins
BUGFIX: re-sign should accept ranges
3677
            if len(revision) == 1:
3678
                revno, rev_id = revision[0].in_history(b)
3010.1.17 by Robert Collins
Lock correctness and commit_group management for re-sign, in builtins.
3679
                b.repository.start_write_group()
3680
                try:
3681
                    b.repository.sign_revision(rev_id, gpg_strategy)
3682
                except:
3683
                    b.repository.abort_write_group()
3684
                    raise
3685
                else:
3686
                    b.repository.commit_write_group()
1483 by Robert Collins
BUGFIX: re-sign should accept ranges
3687
            elif len(revision) == 2:
3688
                # are they both on rh- if so we can walk between them
3689
                # might be nice to have a range helper for arbitrary
3690
                # revision paths. hmm.
3691
                from_revno, from_revid = revision[0].in_history(b)
3692
                to_revno, to_revid = revision[1].in_history(b)
3693
                if to_revid is None:
3694
                    to_revno = b.revno()
3695
                if from_revno is None or to_revno is None:
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
3696
                    raise errors.BzrCommandError('Cannot sign a range of non-revision-history revisions')
3010.1.17 by Robert Collins
Lock correctness and commit_group management for re-sign, in builtins.
3697
                b.repository.start_write_group()
3698
                try:
3699
                    for revno in range(from_revno, to_revno + 1):
3700
                        b.repository.sign_revision(b.get_rev_id(revno),
3701
                                                   gpg_strategy)
3702
                except:
3703
                    b.repository.abort_write_group()
3704
                    raise
3705
                else:
3706
                    b.repository.commit_write_group()
1483 by Robert Collins
BUGFIX: re-sign should accept ranges
3707
            else:
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
3708
                raise errors.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.
3709
1505.1.22 by John Arbash Meinel
Some small cleanup and discussion in preparation for modifying commit, pull, and merge
3710
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
3711
class cmd_bind(Command):
2270.1.2 by John Arbash Meinel
Tweak the help text for bind/unbind according to Robert's suggestions.
3712
    """Convert the current branch into a checkout of the supplied branch.
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
3713
2270.1.2 by John Arbash Meinel
Tweak the help text for bind/unbind according to Robert's suggestions.
3714
    Once converted into a checkout, commits must succeed on the master branch
3715
    before they will be applied to the local branch.
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
3716
    """
3717
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
3718
    _see_also = ['checkouts', 'unbind']
2230.3.31 by Aaron Bentley
Implement re-binding previously-bound branches
3719
    takes_args = ['location?']
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
3720
    takes_options = []
3721
3722
    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
3723
        b, relpath = Branch.open_containing(u'.')
2230.3.31 by Aaron Bentley
Implement re-binding previously-bound branches
3724
        if location is None:
3725
            try:
3726
                location = b.get_old_bound_location()
3727
            except errors.UpgradeRequired:
3728
                raise errors.BzrCommandError('No location supplied.  '
3729
                    'This format does not remember old locations.')
3730
            else:
3731
                if location is None:
2230.3.45 by Aaron Bentley
Change error message (mpool)
3732
                    raise errors.BzrCommandError('No location supplied and no '
3733
                        'previous location known')
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
3734
        b_other = Branch.open(location)
1505.1.3 by John Arbash Meinel
(broken) Adding more tests, and some functionality
3735
        try:
3736
            b.bind(b_other)
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
3737
        except errors.DivergedBranches:
3738
            raise errors.BzrCommandError('These branches have diverged.'
3739
                                         ' Try merging, and then bind again.')
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
3740
1505.1.22 by John Arbash Meinel
Some small cleanup and discussion in preparation for modifying commit, pull, and merge
3741
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
3742
class cmd_unbind(Command):
2270.1.2 by John Arbash Meinel
Tweak the help text for bind/unbind according to Robert's suggestions.
3743
    """Convert the current checkout into a regular branch.
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
3744
2270.1.2 by John Arbash Meinel
Tweak the help text for bind/unbind according to Robert's suggestions.
3745
    After unbinding, the local branch is considered independent and subsequent
3746
    commits will be local only.
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
3747
    """
3748
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
3749
    _see_also = ['checkouts', 'bind']
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
3750
    takes_args = []
3751
    takes_options = []
3752
3753
    def run(self):
1505.1.22 by John Arbash Meinel
Some small cleanup and discussion in preparation for modifying commit, pull, and merge
3754
        b, relpath = Branch.open_containing(u'.')
3755
        if not b.unbind():
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
3756
            raise errors.BzrCommandError('Local branch is not bound')
1505.1.22 by John Arbash Meinel
Some small cleanup and discussion in preparation for modifying commit, pull, and merge
3757
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
3758
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
3759
class cmd_uncommit(Command):
1185.31.24 by John Arbash Meinel
[merge] Added the uncommit plugin
3760
    """Remove the last committed revision.
3761
3762
    --verbose will print out what is being removed.
3763
    --dry-run will go through all the motions, but not actually
3764
    remove anything.
2747.2.1 by Daniel Watkins
Modified the help message of 'uncommit'.
3765
3766
    If --revision is specified, uncommit revisions to leave the branch at the
3767
    specified revision.  For example, "bzr uncommit -r 15" will leave the
3768
    branch at revision 15.
3769
1551.19.39 by Aaron Bentley
Update 'uncommit' docs
3770
    Uncommit leaves the working tree ready for a new commit.  The only change
3771
    it may make is to restore any pending merges that were present before
3772
    the commit.
1553.5.34 by Martin Pool
Stub lock-breaking command
3773
    """
1185.62.11 by John Arbash Meinel
Added TODO for bzr uncommit to remove unreferenced information.
3774
1553.5.34 by Martin Pool
Stub lock-breaking command
3775
    # TODO: jam 20060108 Add an option to allow uncommit to remove
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
3776
    # unreferenced information in 'branch-as-repository' branches.
1553.5.34 by Martin Pool
Stub lock-breaking command
3777
    # TODO: jam 20060108 Add the ability for uncommit to remove unreferenced
3778
    # information in shared branches as well.
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
3779
    _see_also = ['commit']
1185.62.10 by John Arbash Meinel
Removed --all from bzr uncommit, it was broken anyway.
3780
    takes_options = ['verbose', 'revision',
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
3781
                    Option('dry-run', help='Don\'t actually make changes.'),
3280.4.1 by John Arbash Meinel
Add uncommit --local.
3782
                    Option('force', help='Say yes to all questions.'),
3783
                    Option('local',
3784
                           help="Only remove the commits from the local branch"
3785
                                " when in a checkout."
3786
                           ),
3787
                    ]
1185.31.24 by John Arbash Meinel
[merge] Added the uncommit plugin
3788
    takes_args = ['location?']
3789
    aliases = []
3101.1.1 by Aaron Bentley
Uncommit doesn't throw when it encounters un-encodable characters
3790
    encoding_type = 'replace'
1185.31.24 by John Arbash Meinel
[merge] Added the uncommit plugin
3791
1850.3.2 by John Arbash Meinel
Change uncommit -r 10 so that it uncommits *to* 10, rather than removing 10
3792
    def run(self, location=None,
1185.31.24 by John Arbash Meinel
[merge] Added the uncommit plugin
3793
            dry_run=False, verbose=False,
3280.4.1 by John Arbash Meinel
Add uncommit --local.
3794
            revision=None, force=False, local=False):
1185.31.24 by John Arbash Meinel
[merge] Added the uncommit plugin
3795
        if location is None:
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
3796
            location = u'.'
1558.1.12 by Aaron Bentley
Got uncommit working properly with checkouts
3797
        control, relpath = bzrdir.BzrDir.open_containing(location)
3798
        try:
3799
            tree = control.open_workingtree()
1558.9.1 by Aaron Bentley
Fix uncommit to handle bound branches, and to do locking
3800
            b = tree.branch
1558.1.12 by Aaron Bentley
Got uncommit working properly with checkouts
3801
        except (errors.NoWorkingTree, errors.NotLocalUrl):
3802
            tree = None
1558.9.1 by Aaron Bentley
Fix uncommit to handle bound branches, and to do locking
3803
            b = control.open_branch()
1185.31.24 by John Arbash Meinel
[merge] Added the uncommit plugin
3804
3065.2.2 by John Arbash Meinel
During bzr uncommit, lock the working tree if it is available.
3805
        if tree is not None:
3806
            tree.lock_write()
3807
        else:
3808
            b.lock_write()
3065.2.1 by Lukáš Lalinský
Add a global branch write lock to cmd_uncommit and avoid unnecessary Branch.revno calls.
3809
        try:
3280.4.1 by John Arbash Meinel
Add uncommit --local.
3810
            return self._run(b, tree, dry_run, verbose, revision, force,
3811
                             local=local)
3065.2.1 by Lukáš Lalinský
Add a global branch write lock to cmd_uncommit and avoid unnecessary Branch.revno calls.
3812
        finally:
3065.2.2 by John Arbash Meinel
During bzr uncommit, lock the working tree if it is available.
3813
            if tree is not None:
3814
                tree.unlock()
3815
            else:
3816
                b.unlock()
3065.2.1 by Lukáš Lalinský
Add a global branch write lock to cmd_uncommit and avoid unnecessary Branch.revno calls.
3817
3280.4.1 by John Arbash Meinel
Add uncommit --local.
3818
    def _run(self, b, tree, dry_run, verbose, revision, force, local=False):
3065.2.1 by Lukáš Lalinský
Add a global branch write lock to cmd_uncommit and avoid unnecessary Branch.revno calls.
3819
        from bzrlib.log import log_formatter, show_log
3820
        from bzrlib.uncommit import uncommit
3821
3822
        last_revno, last_rev_id = b.last_revision_info()
3823
1850.3.2 by John Arbash Meinel
Change uncommit -r 10 so that it uncommits *to* 10, rather than removing 10
3824
        rev_id = None
1185.31.24 by John Arbash Meinel
[merge] Added the uncommit plugin
3825
        if revision is None:
3065.2.1 by Lukáš Lalinský
Add a global branch write lock to cmd_uncommit and avoid unnecessary Branch.revno calls.
3826
            revno = last_revno
3827
            rev_id = last_rev_id
1185.31.24 by John Arbash Meinel
[merge] Added the uncommit plugin
3828
        else:
1850.3.2 by John Arbash Meinel
Change uncommit -r 10 so that it uncommits *to* 10, rather than removing 10
3829
            # 'bzr uncommit -r 10' actually means uncommit
3830
            # so that the final tree is at revno 10.
3831
            # but bzrlib.uncommit.uncommit() actually uncommits
3832
            # the revisions that are supplied.
3833
            # So we need to offset it by one
3065.2.1 by Lukáš Lalinský
Add a global branch write lock to cmd_uncommit and avoid unnecessary Branch.revno calls.
3834
            revno = revision[0].in_history(b).revno + 1
3835
            if revno <= last_revno:
3836
                rev_id = b.get_rev_id(revno)
1850.3.2 by John Arbash Meinel
Change uncommit -r 10 so that it uncommits *to* 10, rather than removing 10
3837
2948.2.2 by John Arbash Meinel
Re-introduce the None check in case someone asks to uncommit *to* the last revision
3838
        if rev_id is None or _mod_revision.is_null(rev_id):
1850.3.2 by John Arbash Meinel
Change uncommit -r 10 so that it uncommits *to* 10, rather than removing 10
3839
            self.outf.write('No revisions to uncommit.\n')
3840
            return 1
3841
3842
        lf = log_formatter('short',
3843
                           to_file=self.outf,
3629.1.2 by John Arbash Meinel
Change to just display the command to restore the tip,
3844
                           show_timezone='original')
1850.3.2 by John Arbash Meinel
Change uncommit -r 10 so that it uncommits *to* 10, rather than removing 10
3845
3846
        show_log(b,
3847
                 lf,
3848
                 verbose=False,
3849
                 direction='forward',
3850
                 start_revision=revno,
3065.2.1 by Lukáš Lalinský
Add a global branch write lock to cmd_uncommit and avoid unnecessary Branch.revno calls.
3851
                 end_revision=last_revno)
1185.31.24 by John Arbash Meinel
[merge] Added the uncommit plugin
3852
3853
        if dry_run:
3854
            print 'Dry-run, pretending to remove the above revisions.'
3855
            if not force:
3856
                val = raw_input('Press <enter> to continue')
3857
        else:
3858
            print 'The above revision(s) will be removed.'
3859
            if not force:
3860
                val = raw_input('Are you sure [y/N]? ')
3861
                if val.lower() not in ('y', 'yes'):
3862
                    print 'Canceled'
3863
                    return 0
3864
3629.1.1 by John Arbash Meinel
Change 'bzr uncommit' to display the revision ids and log them.
3865
        mutter('Uncommitting from {%s} to {%s}',
3866
               last_rev_id, rev_id)
1558.1.12 by Aaron Bentley
Got uncommit working properly with checkouts
3867
        uncommit(b, tree=tree, dry_run=dry_run, verbose=verbose,
3280.4.1 by John Arbash Meinel
Add uncommit --local.
3868
                 revno=revno, local=local)
3629.1.2 by John Arbash Meinel
Change to just display the command to restore the tip,
3869
        note('You can restore the old tip by running:\n'
3870
             '  bzr pull . -r revid:%s', last_rev_id)
1185.31.24 by John Arbash Meinel
[merge] Added the uncommit plugin
3871
3872
1553.5.34 by Martin Pool
Stub lock-breaking command
3873
class cmd_break_lock(Command):
3874
    """Break a dead lock on a repository, branch or working directory.
3875
1553.5.35 by Martin Pool
Start break-lock --show
3876
    CAUTION: Locks should only be broken when you are sure that the process
1553.5.34 by Martin Pool
Stub lock-breaking command
3877
    holding the lock has been stopped.
1687.1.12 by Robert Collins
Hook in the full break-lock ui.
3878
3879
    You can get information on what locks are open via the 'bzr info' command.
1553.5.35 by Martin Pool
Start break-lock --show
3880
    
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
3881
    :Examples:
1687.1.12 by Robert Collins
Hook in the full break-lock ui.
3882
        bzr break-lock
1553.5.34 by Martin Pool
Stub lock-breaking command
3883
    """
1687.1.12 by Robert Collins
Hook in the full break-lock ui.
3884
    takes_args = ['location?']
3885
3886
    def run(self, location=None, show=False):
3887
        if location is None:
3888
            location = u'.'
3889
        control, relpath = bzrdir.BzrDir.open_containing(location)
1687.1.17 by Robert Collins
Test break lock on old format branches.
3890
        try:
3891
            control.break_lock()
3892
        except NotImplementedError:
3893
            pass
1687.1.12 by Robert Collins
Hook in the full break-lock ui.
3894
        
1553.5.35 by Martin Pool
Start break-lock --show
3895
1910.17.2 by Andrew Bennetts
Add start_bzr_subprocess and stop_bzr_subprocess to allow test code to continue
3896
class cmd_wait_until_signalled(Command):
3897
    """Test helper for test_start_and_stop_bzr_subprocess_send_signal.
3898
3899
    This just prints a line to signal when it is ready, then blocks on stdin.
3900
    """
3901
3902
    hidden = True
3903
3904
    def run(self):
1910.17.6 by Andrew Bennetts
Use sys.stdout consistently, rather than mixed with print.
3905
        sys.stdout.write("running\n")
1910.17.2 by Andrew Bennetts
Add start_bzr_subprocess and stop_bzr_subprocess to allow test code to continue
3906
        sys.stdout.flush()
3907
        sys.stdin.readline()
3908
1553.5.35 by Martin Pool
Start break-lock --show
3909
1910.19.1 by Andrew Bennetts
Support bzr:// urls to work with the new RPC-based transport which will be used
3910
class cmd_serve(Command):
2020.1.1 by Robert Collins
Add readonly support to the smart server, enabled by default via `bzr server`.
3911
    """Run the bzr server."""
3912
3913
    aliases = ['server']
3914
1910.19.1 by Andrew Bennetts
Support bzr:// urls to work with the new RPC-based transport which will be used
3915
    takes_options = [
3916
        Option('inet',
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
3917
               help='Serve on stdin/out for use from inetd or sshd.'),
1910.19.1 by Andrew Bennetts
Support bzr:// urls to work with the new RPC-based transport which will be used
3918
        Option('port',
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
3919
               help='Listen for connections on nominated port of the form '
3920
                    '[hostname:]portnumber.  Passing 0 as the port number will '
3921
                    'result in a dynamically allocated port.  The default port is '
2298.4.1 by Andrew Bennetts
Give bzr:// a default port of 4155.
3922
                    '4155.',
1910.19.7 by Andrew Bennetts
Allow specifying the host/interface to bzr serve, and use the new test
3923
               type=str),
1910.19.1 by Andrew Bennetts
Support bzr:// urls to work with the new RPC-based transport which will be used
3924
        Option('directory',
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
3925
               help='Serve contents of this directory.',
1910.19.1 by Andrew Bennetts
Support bzr:// urls to work with the new RPC-based transport which will be used
3926
               type=unicode),
2020.1.1 by Robert Collins
Add readonly support to the smart server, enabled by default via `bzr server`.
3927
        Option('allow-writes',
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
3928
               help='By default the server is a readonly server.  Supplying '
2020.1.1 by Robert Collins
Add readonly support to the smart server, enabled by default via `bzr server`.
3929
                    '--allow-writes enables write access to the contents of '
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
3930
                    'the served directory and below.'
2020.1.1 by Robert Collins
Add readonly support to the smart server, enabled by default via `bzr server`.
3931
                ),
1910.19.1 by Andrew Bennetts
Support bzr:// urls to work with the new RPC-based transport which will be used
3932
        ]
3933
2020.1.1 by Robert Collins
Add readonly support to the smart server, enabled by default via `bzr server`.
3934
    def run(self, port=None, inet=False, directory=None, allow_writes=False):
3118.3.1 by Andrew Bennetts
Reduce lockdir timeout to 0 seconds in cmd_serve.
3935
        from bzrlib import lockdir
2018.5.22 by Andrew Bennetts
Fix cmd_serve after move of bzrlib.transport.smart
3936
        from bzrlib.smart import medium, server
1910.19.1 by Andrew Bennetts
Support bzr:// urls to work with the new RPC-based transport which will be used
3937
        from bzrlib.transport import get_transport
2018.5.121 by Andrew Bennetts
Fix cmd_serve.
3938
        from bzrlib.transport.chroot import ChrootServer
1910.19.1 by Andrew Bennetts
Support bzr:// urls to work with the new RPC-based transport which will be used
3939
        if directory is None:
3940
            directory = os.getcwd()
2044.2.1 by Lukáš Lalinský
Use urlutils.local_path_to_url to get an URL from the directory path.
3941
        url = urlutils.local_path_to_url(directory)
2020.1.1 by Robert Collins
Add readonly support to the smart server, enabled by default via `bzr server`.
3942
        if not allow_writes:
3943
            url = 'readonly+' + url
2018.5.121 by Andrew Bennetts
Fix cmd_serve.
3944
        chroot_server = ChrootServer(get_transport(url))
3945
        chroot_server.setUp()
3946
        t = get_transport(chroot_server.get_url())
1910.19.1 by Andrew Bennetts
Support bzr:// urls to work with the new RPC-based transport which will be used
3947
        if inet:
2018.5.121 by Andrew Bennetts
Fix cmd_serve.
3948
            smart_server = medium.SmartServerPipeStreamMedium(
2018.5.14 by Andrew Bennetts
Move SmartTCPServer to smart/server.py, and SmartServerRequestHandler to smart/request.py.
3949
                sys.stdin, sys.stdout, t)
2298.4.1 by Andrew Bennetts
Give bzr:// a default port of 4155.
3950
        else:
3004.2.1 by Vincent Ladeuil
Fix 150860 by leaving port as user specified it.
3951
            host = medium.BZR_DEFAULT_INTERFACE
2298.4.1 by Andrew Bennetts
Give bzr:// a default port of 4155.
3952
            if port is None:
3004.2.1 by Vincent Ladeuil
Fix 150860 by leaving port as user specified it.
3953
                port = medium.BZR_DEFAULT_PORT
2298.4.1 by Andrew Bennetts
Give bzr:// a default port of 4155.
3954
            else:
3955
                if ':' in port:
3956
                    host, port = port.split(':')
3957
                port = int(port)
2018.5.121 by Andrew Bennetts
Fix cmd_serve.
3958
            smart_server = server.SmartTCPServer(t, host=host, port=port)
2018.5.15 by Andrew Bennetts
Tidy some imports, and bugs introduced when adding server.py
3959
            print 'listening on port: ', smart_server.port
1910.19.7 by Andrew Bennetts
Allow specifying the host/interface to bzr serve, and use the new test
3960
            sys.stdout.flush()
2018.5.69 by Robert Collins
Prevent the smart server sending cruft over stderr to the client.
3961
        # for the duration of this server, no UI output is permitted.
3962
        # note that this may cause problems with blackbox tests. This should
3963
        # be changed with care though, as we dont want to use bandwidth sending
3964
        # progress over stderr to smart server clients!
3965
        old_factory = ui.ui_factory
3118.3.1 by Andrew Bennetts
Reduce lockdir timeout to 0 seconds in cmd_serve.
3966
        old_lockdir_timeout = lockdir._DEFAULT_TIMEOUT_SECONDS
2018.5.69 by Robert Collins
Prevent the smart server sending cruft over stderr to the client.
3967
        try:
3968
            ui.ui_factory = ui.SilentUIFactory()
3118.3.1 by Andrew Bennetts
Reduce lockdir timeout to 0 seconds in cmd_serve.
3969
            lockdir._DEFAULT_TIMEOUT_SECONDS = 0
2018.5.69 by Robert Collins
Prevent the smart server sending cruft over stderr to the client.
3970
            smart_server.serve()
3971
        finally:
3972
            ui.ui_factory = old_factory
3118.3.1 by Andrew Bennetts
Reduce lockdir timeout to 0 seconds in cmd_serve.
3973
            lockdir._DEFAULT_TIMEOUT_SECONDS = old_lockdir_timeout
1910.19.1 by Andrew Bennetts
Support bzr:// urls to work with the new RPC-based transport which will be used
3974
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
3975
1731.2.7 by Aaron Bentley
Add join command
3976
class cmd_join(Command):
3977
    """Combine a subtree into its containing tree.
3978
    
2338.3.1 by Aaron Bentley
Hide nested-tree commands and improve their docs
3979
    This command is for experimental use only.  It requires the target tree
3980
    to be in dirstate-with-subtree format, which cannot be converted into
3981
    earlier formats.
3982
3983
    The TREE argument should be an independent tree, inside another tree, but
3984
    not part of it.  (Such trees can be produced by "bzr split", but also by
3985
    running "bzr branch" with the target inside a tree.)
3986
3987
    The result is a combined tree, with the subtree no longer an independant
3988
    part.  This is marked as a merge of the subtree into the containing tree,
3989
    and all history is preserved.
3990
3991
    If --reference is specified, the subtree retains its independence.  It can
3992
    be branched by itself, and can be part of multiple projects at the same
3993
    time.  But operations performed in the containing tree, such as commit
3994
    and merge, will recurse into the subtree.
1731.2.7 by Aaron Bentley
Add join command
3995
    """
3996
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
3997
    _see_also = ['split']
1731.2.7 by Aaron Bentley
Add join command
3998
    takes_args = ['tree']
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
3999
    takes_options = [
4000
            Option('reference', help='Join by reference.'),
4001
            ]
2338.3.1 by Aaron Bentley
Hide nested-tree commands and improve their docs
4002
    hidden = True
1731.2.7 by Aaron Bentley
Add join command
4003
2100.3.11 by Aaron Bentley
Add join --reference support
4004
    def run(self, tree, reference=False):
1731.2.7 by Aaron Bentley
Add join command
4005
        sub_tree = WorkingTree.open(tree)
4006
        parent_dir = osutils.dirname(sub_tree.basedir)
4007
        containing_tree = WorkingTree.open_containing(parent_dir)[0]
2255.2.235 by Martin Pool
Add blackbox test that join gives clean error when the repository doesn't support rich roots
4008
        repo = containing_tree.branch.repository
4009
        if not repo.supports_rich_root():
4010
            raise errors.BzrCommandError(
4011
                "Can't join trees because %s doesn't support rich root data.\n"
4012
                "You can use bzr upgrade on the repository."
4013
                % (repo,))
2100.3.11 by Aaron Bentley
Add join --reference support
4014
        if reference:
2255.2.219 by Martin Pool
fix unbound local error in cmd_join
4015
            try:
2100.3.11 by Aaron Bentley
Add join --reference support
4016
                containing_tree.add_reference(sub_tree)
2255.2.219 by Martin Pool
fix unbound local error in cmd_join
4017
            except errors.BadReferenceTarget, e:
2255.2.235 by Martin Pool
Add blackbox test that join gives clean error when the repository doesn't support rich roots
4018
                # XXX: Would be better to just raise a nicely printable
4019
                # exception from the real origin.  Also below.  mbp 20070306
2255.2.219 by Martin Pool
fix unbound local error in cmd_join
4020
                raise errors.BzrCommandError("Cannot join %s.  %s" %
2100.3.11 by Aaron Bentley
Add join --reference support
4021
                                             (tree, e.reason))
4022
        else:
4023
            try:
4024
                containing_tree.subsume(sub_tree)
4025
            except errors.BadSubsumeSource, e:
4026
                raise errors.BzrCommandError("Cannot join %s.  %s" % 
4027
                                             (tree, e.reason))
1553.5.35 by Martin Pool
Start break-lock --show
4028
1731.2.22 by Aaron Bentley
Initial work on split command
4029
4030
class cmd_split(Command):
3113.6.2 by Aaron Bentley
Un-hide split command, add NEWS
4031
    """Split a subdirectory of a tree into a separate tree.
2338.3.1 by Aaron Bentley
Hide nested-tree commands and improve their docs
4032
3113.6.2 by Aaron Bentley
Un-hide split command, add NEWS
4033
    This command will produce a target tree in a format that supports
4034
    rich roots, like 'rich-root' or 'rich-root-pack'.  These formats cannot be
4035
    converted into earlier formats like 'dirstate-tags'.
2338.3.1 by Aaron Bentley
Hide nested-tree commands and improve their docs
4036
4037
    The TREE argument should be a subdirectory of a working tree.  That
4038
    subdirectory will be converted into an independent tree, with its own
4039
    branch.  Commits in the top-level tree will not apply to the new subtree.
1731.2.22 by Aaron Bentley
Initial work on split command
4040
    """
4041
3113.6.2 by Aaron Bentley
Un-hide split command, add NEWS
4042
    # join is not un-hidden yet
4043
    #_see_also = ['join']
1731.2.22 by Aaron Bentley
Initial work on split command
4044
    takes_args = ['tree']
4045
4046
    def run(self, tree):
4047
        containing_tree, subdir = WorkingTree.open_containing(tree)
4048
        sub_id = containing_tree.path2id(subdir)
4049
        if sub_id is None:
4050
            raise errors.NotVersionedError(subdir)
1731.2.23 by Aaron Bentley
Throw user-friendly error splitting in shared repo with wrong format
4051
        try:
4052
            containing_tree.extract(sub_id)
4053
        except errors.RootNotRich:
4054
            raise errors.UpgradeRequired(containing_tree.branch.base)
1731.2.22 by Aaron Bentley
Initial work on split command
4055
4056
1551.12.8 by Aaron Bentley
Add merge-directive command
4057
class cmd_merge_directive(Command):
1551.12.32 by Aaron Bentley
Improve merge directive help
4058
    """Generate a merge directive for auto-merge tools.
4059
4060
    A directive requests a merge to be performed, and also provides all the
4061
    information necessary to do so.  This means it must either include a
4062
    revision bundle, or the location of a branch containing the desired
4063
    revision.
4064
4065
    A submit branch (the location to merge into) must be supplied the first
4066
    time the command is issued.  After it has been supplied once, it will
4067
    be remembered as the default.
4068
4069
    A public branch is optional if a revision bundle is supplied, but required
4070
    if --diff or --plain is specified.  It will be remembered as the default
4071
    after the first use.
4072
    """
1551.12.20 by Aaron Bentley
Pull directive registry into command class
4073
1551.12.14 by Aaron Bentley
Get merge-directive command basically working
4074
    takes_args = ['submit_branch?', 'public_branch?']
4075
2520.5.4 by Aaron Bentley
Replace 'bundle-revisions' with 'submit' command
4076
    hidden = True
4077
2681.1.4 by Aaron Bentley
Fix reference to told submit command
4078
    _see_also = ['send']
2520.4.121 by Aaron Bentley
Polish up submit command
4079
1551.12.43 by Aaron Bentley
Misc changes from review
4080
    takes_options = [
4081
        RegistryOption.from_kwargs('patch-type',
2681.1.7 by Aaron Bentley
Fix option grammar
4082
            'The type of patch to include in the directive.',
2598.1.2 by Martin Pool
Also check that option help ends in a period, and fix those that don't
4083
            title='Patch type',
4084
            value_switches=True,
4085
            enum_switch=False,
4086
            bundle='Bazaar revision bundle (default).',
4087
            diff='Normal unified diff.',
4088
            plain='No patch, just directive.'),
4089
        Option('sign', help='GPG-sign the directive.'), 'revision',
1551.12.26 by Aaron Bentley
Get email working, with optional message
4090
        Option('mail-to', type=str,
2598.1.2 by Martin Pool
Also check that option help ends in a period, and fix those that don't
4091
            help='Instead of printing the directive, email to this address.'),
1551.12.27 by Aaron Bentley
support custom message everywhere
4092
        Option('message', type=str, short_name='m',
2598.1.2 by Martin Pool
Also check that option help ends in a period, and fix those that don't
4093
            help='Message to use when committing this merge.')
1551.12.27 by Aaron Bentley
support custom message everywhere
4094
        ]
1551.12.14 by Aaron Bentley
Get merge-directive command basically working
4095
2530.2.1 by Adeodato Simó
Add encoding_type = 'exact' to cmd_merge_directive. (LP #120591)
4096
    encoding_type = 'exact'
4097
1551.12.16 by Aaron Bentley
Enable signing merge directives
4098
    def run(self, submit_branch=None, public_branch=None, patch_type='bundle',
1551.12.27 by Aaron Bentley
support custom message everywhere
4099
            sign=False, revision=None, mail_to=None, message=None):
2490.2.28 by Aaron Bentley
Fix handling of null revision
4100
        from bzrlib.revision import ensure_null, NULL_REVISION
2520.5.4 by Aaron Bentley
Replace 'bundle-revisions' with 'submit' command
4101
        include_patch, include_bundle = {
4102
            'plain': (False, False),
4103
            'diff': (True, False),
4104
            'bundle': (True, True),
4105
            }[patch_type]
1551.12.8 by Aaron Bentley
Add merge-directive command
4106
        branch = Branch.open('.')
1551.12.44 by Aaron Bentley
Add (set|get)_public_branch
4107
        stored_submit_branch = branch.get_submit_branch()
1551.12.14 by Aaron Bentley
Get merge-directive command basically working
4108
        if submit_branch is None:
1551.12.44 by Aaron Bentley
Add (set|get)_public_branch
4109
            submit_branch = stored_submit_branch
1551.12.14 by Aaron Bentley
Get merge-directive command basically working
4110
        else:
1551.12.44 by Aaron Bentley
Add (set|get)_public_branch
4111
            if stored_submit_branch is None:
1551.12.14 by Aaron Bentley
Get merge-directive command basically working
4112
                branch.set_submit_branch(submit_branch)
4113
        if submit_branch is None:
4114
            submit_branch = branch.get_parent()
4115
        if submit_branch is None:
4116
            raise errors.BzrCommandError('No submit branch specified or known')
1551.12.44 by Aaron Bentley
Add (set|get)_public_branch
4117
4118
        stored_public_branch = branch.get_public_branch()
1551.12.14 by Aaron Bentley
Get merge-directive command basically working
4119
        if public_branch is None:
1551.12.44 by Aaron Bentley
Add (set|get)_public_branch
4120
            public_branch = stored_public_branch
4121
        elif stored_public_branch is None:
4122
            branch.set_public_branch(public_branch)
2520.5.4 by Aaron Bentley
Replace 'bundle-revisions' with 'submit' command
4123
        if not include_bundle and public_branch is None:
1551.12.24 by Aaron Bentley
Add RegistryOption.from_swargs to simplify simple registry options
4124
            raise errors.BzrCommandError('No public branch specified or'
4125
                                         ' known')
2520.4.112 by Aaron Bentley
Make cherry-pick merge directives possible
4126
        base_revision_id = None
1551.12.17 by Aaron Bentley
add revision selection to mergedirective
4127
        if revision is not None:
2520.4.112 by Aaron Bentley
Make cherry-pick merge directives possible
4128
            if len(revision) > 2:
1551.12.17 by Aaron Bentley
add revision selection to mergedirective
4129
                raise errors.BzrCommandError('bzr merge-directive takes '
2520.4.112 by Aaron Bentley
Make cherry-pick merge directives possible
4130
                    'at most two one revision identifiers')
3298.2.8 by John Arbash Meinel
Get rid of .in_branch(need_revno=False) in favor of simpler .as_revision_id()
4131
            revision_id = revision[-1].as_revision_id(branch)
2520.4.112 by Aaron Bentley
Make cherry-pick merge directives possible
4132
            if len(revision) == 2:
3298.2.8 by John Arbash Meinel
Get rid of .in_branch(need_revno=False) in favor of simpler .as_revision_id()
4133
                base_revision_id = revision[0].as_revision_id(branch)
1551.12.17 by Aaron Bentley
add revision selection to mergedirective
4134
        else:
4135
            revision_id = branch.last_revision()
2490.2.28 by Aaron Bentley
Fix handling of null revision
4136
        revision_id = ensure_null(revision_id)
4137
        if revision_id == NULL_REVISION:
4138
            raise errors.BzrCommandError('No revisions to bundle.')
2520.4.73 by Aaron Bentley
Implement new merge directive format
4139
        directive = merge_directive.MergeDirective2.from_objects(
1551.12.17 by Aaron Bentley
add revision selection to mergedirective
4140
            branch.repository, revision_id, time.time(),
1551.12.8 by Aaron Bentley
Add merge-directive command
4141
            osutils.local_time_offset(), submit_branch,
2520.5.4 by Aaron Bentley
Replace 'bundle-revisions' with 'submit' command
4142
            public_branch=public_branch, include_patch=include_patch,
4143
            include_bundle=include_bundle, message=message,
4144
            base_revision_id=base_revision_id)
1551.12.26 by Aaron Bentley
Get email working, with optional message
4145
        if mail_to is None:
4146
            if sign:
4147
                self.outf.write(directive.to_signed(branch))
4148
            else:
4149
                self.outf.writelines(directive.to_lines())
1551.12.16 by Aaron Bentley
Enable signing merge directives
4150
        else:
1551.12.26 by Aaron Bentley
Get email working, with optional message
4151
            message = directive.to_email(mail_to, branch, sign)
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
4152
            s = SMTPConnection(branch.get_config())
4153
            s.send_email(message)
1551.12.8 by Aaron Bentley
Add merge-directive command
4154
1551.12.14 by Aaron Bentley
Get merge-directive command basically working
4155
2654.3.1 by Aaron Bentley
Rename submit to send, make -o required, support -o- for stdout
4156
class cmd_send(Command):
2681.1.13 by Aaron Bentley
Add support for submit_to config option
4157
    """Mail or create a merge-directive for submiting changes.
2520.5.4 by Aaron Bentley
Replace 'bundle-revisions' with 'submit' command
4158
4159
    A merge directive provides many things needed for requesting merges:
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
4160
4161
    * A machine-readable description of the merge to perform
4162
4163
    * An optional patch that is a preview of the changes requested
4164
4165
    * An optional bundle of revision data, so that the changes can be applied
2520.5.4 by Aaron Bentley
Replace 'bundle-revisions' with 'submit' command
4166
      directly from the merge directive, without retrieving data from a
4167
      branch.
4168
4169
    If --no-bundle is specified, then public_branch is needed (and must be
4170
    up-to-date), so that the receiver can perform the merge using the
4171
    public_branch.  The public_branch is always included if known, so that
4172
    people can check it later.
4173
4174
    The submit branch defaults to the parent, but can be overridden.  Both
4175
    submit branch and public branch will be remembered if supplied.
4176
4177
    If a public_branch is known for the submit_branch, that public submit
4178
    branch is used in the merge instructions.  This means that a local mirror
2520.4.122 by Aaron Bentley
Clarify doc
4179
    can be used as your actual submit branch, once you have set public_branch
4180
    for that mirror.
2681.1.6 by Aaron Bentley
Update help to describe available formats
4181
2681.1.30 by Aaron Bentley
Update NEWS and docs
4182
    Mail is sent using your preferred mail program.  This should be transparent
3065.3.2 by Alexander Belchenko
fix ReST formatting in cmd_send help
4183
    on Windows (it uses MAPI).  On Linux, it requires the xdg-email utility.
4184
    If the preferred client can't be found (or used), your editor will be used.
2681.1.30 by Aaron Bentley
Update NEWS and docs
4185
    
4186
    To use a specific mail program, set the mail_client configuration option.
2790.2.2 by Keir Mierle
Change alphabetic ordering into two categories; one for specific clients the other for generic options.
4187
    (For Thunderbird 1.5, this works around some bugs.)  Supported values for
3506.1.5 by Christophe Troestler
Moved "emacsclient" to the `generic options' in `bzr help send'.
4188
    specific clients are "evolution", "kmail", "mutt", and "thunderbird";
4189
    generic options are "default", "editor", "emacsclient", "mapi", and
3638.2.3 by Neil Martinsen-Burrell
Mention mail_client_registry in NEWS and help
4190
    "xdg-email".  Plugins may also add supported clients.
2681.1.13 by Aaron Bentley
Add support for submit_to config option
4191
4192
    If mail is being sent, a to address is required.  This can be supplied
3251.1.2 by Jelmer Vernooij
``bzr send`` now supports new ``child_submit_to`` option in the submit branch
4193
    either on the commandline, by setting the submit_to configuration
4194
    option in the branch itself or the child_submit_to configuration option 
4195
    in the submit branch.
2681.1.13 by Aaron Bentley
Add support for submit_to config option
4196
2681.1.6 by Aaron Bentley
Update help to describe available formats
4197
    Two formats are currently supported: "4" uses revision bundle format 4 and
4198
    merge directive format 2.  It is significantly faster and smaller than
4199
    older formats.  It is compatible with Bazaar 0.19 and later.  It is the
4200
    default.  "0.9" uses revision bundle format 0.9 and merge directive
4201
    format 1.  It is compatible with Bazaar 0.12 - 0.18.
3277.1.1 by Peter Schuller
Document the relationship between bzr send and bzr merge. In
4202
    
3313.1.1 by Ian Clatworthy
Improve doc on send/merge relationship (Peter Schuller)
4203
    Merge directives are applied using the merge command or the pull command.
2520.5.4 by Aaron Bentley
Replace 'bundle-revisions' with 'submit' command
4204
    """
4205
4206
    encoding_type = 'exact'
4207
3313.1.1 by Ian Clatworthy
Improve doc on send/merge relationship (Peter Schuller)
4208
    _see_also = ['merge', 'pull']
2520.4.121 by Aaron Bentley
Polish up submit command
4209
2520.5.4 by Aaron Bentley
Replace 'bundle-revisions' with 'submit' command
4210
    takes_args = ['submit_branch?', 'public_branch?']
2654.3.1 by Aaron Bentley
Rename submit to send, make -o required, support -o- for stdout
4211
2520.4.121 by Aaron Bentley
Polish up submit command
4212
    takes_options = [
4213
        Option('no-bundle',
2520.4.132 by Aaron Bentley
Merge from bzr.dev
4214
               help='Do not include a bundle in the merge directive.'),
2520.4.121 by Aaron Bentley
Polish up submit command
4215
        Option('no-patch', help='Do not include a preview patch in the merge'
2520.4.132 by Aaron Bentley
Merge from bzr.dev
4216
               ' directive.'),
2520.4.121 by Aaron Bentley
Polish up submit command
4217
        Option('remember',
2520.4.132 by Aaron Bentley
Merge from bzr.dev
4218
               help='Remember submit and public branch.'),
2520.4.121 by Aaron Bentley
Polish up submit command
4219
        Option('from',
2520.4.132 by Aaron Bentley
Merge from bzr.dev
4220
               help='Branch to generate the submission from, '
4221
               'rather than the one containing the working directory.',
2520.4.121 by Aaron Bentley
Polish up submit command
4222
               short_name='f',
4223
               type=unicode),
3377.2.1 by Martin Pool
doc: send -o, and more on send in user guide
4224
        Option('output', short_name='o',
3377.2.2 by Martin Pool
Say 'merge directive' rather than just 'directive' in help
4225
               help='Write merge directive to this file; '
3377.2.1 by Martin Pool
doc: send -o, and more on send in user guide
4226
                    'use - for stdout.',
2520.4.121 by Aaron Bentley
Polish up submit command
4227
               type=unicode),
2681.1.32 by Aaron Bentley
Fix option grammar
4228
        Option('mail-to', help='Mail the request to this address.',
2681.1.9 by Aaron Bentley
Add support for mail-from-editor
4229
               type=unicode),
2520.4.121 by Aaron Bentley
Polish up submit command
4230
        'revision',
2681.1.9 by Aaron Bentley
Add support for mail-from-editor
4231
        'message',
2681.1.7 by Aaron Bentley
Fix option grammar
4232
        RegistryOption.from_kwargs('format',
4233
        'Use the specified output format.',
2681.1.2 by Aaron Bentley
Add support for selecting bundle format
4234
        **{'4': 'Bundle format 4, Merge Directive 2 (default)',
2681.1.5 by Aaron Bentley
Display correct help message in from_kwargs
4235
           '0.9': 'Bundle format 0.9, Merge Directive 1',})
2520.4.121 by Aaron Bentley
Polish up submit command
4236
        ]
2520.5.4 by Aaron Bentley
Replace 'bundle-revisions' with 'submit' command
4237
4238
    def run(self, submit_branch=None, public_branch=None, no_bundle=False,
2520.4.121 by Aaron Bentley
Polish up submit command
4239
            no_patch=False, revision=None, remember=False, output=None,
2681.1.9 by Aaron Bentley
Add support for mail-from-editor
4240
            format='4', mail_to=None, message=None, **kwargs):
2681.1.2 by Aaron Bentley
Add support for selecting bundle format
4241
        return self._run(submit_branch, revision, public_branch, remember,
4242
                         format, no_bundle, no_patch, output,
2681.1.9 by Aaron Bentley
Add support for mail-from-editor
4243
                         kwargs.get('from', '.'), mail_to, message)
2681.1.1 by Aaron Bentley
Split 'send' into 'send' and 'bundle'.
4244
2681.1.2 by Aaron Bentley
Add support for selecting bundle format
4245
    def _run(self, submit_branch, revision, public_branch, remember, format,
2681.1.9 by Aaron Bentley
Add support for mail-from-editor
4246
             no_bundle, no_patch, output, from_, mail_to, message):
2872.2.1 by Andrew Bennetts
Remove unused imports in builtins.py revealed by pyflakes, and fix one undefined name.
4247
        from bzrlib.revision import NULL_REVISION
3060.2.1 by Lukáš Lalinský
Fix misplaced branch lock in cmd_send.
4248
        branch = Branch.open_containing(from_)[0]
2681.1.8 by Aaron Bentley
Add Thunderbird support to bzr send
4249
        if output is None:
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
4250
            outfile = cStringIO.StringIO()
2681.1.8 by Aaron Bentley
Add Thunderbird support to bzr send
4251
        elif output == '-':
2520.4.121 by Aaron Bentley
Polish up submit command
4252
            outfile = self.outf
2520.5.4 by Aaron Bentley
Replace 'bundle-revisions' with 'submit' command
4253
        else:
2520.4.121 by Aaron Bentley
Polish up submit command
4254
            outfile = open(output, 'wb')
3060.2.1 by Lukáš Lalinský
Fix misplaced branch lock in cmd_send.
4255
        # we may need to write data into branch's repository to calculate
4256
        # the data to send.
4257
        branch.lock_write()
2520.4.121 by Aaron Bentley
Polish up submit command
4258
        try:
2681.1.10 by Aaron Bentley
Clean up handling of unknown mail clients
4259
            if output is None:
2681.1.13 by Aaron Bentley
Add support for submit_to config option
4260
                config = branch.get_config()
4261
                if mail_to is None:
4262
                    mail_to = config.get_user_option('submit_to')
4263
                mail_client = config.get_mail_client()
2520.4.121 by Aaron Bentley
Polish up submit command
4264
            if remember and submit_branch is None:
4265
                raise errors.BzrCommandError(
4266
                    '--remember requires a branch to be specified.')
4267
            stored_submit_branch = branch.get_submit_branch()
3596.3.1 by James Westby
Give the user a bit more information about which saved location is being used.
4268
            remembered_submit_branch = None
2520.4.121 by Aaron Bentley
Polish up submit command
4269
            if submit_branch is None:
4270
                submit_branch = stored_submit_branch
3596.3.1 by James Westby
Give the user a bit more information about which saved location is being used.
4271
                remembered_submit_branch = "submit"
2520.4.121 by Aaron Bentley
Polish up submit command
4272
            else:
4273
                if stored_submit_branch is None or remember:
4274
                    branch.set_submit_branch(submit_branch)
4275
            if submit_branch is None:
4276
                submit_branch = branch.get_parent()
3596.3.1 by James Westby
Give the user a bit more information about which saved location is being used.
4277
                remembered_submit_branch = "parent"
2520.4.121 by Aaron Bentley
Polish up submit command
4278
            if submit_branch is None:
4279
                raise errors.BzrCommandError('No submit branch known or'
4280
                                             ' specified')
3596.3.1 by James Westby
Give the user a bit more information about which saved location is being used.
4281
            if remembered_submit_branch is not None:
4282
                note('Using saved %s location "%s" to determine what '
4283
                        'changes to submit.', remembered_submit_branch,
4284
                        submit_branch)
2520.5.4 by Aaron Bentley
Replace 'bundle-revisions' with 'submit' command
4285
3251.1.2 by Jelmer Vernooij
``bzr send`` now supports new ``child_submit_to`` option in the submit branch
4286
            if mail_to is None:
3251.1.3 by Jelmer Vernooij
Fix formatting.
4287
                submit_config = Branch.open(submit_branch).get_config()
4288
                mail_to = submit_config.get_user_option("child_submit_to")
3251.1.2 by Jelmer Vernooij
``bzr send`` now supports new ``child_submit_to`` option in the submit branch
4289
2520.4.121 by Aaron Bentley
Polish up submit command
4290
            stored_public_branch = branch.get_public_branch()
4291
            if public_branch is None:
4292
                public_branch = stored_public_branch
4293
            elif stored_public_branch is None or remember:
4294
                branch.set_public_branch(public_branch)
4295
            if no_bundle and public_branch is None:
4296
                raise errors.BzrCommandError('No public branch specified or'
4297
                                             ' known')
4298
            base_revision_id = None
2747.3.1 by Aaron Bentley
'send' and 'bundle' now handle partial ranges correctly (#61685)
4299
            revision_id = None
2520.4.121 by Aaron Bentley
Polish up submit command
4300
            if revision is not None:
4301
                if len(revision) > 2:
2654.3.1 by Aaron Bentley
Rename submit to send, make -o required, support -o- for stdout
4302
                    raise errors.BzrCommandError('bzr send takes '
2520.4.121 by Aaron Bentley
Polish up submit command
4303
                        'at most two one revision identifiers')
3298.2.8 by John Arbash Meinel
Get rid of .in_branch(need_revno=False) in favor of simpler .as_revision_id()
4304
                revision_id = revision[-1].as_revision_id(branch)
2520.4.121 by Aaron Bentley
Polish up submit command
4305
                if len(revision) == 2:
3298.2.8 by John Arbash Meinel
Get rid of .in_branch(need_revno=False) in favor of simpler .as_revision_id()
4306
                    base_revision_id = revision[0].as_revision_id(branch)
2747.3.1 by Aaron Bentley
'send' and 'bundle' now handle partial ranges correctly (#61685)
4307
            if revision_id is None:
2520.4.121 by Aaron Bentley
Polish up submit command
4308
                revision_id = branch.last_revision()
4309
            if revision_id == NULL_REVISION:
4310
                raise errors.BzrCommandError('No revisions to submit.')
2681.1.2 by Aaron Bentley
Add support for selecting bundle format
4311
            if format == '4':
4312
                directive = merge_directive.MergeDirective2.from_objects(
4313
                    branch.repository, revision_id, time.time(),
4314
                    osutils.local_time_offset(), submit_branch,
4315
                    public_branch=public_branch, include_patch=not no_patch,
2681.1.9 by Aaron Bentley
Add support for mail-from-editor
4316
                    include_bundle=not no_bundle, message=message,
2681.1.2 by Aaron Bentley
Add support for selecting bundle format
4317
                    base_revision_id=base_revision_id)
4318
            elif format == '0.9':
4319
                if not no_bundle:
4320
                    if not no_patch:
4321
                        patch_type = 'bundle'
4322
                    else:
4323
                        raise errors.BzrCommandError('Format 0.9 does not'
4324
                            ' permit bundle with no patch')
4325
                else:
4326
                    if not no_patch:
4327
                        patch_type = 'diff'
4328
                    else:
4329
                        patch_type = None
4330
                directive = merge_directive.MergeDirective.from_objects(
4331
                    branch.repository, revision_id, time.time(),
4332
                    osutils.local_time_offset(), submit_branch,
4333
                    public_branch=public_branch, patch_type=patch_type,
2681.1.9 by Aaron Bentley
Add support for mail-from-editor
4334
                    message=message)
2681.1.2 by Aaron Bentley
Add support for selecting bundle format
4335
2520.4.121 by Aaron Bentley
Polish up submit command
4336
            outfile.writelines(directive.to_lines())
2681.1.8 by Aaron Bentley
Add Thunderbird support to bzr send
4337
            if output is None:
2681.1.9 by Aaron Bentley
Add support for mail-from-editor
4338
                subject = '[MERGE] '
4339
                if message is not None:
4340
                    subject += message
4341
                else:
4342
                    revision = branch.repository.get_revision(revision_id)
2681.3.5 by Lukáš Lalinsky
Don't send e-mails with multi-line subjects.
4343
                    subject += revision.get_summary()
3251.2.1 by Aaron Bentley
Use nick/revno-based names for merge directives
4344
                basename = directive.get_disk_name(branch)
2681.1.11 by Aaron Bentley
Add docstrings, add compose_merge_request
4345
                mail_client.compose_merge_request(mail_to, subject,
3251.2.1 by Aaron Bentley
Use nick/revno-based names for merge directives
4346
                                                  outfile.getvalue(), basename)
2520.4.121 by Aaron Bentley
Polish up submit command
4347
        finally:
2654.3.1 by Aaron Bentley
Rename submit to send, make -o required, support -o- for stdout
4348
            if output != '-':
2520.4.121 by Aaron Bentley
Polish up submit command
4349
                outfile.close()
3010.1.17 by Robert Collins
Lock correctness and commit_group management for re-sign, in builtins.
4350
            branch.unlock()
2520.5.4 by Aaron Bentley
Replace 'bundle-revisions' with 'submit' command
4351
2654.3.1 by Aaron Bentley
Rename submit to send, make -o required, support -o- for stdout
4352
2681.1.1 by Aaron Bentley
Split 'send' into 'send' and 'bundle'.
4353
class cmd_bundle_revisions(cmd_send):
4354
4355
    """Create a merge-directive for submiting changes.
4356
4357
    A merge directive provides many things needed for requesting merges:
4358
4359
    * A machine-readable description of the merge to perform
4360
4361
    * An optional patch that is a preview of the changes requested
4362
4363
    * An optional bundle of revision data, so that the changes can be applied
4364
      directly from the merge directive, without retrieving data from a
4365
      branch.
4366
4367
    If --no-bundle is specified, then public_branch is needed (and must be
4368
    up-to-date), so that the receiver can perform the merge using the
4369
    public_branch.  The public_branch is always included if known, so that
4370
    people can check it later.
4371
4372
    The submit branch defaults to the parent, but can be overridden.  Both
4373
    submit branch and public branch will be remembered if supplied.
4374
4375
    If a public_branch is known for the submit_branch, that public submit
4376
    branch is used in the merge instructions.  This means that a local mirror
4377
    can be used as your actual submit branch, once you have set public_branch
4378
    for that mirror.
2681.1.6 by Aaron Bentley
Update help to describe available formats
4379
4380
    Two formats are currently supported: "4" uses revision bundle format 4 and
4381
    merge directive format 2.  It is significantly faster and smaller than
4382
    older formats.  It is compatible with Bazaar 0.19 and later.  It is the
4383
    default.  "0.9" uses revision bundle format 0.9 and merge directive
4384
    format 1.  It is compatible with Bazaar 0.12 - 0.18.
2681.1.1 by Aaron Bentley
Split 'send' into 'send' and 'bundle'.
4385
    """
4386
2681.1.9 by Aaron Bentley
Add support for mail-from-editor
4387
    takes_options = [
4388
        Option('no-bundle',
4389
               help='Do not include a bundle in the merge directive.'),
4390
        Option('no-patch', help='Do not include a preview patch in the merge'
4391
               ' directive.'),
4392
        Option('remember',
4393
               help='Remember submit and public branch.'),
4394
        Option('from',
4395
               help='Branch to generate the submission from, '
4396
               'rather than the one containing the working directory.',
4397
               short_name='f',
4398
               type=unicode),
4399
        Option('output', short_name='o', help='Write directive to this file.',
4400
               type=unicode),
4401
        'revision',
4402
        RegistryOption.from_kwargs('format',
4403
        'Use the specified output format.',
4404
        **{'4': 'Bundle format 4, Merge Directive 2 (default)',
4405
           '0.9': 'Bundle format 0.9, Merge Directive 1',})
4406
        ]
2681.1.1 by Aaron Bentley
Split 'send' into 'send' and 'bundle'.
4407
    aliases = ['bundle']
4408
4409
    _see_also = ['send', 'merge']
4410
4411
    hidden = True
4412
4413
    def run(self, submit_branch=None, public_branch=None, no_bundle=False,
4414
            no_patch=False, revision=None, remember=False, output=None,
2681.1.2 by Aaron Bentley
Add support for selecting bundle format
4415
            format='4', **kwargs):
2681.1.1 by Aaron Bentley
Split 'send' into 'send' and 'bundle'.
4416
        if output is None:
4417
            output = '-'
2681.1.2 by Aaron Bentley
Add support for selecting bundle format
4418
        return self._run(submit_branch, revision, public_branch, remember,
4419
                         format, no_bundle, no_patch, output,
2681.1.12 by Aaron Bentley
Fix bundle command
4420
                         kwargs.get('from', '.'), None, None)
2681.1.1 by Aaron Bentley
Split 'send' into 'send' and 'bundle'.
4421
4422
2220.2.2 by Martin Pool
Add tag command and basic implementation
4423
class cmd_tag(Command):
2664.1.1 by Joachim Nilsson
Change tag description for "help commands" to make it easier to find
4424
    """Create, remove or modify a tag naming a revision.
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
4425
    
4426
    Tags give human-meaningful names to revisions.  Commands that take a -r
4427
    (--revision) option can be given -rtag:X, where X is any previously
4428
    created tag.
4429
2220.2.41 by Martin Pool
Fix tag help (fullermd)
4430
    Tags are stored in the branch.  Tags are copied from one branch to another
4431
    along when you branch, push, pull or merge.
2220.2.42 by Martin Pool
Tag command refuses to replace existing tags unless you force it.
4432
4433
    It is an error to give a tag name that already exists unless you pass 
4434
    --force, in which case the tag is moved to point to the new revision.
3566.2.1 by Benjamin Peterson
document how the rename tags
4435
3566.2.2 by Benjamin Peterson
fix markup
4436
    To rename a tag (change the name but keep it on the same revsion), run ``bzr
4437
    tag new-name -r tag:old-name`` and then ``bzr tag --delete oldname``.
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
4438
    """
2220.2.2 by Martin Pool
Add tag command and basic implementation
4439
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
4440
    _see_also = ['commit', 'tags']
2220.2.2 by Martin Pool
Add tag command and basic implementation
4441
    takes_args = ['tag_name']
4442
    takes_options = [
2220.2.21 by Martin Pool
Add tag --delete command and implementation
4443
        Option('delete',
2220.2.42 by Martin Pool
Tag command refuses to replace existing tags unless you force it.
4444
            help='Delete this tag rather than placing it.',
4445
            ),
4446
        Option('directory',
4447
            help='Branch in which to place the tag.',
4448
            short_name='d',
4449
            type=unicode,
4450
            ),
4451
        Option('force',
2598.1.2 by Martin Pool
Also check that option help ends in a period, and fix those that don't
4452
            help='Replace existing tags.',
2220.2.21 by Martin Pool
Add tag --delete command and implementation
4453
            ),
2220.2.6 by Martin Pool
Add tag -r option
4454
        'revision',
2220.2.2 by Martin Pool
Add tag command and basic implementation
4455
        ]
4456
2220.2.42 by Martin Pool
Tag command refuses to replace existing tags unless you force it.
4457
    def run(self, tag_name,
4458
            delete=None,
4459
            directory='.',
4460
            force=None,
2220.2.21 by Martin Pool
Add tag --delete command and implementation
4461
            revision=None,
2220.2.42 by Martin Pool
Tag command refuses to replace existing tags unless you force it.
4462
            ):
2220.2.2 by Martin Pool
Add tag command and basic implementation
4463
        branch, relpath = Branch.open_containing(directory)
2220.2.42 by Martin Pool
Tag command refuses to replace existing tags unless you force it.
4464
        branch.lock_write()
4465
        try:
4466
            if delete:
4467
                branch.tags.delete_tag(tag_name)
4468
                self.outf.write('Deleted tag %s.\n' % tag_name)
2220.2.21 by Martin Pool
Add tag --delete command and implementation
4469
            else:
2220.2.42 by Martin Pool
Tag command refuses to replace existing tags unless you force it.
4470
                if revision:
4471
                    if len(revision) != 1:
4472
                        raise errors.BzrCommandError(
4473
                            "Tags can only be placed on a single revision, "
4474
                            "not on a range")
3298.2.8 by John Arbash Meinel
Get rid of .in_branch(need_revno=False) in favor of simpler .as_revision_id()
4475
                    revision_id = revision[0].as_revision_id(branch)
2220.2.42 by Martin Pool
Tag command refuses to replace existing tags unless you force it.
4476
                else:
4477
                    revision_id = branch.last_revision()
4478
                if (not force) and branch.tags.has_tag(tag_name):
4479
                    raise errors.TagAlreadyExists(tag_name)
4480
                branch.tags.set_tag(tag_name, revision_id)
4481
                self.outf.write('Created tag %s.\n' % tag_name)
4482
        finally:
4483
            branch.unlock()
2220.2.2 by Martin Pool
Add tag command and basic implementation
4484
4485
2220.2.24 by Martin Pool
Add tags command
4486
class cmd_tags(Command):
4487
    """List tags.
4488
3007.1.1 by Adeodato Simó
Small fix to tags' help.
4489
    This command shows a table of tag names and the revisions they reference.
2220.2.24 by Martin Pool
Add tags command
4490
    """
4491
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
4492
    _see_also = ['tag']
2220.2.24 by Martin Pool
Add tags command
4493
    takes_options = [
4494
        Option('directory',
2598.1.2 by Martin Pool
Also check that option help ends in a period, and fix those that don't
4495
            help='Branch whose tags should be displayed.',
2220.2.24 by Martin Pool
Add tags command
4496
            short_name='d',
4497
            type=unicode,
4498
            ),
2805.8.6 by Adeodato Simó
Don't sort by revno; only by time if --sort=time is passed.
4499
        RegistryOption.from_kwargs('sort',
4500
            'Sort tags by different criteria.', title='Sorting',
4501
            alpha='Sort tags lexicographically (default).',
4502
            time='Sort tags chronologically.',
4503
            ),
2805.8.3 by Adeodato Simó
Show dotted revnos, and revids only with --show-ids.
4504
        'show-ids',
2220.2.24 by Martin Pool
Add tags command
4505
    ]
4506
4507
    @display_command
4508
    def run(self,
4509
            directory='.',
2805.8.6 by Adeodato Simó
Don't sort by revno; only by time if --sort=time is passed.
4510
            sort='alpha',
2805.8.3 by Adeodato Simó
Show dotted revnos, and revids only with --show-ids.
4511
            show_ids=False,
2220.2.24 by Martin Pool
Add tags command
4512
            ):
4513
        branch, relpath = Branch.open_containing(directory)
2805.8.6 by Adeodato Simó
Don't sort by revno; only by time if --sort=time is passed.
4514
        tags = branch.tags.get_tag_dict().items()
3553.1.1 by Robert Collins
Do not scan history for tags when none are present.
4515
        if not tags:
4516
            return
2805.8.6 by Adeodato Simó
Don't sort by revno; only by time if --sort=time is passed.
4517
        if sort == 'alpha':
4518
            tags.sort()
4519
        elif sort == 'time':
4520
            timestamps = {}
4521
            for tag, revid in tags:
4522
                try:
4523
                    revobj = branch.repository.get_revision(revid)
4524
                except errors.NoSuchRevision:
4525
                    timestamp = sys.maxint # place them at the end
4526
                else:
4527
                    timestamp = revobj.timestamp
4528
                timestamps[revid] = timestamp
4529
            tags.sort(key=lambda x: timestamps[x[1]])
4530
        if not show_ids:
4531
            # [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
4532
            revno_map = branch.get_revision_id_to_revno_map()
4533
            tags = [ (tag, '.'.join(map(str, revno_map.get(revid, ('?',)))))
4534
                        for tag, revid in tags ]
4535
        for tag, revspec in tags:
4536
            self.outf.write('%-20s %s\n' % (tag, revspec))
2220.2.24 by Martin Pool
Add tags command
4537
4538
2796.2.5 by Aaron Bentley
Implement reconfigure command
4539
class cmd_reconfigure(Command):
2796.2.15 by Aaron Bentley
More updates from review
4540
    """Reconfigure the type of a bzr directory.
4541
4542
    A target configuration must be specified.
4543
4544
    For checkouts, the bind-to location will be auto-detected if not specified.
4545
    The order of preference is
4546
    1. For a lightweight checkout, the current bound location.
4547
    2. For branches that used to be checkouts, the previously-bound location.
4548
    3. The push location.
4549
    4. The parent location.
4550
    If none of these is available, --bind-to must be specified.
4551
    """
2796.2.5 by Aaron Bentley
Implement reconfigure command
4552
3535.4.1 by Marius Kruger
Update reconfigure help to say exactly what it wil do.
4553
    _see_also = ['branches', 'checkouts', 'standalone-trees', 'working-trees']
2796.2.5 by Aaron Bentley
Implement reconfigure command
4554
    takes_args = ['location?']
4555
    takes_options = [RegistryOption.from_kwargs('target_type',
4556
                     title='Target type',
4557
                     help='The type to reconfigure the directory to.',
4558
                     value_switches=True, enum_switch=False,
3535.4.1 by Marius Kruger
Update reconfigure help to say exactly what it wil do.
4559
                     branch='Reconfigure to be an unbound branch '
4560
                        'with no working tree.',
4561
                     tree='Reconfigure to be an unbound branch '
4562
                        'with a working tree.',
4563
                     checkout='Reconfigure to be a bound branch '
4564
                        'with a working tree.',
4565
                     lightweight_checkout='Reconfigure to be a lightweight'
4566
                     ' checkout (with no local history).',
4567
                     standalone='Reconfigure to be a standalone branch '
4568
                        '(i.e. stop using shared repository).',
3311.2.6 by Aaron Bentley
rename 'sharing' to 'use-shared'
4569
                     use_shared='Reconfigure to use a shared repository.'),
2796.2.5 by Aaron Bentley
Implement reconfigure command
4570
                     Option('bind-to', help='Branch to bind checkout to.',
4571
                            type=str),
4572
                     Option('force',
4573
                        help='Perform reconfiguration even if local changes'
4574
                        ' will be lost.')
4575
                     ]
4576
4577
    def run(self, location=None, target_type=None, bind_to=None, force=False):
4578
        directory = bzrdir.BzrDir.open(location)
2796.2.15 by Aaron Bentley
More updates from review
4579
        if target_type is None:
2830.2.4 by Martin Pool
Fix previously hidden NameError in reconfigure
4580
            raise errors.BzrCommandError('No target configuration specified')
2796.2.15 by Aaron Bentley
More updates from review
4581
        elif target_type == 'branch':
2796.2.5 by Aaron Bentley
Implement reconfigure command
4582
            reconfiguration = reconfigure.Reconfigure.to_branch(directory)
4583
        elif target_type == 'tree':
4584
            reconfiguration = reconfigure.Reconfigure.to_tree(directory)
4585
        elif target_type == 'checkout':
4586
            reconfiguration = reconfigure.Reconfigure.to_checkout(directory,
4587
                                                                  bind_to)
2796.2.19 by Aaron Bentley
Support reconfigure --lightweight-checkout
4588
        elif target_type == 'lightweight-checkout':
4589
            reconfiguration = reconfigure.Reconfigure.to_lightweight_checkout(
4590
                directory, bind_to)
3311.2.6 by Aaron Bentley
rename 'sharing' to 'use-shared'
4591
        elif target_type == 'use-shared':
4592
            reconfiguration = reconfigure.Reconfigure.to_use_shared(directory)
3311.2.5 by Aaron Bentley
Implement reconfigure --standalone and --sharing
4593
        elif target_type == 'standalone':
4594
            reconfiguration = reconfigure.Reconfigure.to_standalone(directory)
2796.2.5 by Aaron Bentley
Implement reconfigure command
4595
        reconfiguration.apply(force)
4596
4597
2999.1.1 by Ian Clatworthy
migrate switch command into the core - was in BzrTools
4598
class cmd_switch(Command):
3078.2.2 by Ian Clatworthy
get switch tests passing on heavyweight checkouts
4599
    """Set the branch of a checkout and update.
4600
    
4601
    For lightweight checkouts, this changes the branch being referenced.
4602
    For heavyweight checkouts, this checks that there are no local commits
4603
    versus the current bound branch, then it makes the local branch a mirror
4604
    of the new location and binds to it.
4605
    
4606
    In both cases, the working tree is updated and uncommitted changes
4607
    are merged. The user can commit or revert these as they desire.
4608
4609
    Pending merges need to be committed or reverted before using switch.
3246.5.1 by Robert Collins
* ``bzr switch`` will attempt to find branches to switch to relative to the
4610
4611
    The path to the branch to switch to can be specified relative to the parent
4612
    directory of the current branch. For example, if you are currently in a
4613
    checkout of /path/to/branch, specifying 'newbranch' will find a branch at
4614
    /path/to/newbranch.
3078.2.2 by Ian Clatworthy
get switch tests passing on heavyweight checkouts
4615
    """
2999.1.1 by Ian Clatworthy
migrate switch command into the core - was in BzrTools
4616
4617
    takes_args = ['to_location']
3078.2.2 by Ian Clatworthy
get switch tests passing on heavyweight checkouts
4618
    takes_options = [Option('force',
4619
                        help='Switch even if local commits will be lost.')
4620
                     ]
2999.1.1 by Ian Clatworthy
migrate switch command into the core - was in BzrTools
4621
3078.2.2 by Ian Clatworthy
get switch tests passing on heavyweight checkouts
4622
    def run(self, to_location, force=False):
2999.1.2 by Ian Clatworthy
incorporate review feedback including basic blackbox tests
4623
        from bzrlib import switch
2999.1.1 by Ian Clatworthy
migrate switch command into the core - was in BzrTools
4624
        tree_location = '.'
2999.1.2 by Ian Clatworthy
incorporate review feedback including basic blackbox tests
4625
        control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
3246.5.1 by Robert Collins
* ``bzr switch`` will attempt to find branches to switch to relative to the
4626
        try:
4627
            to_branch = Branch.open(to_location)
4628
        except errors.NotBranchError:
3602.3.2 by Adrian Wilkins
`bzr switch` now finds the sibling of the bound branch of a heavy checkout when passed a location that does not immediately resolve to a branch.
4629
            this_branch = control_dir.open_branch()
3602.3.4 by Adrian Wilkins
Improved comments and documentation
4630
            # This may be a heavy checkout, where we want the master branch
3602.3.3 by Adrian Wilkins
Tweaked as suggested to be more lightweight about opening branches.
4631
            this_url = this_branch.get_bound_location()
3602.3.4 by Adrian Wilkins
Improved comments and documentation
4632
            # If not, use a local sibling
3602.3.3 by Adrian Wilkins
Tweaked as suggested to be more lightweight about opening branches.
4633
            if this_url is None:
4634
                this_url = this_branch.base
3246.5.1 by Robert Collins
* ``bzr switch`` will attempt to find branches to switch to relative to the
4635
            to_branch = Branch.open(
3602.3.4 by Adrian Wilkins
Improved comments and documentation
4636
                urlutils.join(this_url, '..', to_location))
3078.2.2 by Ian Clatworthy
get switch tests passing on heavyweight checkouts
4637
        switch.switch(control_dir, to_branch, force)
2999.1.1 by Ian Clatworthy
migrate switch command into the core - was in BzrTools
4638
        note('Switched to branch: %s',
4639
            urlutils.unescape_for_display(to_branch.base, 'utf-8'))
4640
4641
3254.2.1 by Daniel Watkins
Added cmd_hooks.
4642
class cmd_hooks(Command):
4643
    """Show a branch's currently registered hooks.
4644
    """
4645
3254.2.9 by Daniel Watkins
Made cmd_hooks hidden.
4646
    hidden = True
3254.2.1 by Daniel Watkins
Added cmd_hooks.
4647
    takes_args = ['path?']
4648
4649
    def run(self, path=None):
4650
        if path is None:
4651
            path = '.'
4652
        branch_hooks = Branch.open(path).hooks
4653
        for hook_type in branch_hooks:
4654
            hooks = branch_hooks[hook_type]
3254.2.4 by Daniel Watkins
Changed output to conform to tests.
4655
            self.outf.write("%s:\n" % (hook_type,))
3254.2.1 by Daniel Watkins
Added cmd_hooks.
4656
            if hooks:
4657
                for hook in hooks:
3254.2.4 by Daniel Watkins
Changed output to conform to tests.
4658
                    self.outf.write("  %s\n" %
4659
                                    (branch_hooks.get_hook_name(hook),))
3254.2.1 by Daniel Watkins
Added cmd_hooks.
4660
            else:
3254.2.4 by Daniel Watkins
Changed output to conform to tests.
4661
                self.outf.write("  <no hooks installed>\n")
3254.2.1 by Daniel Watkins
Added cmd_hooks.
4662
4663
2524.1.1 by Aaron Bentley
Revert broken changes
4664
def _create_prefix(cur_transport):
4665
    needed = [cur_transport]
4666
    # Recurse upwards until we can create a directory successfully
4667
    while True:
4668
        new_transport = cur_transport.clone('..')
4669
        if new_transport.base == cur_transport.base:
2604.1.1 by Martin Pool
Fix unbound variable in _create_prefix (thanks vila)
4670
            raise errors.BzrCommandError(
4671
                "Failed to create path prefix for %s."
4672
                % cur_transport.base)
2524.1.1 by Aaron Bentley
Revert broken changes
4673
        try:
4674
            new_transport.mkdir('.')
4675
        except errors.NoSuchFile:
4676
            needed.append(new_transport)
4677
            cur_transport = new_transport
4678
        else:
4679
            break
4680
    # Now we only need to create child directories
4681
    while needed:
4682
        cur_transport = needed.pop()
4683
        cur_transport.ensure_base()
4684
2604.1.1 by Martin Pool
Fix unbound variable in _create_prefix (thanks vila)
4685
1185.16.33 by Martin Pool
- move 'conflict' and 'resolved' from shipped plugin to regular builtins
4686
# these get imported and then picked up by the scan for cmd_*
4687
# TODO: Some more consistent way to split command definitions across files;
4688
# 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'.
4689
# aliases.  ideally we would avoid loading the implementation until the
4690
# details were needed.
2022.1.2 by John Arbash Meinel
rename version_info => cmd_version_info
4691
from bzrlib.cmd_version_info import cmd_version_info
1185.35.4 by Aaron Bentley
Implemented remerge
4692
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore
2520.4.35 by Aaron Bentley
zap obsolete changeset commands, add bundle-info command
4693
from bzrlib.bundle.commands import (
4694
    cmd_bundle_info,
4695
    )
1185.78.6 by John Arbash Meinel
Adding sign-my-commits as a builtin, along with some simple tests.
4696
from bzrlib.sign_my_commits import cmd_sign_my_commits
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
4697
from bzrlib.weave_commands import cmd_versionedfile_list, \
1616.1.17 by Martin Pool
New 'weave-plan-merge' and 'weave-merge-text' commands lifted from weave.py
4698
        cmd_weave_plan_merge, cmd_weave_merge_text