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