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