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