/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
5557.1.7 by John Arbash Meinel
Merge in the bzr.dev 5582
1
# Copyright (C) 2005-2011 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
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
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
6207.3.11 by Jelmer Vernooij
Make sure bzrlib.bzrdir is imported.
21
import bzrlib.bzrdir
22
1996.3.1 by John Arbash Meinel
Demandloading builtins.py drops our load time from 350ms to 291ms
23
from bzrlib.lazy_import import lazy_import
24
lazy_import(globals(), """
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.
25
import cStringIO
6357.1.2 by Martin Packman
Don't complain on mkdir -p if a directory exists
26
import errno
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
27
import sys
1551.12.8 by Aaron Bentley
Add merge-directive command
28
import time
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
29
1773.4.2 by Martin Pool
Cleanup of imports; undeprecate all_revision_ids()
30
import bzrlib
1836.1.26 by John Arbash Meinel
[merge] bzr.dev 1869
31
from bzrlib import (
2376.4.22 by Jonathan Lange
Variety of whitespace cleanups, tightening of tests and docstring changes in
32
    bugtracker,
1836.1.26 by John Arbash Meinel
[merge] bzr.dev 1869
33
    bundle,
3770.1.2 by John Arbash Meinel
Add a --raw output for dump-btree.
34
    btree_index,
6207.3.3 by jelmer at samba
Fix tests and the like.
35
    controldir,
4879.2.1 by Neil Martinsen-Burrell
switch should use directory services when creating a branch
36
    directory_service,
2225.1.1 by Aaron Bentley
Added revert change display, with tests
37
    delta,
5345.5.9 by Vincent Ladeuil
Implements 'bzr lock --config <file>'.
38
    config as _mod_config,
1836.1.26 by John Arbash Meinel
[merge] bzr.dev 1869
39
    errors,
2298.8.1 by Kent Gibson
Normalise ignore patterns to use '/' path separator.
40
    globbing,
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
41
    hooks,
1836.1.26 by John Arbash Meinel
[merge] bzr.dev 1869
42
    log,
1996.3.5 by John Arbash Meinel
Cleanup, deprecated, and get the tests passing again.
43
    merge as _mod_merge,
1551.12.8 by Aaron Bentley
Add merge-directive command
44
    merge_directive,
1836.1.26 by John Arbash Meinel
[merge] bzr.dev 1869
45
    osutils,
2796.2.5 by Aaron Bentley
Implement reconfigure command
46
    reconfigure,
3193.8.18 by Aaron Bentley
Move all rename-guessing into RenameMap
47
    rename_map,
2598.5.1 by Aaron Bentley
Start eliminating the use of None to indicate null revision
48
    revision as _mod_revision,
4789.28.3 by John Arbash Meinel
Add a static_tuple.as_tuples() helper.
49
    static_tuple,
4766.2.1 by Alexander Sack
add --commit-time Option to built-in 'commit' command (LP: #459276)
50
    timestamp,
1836.1.26 by John Arbash Meinel
[merge] bzr.dev 1869
51
    transport,
52
    ui,
53
    urlutils,
3586.1.20 by Ian Clatworthy
centralise formatting of view file lists
54
    views,
5971.1.60 by Jonathan Riddell
move checking for gpgme availability into gpg.py
55
    gpg,
1836.1.26 by John Arbash Meinel
[merge] bzr.dev 1869
56
    )
1996.3.1 by John Arbash Meinel
Demandloading builtins.py drops our load time from 350ms to 291ms
57
from bzrlib.branch import Branch
2120.7.2 by Aaron Bentley
Move autoresolve functionality to workingtree
58
from bzrlib.conflicts import ConflictList
5017.3.45 by Vincent Ladeuil
Move MemoryServer back into bzrlib.transport.memory as it's needed as soon as a MemoryTransport is used. Add a NEWS entry.
59
from bzrlib.transport import memory
3936.3.40 by Ian Clatworthy
review feedback from jam
60
from bzrlib.revisionspec import RevisionSpec, RevisionInfo
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
61
from bzrlib.smtp_connection import SMTPConnection
1996.3.1 by John Arbash Meinel
Demandloading builtins.py drops our load time from 350ms to 291ms
62
from bzrlib.workingtree import WorkingTree
6143.1.1 by Jonathan Riddell
use ngettext for plurals
63
from bzrlib.i18n import gettext, ngettext
1996.3.1 by John Arbash Meinel
Demandloading builtins.py drops our load time from 350ms to 291ms
64
""")
65
5127.1.1 by Martin Pool
version-info is lazily loaded
66
from bzrlib.commands import (
67
    Command,
68
    builtin_command_registry,
69
    display_command,
70
    )
3921.3.9 by Marius Kruger
* add some blackbox tests and another whitebox test
71
from bzrlib.option import (
72
    ListOption,
73
    Option,
74
    RegistryOption,
75
    custom_help,
76
    _parse_revision_str,
77
    )
3874.1.4 by Vincent Ladeuil
Fixed as per Aarons' comment.
78
from bzrlib.trace import mutter, note, warning, is_quiet, get_verbosity_level
5904.1.1 by Martin Pool
Pyflakes-driven cleanups
79
from bzrlib import (
80
    symbol_versioning,
81
    )
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
82
83
5346.4.5 by Martin Pool
Deprecate and avoid internal_tree_files and tree_files.
84
@symbol_versioning.deprecated_function(symbol_versioning.deprecated_in((2, 3, 0)))
3586.1.32 by Ian Clatworthy
merge bzr.dev r3998
85
def tree_files(file_list, default_branch=u'.', canonicalize=True,
86
    apply_view=True):
5346.3.1 by Martin Pool
* `PathNotChild` should not give a traceback.
87
    return internal_tree_files(file_list, default_branch, canonicalize,
88
        apply_view)
1185.35.28 by Aaron Bentley
Support diff with two branches as input.
89
1185.85.12 by John Arbash Meinel
Refactoring AddAction to allow redirecting to an encoding file.
90
3586.1.34 by Ian Clatworthy
fix tree/path handling for add
91
def tree_files_for_add(file_list):
4301.2.2 by Aaron Bentley
Update style
92
    """
93
    Return a tree and list of absolute paths from a file list.
94
95
    Similar to tree_files, but add handles files a bit differently, so it a
96
    custom implementation.  In particular, MutableTreeTree.smart_add expects
97
    absolute paths, which it immediately converts to relative paths.
98
    """
99
    # FIXME Would be nice to just return the relative paths like
100
    # internal_tree_files does, but there are a large number of unit tests
101
    # that assume the current interface to mutabletree.smart_add
3586.1.34 by Ian Clatworthy
fix tree/path handling for add
102
    if file_list:
4301.1.1 by Geoff Bache
Fixing bug 183831, where 'bzr add' fails with a python stack if the path contains a symbolic link
103
        tree, relpath = WorkingTree.open_containing(file_list[0])
4301.2.5 by Aaron Bentley
Move file_list updates after view_files check.
104
        if tree.supports_views():
105
            view_files = tree.views.lookup_view()
106
            if view_files:
107
                for filename in file_list:
108
                    if not osutils.is_inside_any(view_files, filename):
109
                        raise errors.FileOutsideView(filename, view_files)
4301.2.4 by Aaron Bentley
Further cleanups
110
        file_list = file_list[:]
4301.2.3 by Aaron Bentley
Clean up tree_add_files
111
        file_list[0] = tree.abspath(relpath)
3586.1.34 by Ian Clatworthy
fix tree/path handling for add
112
    else:
113
        tree = WorkingTree.open_containing(u'.')[0]
114
        if tree.supports_views():
115
            view_files = tree.views.lookup_view()
116
            if view_files:
117
                file_list = view_files
118
                view_str = views.view_display_str(view_files)
6138.2.2 by Jonathan Riddell
gettext builtin.py's note() usage
119
                note(gettext("Ignoring files outside view. View is %s") % view_str)
4301.2.3 by Aaron Bentley
Clean up tree_add_files
120
    return tree, file_list
3586.1.34 by Ian Clatworthy
fix tree/path handling for add
121
122
3984.3.5 by Daniel Watkins
Changed from option type to helper function.
123
def _get_one_revision(command_name, revisions):
124
    if revisions is None:
125
        return None
126
    if len(revisions) != 1:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
127
        raise errors.BzrCommandError(gettext(
128
            'bzr %s --revision takes exactly one revision identifier') % (
3984.3.5 by Daniel Watkins
Changed from option type to helper function.
129
                command_name,))
130
    return revisions[0]
131
132
3732.1.1 by Ian Clatworthy
fix bzr st -rbranch:path-to-branch (Lukas Lalinsky)
133
def _get_one_revision_tree(command_name, revisions, branch=None, tree=None):
4595.13.2 by Alexander Belchenko
[cherrypick revno 4650 from bzr.dev] Fix shelve on windows. (Robert Collins, #305006)
134
    """Get a revision tree. Not suitable for commands that change the tree.
135
    
136
    Specifically, the basis tree in dirstate trees is coupled to the dirstate
137
    and doing a commit/uncommit/pull will at best fail due to changing the
138
    basis revision data.
139
140
    If tree is passed in, it should be already locked, for lifetime management
141
    of the trees internal cached state.
142
    """
3655.3.1 by Lukáš Lalinský
Fix `bzr st -rbranch:PATH_TO_BRANCH`
143
    if branch is None:
144
        branch = tree.branch
3732.1.1 by Ian Clatworthy
fix bzr st -rbranch:path-to-branch (Lukas Lalinsky)
145
    if revisions is None:
3655.3.1 by Lukáš Lalinský
Fix `bzr st -rbranch:PATH_TO_BRANCH`
146
        if tree is not None:
147
            rev_tree = tree.basis_tree()
148
        else:
149
            rev_tree = branch.basis_tree()
150
    else:
3984.3.5 by Daniel Watkins
Changed from option type to helper function.
151
        revision = _get_one_revision(command_name, revisions)
152
        rev_tree = revision.as_tree(branch)
3655.3.1 by Lukáš Lalinský
Fix `bzr st -rbranch:PATH_TO_BRANCH`
153
    return rev_tree
154
155
1658.1.9 by Martin Pool
Give an error for bzr diff on an nonexistent file (Malone #3619)
156
# XXX: Bad function name; should possibly also be a class method of
157
# WorkingTree rather than a function.
5346.4.5 by Martin Pool
Deprecate and avoid internal_tree_files and tree_files.
158
@symbol_versioning.deprecated_function(symbol_versioning.deprecated_in((2, 3, 0)))
3586.1.32 by Ian Clatworthy
merge bzr.dev r3998
159
def internal_tree_files(file_list, default_branch=u'.', canonicalize=True,
160
    apply_view=True):
1658.1.8 by Martin Pool
(internal_tree_files) Better docstring
161
    """Convert command-line paths to a WorkingTree and relative paths.
162
5346.4.2 by Martin Pool
Move internal_tree_files and safe_relpath_files onto WorkingTree
163
    Deprecated: use WorkingTree.open_containing_paths instead.
164
1658.1.8 by Martin Pool
(internal_tree_files) Better docstring
165
    This is typically used for command-line processors that take one or
166
    more filenames, and infer the workingtree that contains them.
167
168
    The filenames given are not required to exist.
169
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
170
    :param file_list: Filenames to convert.
1658.1.8 by Martin Pool
(internal_tree_files) Better docstring
171
2091.3.2 by Aaron Bentley
Traverse non-terminal symlinks for mv et al
172
    :param default_branch: Fallback tree path to use if file_list is empty or
173
        None.
1658.1.8 by Martin Pool
(internal_tree_files) Better docstring
174
3586.1.9 by Ian Clatworthy
first cut at view command
175
    :param apply_view: if True and a view is set, apply it or check that
176
        specified files are within it
177
1658.1.8 by Martin Pool
(internal_tree_files) Better docstring
178
    :return: workingtree, [relative_paths]
1185.12.101 by Aaron Bentley
Made commit take branch from first argument, if supplied.
179
    """
5346.4.2 by Martin Pool
Move internal_tree_files and safe_relpath_files onto WorkingTree
180
    return WorkingTree.open_containing_paths(
181
        file_list, default_directory='.',
182
        canonicalize=True,
183
        apply_view=True)
1553.5.78 by Martin Pool
New bzr init --format option and test
184
185
3586.1.31 by Ian Clatworthy
view filtering for pull, update & merge
186
def _get_view_info_for_change_reporter(tree):
187
    """Get the view information from a tree for change reporting."""
188
    view_info = None
189
    try:
190
        current_view = tree.views.get_view_info()[0]
191
        if current_view is not None:
192
            view_info = (current_view, tree.views.lookup_view())
193
    except errors.ViewsNotSupported:
194
        pass
195
    return view_info
196
197
5171.3.9 by Martin von Gagern
Rename function to _open_directory_or_containing_tree_or_branch.
198
def _open_directory_or_containing_tree_or_branch(filename, directory):
5171.3.3 by Martin von Gagern
Add --directory option to ls, cat and annotate.
199
    """Open the tree or branch containing the specified file, unless
200
    the --directory option is used to specify a different branch."""
201
    if directory is not None:
202
        return (None, Branch.open(directory), filename)
6207.3.3 by jelmer at samba
Fix tests and the like.
203
    return controldir.ControlDir.open_containing_tree_or_branch(filename)
5171.3.3 by Martin von Gagern
Add --directory option to ls, cat and annotate.
204
205
1185.16.112 by mbp at sourcefrog
todo
206
# TODO: Make sure no commands unconditionally use the working directory as a
207
# branch.  If a filename argument is used, the first of them should be used to
208
# specify the branch.  (Perhaps this can be factored out into some kind of
209
# Argument class, representing a file in a branch, where the first occurrence
210
# opens the branch?)
211
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
212
class cmd_status(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
213
    __doc__ = """Display status summary.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
214
215
    This reports on versioned and unknown files, reporting them
216
    grouped by state.  Possible states are:
217
1551.10.10 by Aaron Bentley
Add help text
218
    added
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
219
        Versioned in the working copy but not in the previous revision.
220
1551.10.10 by Aaron Bentley
Add help text
221
    removed
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
222
        Versioned in the previous revision but removed or deleted
223
        in the working copy.
224
1551.10.10 by Aaron Bentley
Add help text
225
    renamed
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
226
        Path of this file changed from the previous revision;
227
        the text may also have changed.  This includes files whose
228
        parent directory was renamed.
229
1551.10.10 by Aaron Bentley
Add help text
230
    modified
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
231
        Text has changed since the previous revision.
232
1551.10.10 by Aaron Bentley
Add help text
233
    kind changed
234
        File kind has been changed (e.g. from file to directory).
235
236
    unknown
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
237
        Not versioned and not matching an ignore pattern.
238
5945.2.1 by Martin von Gagern
Make kind markers optional.
239
    Additionally for directories, symlinks and files with a changed
240
    executable bit, Bazaar indicates their type using a trailing
241
    character: '/', '@' or '*' respectively. These decorations can be
5945.2.2 by Martin von Gagern
Change from no_decorate to classify as name for the argument.
242
    disabled using the '--no-classify' option.
4798.5.2 by Neil Martinsen-Burrell
Put discussion of type indicators in the appropriate place under status
243
2374.1.1 by Ian Clatworthy
Help and man page fixes
244
    To see ignored files use 'bzr ignored'.  For details on the
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
245
    changes to file texts, use 'bzr diff'.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
246
2792.1.1 by Ian Clatworthy
Add short options to status to assist migrating svn users (Daniel Watkins)
247
    Note that --short or -S gives status flags for each item, similar
248
    to Subversion's status command. To get output similar to svn -q,
4798.5.2 by Neil Martinsen-Burrell
Put discussion of type indicators in the appropriate place under status
249
    use bzr status -SV.
1551.10.10 by Aaron Bentley
Add help text
250
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
251
    If no arguments are specified, the status of the entire working
252
    directory is shown.  Otherwise, only the status of the specified
253
    files or directories is reported.  If a directory is given, status
254
    is reported for everything inside that directory.
1185.1.35 by Robert Collins
Heikki Paajanen's status -r patch
255
3936.2.2 by Ian Clatworthy
add NEWS item & improve status help
256
    Before merges are committed, the pending merge tip revisions are
257
    shown. To see all pending merge revisions, use the -v option.
258
    To skip the display of pending merge information altogether, use
259
    the no-pending option or specify a file/directory.
260
5432.7.2 by John C Barstow
Rewrite docs for bzr st revision argument
261
    To compare the working directory to a specific revision, pass a
262
    single revision to the revision argument.
263
5432.7.1 by John C Barstow
Clarify the usage of the revision argument for 'bzr st'
264
    To see which files have changed in a specific revision, or between
5432.7.2 by John C Barstow
Rewrite docs for bzr st revision argument
265
    two revisions, pass a revision range to the revision argument.
266
    This will produce the same results as calling 'bzr diff --summarize'.
1185.3.2 by Martin Pool
- remove -r option from status command because it's not used
267
    """
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
268
1185.16.76 by Martin Pool
doc
269
    # TODO: --no-recurse, --recurse options
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
270
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
271
    takes_args = ['file*']
3936.2.1 by Ian Clatworthy
verbose flag for status - code & tests
272
    takes_options = ['show-ids', 'revision', 'change', 'verbose',
2792.1.1 by Ian Clatworthy
Add short options to status to assist migrating svn users (Daniel Watkins)
273
                     Option('short', help='Use short status indicators.',
2663.1.7 by Daniel Watkins
Capitalised short names.
274
                            short_name='S'),
2663.1.5 by Daniel Watkins
Changed 'bzr stat --quiet' to 'bzr stat -(vs|sv)', as per list suggestions.
275
                     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)
276
                            short_name='V'),
277
                     Option('no-pending', help='Don\'t show pending merges.',
278
                           ),
5945.2.2 by Martin von Gagern
Change from no_decorate to classify as name for the argument.
279
                     Option('no-classify',
280
                            help='Do not mark object type using indicator.',
5945.2.1 by Martin von Gagern
Make kind markers optional.
281
                           ),
2663.1.5 by Daniel Watkins
Changed 'bzr stat --quiet' to 'bzr stat -(vs|sv)', as per list suggestions.
282
                     ]
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
283
    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()
284
285
    encoding_type = 'replace'
2520.1.3 by Daniel Watkins
'help status' now points to 'help status-flags'.
286
    _see_also = ['diff', 'revert', 'status-flags']
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
287
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
288
    @display_command
2318.2.1 by Kent Gibson
Apply status versioned patch
289
    def run(self, show_ids=False, file_list=None, revision=None, short=False,
5945.2.1 by Martin von Gagern
Make kind markers optional.
290
            versioned=False, no_pending=False, verbose=False,
5945.2.2 by Martin von Gagern
Change from no_decorate to classify as name for the argument.
291
            no_classify=False):
1551.2.9 by Aaron Bentley
Fix status to work with checkouts
292
        from bzrlib.status import show_tree_status
1185.85.15 by John Arbash Meinel
Updated bzr status, adding test_cat
293
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.
294
        if revision and len(revision) > 2:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
295
            raise errors.BzrCommandError(gettext('bzr status --revision takes exactly'
296
                                         ' 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)
297
5346.4.5 by Martin Pool
Deprecate and avoid internal_tree_files and tree_files.
298
        tree, relfile_list = WorkingTree.open_containing_paths(file_list)
3636.1.1 by Robert Collins
Stop passing specific_file lists to show_tree_status when the specific
299
        # Avoid asking for specific files when that is not needed.
300
        if relfile_list == ['']:
301
            relfile_list = None
302
            # Don't disable pending merges for full trees other than '.'.
303
            if file_list == ['.']:
304
                no_pending = True
305
        # A specific path within a tree was given.
306
        elif relfile_list is not None:
307
            no_pending = True
1773.1.2 by Robert Collins
Remove --all option from status.
308
        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
309
                         specific_files=relfile_list, revision=revision,
3270.6.1 by James Westby
Add --no-pending to status to not show the pending merges. (#202830)
310
                         to_file=self.outf, short=short, versioned=versioned,
5945.2.1 by Martin von Gagern
Make kind markers optional.
311
                         show_pending=(not no_pending), verbose=verbose,
5945.2.2 by Martin von Gagern
Change from no_decorate to classify as name for the argument.
312
                         classify=not no_classify)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
313
314
315
class cmd_cat_revision(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
316
    __doc__ = """Write out metadata for a revision.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
317
1185.5.3 by John Arbash Meinel
cat-revision allows --revision for easier investigation.
318
    The revision to print can either be specified by a specific
319
    revision identifier, or you can use --revision.
320
    """
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
321
322
    hidden = True
1185.5.3 by John Arbash Meinel
cat-revision allows --revision for easier investigation.
323
    takes_args = ['revision_id?']
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
324
    takes_options = ['directory', 'revision']
1685.1.76 by Wouter van Heyst
codecleanup
325
    # cat-revision is more for frontends so should be exact
326
    encoding = 'strict'
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
327
5035.2.1 by Jelmer Vernooij
Repository.get_revision_xml() has been removed.
328
    def print_revision(self, revisions, revid):
329
        stream = revisions.get_record_stream([(revid,)], 'unordered', True)
330
        record = stream.next()
331
        if record.storage_kind == 'absent':
332
            raise errors.NoSuchRevision(revisions, revid)
333
        revtext = record.get_bytes_as('fulltext')
334
        self.outf.write(revtext.decode('utf-8'))
335
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
336
    @display_command
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
337
    def run(self, revision_id=None, revision=None, directory=u'.'):
1185.5.3 by John Arbash Meinel
cat-revision allows --revision for easier investigation.
338
        if revision_id is not None and revision is not None:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
339
            raise errors.BzrCommandError(gettext('You can only supply one of'
340
                                         ' revision_id or --revision'))
1185.5.3 by John Arbash Meinel
cat-revision allows --revision for easier investigation.
341
        if revision_id is None and revision is None:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
342
            raise errors.BzrCommandError(gettext('You must supply either'
343
                                         ' --revision or a revision_id'))
5616.4.1 by Jelmer Vernooij
'bzr cat-revision' no longer requires a working tree.
344
6207.3.3 by jelmer at samba
Fix tests and the like.
345
        b = controldir.ControlDir.open_containing_tree_or_branch(directory)[1]
1185.85.72 by John Arbash Meinel
Fix some of the tests.
346
5035.2.1 by Jelmer Vernooij
Repository.get_revision_xml() has been removed.
347
        revisions = b.repository.revisions
348
        if revisions is None:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
349
            raise errors.BzrCommandError(gettext('Repository %r does not support '
350
                'access to raw revision texts'))
3770.1.1 by John Arbash Meinel
First draft of a basic dump-btree command.
351
5035.2.1 by Jelmer Vernooij
Repository.get_revision_xml() has been removed.
352
        b.repository.lock_read()
353
        try:
354
            # TODO: jam 20060112 should cat-revision always output utf-8?
355
            if revision_id is not None:
356
                revision_id = osutils.safe_revision_id(revision_id, warn=False)
357
                try:
358
                    self.print_revision(revisions, revision_id)
359
                except errors.NoSuchRevision:
6138.2.4 by Jonathan Riddell
use format strings where there are multiple substitutions to allow for translations
360
                    msg = gettext("The repository {0} contains no revision {1}.").format(
5035.2.1 by Jelmer Vernooij
Repository.get_revision_xml() has been removed.
361
                        b.repository.base, revision_id)
362
                    raise errors.BzrCommandError(msg)
363
            elif revision is not None:
364
                for rev in revision:
365
                    if rev is None:
366
                        raise errors.BzrCommandError(
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
367
                            gettext('You cannot specify a NULL revision.'))
5035.2.1 by Jelmer Vernooij
Repository.get_revision_xml() has been removed.
368
                    rev_id = rev.as_revision_id(b)
369
                    self.print_revision(revisions, rev_id)
370
        finally:
371
            b.repository.unlock()
372
        
3770.1.1 by John Arbash Meinel
First draft of a basic dump-btree command.
373
374
class cmd_dump_btree(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
375
    __doc__ = """Dump the contents of a btree index file to stdout.
3770.1.4 by John Arbash Meinel
Clarify the help text a bit.
376
377
    PATH is a btree index file, it can be any URL. This includes things like
378
    .bzr/repository/pack-names, or .bzr/repository/indices/a34b3a...ca4a4.iix
379
380
    By default, the tuples stored in the index file will be displayed. With
381
    --raw, we will uncompress the pages, but otherwise display the raw bytes
382
    stored in the index.
3770.1.1 by John Arbash Meinel
First draft of a basic dump-btree command.
383
    """
384
385
    # TODO: Do we want to dump the internal nodes as well?
386
    # TODO: It would be nice to be able to dump the un-parsed information,
387
    #       rather than only going through iter_all_entries. However, this is
388
    #       good enough for a start
389
    hidden = True
3770.1.2 by John Arbash Meinel
Add a --raw output for dump-btree.
390
    encoding_type = 'exact'
3770.1.1 by John Arbash Meinel
First draft of a basic dump-btree command.
391
    takes_args = ['path']
3770.1.2 by John Arbash Meinel
Add a --raw output for dump-btree.
392
    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'
393
                                        ' rather than the parsed tuples.'),
3770.1.2 by John Arbash Meinel
Add a --raw output for dump-btree.
394
                    ]
395
396
    def run(self, path, raw=False):
3770.1.1 by John Arbash Meinel
First draft of a basic dump-btree command.
397
        dirname, basename = osutils.split(path)
398
        t = transport.get_transport(dirname)
3770.1.2 by John Arbash Meinel
Add a --raw output for dump-btree.
399
        if raw:
400
            self._dump_raw_bytes(t, basename)
401
        else:
402
            self._dump_entries(t, basename)
403
404
    def _get_index_and_bytes(self, trans, basename):
405
        """Create a BTreeGraphIndex and raw bytes."""
406
        bt = btree_index.BTreeGraphIndex(trans, basename, None)
407
        bytes = trans.get_bytes(basename)
408
        bt._file = cStringIO.StringIO(bytes)
409
        bt._size = len(bytes)
410
        return bt, bytes
411
412
    def _dump_raw_bytes(self, trans, basename):
413
        import zlib
414
415
        # We need to parse at least the root node.
416
        # This is because the first page of every row starts with an
417
        # uncompressed header.
418
        bt, bytes = self._get_index_and_bytes(trans, basename)
3770.1.3 by John Arbash Meinel
Simplify the --raw mode.
419
        for page_idx, page_start in enumerate(xrange(0, len(bytes),
420
                                                     btree_index._PAGE_SIZE)):
421
            page_end = min(page_start + btree_index._PAGE_SIZE, len(bytes))
422
            page_bytes = bytes[page_start:page_end]
423
            if page_idx == 0:
3770.1.2 by John Arbash Meinel
Add a --raw output for dump-btree.
424
                self.outf.write('Root node:\n')
3770.1.3 by John Arbash Meinel
Simplify the --raw mode.
425
                header_end, data = bt._parse_header_from_bytes(page_bytes)
426
                self.outf.write(page_bytes[:header_end])
427
                page_bytes = data
428
            self.outf.write('\nPage %d\n' % (page_idx,))
5651.2.1 by Eric Siegerman
Fix traceback attempting to "bzr dump-btree --raw btree-with-0-rows".
429
            if len(page_bytes) == 0:
430
                self.outf.write('(empty)\n');
431
            else:
432
                decomp_bytes = zlib.decompress(page_bytes)
433
                self.outf.write(decomp_bytes)
434
                self.outf.write('\n')
3770.1.2 by John Arbash Meinel
Add a --raw output for dump-btree.
435
436
    def _dump_entries(self, trans, basename):
3770.1.1 by John Arbash Meinel
First draft of a basic dump-btree command.
437
        try:
3770.1.2 by John Arbash Meinel
Add a --raw output for dump-btree.
438
            st = trans.stat(basename)
3770.1.1 by John Arbash Meinel
First draft of a basic dump-btree command.
439
        except errors.TransportNotPossible:
440
            # We can't stat, so we'll fake it because we have to do the 'get()'
441
            # anyway.
3770.1.2 by John Arbash Meinel
Add a --raw output for dump-btree.
442
            bt, _ = self._get_index_and_bytes(trans, basename)
3770.1.1 by John Arbash Meinel
First draft of a basic dump-btree command.
443
        else:
3770.1.2 by John Arbash Meinel
Add a --raw output for dump-btree.
444
            bt = btree_index.BTreeGraphIndex(trans, basename, st.st_size)
3770.1.1 by John Arbash Meinel
First draft of a basic dump-btree command.
445
        for node in bt.iter_all_entries():
446
            # Node is made up of:
447
            # (index, key, value, [references])
5091.1.1 by Andrew Bennetts
Fix dump-btree to handle *.cix and *.six files.
448
            try:
449
                refs = node[3]
450
            except IndexError:
451
                refs_as_tuples = None
452
            else:
453
                refs_as_tuples = static_tuple.as_tuples(refs)
4679.8.9 by John Arbash Meinel
Cast objects back to tuples for 'dump-btree'
454
            as_tuple = (tuple(node[1]), node[2], refs_as_tuples)
455
            self.outf.write('%s\n' % (as_tuple,))
3770.1.1 by John Arbash Meinel
First draft of a basic dump-btree command.
456
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
457
2127.2.1 by Daniel Silverstone
Add remove-tree and its blackbox tests
458
class cmd_remove_tree(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
459
    __doc__ = """Remove the working tree from a given branch/checkout.
2127.2.1 by Daniel Silverstone
Add remove-tree and its blackbox tests
460
461
    Since a lightweight checkout is little more than a working tree
462
    this will refuse to run against one.
2374.1.3 by Ian Clatworthy
Minor man page fixes for add, commit, export
463
2374.1.4 by Ian Clatworthy
Include feedback from mailing list.
464
    To re-create the working tree, use "bzr checkout".
2127.2.1 by Daniel Silverstone
Add remove-tree and its blackbox tests
465
    """
2485.1.2 by James Westby
Update with comments from review, thanks to John and Aaron.
466
    _see_also = ['checkout', 'working-trees']
4748.1.1 by Jared Hance
Fixed bug by changing location to a list and iterating through list.
467
    takes_args = ['location*']
3667.2.1 by Lukáš Lalinský
Make `bzr remove-tree` not remove trees with uncommitted changes by default
468
    takes_options = [
469
        Option('force',
470
               help='Remove the working tree even if it has '
5268.3.1 by Matt Giuca
remove-tree now refuses to run without --force if there are shelved changes.
471
                    'uncommitted or shelved changes.'),
3667.2.1 by Lukáš Lalinský
Make `bzr remove-tree` not remove trees with uncommitted changes by default
472
        ]
2127.2.1 by Daniel Silverstone
Add remove-tree and its blackbox tests
473
4748.1.1 by Jared Hance
Fixed bug by changing location to a list and iterating through list.
474
    def run(self, location_list, force=False):
475
        if not location_list:
476
            location_list=['.']
477
478
        for location in location_list:
6207.3.3 by jelmer at samba
Fix tests and the like.
479
            d = controldir.ControlDir.open(location)
480
4748.1.1 by Jared Hance
Fixed bug by changing location to a list and iterating through list.
481
            try:
482
                working = d.open_workingtree()
483
            except errors.NoWorkingTree:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
484
                raise errors.BzrCommandError(gettext("No working tree to remove"))
4748.1.1 by Jared Hance
Fixed bug by changing location to a list and iterating through list.
485
            except errors.NotLocalUrl:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
486
                raise errors.BzrCommandError(gettext("You cannot remove the working tree"
487
                                             " of a remote path"))
4748.1.1 by Jared Hance
Fixed bug by changing location to a list and iterating through list.
488
            if not force:
489
                if (working.has_changes()):
490
                    raise errors.UncommittedChanges(working)
5268.3.1 by Matt Giuca
remove-tree now refuses to run without --force if there are shelved changes.
491
                if working.get_shelf_manager().last_shelf() is not None:
492
                    raise errors.ShelvedChanges(working)
4748.1.1 by Jared Hance
Fixed bug by changing location to a list and iterating through list.
493
5158.6.9 by Martin Pool
Simplify various code to use user_url
494
            if working.user_url != working.branch.user_url:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
495
                raise errors.BzrCommandError(gettext("You cannot remove the working tree"
496
                                             " from a lightweight checkout"))
4748.1.1 by Jared Hance
Fixed bug by changing location to a list and iterating through list.
497
4748.1.9 by Andrew Bennetts
Fix bug introduced by the change to take multiple locations, and add a test for multiple locations.
498
            d.destroy_workingtree()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
499
2127.2.1 by Daniel Silverstone
Add remove-tree and its blackbox tests
500
5630.2.8 by John Arbash Meinel
Rename the command to 'repair-workingtree' as mentioned by vila.
501
class cmd_repair_workingtree(Command):
5630.2.1 by John Arbash Meinel
Rough outline of what I'm trying to accomplish, docs, etc.
502
    __doc__ = """Reset the working tree state file.
503
504
    This is not meant to be used normally, but more as a way to recover from
505
    filesystem corruption, etc. This rebuilds the working inventory back to a
506
    'known good' state. Any new modifications (adding a file, renaming, etc)
507
    will be lost, though modified files will still be detected as such.
508
509
    Most users will want something more like "bzr revert" or "bzr update"
510
    unless the state file has become corrupted.
511
512
    By default this attempts to recover the current state by looking at the
513
    headers of the state file. If the state file is too corrupted to even do
514
    that, you can supply --revision to force the state of the tree.
515
    """
516
5630.2.7 by John Arbash Meinel
Handle --force flags and propmting the user for what they might really want.
517
    takes_options = ['revision', 'directory',
518
        Option('force',
519
               help='Reset the tree even if it doesn\'t appear to be'
520
                    ' corrupted.'),
521
    ]
5630.2.1 by John Arbash Meinel
Rough outline of what I'm trying to accomplish, docs, etc.
522
    hidden = True
523
5630.2.7 by John Arbash Meinel
Handle --force flags and propmting the user for what they might really want.
524
    def run(self, revision=None, directory='.', force=False):
525
        tree, _ = WorkingTree.open_containing(directory)
526
        self.add_cleanup(tree.lock_tree_write().unlock)
527
        if not force:
528
            try:
529
                tree.check_state()
530
            except errors.BzrError:
531
                pass # There seems to be a real error here, so we'll reset
532
            else:
533
                # Refuse
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
534
                raise errors.BzrCommandError(gettext(
5630.2.7 by John Arbash Meinel
Handle --force flags and propmting the user for what they might really want.
535
                    'The tree does not appear to be corrupt. You probably'
536
                    ' want "bzr revert" instead. Use "--force" if you are'
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
537
                    ' sure you want to reset the working tree.'))
5630.2.7 by John Arbash Meinel
Handle --force flags and propmting the user for what they might really want.
538
        if revision is None:
539
            revision_ids = None
540
        else:
541
            revision_ids = [r.as_revision_id(tree.branch) for r in revision]
542
        try:
543
            tree.reset_state(revision_ids)
544
        except errors.BzrError, e:
545
            if revision_ids is None:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
546
                extra = (gettext(', the header appears corrupt, try passing -r -1'
547
                         ' to set the state to the last commit'))
5630.2.7 by John Arbash Meinel
Handle --force flags and propmting the user for what they might really want.
548
            else:
549
                extra = ''
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
550
            raise errors.BzrCommandError(gettext('failed to reset the tree state{0}').format(extra))
5630.2.1 by John Arbash Meinel
Rough outline of what I'm trying to accomplish, docs, etc.
551
552
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
553
class cmd_revno(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
554
    __doc__ = """Show current revision number.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
555
1185.85.24 by John Arbash Meinel
Moved run_bzr_decode into TestCase
556
    This is equal to the number of revisions on this branch.
557
    """
558
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
559
    _see_also = ['info']
1185.50.16 by John Arbash Meinel
[patch] Michael Ellerman: 'Trivial patch to allow revno to take a location'
560
    takes_args = ['location?']
4409.1.1 by Matthew Fuller
Add a --tree option to revno.
561
    takes_options = [
6259.2.5 by Martin Packman
Add full stops to various option help text so test_option_grammar passes
562
        Option('tree', help='Show revno of working tree.'),
6202.1.1 by Jelmer Vernooij
'bzr revno' now takes a --revision argument.
563
        'revision',
4409.1.1 by Matthew Fuller
Add a --tree option to revno.
564
        ]
1185.85.24 by John Arbash Meinel
Moved run_bzr_decode into TestCase
565
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
566
    @display_command
6202.1.1 by Jelmer Vernooij
'bzr revno' now takes a --revision argument.
567
    def run(self, tree=False, location=u'.', revision=None):
568
        if revision is not None and tree:
569
            raise errors.BzrCommandError(gettext("--tree and --revision can "
570
                "not be used together"))
571
4409.1.21 by Vincent Ladeuil
Fix failing test.
572
        if tree:
573
            try:
574
                wt = WorkingTree.open_containing(location)[0]
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
575
                self.add_cleanup(wt.lock_read().unlock)
4409.1.21 by Vincent Ladeuil
Fix failing test.
576
            except (errors.NoWorkingTree, errors.NotLocalUrl):
577
                raise errors.NoWorkingTree(location)
6202.1.1 by Jelmer Vernooij
'bzr revno' now takes a --revision argument.
578
            b = wt.branch
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
579
            revid = wt.last_revision()
4409.1.21 by Vincent Ladeuil
Fix failing test.
580
        else:
581
            b = Branch.open_containing(location)[0]
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
582
            self.add_cleanup(b.lock_read().unlock)
6202.1.1 by Jelmer Vernooij
'bzr revno' now takes a --revision argument.
583
            if revision:
584
                if len(revision) != 1:
585
                    raise errors.BzrCommandError(gettext(
586
                        "Tags can only be placed on a single revision, "
587
                        "not on a range"))
588
                revid = revision[0].as_revision_id(b)
589
            else:
590
                revid = b.last_revision()
591
        try:
592
            revno_t = b.revision_id_to_dotted_revno(revid)
593
        except errors.NoSuchRevision:
594
            revno_t = ('???',)
595
        revno = ".".join(str(n) for n in revno_t)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
596
        self.cleanup_now()
6202.1.1 by Jelmer Vernooij
'bzr revno' now takes a --revision argument.
597
        self.outf.write(revno + '\n')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
598
1182 by Martin Pool
- more disentangling of xml storage format from objects
599
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
600
class cmd_revision_info(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
601
    __doc__ = """Show revision number and revision id for a given revision identifier.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
602
    """
603
    hidden = True
604
    takes_args = ['revision_info*']
3886.1.1 by Michael Hudson
support -d in the revision-info command
605
    takes_options = [
606
        'revision',
5171.3.1 by Martin von Gagern
Turn --directory and -d into a global option.
607
        custom_help('directory',
3886.1.1 by Michael Hudson
support -d in the revision-info command
608
            help='Branch to examine, '
5171.3.1 by Martin von Gagern
Turn --directory and -d into a global option.
609
                 'rather than the one containing the working directory.'),
6259.2.5 by Martin Packman
Add full stops to various option help text so test_option_grammar passes
610
        Option('tree', help='Show revno of working tree.'),
3886.1.1 by Michael Hudson
support -d in the revision-info command
611
        ]
1185.85.24 by John Arbash Meinel
Moved run_bzr_decode into TestCase
612
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
613
    @display_command
4409.1.3 by Matthew Fuller
Add --tree option to revision-info too.
614
    def run(self, revision=None, directory=u'.', tree=False,
615
            revision_info_list=[]):
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
616
4409.1.10 by John Arbash Meinel
Clean up 'bzr revision-info' to support revision not in the branch history.
617
        try:
618
            wt = WorkingTree.open_containing(directory)[0]
619
            b = wt.branch
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
620
            self.add_cleanup(wt.lock_read().unlock)
4409.1.10 by John Arbash Meinel
Clean up 'bzr revision-info' to support revision not in the branch history.
621
        except (errors.NoWorkingTree, errors.NotLocalUrl):
622
            wt = None
623
            b = Branch.open_containing(directory)[0]
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
624
            self.add_cleanup(b.lock_read().unlock)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
625
        revision_ids = []
626
        if revision is not None:
627
            revision_ids.extend(rev.as_revision_id(b) for rev in revision)
628
        if revision_info_list is not None:
629
            for rev_str in revision_info_list:
630
                rev_spec = RevisionSpec.from_string(rev_str)
631
                revision_ids.append(rev_spec.as_revision_id(b))
632
        # No arguments supplied, default to the last revision
633
        if len(revision_ids) == 0:
634
            if tree:
635
                if wt is None:
636
                    raise errors.NoWorkingTree(directory)
637
                revision_ids.append(wt.last_revision())
4409.1.3 by Matthew Fuller
Add --tree option to revision-info too.
638
            else:
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
639
                revision_ids.append(b.last_revision())
640
641
        revinfos = []
642
        maxlen = 0
643
        for revision_id in revision_ids:
644
            try:
645
                dotted_revno = b.revision_id_to_dotted_revno(revision_id)
646
                revno = '.'.join(str(i) for i in dotted_revno)
647
            except errors.NoSuchRevision:
648
                revno = '???'
649
            maxlen = max(maxlen, len(revno))
650
            revinfos.append([revno, revision_id])
651
652
        self.cleanup_now()
4409.2.1 by Matthew Fuller
Rework revision-info command so that it:
653
        for ri in revinfos:
4409.1.17 by Matthew Fuller
Merge in revision-info cleanups and changes.
654
            self.outf.write('%*s %s\n' % (maxlen, ri[0], ri[1]))
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
655
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
656
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
657
class cmd_add(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
658
    __doc__ = """Add specified files or directories.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
659
660
    In non-recursive mode, all the named items are added, regardless
661
    of whether they were previously ignored.  A warning is given if
662
    any of the named files are already versioned.
663
664
    In recursive mode (the default), files are treated the same way
665
    but the behaviour for directories is different.  Directories that
666
    are already versioned do not give a warning.  All directories,
667
    whether already versioned or not, are searched for files or
668
    subdirectories that are neither versioned or ignored, and these
669
    are added.  This search proceeds recursively into versioned
670
    directories.  If no names are given '.' is assumed.
671
6159.1.1 by Jelmer Vernooij
Add note about warning on nested trees.
672
    A warning will be printed when nested trees are encountered,
673
    unless they are explicitly ignored.
674
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
675
    Therefore simply saying 'bzr add' will version all files that
676
    are currently unknown.
677
1185.3.3 by Martin Pool
- patch from mpe to automatically add parent directories
678
    Adding a file whose parent directory is not versioned will
679
    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).
680
    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
681
    get added when you add a file in the directory.
1185.33.90 by Martin Pool
[merge] add --dry-run option (mpe)
682
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
683
    --dry-run will show which files would be added, but not actually
1185.33.90 by Martin Pool
[merge] add --dry-run option (mpe)
684
    add them.
1911.3.2 by John Arbash Meinel
Adding the AddFromBaseAction, which tries to reuse file ids from another tree
685
686
    --file-ids-from will try to use the file ids from the supplied path.
687
    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
688
    same filename, and then by pure path. This option is rarely needed
689
    but can be useful when adding the same logical file into two
690
    branches that will be merged later (without showing the two different
2374.1.4 by Ian Clatworthy
Include feedback from mailing list.
691
    adds as a conflict). It is also useful when merging another project
692
    into a subdirectory of this one.
4595.1.1 by Jason Spashett
Further tweaks to bzr add
693
    
4595.1.2 by Martin Pool
typo
694
    Any files matching patterns in the ignore list will not be added
4595.1.1 by Jason Spashett
Further tweaks to bzr add
695
    unless they are explicitly mentioned.
6046.2.5 by Shannon Weyrick
Document add.maximum_file_size more
696
    
6046.2.9 by Shannon Weyrick
Make it explicit in docs that large file skips happen only in recursive mode. Add test.
697
    In recursive mode, files larger than the configuration option 
698
    add.maximum_file_size will be skipped. Named items are never skipped due
699
    to file size.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
700
    """
701
    takes_args = ['file*']
2598.1.10 by Martin Pool
Clean up options that are registered globally and used once or not at all.
702
    takes_options = [
703
        Option('no-recurse',
2598.1.11 by Martin Pool
Insist that all options have a help string and fix those that don't.
704
               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.
705
        Option('dry-run',
706
               help="Show what would be done, but don't actually do anything."),
707
        'verbose',
708
        Option('file-ids-from',
709
               type=unicode,
710
               help='Lookup file ids from this tree.'),
711
        ]
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()
712
    encoding_type = 'replace'
4595.1.1 by Jason Spashett
Further tweaks to bzr add
713
    _see_also = ['remove', 'ignore']
1185.53.1 by Michael Ellerman
Add support for bzr add --dry-run
714
1911.3.2 by John Arbash Meinel
Adding the AddFromBaseAction, which tries to reuse file ids from another tree
715
    def run(self, file_list, no_recurse=False, dry_run=False, verbose=False,
716
            file_ids_from=None):
1185.53.1 by Michael Ellerman
Add support for bzr add --dry-run
717
        import bzrlib.add
718
2255.7.69 by Robert Collins
Fix all blackbox add tests, and the add --from-ids case in the UI.
719
        base_tree = None
1911.3.2 by John Arbash Meinel
Adding the AddFromBaseAction, which tries to reuse file ids from another tree
720
        if file_ids_from is not None:
721
            try:
722
                base_tree, base_path = WorkingTree.open_containing(
723
                                            file_ids_from)
724
            except errors.NoWorkingTree:
1996.3.1 by John Arbash Meinel
Demandloading builtins.py drops our load time from 350ms to 291ms
725
                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
726
                                            file_ids_from)
727
                base_tree = base_branch.basis_tree()
728
729
            action = bzrlib.add.AddFromBaseAction(base_tree, base_path,
730
                          to_file=self.outf, should_print=(not is_quiet()))
731
        else:
6046.2.4 by Shannon Weyrick
Change AddAction interface to include a method for deciding whether to
732
            action = bzrlib.add.AddWithSkipLargeAction(to_file=self.outf,
1911.3.2 by John Arbash Meinel
Adding the AddFromBaseAction, which tries to reuse file ids from another tree
733
                should_print=(not is_quiet()))
734
2255.7.69 by Robert Collins
Fix all blackbox add tests, and the add --from-ids case in the UI.
735
        if base_tree:
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
736
            self.add_cleanup(base_tree.lock_read().unlock)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
737
        tree, file_list = tree_files_for_add(file_list)
738
        added, ignored = tree.smart_add(file_list, not
739
            no_recurse, action=action, save=not dry_run)
740
        self.cleanup_now()
1185.46.8 by Aaron Bentley
bzr add reports ignored patterns.
741
        if len(ignored) > 0:
1711.1.2 by Robert Collins
'bzr add' is now less verbose in telling you what ignore globs were
742
            if verbose:
743
                for glob in sorted(ignored.keys()):
1185.46.9 by Aaron Bentley
Added verbose option to bzr add, to list all ignored files.
744
                    for path in ignored[glob]:
6138.2.4 by Jonathan Riddell
use format strings where there are multiple substitutions to allow for translations
745
                        self.outf.write(
746
                         gettext("ignored {0} matching \"{1}\"\n").format(
747
                         path, glob))
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
748
749
750
class cmd_mkdir(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
751
    __doc__ = """Create a new versioned directory.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
752
753
    This is equivalent to creating the directory and then adding it.
754
    """
1685.1.80 by Wouter van Heyst
more code cleanup
755
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
756
    takes_args = ['dir+']
6352.1.1 by Jelmer Vernooij
add blackbox tests for mkdir.
757
    takes_options = [
4744.4.1 by Jared Hance
Added -p (--parents) option to "bzr mkdir" (For adding directories recursively)
758
        Option(
759
            'parents',
4744.4.10 by Jared Hance
Fix help message and change "None" to "False" because it is a boolean variable.
760
            help='No error if existing, make parent directories as needed.',
4744.4.1 by Jared Hance
Added -p (--parents) option to "bzr mkdir" (For adding directories recursively)
761
            short_name='p'
762
            )
6352.1.1 by Jelmer Vernooij
add blackbox tests for mkdir.
763
        ]
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()
764
    encoding_type = 'replace'
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
765
6352.1.5 by Jelmer Vernooij
make add_files a class method rather than nested.
766
    @classmethod
767
    def add_file_with_parents(cls, wt, relpath):
768
        if wt.path2id(relpath) is not None:
769
            return
770
        cls.add_file_with_parents(wt, osutils.dirname(relpath))
771
        wt.add([relpath])
772
773
    @classmethod
774
    def add_file_single(cls, wt, relpath):
775
        wt.add([relpath])
776
4744.4.10 by Jared Hance
Fix help message and change "None" to "False" because it is a boolean variable.
777
    def run(self, dir_list, parents=False):
6352.1.2 by Jelmer Vernooij
Merge mkdir work from Jared Hance.
778
        if parents:
6352.1.5 by Jelmer Vernooij
make add_files a class method rather than nested.
779
            add_file = self.add_file_with_parents
6352.1.2 by Jelmer Vernooij
Merge mkdir work from Jared Hance.
780
        else:
6352.1.5 by Jelmer Vernooij
make add_files a class method rather than nested.
781
            add_file = self.add_file_single
6352.1.4 by Jelmer Vernooij
Fix tests.
782
        for dir in dir_list:
783
            wt, relpath = WorkingTree.open_containing(dir)
4744.4.10 by Jared Hance
Fix help message and change "None" to "False" because it is a boolean variable.
784
            if parents:
6357.1.2 by Martin Packman
Don't complain on mkdir -p if a directory exists
785
                try:
786
                    os.makedirs(dir)
787
                except OSError, e:
788
                    if e.errno != errno.EEXIST:
789
                        raise
4744.4.2 by Jared Hance
Forgot to use -p originally and automatically assumed to recursively add. Fixed.
790
            else:
6352.1.4 by Jelmer Vernooij
Fix tests.
791
                os.mkdir(dir)
6352.1.5 by Jelmer Vernooij
make add_files a class method rather than nested.
792
            add_file(wt, relpath)
6352.1.2 by Jelmer Vernooij
Merge mkdir work from Jared Hance.
793
            if not is_quiet():
6352.1.4 by Jelmer Vernooij
Fix tests.
794
                self.outf.write(gettext('added %s\n') % dir)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
795
796
797
class cmd_relpath(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
798
    __doc__ = """Show path of a file relative to root"""
1685.1.80 by Wouter van Heyst
more code cleanup
799
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
800
    takes_args = ['filename']
801
    hidden = True
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
802
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
803
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
804
    def run(self, filename):
1185.85.19 by John Arbash Meinel
Updated bzr relpath
805
        # TODO: jam 20050106 Can relpath return a munged path if
806
        #       sys.stdout encoding cannot represent it?
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
807
        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()
808
        self.outf.write(relpath)
809
        self.outf.write('\n')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
810
811
812
class cmd_inventory(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
813
    __doc__ = """Show inventory of the current working copy or a revision.
1185.33.33 by Martin Pool
[patch] add 'bzr inventory --kind directory'; remove 'bzr directories'
814
815
    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'
816
    type using the --kind option.  For example: --kind file.
817
818
    It is also possible to restrict the list of files to a specific
819
    set. For example: bzr inventory --show-ids this/file
1185.33.33 by Martin Pool
[patch] add 'bzr inventory --kind directory'; remove 'bzr directories'
820
    """
1685.1.80 by Wouter van Heyst
more code cleanup
821
1551.10.13 by Aaron Bentley
Hide 'unknowns', document alterntatives to hidden commands
822
    hidden = True
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
823
    _see_also = ['ls']
2598.1.11 by Martin Pool
Insist that all options have a help string and fix those that don't.
824
    takes_options = [
825
        'revision',
826
        'show-ids',
827
        Option('kind',
2598.1.12 by Martin Pool
Fix up --kind options
828
               help='List entries of a particular kind: file, directory, symlink.',
829
               type=unicode),
2598.1.11 by Martin Pool
Insist that all options have a help string and fix those that don't.
830
        ]
2027.4.2 by John Arbash Meinel
Fix bug #3631, allow 'bzr inventory filename'
831
    takes_args = ['file*']
832
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
833
    @display_command
2027.4.2 by John Arbash Meinel
Fix bug #3631, allow 'bzr inventory filename'
834
    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'
835
        if kind and kind not in ['file', 'directory', 'symlink']:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
836
            raise errors.BzrCommandError(gettext('invalid kind %r specified') % (kind,))
2027.4.3 by John Arbash Meinel
Change how 'bzr inventory' finds paths
837
3984.3.7 by Daniel Watkins
Fixed incorrect calls.
838
        revision = _get_one_revision('inventory', revision)
5346.4.5 by Martin Pool
Deprecate and avoid internal_tree_files and tree_files.
839
        work_tree, file_list = WorkingTree.open_containing_paths(file_list)
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
840
        self.add_cleanup(work_tree.lock_read().unlock)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
841
        if revision is not None:
842
            tree = revision.as_tree(work_tree.branch)
843
844
            extra_trees = [work_tree]
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
845
            self.add_cleanup(tree.lock_read().unlock)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
846
        else:
847
            tree = work_tree
848
            extra_trees = []
849
850
        if file_list is not None:
851
            file_ids = tree.paths2ids(file_list, trees=extra_trees,
852
                                      require_versioned=True)
853
            # find_ids_across_trees may include some paths that don't
854
            # exist in 'tree'.
5967.7.1 by Martin Pool
Deprecate __contains__ on Tree and Inventory
855
            entries = sorted(
856
                (tree.id2path(file_id), tree.inventory[file_id])
857
                for file_id in file_ids if tree.has_id(file_id))
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
858
        else:
859
            entries = tree.inventory.entries()
860
861
        self.cleanup_now()
2027.4.2 by John Arbash Meinel
Fix bug #3631, allow 'bzr inventory filename'
862
        for path, entry in entries:
1185.33.33 by Martin Pool
[patch] add 'bzr inventory --kind directory'; remove 'bzr directories'
863
            if kind and kind != entry.kind:
864
                continue
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
865
            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()
866
                self.outf.write('%-50s %s\n' % (path, entry.file_id))
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
867
            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()
868
                self.outf.write(path)
869
                self.outf.write('\n')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
870
871
872
class cmd_mv(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
873
    __doc__ = """Move or rename a file.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
874
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
875
    :Usage:
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
876
        bzr mv OLDNAME NEWNAME
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
877
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
878
        bzr mv SOURCE... DESTINATION
879
880
    If the last argument is a versioned directory, all the other names
881
    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
882
    and the file is changed to a new name.
883
884
    If OLDNAME does not exist on the filesystem but is versioned and
885
    NEWNAME does exist on the filesystem but is not versioned, mv
886
    assumes that the file has been manually moved and only updates
887
    its internal inventory to reflect that change.
888
    The same is valid when moving many SOURCE files to a DESTINATION.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
889
890
    Files cannot be moved between branches.
891
    """
1685.1.80 by Wouter van Heyst
more code cleanup
892
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
893
    takes_args = ['names*']
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
894
    takes_options = [Option("after", help="Move only the bzr identifier"
895
        " of the file, because the file has already been moved."),
3193.8.37 by Aaron Bentley
Finish up conversion to mv --auto.
896
        Option('auto', help='Automatically guess renames.'),
897
        Option('dry-run', help='Avoid making changes when guessing renames.'),
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
898
        ]
1616.1.8 by Martin Pool
Unify 'mv', 'move', 'rename'. (#5379, Matthew Fuller)
899
    aliases = ['move', 'rename']
1185.85.26 by John Arbash Meinel
bzr mv should succeed even if it can't display the paths.
900
    encoding_type = 'replace'
901
3193.8.37 by Aaron Bentley
Finish up conversion to mv --auto.
902
    def run(self, names_list, after=False, auto=False, dry_run=False):
3193.8.35 by Aaron Bentley
Implement mv --auto.
903
        if auto:
3193.8.37 by Aaron Bentley
Finish up conversion to mv --auto.
904
            return self.run_auto(names_list, after, dry_run)
905
        elif dry_run:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
906
            raise errors.BzrCommandError(gettext('--dry-run requires --auto.'))
1846.1.1 by Wouter van Heyst
Don't fail on 'bzr mv', extract move tests from OldTests.
907
        if names_list is None:
908
            names_list = []
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
909
        if len(names_list) < 2:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
910
            raise errors.BzrCommandError(gettext("missing file argument"))
5346.4.5 by Martin Pool
Deprecate and avoid internal_tree_files and tree_files.
911
        tree, rel_names = WorkingTree.open_containing_paths(names_list, canonicalize=False)
6220.3.5 by Jonathan Riddell
check all files being moved
912
        for file_name in rel_names[0:-1]:
913
            if file_name == '':
914
                raise errors.BzrCommandError(gettext("can not move root of branch"))
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
915
        self.add_cleanup(tree.lock_tree_write().unlock)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
916
        self._run(tree, names_list, rel_names, after)
3246.1.1 by Alexander Belchenko
Allow rename (change case of name) directory on case-insensitive filesystem.
917
3193.8.37 by Aaron Bentley
Finish up conversion to mv --auto.
918
    def run_auto(self, names_list, after, dry_run):
3193.8.36 by Aaron Bentley
Get remaining behaviour under test.
919
        if names_list is not None and len(names_list) > 1:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
920
            raise errors.BzrCommandError(gettext('Only one path may be specified to'
921
                                         ' --auto.'))
3193.8.37 by Aaron Bentley
Finish up conversion to mv --auto.
922
        if after:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
923
            raise errors.BzrCommandError(gettext('--after cannot be specified with'
924
                                         ' --auto.'))
5346.4.5 by Martin Pool
Deprecate and avoid internal_tree_files and tree_files.
925
        work_tree, file_list = WorkingTree.open_containing_paths(
5346.4.6 by Martin Pool
Update parameter name
926
            names_list, default_directory='.')
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
927
        self.add_cleanup(work_tree.lock_tree_write().unlock)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
928
        rename_map.RenameMap.guess_renames(work_tree, dry_run)
3193.8.35 by Aaron Bentley
Implement mv --auto.
929
3201.2.1 by Lukáš Lalinský
Make 'mv a b' work for already renamed directories, like it does for files
930
    def _run(self, tree, names_list, rel_names, after):
931
        into_existing = osutils.isdir(names_list[-1])
932
        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.
933
            # special cases:
934
            # a. case-insensitive filesystem and change case of dir
935
            # b. move directory after the fact (if the source used to be
936
            #    a directory, but now doesn't exist in the working tree
937
            #    and the target is an existing directory, just rename it)
938
            if (not tree.case_sensitive
939
                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
940
                into_existing = False
3249.4.1 by Alexander Belchenko
merge Lukas' patch and update it with case-insensitive rename check.
941
            else:
942
                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.
943
                # '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'
944
                from_id = tree.path2id(
945
                            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.
946
                if (not osutils.lexists(names_list[0]) and
947
                    from_id and inv.get_file_kind(from_id) == "directory"):
948
                    into_existing = False
949
        # move/rename
3201.2.1 by Lukáš Lalinský
Make 'mv a b' work for already renamed directories, like it does for files
950
        if into_existing:
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
951
            # 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.
952
            # All entries reference existing inventory items, so fix them up
953
            # 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'
954
            rel_names = tree.get_canonical_inventory_paths(rel_names)
4795.2.1 by Gordon Tyler
Fixed cmd_mv to use trace.note so that it obeys the --quiet option.
955
            for src, dest in tree.move(rel_names[:-1], rel_names[-1], after=after):
4795.2.4 by Gordon Tyler
Reverted cmd_mv back to using self.outf.write but checking for is_quiet.
956
                if not is_quiet():
957
                    self.outf.write("%s => %s\n" % (src, dest))
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
958
        else:
959
            if len(names_list) != 2:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
960
                raise errors.BzrCommandError(gettext('to mv multiple files the'
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
961
                                             ' destination must be a versioned'
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
962
                                             ' 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.
963
964
            # for cicp file-systems: the src references an existing inventory
965
            # item:
3794.5.20 by Mark Hammond
Use get_canonical_inventory_path and get_canonical_inventory_paths, and handle more edge cases in 'mv'
966
            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.
967
            # Find the canonical version of the destination:  In all cases, the
968
            # 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'
969
            # canonical version from there (we do not always *use* the
970
            # canonicalized tail portion - we may be attempting to rename the
971
            # case of the tail)
972
            canon_dest = tree.get_canonical_inventory_path(rel_names[1])
973
            dest_parent = osutils.dirname(canon_dest)
974
            spec_tail = osutils.basename(rel_names[1])
975
            # For a CICP file-system, we need to avoid creating 2 inventory
976
            # entries that differ only by case.  So regardless of the case
977
            # we *want* to use (ie, specified by the user or the file-system),
978
            # we must always choose to use the case of any existing inventory
979
            # items.  The only exception to this is when we are attempting a
980
            # case-only rename (ie, canonical versions of src and dest are
981
            # the same)
982
            dest_id = tree.path2id(canon_dest)
983
            if dest_id is None or tree.path2id(src) == dest_id:
984
                # No existing item we care about, so work out what case we
985
                # are actually going to use.
986
                if after:
987
                    # If 'after' is specified, the tail must refer to a file on disk.
988
                    if dest_parent:
989
                        dest_parent_fq = osutils.pathjoin(tree.basedir, dest_parent)
990
                    else:
991
                        # pathjoin with an empty tail adds a slash, which breaks
992
                        # relpath :(
993
                        dest_parent_fq = tree.basedir
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
994
3794.5.20 by Mark Hammond
Use get_canonical_inventory_path and get_canonical_inventory_paths, and handle more edge cases in 'mv'
995
                    dest_tail = osutils.canonical_relpath(
996
                                    dest_parent_fq,
997
                                    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.
998
                else:
3794.5.20 by Mark Hammond
Use get_canonical_inventory_path and get_canonical_inventory_paths, and handle more edge cases in 'mv'
999
                    # not 'after', so case as specified is used
1000
                    dest_tail = spec_tail
1001
            else:
1002
                # Use the existing item so 'mv' fails with AlreadyVersioned.
1003
                dest_tail = os.path.basename(canon_dest)
3794.5.11 by Mark Hammond
whitespace/logging changes.
1004
            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'
1005
            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.
1006
            tree.rename_one(src, dest, after=after)
4795.2.4 by Gordon Tyler
Reverted cmd_mv back to using self.outf.write but checking for is_quiet.
1007
            if not is_quiet():
1008
                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.
1009
1010
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1011
class cmd_pull(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
1012
    __doc__ = """Turn this branch into a mirror of another branch.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1013
4840.1.1 by Patrick Regan
Added extra clarification to pull cmd.
1014
    By default, this command only works on branches that have not diverged.
1015
    Branches are considered diverged if the destination branch's most recent 
1016
    commit is one that has not been merged (directly or indirectly) into the 
1017
    parent.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1018
1661.1.1 by Martin Pool
[merge] olaf's --remember changes
1019
    If branches have diverged, you can use 'bzr merge' to integrate the changes
1020
    from one into the other.  Once one branch has merged, the other should
1021
    be able to pull it again.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1022
4840.1.1 by Patrick Regan
Added extra clarification to pull cmd.
1023
    If you want to replace your local changes and just want your branch to
1024
    match the remote one, use pull --overwrite. This will work even if the two
1025
    branches have diverged.
1614.2.3 by Olaf Conradi
In commands push and pull, moved help text for --remember down. It's not
1026
5861.1.3 by Vincent Ladeuil
Fix the docs for push/pull/send regarding --no-remember.
1027
    If there is no default location set, the first pull will set it (use
6105.2.4 by Martin von Gagern
Drive-by typo correction in command docstrings.
1028
    --no-remember to avoid setting it). After that, you can omit the
5861.1.3 by Vincent Ladeuil
Fix the docs for push/pull/send regarding --no-remember.
1029
    location to use the default.  To change the default, use --remember. The
1030
    value will only be saved if the remote location can be accessed.
3313.1.1 by Ian Clatworthy
Improve doc on send/merge relationship (Peter Schuller)
1031
6175.2.4 by Vincent Ladeuil
Add script tests and documentation.
1032
    The --verbose option will display the revisions pulled using the log_format
1033
    configuration option. You can use a different format by overriding it with
1034
    -Olog_format=<other_format>.
1035
3313.1.1 by Ian Clatworthy
Improve doc on send/merge relationship (Peter Schuller)
1036
    Note: The location can be specified either in the form of a branch,
1037
    or in the form of a path to a file containing a merge directive generated
1038
    with bzr send.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1039
    """
1685.1.80 by Wouter van Heyst
more code cleanup
1040
4095.2.1 by Neil Martinsen-Burrell
Better help for bzr send
1041
    _see_also = ['push', 'update', 'status-flags', 'send']
1551.17.4 by Aaron Bentley
Make pull -v description more specific
1042
    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
1043
        custom_help('verbose',
1551.17.4 by Aaron Bentley
Make pull -v description more specific
1044
            help='Show logs of pulled revisions.'),
5171.3.1 by Martin von Gagern
Turn --directory and -d into a global option.
1045
        custom_help('directory',
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
1046
            help='Branch to pull into, '
5171.3.1 by Martin von Gagern
Turn --directory and -d into a global option.
1047
                 'rather than the one containing the working directory.'),
4056.6.1 by Gary van der Merwe
Add --local option to pull.
1048
        Option('local',
1049
            help="Perform a local pull in a bound "
1050
                 "branch.  Local pulls are not applied to "
1051
                 "the master branch."
1052
            ),
5430.7.1 by Rory Yorke
Added --show-base to pull and update (bug 202374).
1053
        Option('show-base',
1054
            help="Show base revision text in conflicts.")
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
1055
        ]
2520.1.6 by Daniel Watkins
Fixed 'pull' help.
1056
    takes_args = ['location?']
1185.85.27 by John Arbash Meinel
Updated bzr branch and bzr pull
1057
    encoding_type = 'replace'
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1058
5861.1.10 by Vincent Ladeuil
Fix --no-remember for the first pull.
1059
    def run(self, location=None, remember=None, overwrite=False,
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
1060
            revision=None, verbose=False,
5430.7.1 by Rory Yorke
Added --show-base to pull and update (bug 202374).
1061
            directory=None, local=False,
1062
            show_base=False):
1558.5.6 by Aaron Bentley
Renamed make-repo init-repo
1063
        # FIXME: too much stuff is in the command class
1551.14.11 by Aaron Bentley
rename rev_id and other_rev_id
1064
        revision_id = None
1551.14.7 by Aaron Bentley
test suite fixes
1065
        mergeable = None
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
1066
        if directory is None:
1067
            directory = u'.'
1558.5.6 by Aaron Bentley
Renamed make-repo init-repo
1068
        try:
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
1069
            tree_to = WorkingTree.open_containing(directory)[0]
1558.5.6 by Aaron Bentley
Renamed make-repo init-repo
1070
            branch_to = tree_to.branch
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
1071
            self.add_cleanup(tree_to.lock_write().unlock)
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
1072
        except errors.NoWorkingTree:
1558.5.6 by Aaron Bentley
Renamed make-repo init-repo
1073
            tree_to = None
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
1074
            branch_to = Branch.open_containing(directory)[0]
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
1075
            self.add_cleanup(branch_to.lock_write().unlock)
5147.1.1 by Andrew Bennetts
Avoid relocking in cmd_pull.
1076
5430.7.1 by Rory Yorke
Added --show-base to pull and update (bug 202374).
1077
        if tree_to is None and show_base:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
1078
            raise errors.BzrCommandError(gettext("Need working tree for --show-base."))
5430.7.1 by Rory Yorke
Added --show-base to pull and update (bug 202374).
1079
4056.6.4 by Gary van der Merwe
Implement pull --local.
1080
        if local and not branch_to.get_bound_location():
1081
            raise errors.LocalRequiresBoundBranch()
1711.3.3 by John Arbash Meinel
Allow pull to use a bundle as a target,
1082
2817.4.3 by Vincent Ladeuil
Add tests for commit, reuse master branch transport.
1083
        possible_transports = []
1711.3.3 by John Arbash Meinel
Allow pull to use a bundle as a target,
1084
        if location is not None:
3251.4.10 by Aaron Bentley
Pull of launchpad locations works (abentley, #181945)
1085
            try:
1086
                mergeable = bundle.read_mergeable_from_url(location,
1087
                    possible_transports=possible_transports)
1088
            except errors.NotABundle:
1089
                mergeable = None
1711.3.3 by John Arbash Meinel
Allow pull to use a bundle as a target,
1090
1558.5.6 by Aaron Bentley
Renamed make-repo init-repo
1091
        stored_loc = branch_to.get_parent()
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1092
        if location is None:
1093
            if stored_loc is None:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
1094
                raise errors.BzrCommandError(gettext("No pull location known or"
1095
                                             " specified."))
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1096
            else:
1685.1.58 by Martin Pool
urlutils.unescape_for_display should return Unicode
1097
                display_url = urlutils.unescape_for_display(stored_loc,
1098
                        self.outf.encoding)
3200.1.1 by James Westby
Make pull --quiet more quiet. Fixes #185907.
1099
                if not is_quiet():
6138.2.1 by Jonathan Riddell
add gettext to all the builtin commands outf usage
1100
                    self.outf.write(gettext("Using saved parent location: %s\n") % display_url)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1101
                location = stored_loc
1185.56.1 by Michael Ellerman
Simplify handling of DivergedBranches in cmd_pull()
1102
3993.1.1 by Ian Clatworthy
helper function when only one revision required (Daniel Watkins)
1103
        revision = _get_one_revision('pull', revision)
1551.14.4 by Aaron Bentley
Change bundle reader and merge directive to both be 'mergeables'
1104
        if mergeable is not None:
1105
            if revision is not None:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
1106
                raise errors.BzrCommandError(gettext(
1107
                    'Cannot use -r with merge directives or bundles'))
2520.4.109 by Aaron Bentley
start work on directive cherry-picking
1108
            mergeable.install_revisions(branch_to.repository)
1109
            base_revision_id, revision_id, verified = \
1110
                mergeable.get_merge_request(branch_to.repository)
1711.3.3 by John Arbash Meinel
Allow pull to use a bundle as a target,
1111
            branch_from = branch_to
1112
        else:
3251.4.10 by Aaron Bentley
Pull of launchpad locations works (abentley, #181945)
1113
            branch_from = Branch.open(location,
1114
                possible_transports=possible_transports)
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
1115
            self.add_cleanup(branch_from.lock_read().unlock)
5861.1.11 by Vincent Ladeuil
Add news entry and same comments.
1116
            # Remembers if asked explicitly or no previous location is set
5861.1.10 by Vincent Ladeuil
Fix --no-remember for the first pull.
1117
            if (remember
1118
                or (remember is None and branch_to.get_parent() is None)):
1711.3.3 by John Arbash Meinel
Allow pull to use a bundle as a target,
1119
                branch_to.set_parent(branch_from.base)
1120
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
1121
        if revision is not None:
1122
            revision_id = revision.as_revision_id(branch_from)
1123
1124
        if tree_to is not None:
1125
            view_info = _get_view_info_for_change_reporter(tree_to)
1126
            change_reporter = delta._ChangeReporter(
1127
                unversioned_filter=tree_to.is_ignored,
1128
                view_info=view_info)
1129
            result = tree_to.pull(
1130
                branch_from, overwrite, revision_id, change_reporter,
6105.2.5 by Martin von Gagern
Adjust line wrapping.
1131
                local=local, show_base=show_base)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
1132
        else:
1133
            result = branch_to.pull(
1134
                branch_from, overwrite, revision_id, local=local)
1135
1136
        result.report(self.outf)
1137
        if verbose and result.old_revid != result.new_revid:
1138
            log.show_branch_change(
1139
                branch_to, self.outf, result.old_revno,
1140
                result.old_revid)
5616.6.1 by Jelmer Vernooij
Exit with 1 if there were tag conflicts during pull.
1141
        if getattr(result, 'tag_conflicts', None):
1142
            return 1
1143
        else:
1144
            return 0
1185.31.5 by John Arbash Meinel
Merged pull --verbose changes
1145
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1146
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1147
class cmd_push(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
1148
    __doc__ = """Update a mirror of this branch.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1149
1649.1.1 by Robert Collins
* 'pull' and 'push' now normalise the revision history, so that any two
1150
    The target branch will not have its working tree populated because this
1151
    is both expensive, and is not supported on remote file systems.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1152
1649.1.1 by Robert Collins
* 'pull' and 'push' now normalise the revision history, so that any two
1153
    Some smart servers or protocols *may* put the working tree in place in
1154
    the future.
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1155
1156
    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
1157
    considered diverged if the destination branch's most recent commit is one
1158
    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.
1159
1160
    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
1161
    the other branch completely, discarding its unmerged changes.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1162
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1163
    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
1164
    do a merge (see bzr help merge) from the other branch, and commit that.
1165
    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
1166
5861.1.3 by Vincent Ladeuil
Fix the docs for push/pull/send regarding --no-remember.
1167
    If there is no default push location set, the first push will set it (use
6105.2.4 by Martin von Gagern
Drive-by typo correction in command docstrings.
1168
    --no-remember to avoid setting it).  After that, you can omit the
5861.1.3 by Vincent Ladeuil
Fix the docs for push/pull/send regarding --no-remember.
1169
    location to use the default.  To change the default, use --remember. The
1170
    value will only be saved if the remote location can be accessed.
6175.2.4 by Vincent Ladeuil
Add script tests and documentation.
1171
1172
    The --verbose option will display the revisions pushed using the log_format
1173
    configuration option. You can use a different format by overriding it with
1174
    -Olog_format=<other_format>.
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1175
    """
1685.1.80 by Wouter van Heyst
more code cleanup
1176
2485.1.2 by James Westby
Update with comments from review, thanks to John and Aaron.
1177
    _see_also = ['pull', 'update', 'working-trees']
3256.1.2 by Daniel Watkins
Added revision argument to push.
1178
    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)
1179
        Option('create-prefix',
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
1180
               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
1181
                    'if it does not already exist.'),
5171.3.1 by Martin von Gagern
Turn --directory and -d into a global option.
1182
        custom_help('directory',
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
1183
            help='Branch to push from, '
5171.3.1 by Martin von Gagern
Turn --directory and -d into a global option.
1184
                 'rather than the one containing the working directory.'),
2279.3.1 by mbp at sourcefrog
Add a -d option to push, pull, merge (ported from tags branch)
1185
        Option('use-existing-dir',
1186
               help='By default push will fail if the target'
1187
                    ' 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
1188
                    ' 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)
1189
                    ' allow push to proceed.'),
3549.1.1 by Martin Pool
rename push --reference to --stacked-on
1190
        Option('stacked',
1191
            help='Create a stacked branch that references the public location '
1192
                'of the parent branch.'),
1193
        Option('stacked-on',
3221.19.4 by Ian Clatworthy
shallow -> stacked
1194
            help='Create a stacked branch that refers to another branch '
3221.19.2 by Ian Clatworthy
tweaks to ui during review by igc
1195
                'for the commit history. Only the work not present in the '
1196
                'referenced branch is included in the branch created.',
3221.11.12 by Robert Collins
Basic push --reference support, requires url, slow.
1197
            type=unicode),
4420.1.2 by Vincent Ladeuil
Fix bug #284038 by adding a --strict option to push.
1198
        Option('strict',
1199
               help='Refuse to push if there are uncommitted changes in'
4464.3.11 by Vincent Ladeuil
Add a check for tree/branch sync and tweak help.
1200
               ' the working tree, --no-strict disables the check.'),
5448.6.1 by Matthew Gordon
Added --no-tree option to pull. Needs testing and help text.
1201
        Option('no-tree',
5448.6.3 by Matthew Gordon
Added help text for pull --no-tree.
1202
               help="Don't populate the working tree, even for protocols"
1203
               " that support it."),
2279.3.1 by mbp at sourcefrog
Add a -d option to push, pull, merge (ported from tags branch)
1204
        ]
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1205
    takes_args = ['location?']
1185.85.31 by John Arbash Meinel
Updated bzr push, including bringing in the unused --verbose flag.
1206
    encoding_type = 'replace'
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1207
5861.1.9 by Vincent Ladeuil
Fix --no-remember for the first push.
1208
    def run(self, location=None, remember=None, overwrite=False,
3221.14.3 by Ian Clatworthy
Merge bzr.dev r3466
1209
        create_prefix=False, verbose=False, revision=None,
3549.1.1 by Martin Pool
rename push --reference to --stacked-on
1210
        use_existing_dir=False, directory=None, stacked_on=None,
5448.6.2 by Matthew Gordon
Tested push --no-tree ang gor it working right.
1211
        stacked=False, strict=None, no_tree=False):
3221.19.1 by Ian Clatworthy
refactor cmd_push to use a helper function
1212
        from bzrlib.push import _show_push_branch
1213
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
1214
        if directory is None:
1215
            directory = '.'
4420.1.2 by Vincent Ladeuil
Fix bug #284038 by adding a --strict option to push.
1216
        # Get the source branch
4453.1.4 by Vincent Ladeuil
Cleanup.
1217
        (tree, br_from,
6207.3.3 by jelmer at samba
Fix tests and the like.
1218
         _unused) = controldir.ControlDir.open_containing_tree_or_branch(directory)
4420.1.2 by Vincent Ladeuil
Fix bug #284038 by adding a --strict option to push.
1219
        # Get the tip's revision_id
3984.3.9 by Daniel Watkins
Converted cmd_push.
1220
        revision = _get_one_revision('push', revision)
3221.19.1 by Ian Clatworthy
refactor cmd_push to use a helper function
1221
        if revision is not None:
3984.3.9 by Daniel Watkins
Converted cmd_push.
1222
            revision_id = revision.in_history(br_from).rev_id
3221.19.1 by Ian Clatworthy
refactor cmd_push to use a helper function
1223
        else:
4294.2.1 by Robert Collins
Move directory checking for bzr push options into Branch.create_clone_on_transport.
1224
            revision_id = None
5147.2.2 by Vincent Ladeuil
Fix bug #519319 by defaulting to a warning for dirty trees.
1225
        if tree is not None and revision_id is None:
5171.2.2 by Vincent Ladeuil
Explain that the uncommitted changes are not processed when
1226
            tree.check_changed_or_out_of_date(
1227
                strict, 'push_strict',
1228
                more_error='Use --no-strict to force the push.',
1229
                more_warning='Uncommitted changes will not be pushed.')
3549.1.1 by Martin Pool
rename push --reference to --stacked-on
1230
        # Get the stacked_on branch, if any
1231
        if stacked_on is not None:
1232
            stacked_on = urlutils.normalize_url(stacked_on)
3221.19.4 by Ian Clatworthy
shallow -> stacked
1233
        elif stacked:
3221.11.15 by Robert Collins
no parent branch causes an error on push --shallow.
1234
            parent_url = br_from.get_parent()
1235
            if parent_url:
1236
                parent = Branch.open(parent_url)
3549.1.1 by Martin Pool
rename push --reference to --stacked-on
1237
                stacked_on = parent.get_public_branch()
1238
                if not stacked_on:
3221.11.17 by Robert Collins
no public location causes the parent to be used directly with push --shallow.
1239
                    # I considered excluding non-http url's here, thus forcing
1240
                    # 'public' branches only, but that only works for some
3221.14.3 by Ian Clatworthy
Merge bzr.dev r3466
1241
                    # 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.
1242
                    # error by the feedback given to them. RBC 20080227.
3549.1.1 by Martin Pool
rename push --reference to --stacked-on
1243
                    stacked_on = parent_url
1244
            if not stacked_on:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
1245
                raise errors.BzrCommandError(gettext(
1246
                    "Could not determine branch to refer to."))
3221.19.1 by Ian Clatworthy
refactor cmd_push to use a helper function
1247
1248
        # Get the destination location
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1249
        if location is None:
3221.19.1 by Ian Clatworthy
refactor cmd_push to use a helper function
1250
            stored_loc = br_from.get_push_location()
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1251
            if stored_loc is None:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
1252
                raise errors.BzrCommandError(gettext(
1253
                    "No push location known or specified."))
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1254
            else:
1685.1.59 by Martin Pool
[broken] Fix up & refactor display of remembered urls to unescape properly
1255
                display_url = urlutils.unescape_for_display(stored_loc,
1256
                        self.outf.encoding)
6138.2.1 by Jonathan Riddell
add gettext to all the builtin commands outf usage
1257
                note(gettext("Using saved push location: %s") % display_url)
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1258
                location = stored_loc
1685.1.22 by John Arbash Meinel
cmd_push was passing the location directly to relpath, rather than a URL
1259
3221.19.1 by Ian Clatworthy
refactor cmd_push to use a helper function
1260
        _show_push_branch(br_from, revision_id, location, self.outf,
1261
            verbose=verbose, overwrite=overwrite, remember=remember,
3549.1.1 by Martin Pool
rename push --reference to --stacked-on
1262
            stacked_on=stacked_on, create_prefix=create_prefix,
5448.6.1 by Matthew Gordon
Added --no-tree option to pull. Needs testing and help text.
1263
            use_existing_dir=use_existing_dir, no_tree=no_tree)
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1264
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
1265
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1266
class cmd_branch(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
1267
    __doc__ = """Create a new branch that is a copy of an existing branch.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1268
1269
    If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
1270
    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
1271
    If the FROM_LOCATION has no / or path separator embedded, the TO_LOCATION
1272
    is derived from the FROM_LOCATION by stripping a leading scheme or drive
1273
    identifier, if any. For example, "branch lp:foo-bar" will attempt to
1274
    create ./foo-bar.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1275
1276
    To retrieve the branch as of a particular revision, supply the --revision
1277
    parameter, as in "branch foo/bar -r 5".
5741.3.2 by Martin Pool
Show a user warning on 'bzr clone' and 'get'
1278
1279
    The synonyms 'clone' and 'get' for this command are deprecated.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1280
    """
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
1281
1282
    _see_also = ['checkout']
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1283
    takes_args = ['from_location', 'to_location?']
5353.2.1 by John Arbash Meinel
Add flags to enable accelerator trees, but default them to false.
1284
    takes_options = ['revision',
1285
        Option('hardlink', help='Hard-link working tree files where possible.'),
5353.2.2 by John Arbash Meinel
update the test suite.
1286
        Option('files-from', type=str,
1287
               help="Get file contents from this tree."),
3983.1.1 by Daniel Watkins
Merged John Klinger's original work.
1288
        Option('no-tree',
3983.1.2 by Daniel Watkins
Minor cleanup.
1289
            help="Create a branch without a working-tree."),
4596.2.1 by Lukáš Lalinský
Add support for `bzr branch --switch`
1290
        Option('switch',
1291
            help="Switch the checkout in the current directory "
1292
                 "to the new branch."),
3221.20.3 by Ian Clatworthy
shallow -> stacked
1293
        Option('stacked',
1294
            help='Create a stacked branch referring to the source branch. '
3221.11.20 by Robert Collins
Support --shallow on branch.
1295
                'The new branch will depend on the availability of the source '
1296
                'branch for all operations.'),
3696.2.3 by Daniel Watkins
Added --standalone option to branch.
1297
        Option('standalone',
1298
               help='Do not use a shared repository, even if available.'),
4479.2.1 by Alexander Belchenko
branch command now has new flag --use-existing-dir to force branching into existing directory if there is no branch yet.
1299
        Option('use-existing-dir',
1300
               help='By default branch will fail if the target'
1301
                    ' directory exists, but does not already'
1302
                    ' have a control directory.  This flag will'
1303
                    ' allow branch to proceed.'),
4927.3.1 by Ian Clatworthy
branch --bind option
1304
        Option('bind',
1305
            help="Bind new branch to from location."),
3221.11.20 by Robert Collins
Support --shallow on branch.
1306
        ]
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1307
    aliases = ['get', 'clone']
1308
3136.1.3 by Aaron Bentley
Implement hard-link support for branch and checkout
1309
    def run(self, from_location, to_location=None, revision=None,
4479.2.1 by Alexander Belchenko
branch command now has new flag --use-existing-dir to force branching into existing directory if there is no branch yet.
1310
            hardlink=False, stacked=False, standalone=False, no_tree=False,
5353.2.1 by John Arbash Meinel
Add flags to enable accelerator trees, but default them to false.
1311
            use_existing_dir=False, switch=False, bind=False,
5353.2.2 by John Arbash Meinel
update the test suite.
1312
            files_from=None):
4596.2.1 by Lukáš Lalinský
Add support for `bzr branch --switch`
1313
        from bzrlib import switch as _mod_switch
2220.2.30 by Martin Pool
split out tag-merging code and add some tests
1314
        from bzrlib.tag import _merge_tags_if_possible
5741.3.2 by Martin Pool
Show a user warning on 'bzr clone' and 'get'
1315
        if self.invoked_as in ['get', 'clone']:
1316
            ui.ui_factory.show_user_warning(
1317
                'deprecated_command',
1318
                deprecated_name=self.invoked_as,
1319
                recommended_name='branch',
1320
                deprecated_in_version='2.4')
6207.3.3 by jelmer at samba
Fix tests and the like.
1321
        accelerator_tree, br_from = controldir.ControlDir.open_tree_or_branch(
3123.5.11 by Aaron Bentley
Accelerate branching from a lightweight checkout
1322
            from_location)
5353.2.2 by John Arbash Meinel
update the test suite.
1323
        if not (hardlink or files_from):
1324
            # accelerator_tree is usually slower because you have to read N
1325
            # files (no readahead, lots of seeks, etc), but allow the user to
1326
            # explicitly request it
5353.2.1 by John Arbash Meinel
Add flags to enable accelerator trees, but default them to false.
1327
            accelerator_tree = None
5353.2.2 by John Arbash Meinel
update the test suite.
1328
        if files_from is not None and files_from != from_location:
1329
            accelerator_tree = WorkingTree.open(files_from)
3984.3.7 by Daniel Watkins
Fixed incorrect calls.
1330
        revision = _get_one_revision('branch', revision)
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
1331
        self.add_cleanup(br_from.lock_read().unlock)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
1332
        if revision is not None:
1333
            revision_id = revision.as_revision_id(br_from)
1334
        else:
1335
            # FIXME - wt.last_revision, fallback to branch, fall back to
1336
            # None or perhaps NULL_REVISION to mean copy nothing
1337
            # RBC 20060209
1338
            revision_id = br_from.last_revision()
1339
        if to_location is None:
6240.3.1 by Jelmer Vernooij
Name new branches after colocated branches.
1340
            to_location = getattr(br_from, "name", None)
1341
            if to_location is None:
1342
                to_location = urlutils.derive_to_location(from_location)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
1343
        to_transport = transport.get_transport(to_location)
1185.17.3 by Martin Pool
[pick] larger read lock scope for branch command
1344
        try:
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
1345
            to_transport.mkdir('.')
1346
        except errors.FileExists:
6266.1.1 by Jelmer Vernooij
Support branching into colocated branch.
1347
            try:
1348
                to_dir = controldir.ControlDir.open_from_transport(
1349
                    to_transport)
1350
            except errors.NotBranchError:
1351
                if not use_existing_dir:
1352
                    raise errors.BzrCommandError(gettext('Target directory "%s" '
1353
                        'already exists.') % to_location)
1354
                else:
6207.2.1 by jelmer at samba
Fix cloning to colocated branch.
1355
                    to_dir = None
6266.1.1 by Jelmer Vernooij
Support branching into colocated branch.
1356
            else:
1357
                try:
1358
                    to_dir.open_branch()
1359
                except errors.NotBranchError:
1360
                    pass
4479.2.1 by Alexander Belchenko
branch command now has new flag --use-existing-dir to force branching into existing directory if there is no branch yet.
1361
                else:
6266.1.1 by Jelmer Vernooij
Support branching into colocated branch.
1362
                    raise errors.AlreadyBranchError(to_location)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
1363
        except errors.NoSuchFile:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
1364
            raise errors.BzrCommandError(gettext('Parent of "%s" does not exist.')
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
1365
                                         % to_location)
6207.2.1 by jelmer at samba
Fix cloning to colocated branch.
1366
        else:
1367
            to_dir = None
1368
        if to_dir is None:
1369
            try:
1370
                # preserve whatever source format we have.
1371
                to_dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
1372
                                            possible_transports=[to_transport],
1373
                                            accelerator_tree=accelerator_tree,
1374
                                            hardlink=hardlink, stacked=stacked,
1375
                                            force_new_repo=standalone,
1376
                                            create_tree_if_local=not no_tree,
1377
                                            source_branch=br_from)
6305.3.2 by Jelmer Vernooij
Only make a single connection.
1378
                branch = to_dir.open_branch(
1379
                    possible_transports=[
6305.3.5 by Jelmer Vernooij
Avoid .control_transport, as it triggers _ensure_real.
1380
                        br_from.bzrdir.root_transport, to_transport])
6207.2.1 by jelmer at samba
Fix cloning to colocated branch.
1381
            except errors.NoSuchRevision:
1382
                to_transport.delete_tree('.')
1383
                msg = gettext("The branch {0} has no revision {1}.").format(
1384
                    from_location, revision)
1385
                raise errors.BzrCommandError(msg)
1386
        else:
1387
            branch = br_from.sprout(to_dir, revision_id=revision_id)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
1388
        _merge_tags_if_possible(br_from, branch)
1389
        # If the source branch is stacked, the new branch may
1390
        # be stacked whether we asked for that explicitly or not.
1391
        # We therefore need a try/except here and not just 'if stacked:'
1392
        try:
6138.2.2 by Jonathan Riddell
gettext builtin.py's note() usage
1393
            note(gettext('Created new stacked branch referring to %s.') %
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
1394
                branch.get_stacked_on_url())
1395
        except (errors.NotStacked, errors.UnstackableBranchFormat,
1396
            errors.UnstackableRepositoryFormat), e:
6143.1.1 by Jonathan Riddell
use ngettext for plurals
1397
            note(ngettext('Branched %d revision.', 'Branched %d revisions.', branch.revno()) % branch.revno())
4948.3.1 by Ian Clatworthy
branch --bind option
1398
        if bind:
1399
            # Bind to the parent
1400
            parent_branch = Branch.open(from_location)
1401
            branch.bind(parent_branch)
6138.2.2 by Jonathan Riddell
gettext builtin.py's note() usage
1402
            note(gettext('New branch bound to %s') % from_location)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
1403
        if switch:
1404
            # Switch to the new branch
1405
            wt, _ = WorkingTree.open_containing('.')
1406
            _mod_switch.switch(wt.bzrdir, branch)
6138.2.2 by Jonathan Riddell
gettext builtin.py's note() usage
1407
            note(gettext('Switched to branch: %s'),
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
1408
                urlutils.unescape_for_display(branch.base, 'utf-8'))
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1409
1410
6060.6.1 by Jelmer Vernooij
Add 'bzr branches' command.
1411
class cmd_branches(Command):
1412
    __doc__ = """List the branches available at the current location.
1413
6110.8.1 by Jelmer Vernooij
Add --scan option to 'bzr branches'.
1414
    This command will print the names of all the branches at the current
1415
    location.
6060.6.1 by Jelmer Vernooij
Add 'bzr branches' command.
1416
    """
1417
1418
    takes_args = ['location?']
6110.8.1 by Jelmer Vernooij
Add --scan option to 'bzr branches'.
1419
    takes_options = [
6110.8.3 by Jelmer Vernooij
Rename --scan to --recursive.
1420
                  Option('recursive', short_name='R',
1421
                         help='Recursively scan for branches rather than '
1422
                              'just looking in the specified location.')]
6060.6.1 by Jelmer Vernooij
Add 'bzr branches' command.
1423
6110.8.3 by Jelmer Vernooij
Rename --scan to --recursive.
1424
    def run(self, location=".", recursive=False):
1425
        if recursive:
6110.8.1 by Jelmer Vernooij
Add --scan option to 'bzr branches'.
1426
            t = transport.get_transport(location)
1427
            if not t.listable():
1428
                raise errors.BzrCommandError(
1429
                    "Can't scan this type of location.")
6207.3.3 by jelmer at samba
Fix tests and the like.
1430
            for b in controldir.ControlDir.find_branches(t):
6110.8.1 by Jelmer Vernooij
Add --scan option to 'bzr branches'.
1431
                self.outf.write("%s\n" % urlutils.unescape_for_display(
1432
                    urlutils.relative_url(t.base, b.base),
1433
                    self.outf.encoding).rstrip("/"))
1434
        else:
6207.3.3 by jelmer at samba
Fix tests and the like.
1435
            dir = controldir.ControlDir.open_containing(location)[0]
6110.8.1 by Jelmer Vernooij
Add --scan option to 'bzr branches'.
1436
            for branch in dir.list_branches():
1437
                if branch.name is None:
6110.8.4 by Jelmer Vernooij
Merge bzr.dev.
1438
                    self.outf.write(gettext(" (default)\n"))
6110.8.1 by Jelmer Vernooij
Add --scan option to 'bzr branches'.
1439
                else:
1440
                    self.outf.write(" %s\n" % branch.name.encode(
1441
                        self.outf.encoding))
6060.6.1 by Jelmer Vernooij
Add 'bzr branches' command.
1442
1443
1508.1.20 by Robert Collins
Create a checkout command.
1444
class cmd_checkout(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
1445
    __doc__ = """Create a new checkout of an existing branch.
1508.1.20 by Robert Collins
Create a checkout command.
1446
1508.1.28 by Robert Collins
Test using bzr checkout to reconstitute working trees.
1447
    If BRANCH_LOCATION is omitted, checkout will reconstitute a working tree for
1448
    the branch found in '.'. This is useful if you have removed the working tree
1449
    or if it was never created - i.e. if you pushed the branch to its current
1450
    location using SFTP.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1451
1508.1.20 by Robert Collins
Create a checkout command.
1452
    If the TO_LOCATION is omitted, the last component of the BRANCH_LOCATION will
1453
    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
1454
    If the BRANCH_LOCATION has no / or path separator embedded, the TO_LOCATION
1455
    is derived from the BRANCH_LOCATION by stripping a leading scheme or drive
1456
    identifier, if any. For example, "checkout lp:foo-bar" will attempt to
1457
    create ./foo-bar.
1508.1.20 by Robert Collins
Create a checkout command.
1458
1459
    To retrieve the branch as of a particular revision, supply the --revision
1460
    parameter, as in "checkout foo/bar -r 5". Note that this will be immediately
1461
    out of date [so you cannot commit] but it may be useful (i.e. to examine old
1462
    code.)
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
1463
    """
1508.1.20 by Robert Collins
Create a checkout command.
1464
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
1465
    _see_also = ['checkouts', 'branch']
1508.1.28 by Robert Collins
Test using bzr checkout to reconstitute working trees.
1466
    takes_args = ['branch_location?', 'to_location?']
3984.3.5 by Daniel Watkins
Changed from option type to helper function.
1467
    takes_options = ['revision',
1587.1.14 by Robert Collins
Make bound branch creation happen via 'checkout'
1468
                     Option('lightweight',
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
1469
                            help="Perform a lightweight checkout.  Lightweight "
1587.1.14 by Robert Collins
Make bound branch creation happen via 'checkout'
1470
                                 "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
1471
                                 "every operation.  Normal checkouts can perform "
1587.1.14 by Robert Collins
Make bound branch creation happen via 'checkout'
1472
                                 "common operations like diff and status without "
1473
                                 "such access, and also support local commits."
1474
                            ),
3136.1.3 by Aaron Bentley
Implement hard-link support for branch and checkout
1475
                     Option('files-from', type=str,
1476
                            help="Get file contents from this tree."),
1477
                     Option('hardlink',
1478
                            help='Hard-link working tree files where possible.'
1479
                            ),
1587.1.14 by Robert Collins
Make bound branch creation happen via 'checkout'
1480
                     ]
1733.2.8 by Michael Ellerman
Add CVS compatible aliases for checkout and annotate, from fullermd.
1481
    aliases = ['co']
1508.1.20 by Robert Collins
Create a checkout command.
1482
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
1483
    def run(self, branch_location=None, to_location=None, revision=None,
5353.2.2 by John Arbash Meinel
update the test suite.
1484
            lightweight=False, files_from=None, hardlink=False):
1508.1.28 by Robert Collins
Test using bzr checkout to reconstitute working trees.
1485
        if branch_location is None:
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
1486
            branch_location = osutils.getcwd()
1508.1.28 by Robert Collins
Test using bzr checkout to reconstitute working trees.
1487
            to_location = branch_location
6207.3.3 by jelmer at samba
Fix tests and the like.
1488
        accelerator_tree, source = controldir.ControlDir.open_tree_or_branch(
3123.5.20 by Aaron Bentley
Checkout uses branch tree as a fallback accelerator
1489
            branch_location)
5353.2.2 by John Arbash Meinel
update the test suite.
1490
        if not (hardlink or files_from):
1491
            # accelerator_tree is usually slower because you have to read N
1492
            # files (no readahead, lots of seeks, etc), but allow the user to
1493
            # explicitly request it
1494
            accelerator_tree = None
3984.3.7 by Daniel Watkins
Fixed incorrect calls.
1495
        revision = _get_one_revision('checkout', revision)
5353.2.2 by John Arbash Meinel
update the test suite.
1496
        if files_from is not None and files_from != branch_location:
3123.5.20 by Aaron Bentley
Checkout uses branch tree as a fallback accelerator
1497
            accelerator_tree = WorkingTree.open(files_from)
3984.3.4 by Daniel Watkins
Converted cmd_checkout to use 1revision.
1498
        if revision is not None:
1499
            revision_id = revision.as_revision_id(source)
1508.1.20 by Robert Collins
Create a checkout command.
1500
        else:
1501
            revision_id = None
1502
        if to_location is None:
2512.4.1 by Ian Clatworthy
Fixes #115491 - 'branch lp:projname' now creates ./projname as exected
1503
            to_location = urlutils.derive_to_location(branch_location)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1504
        # if the source and to_location are the same,
1508.1.28 by Robert Collins
Test using bzr checkout to reconstitute working trees.
1505
        # and there is no working tree,
1506
        # then reconstitute a branch
1997.1.4 by Robert Collins
``bzr checkout --lightweight`` now operates on readonly branches as well
1507
        if (osutils.abspath(to_location) ==
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
1508
            osutils.abspath(branch_location)):
1508.1.28 by Robert Collins
Test using bzr checkout to reconstitute working trees.
1509
            try:
1510
                source.bzrdir.open_workingtree()
1511
            except errors.NoWorkingTree:
1551.15.60 by Aaron Bentley
bzr checkout -r always works, even with -r0 (#127708)
1512
                source.bzrdir.create_workingtree(revision_id)
1508.1.28 by Robert Collins
Test using bzr checkout to reconstitute working trees.
1513
                return
3123.5.2 by Aaron Bentley
Allow checkout --files_from
1514
        source.create_checkout(to_location, revision_id, lightweight,
3136.1.3 by Aaron Bentley
Implement hard-link support for branch and checkout
1515
                               accelerator_tree, hardlink)
1508.1.20 by Robert Collins
Create a checkout command.
1516
1517
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1518
class cmd_renames(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
1519
    __doc__ = """Show list of renamed files.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1520
    """
1185.16.3 by Martin Pool
- remove all TODOs from bzr help messages
1521
    # TODO: Option to show renames between two historical versions.
1522
1523
    # 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)
1524
    _see_also = ['status']
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1525
    takes_args = ['dir?']
1526
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1527
    @display_command
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
1528
    def run(self, dir=u'.'):
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
1529
        tree = WorkingTree.open_containing(dir)[0]
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
1530
        self.add_cleanup(tree.lock_read().unlock)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
1531
        new_inv = tree.inventory
1532
        old_tree = tree.basis_tree()
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
1533
        self.add_cleanup(old_tree.lock_read().unlock)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
1534
        old_inv = old_tree.inventory
1535
        renames = []
1536
        iterator = tree.iter_changes(old_tree, include_unchanged=True)
1537
        for f, paths, c, v, p, n, k, e in iterator:
1538
            if paths[0] == paths[1]:
1539
                continue
1540
            if None in (paths):
1541
                continue
1542
            renames.append(paths)
1543
        renames.sort()
1544
        for old_name, new_name in renames:
1545
            self.outf.write("%s => %s\n" % (old_name, new_name))
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1546
1547
1508.1.24 by Robert Collins
Add update command for use with checkouts.
1548
class cmd_update(Command):
6178.1.1 by Martin Pool
'bzr update' makes it clear it will only upgrade the whole tree
1549
    __doc__ = """Update a working tree to a new revision.
1550
1551
    This will perform a merge of the destination revision (the tip of the
1552
    branch, or the specified revision) into the working tree, and then make
1553
    that revision the basis revision for the working tree.  
1554
1555
    You can use this to visit an older revision, or to update a working tree
1556
    that is out of date from its branch.
1557
    
1558
    If there are any uncommitted changes in the tree, they will be carried
1559
    across and remain as uncommitted changes after the update.  To discard
1560
    these changes, use 'bzr revert'.  The uncommitted changes may conflict
1561
    with the changes brought in by the change in basis revision.
1562
1563
    If the tree's branch is bound to a master branch, bzr will also update
4916.1.11 by Martin Pool
Don't show extra message about updating from master; it's fairly redundant
1564
    the branch from the master.
6178.1.1 by Martin Pool
'bzr update' makes it clear it will only upgrade the whole tree
1565
1566
    You cannot update just a single file or directory, because each Bazaar
1567
    working tree has just a single basis revision.  If you want to restore a
1568
    file that has been removed locally, use 'bzr revert' instead of 'bzr
1569
    update'.  If you want to restore a file to its state in a previous
1570
    revision, use 'bzr revert' with a '-r' option, or use 'bzr cat' to write
1571
    out the old content of that file to a new location.
6178.1.3 by Martin Pool
'update' with no arguments from a tree subdirectory now works and is tested (thanks vila)
1572
1573
    The 'dir' argument, if given, must be the location of the root of a
1574
    working tree to update.  By default, the working tree that contains the 
1575
    current working directory is used.
1508.1.24 by Robert Collins
Add update command for use with checkouts.
1576
    """
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
1577
2625.5.1 by Daniel Watkins
'bzr update's help now includes a see also reference to 'help status-flags'.
1578
    _see_also = ['pull', 'working-trees', 'status-flags']
1508.1.24 by Robert Collins
Add update command for use with checkouts.
1579
    takes_args = ['dir?']
5430.7.1 by Rory Yorke
Added --show-base to pull and update (bug 202374).
1580
    takes_options = ['revision',
1581
                     Option('show-base',
1582
                            help="Show base revision text in conflicts."),
1583
                     ]
1815.3.1 by Stefan (metze) Metzmacher
add 'up' as alias for 'update'
1584
    aliases = ['up']
1508.1.24 by Robert Collins
Add update command for use with checkouts.
1585
6178.1.3 by Martin Pool
'update' with no arguments from a tree subdirectory now works and is tested (thanks vila)
1586
    def run(self, dir=None, revision=None, show_base=None):
1907.5.1 by Matthieu Moy
update -r implemented
1587
        if revision is not None and len(revision) != 1:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
1588
            raise errors.BzrCommandError(gettext(
6178.1.1 by Martin Pool
'bzr update' makes it clear it will only upgrade the whole tree
1589
                "bzr update --revision takes exactly one revision"))
6178.1.3 by Martin Pool
'update' with no arguments from a tree subdirectory now works and is tested (thanks vila)
1590
        if dir is None:
1591
            tree = WorkingTree.open_containing('.')[0]
1592
        else:
1593
            tree, relpath = WorkingTree.open_containing(dir)
1594
            if relpath:
1595
                # See bug 557886.
1596
                raise errors.BzrCommandError(gettext(
1597
                    "bzr update can only update a whole tree, "
1598
                    "not a file or subdirectory"))
1907.5.7 by Matthieu Moy
Coding style fixes thanks to jam.
1599
        branch = tree.branch
2806.2.2 by Vincent Ladeuil
Fix #128076 and #131396 by reusing bound branch transport.
1600
        possible_transports = []
2009.1.6 by Mark Hammond
more tweaks of the merge to get the tests passing.
1601
        master = branch.get_master_branch(
2806.2.2 by Vincent Ladeuil
Fix #128076 and #131396 by reusing bound branch transport.
1602
            possible_transports=possible_transports)
2084.2.1 by Aaron Bentley
Support updating lightweight checkouts of readonly branches
1603
        if master is not None:
4879.1.1 by Neil Martinsen-Burrell
update provides feedback on which branch it is up to date with.
1604
            branch_location = master.base
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
1605
            tree.lock_write()
2084.2.1 by Aaron Bentley
Support updating lightweight checkouts of readonly branches
1606
        else:
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
1607
            branch_location = tree.branch.base
2084.2.1 by Aaron Bentley
Support updating lightweight checkouts of readonly branches
1608
            tree.lock_tree_write()
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
1609
        self.add_cleanup(tree.unlock)
4879.1.3 by Vincent Ladeuil
Cleanup tests and tweak the text displayed.
1610
        # get rid of the final '/' and be ready for display
5106.2.1 by Martin Pool
Don't unconditionally strip last character of path in cmd_update
1611
        branch_location = urlutils.unescape_for_display(
1612
            branch_location.rstrip('/'),
1613
            self.outf.encoding)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
1614
        existing_pending_merges = tree.get_parent_ids()[1:]
4900.1.4 by Andrew Bennetts
Merge lp:bzr
1615
        if master is None:
1616
            old_tip = None
1617
        else:
1618
            # may need to fetch data into a heavyweight checkout
1619
            # XXX: this may take some time, maybe we should display a
1620
            # message
1621
            old_tip = branch.update(possible_transports)
1622
        if revision is not None:
1623
            revision_id = revision[0].as_revision_id(branch)
1624
        else:
1625
            revision_id = branch.last_revision()
1626
        if revision_id == _mod_revision.ensure_null(tree.last_revision()):
5126.1.1 by Parth Malwankar
update -r now supports dotted revision.
1627
            revno = branch.revision_id_to_dotted_revno(revision_id)
6138.2.4 by Jonathan Riddell
use format strings where there are multiple substitutions to allow for translations
1628
            note(gettext("Tree is up to date at revision {0} of branch {1}"
1629
                        ).format('.'.join(map(str, revno)), branch_location))
4900.1.4 by Andrew Bennetts
Merge lp:bzr
1630
            return 0
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
1631
        view_info = _get_view_info_for_change_reporter(tree)
4900.1.4 by Andrew Bennetts
Merge lp:bzr
1632
        change_reporter = delta._ChangeReporter(
1633
            unversioned_filter=tree.is_ignored,
1634
            view_info=view_info)
1508.1.24 by Robert Collins
Add update command for use with checkouts.
1635
        try:
4900.1.4 by Andrew Bennetts
Merge lp:bzr
1636
            conflicts = tree.update(
1637
                change_reporter,
1638
                possible_transports=possible_transports,
1639
                revision=revision_id,
5430.7.1 by Rory Yorke
Added --show-base to pull and update (bug 202374).
1640
                old_tip=old_tip,
1641
                show_base=show_base)
4900.1.4 by Andrew Bennetts
Merge lp:bzr
1642
        except errors.NoSuchRevision, e:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
1643
            raise errors.BzrCommandError(gettext(
4900.1.4 by Andrew Bennetts
Merge lp:bzr
1644
                                  "branch has no revision %s\n"
1645
                                  "bzr update --revision only works"
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
1646
                                  " for a revision in the branch history")
4900.1.4 by Andrew Bennetts
Merge lp:bzr
1647
                                  % (e.revision))
5126.1.1 by Parth Malwankar
update -r now supports dotted revision.
1648
        revno = tree.branch.revision_id_to_dotted_revno(
4985.3.5 by Gerard Krol
Reverting some unneeded changes.
1649
            _mod_revision.ensure_null(tree.last_revision()))
6138.2.4 by Jonathan Riddell
use format strings where there are multiple substitutions to allow for translations
1650
        note(gettext('Updated to revision {0} of branch {1}').format(
1651
             '.'.join(map(str, revno)), branch_location))
5151.1.1 by Robert Collins
``bzr update`` when a pending merge in the working tree has been merged
1652
        parent_ids = tree.get_parent_ids()
1653
        if parent_ids[1:] and parent_ids[1:] != existing_pending_merges:
6138.2.2 by Jonathan Riddell
gettext builtin.py's note() usage
1654
            note(gettext('Your local commits will now show as pending merges with '
1655
                 "'bzr status', and can be committed with 'bzr commit'."))
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
1656
        if conflicts != 0:
1657
            return 1
1658
        else:
1659
            return 0
1508.1.24 by Robert Collins
Add update command for use with checkouts.
1660
1661
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1662
class cmd_info(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
1663
    __doc__ = """Show information about a working tree, branch or repository.
1694.2.6 by Martin Pool
[merge] bzr.dev
1664
1665
    This command will show all known locations and formats associated to the
4032.2.1 by Ian Clatworthy
omit branch committers from info -v (now requires -vv)
1666
    tree, branch or repository.
4035.1.2 by Ian Clatworthy
clean-up trailing whitespace
1667
4032.2.1 by Ian Clatworthy
omit branch committers from info -v (now requires -vv)
1668
    In verbose mode, statistical information is included with each report.
1669
    To see extended statistic information, use a verbosity level of 2 or
1670
    higher by specifying the verbose option multiple times, e.g. -vv.
1694.2.6 by Martin Pool
[merge] bzr.dev
1671
1672
    Branches and working trees will also report any missing revisions.
4032.2.1 by Ian Clatworthy
omit branch committers from info -v (now requires -vv)
1673
1674
    :Examples:
1675
1676
      Display information on the format and related locations:
1677
1678
        bzr info
1679
1680
      Display the above together with extended format information and
1681
      basic statistics (like the number of files in the working tree and
1682
      number of revisions in the branch and repository):
1683
4217.3.1 by Ian Clatworthy
fix info help
1684
        bzr info -v
4032.2.1 by Ian Clatworthy
omit branch committers from info -v (now requires -vv)
1685
1686
      Display the above together with number of committers to the branch:
1687
4217.3.1 by Ian Clatworthy
fix info help
1688
        bzr info -vv
1694.2.6 by Martin Pool
[merge] bzr.dev
1689
    """
2485.1.2 by James Westby
Update with comments from review, thanks to John and Aaron.
1690
    _see_also = ['revno', 'working-trees', 'repositories']
1694.2.6 by Martin Pool
[merge] bzr.dev
1691
    takes_args = ['location?']
1624.3.21 by Olaf Conradi
Make bzr info command work on both local and remote locations. Support
1692
    takes_options = ['verbose']
2904.3.1 by Lukáš Lalinský
Unicode-safe output from ``bzr info``.
1693
    encoding_type = 'replace'
1694.2.6 by Martin Pool
[merge] bzr.dev
1694
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1695
    @display_command
2768.1.8 by Ian Clatworthy
Get test suite fully working again
1696
    def run(self, location=None, verbose=False):
1697
        if verbose:
4032.2.1 by Ian Clatworthy
omit branch committers from info -v (now requires -vv)
1698
            noise_level = get_verbosity_level()
2768.1.8 by Ian Clatworthy
Get test suite fully working again
1699
        else:
1700
            noise_level = 0
1694.2.6 by Martin Pool
[merge] bzr.dev
1701
        from bzrlib.info import show_bzrdir_info
6207.3.3 by jelmer at samba
Fix tests and the like.
1702
        show_bzrdir_info(controldir.ControlDir.open_containing(location)[0],
2904.3.1 by Lukáš Lalinský
Unicode-safe output from ``bzr info``.
1703
                         verbose=noise_level, outfile=self.outf)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1704
1705
2292.1.13 by Marius Kruger
* merge the unversion command back into the remove command,
1706
class cmd_remove(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
1707
    __doc__ = """Remove files or directories.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1708
5340.8.6 by Marius Kruger
* Update documentation
1709
    This makes Bazaar stop tracking changes to the specified files. Bazaar will
1710
    delete them if they can easily be recovered using revert otherwise they
1711
    will be backed up (adding an extention of the form .~#~). If no options or
1712
    parameters are given Bazaar will scan for files that are being tracked by
1713
    Bazaar but missing in your tree and stop tracking them for you.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1714
    """
1551.6.26 by Aaron Bentley
Add support for remove --new
1715
    takes_args = ['file*']
2292.1.30 by Marius Kruger
* Minor text fixes.
1716
    takes_options = ['verbose',
3619.5.1 by Robert Collins
* ``bzr rm`` will now scan for files that are missing and remove just
1717
        Option('new', help='Only remove files that have never been committed.'),
2292.1.28 by Marius Kruger
* NEWS
1718
        RegistryOption.from_kwargs('file-deletion-strategy',
2681.1.7 by Aaron Bentley
Fix option grammar
1719
            'The file deletion mode to be used.',
2292.1.28 by Marius Kruger
* NEWS
1720
            title='Deletion Strategy', value_switches=True, enum_switch=False,
5340.8.6 by Marius Kruger
* Update documentation
1721
            safe='Backup changed files (default).',
4556.1.1 by Martin Pool
Make 'rm --keep' help more clear
1722
            keep='Delete from bzr but leave the working copy.',
5444.3.1 by Marius Kruger
add 'bzr rm --no-backup' and deprecate the --force opting to be consitent with revert
1723
            no_backup='Don\'t backup changed files.',
2292.1.28 by Marius Kruger
* NEWS
1724
            force='Delete all the specified files, even if they can not be '
5444.3.1 by Marius Kruger
add 'bzr rm --no-backup' and deprecate the --force opting to be consitent with revert
1725
                'recovered and even if they are non-empty directories. '
6259.2.11 by Martin Packman
Revert addition of redundant full stops after brackets
1726
                '(deprecated, use no-backup)')]
3619.5.2 by Robert Collins
* ``bzr rm`` is now aliased to ``bzr del`` for the convenience of svn
1727
    aliases = ['rm', 'del']
1685.1.77 by Wouter van Heyst
WorkingTree.remove takes an optional output file
1728
    encoding_type = 'replace'
2292.1.1 by Marius Kruger
"bzr remove" and "bzr rm" will now remove the working file.
1729
2292.1.30 by Marius Kruger
* Minor text fixes.
1730
    def run(self, file_list, verbose=False, new=False,
2292.1.28 by Marius Kruger
* NEWS
1731
        file_deletion_strategy='safe'):
5444.3.1 by Marius Kruger
add 'bzr rm --no-backup' and deprecate the --force opting to be consitent with revert
1732
        if file_deletion_strategy == 'force':
6138.2.2 by Jonathan Riddell
gettext builtin.py's note() usage
1733
            note(gettext("(The --force option is deprecated, rather use --no-backup "
1734
                "in future.)"))
5444.3.1 by Marius Kruger
add 'bzr rm --no-backup' and deprecate the --force opting to be consitent with revert
1735
            file_deletion_strategy = 'no-backup'
1736
5346.4.5 by Martin Pool
Deprecate and avoid internal_tree_files and tree_files.
1737
        tree, file_list = WorkingTree.open_containing_paths(file_list)
2292.1.1 by Marius Kruger
"bzr remove" and "bzr rm" will now remove the working file.
1738
3794.5.38 by Mark Hammond
Restore missing (apparently pointless) block accidently removed.
1739
        if file_list is not None:
1740
            file_list = [f for f in file_list]
1741
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
1742
        self.add_cleanup(tree.lock_write().unlock)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
1743
        # Heuristics should probably all move into tree.remove_smart or
1744
        # some such?
1745
        if new:
1746
            added = tree.changes_from(tree.basis_tree(),
1747
                specific_files=file_list).added
1748
            file_list = sorted([f[0] for f in added], reverse=True)
1749
            if len(file_list) == 0:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
1750
                raise errors.BzrCommandError(gettext('No matching files.'))
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
1751
        elif file_list is None:
1752
            # missing files show up in iter_changes(basis) as
1753
            # versioned-with-no-kind.
1754
            missing = []
1755
            for change in tree.iter_changes(tree.basis_tree()):
1756
                # Find paths in the working tree that have no kind:
1757
                if change[1][1] is not None and change[6][1] is None:
1758
                    missing.append(change[1][1])
1759
            file_list = sorted(missing, reverse=True)
1760
            file_deletion_strategy = 'keep'
1761
        tree.remove(file_list, verbose=verbose, to_file=self.outf,
1762
            keep_files=file_deletion_strategy=='keep',
5444.3.1 by Marius Kruger
add 'bzr rm --no-backup' and deprecate the --force opting to be consitent with revert
1763
            force=(file_deletion_strategy=='no-backup'))
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1764
1765
1766
class cmd_file_id(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
1767
    __doc__ = """Print file_id of a particular file or directory.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1768
1769
    The file_id is assigned when the file is first added and remains the
1770
    same through all revisions where the file exists, even when it is
1771
    moved or renamed.
1772
    """
1685.1.80 by Wouter van Heyst
more code cleanup
1773
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1774
    hidden = True
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
1775
    _see_also = ['inventory', 'ls']
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1776
    takes_args = ['filename']
1185.85.35 by John Arbash Meinel
Updated file-path
1777
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1778
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1779
    def run(self, filename):
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
1780
        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.
1781
        i = tree.path2id(relpath)
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
1782
        if i is None:
2067.3.1 by Martin Pool
Clean up BzrNewError, other exception classes and users.
1783
            raise errors.NotVersionedError(filename)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1784
        else:
1685.1.80 by Wouter van Heyst
more code cleanup
1785
            self.outf.write(i + '\n')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1786
1787
1788
class cmd_file_path(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
1789
    __doc__ = """Print path of file_ids to a file or directory.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1790
1791
    This prints one line for each directory down to the target,
1185.85.35 by John Arbash Meinel
Updated file-path
1792
    starting at the branch root.
1793
    """
1685.1.80 by Wouter van Heyst
more code cleanup
1794
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1795
    hidden = True
1796
    takes_args = ['filename']
1185.85.35 by John Arbash Meinel
Updated file-path
1797
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1798
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1799
    def run(self, filename):
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
1800
        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.
1801
        fid = tree.path2id(relpath)
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
1802
        if fid is None:
2067.3.1 by Martin Pool
Clean up BzrNewError, other exception classes and users.
1803
            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.
1804
        segments = osutils.splitpath(relpath)
1805
        for pos in range(1, len(segments) + 1):
1806
            path = osutils.joinpath(segments[:pos])
1807
            self.outf.write("%s\n" % tree.path2id(path))
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1808
1809
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
1810
class cmd_reconcile(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
1811
    __doc__ = """Reconcile bzr metadata in a branch.
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
1812
1813
    This can correct data mismatches that may have been caused by
1814
    previous ghost operations or bzr upgrades. You should only
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1815
    need to run this command if 'bzr check' or a bzr developer
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
1816
    advises you to run it.
1817
1818
    If a second branch is provided, cross-branch reconciliation is
1819
    also attempted, which will check that data like the tree root
1820
    id which was not present in very early bzr versions is represented
1821
    correctly in both branches.
1822
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1823
    At the same time it is run it may recompress data resulting in
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
1824
    a potential saving in disk space or performance gain.
1825
1826
    The branch *MUST* be on a listable system such as local disk or sftp.
1827
    """
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
1828
1829
    _see_also = ['check']
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
1830
    takes_args = ['branch?']
5375.1.3 by Andrew Bennetts
Add hidden --canonicalize-chks option to reconcile to trigger GCCHKCanonicalizingPacker, improve progress reporting a little.
1831
    takes_options = [
1832
        Option('canonicalize-chks',
1833
               help='Make sure CHKs are in canonical form (repairs '
1834
                    'bug 522637).',
1835
               hidden=True),
1836
        ]
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
1837
5375.1.3 by Andrew Bennetts
Add hidden --canonicalize-chks option to reconcile to trigger GCCHKCanonicalizingPacker, improve progress reporting a little.
1838
    def run(self, branch=".", canonicalize_chks=False):
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
1839
        from bzrlib.reconcile import reconcile
6207.3.3 by jelmer at samba
Fix tests and the like.
1840
        dir = controldir.ControlDir.open(branch)
5375.1.3 by Andrew Bennetts
Add hidden --canonicalize-chks option to reconcile to trigger GCCHKCanonicalizingPacker, improve progress reporting a little.
1841
        reconcile(dir, canonicalize_chks=canonicalize_chks)
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
1842
1843
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1844
class cmd_revision_history(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
1845
    __doc__ = """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)
1846
1847
    _see_also = ['log']
1733.2.1 by Michael Ellerman
Add an optional location parameter to the 'revision-history' command.
1848
    takes_args = ['location?']
1849
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1850
    hidden = True
1185.85.36 by John Arbash Meinel
Working on tests for revision-history, ancestry, and diff
1851
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1852
    @display_command
1733.2.1 by Michael Ellerman
Add an optional location parameter to the 'revision-history' command.
1853
    def run(self, location="."):
1854
        branch = Branch.open_containing(location)[0]
6165.4.28 by Jelmer Vernooij
Fix last locking issues.
1855
        self.add_cleanup(branch.lock_read().unlock)
6165.4.27 by Jelmer Vernooij
Remove more uses of Branch.revision_history.
1856
        graph = branch.repository.get_graph()
1857
        history = list(graph.iter_lefthand_ancestry(branch.last_revision(),
6165.4.28 by Jelmer Vernooij
Fix last locking issues.
1858
            [_mod_revision.NULL_REVISION]))
6165.4.27 by Jelmer Vernooij
Remove more uses of Branch.revision_history.
1859
        for revid in reversed(history):
1733.2.4 by Michael Ellerman
Merge bzr.dev, fix minor conflict in cmd_revision_history().
1860
            self.outf.write(revid)
1185.85.36 by John Arbash Meinel
Working on tests for revision-history, ancestry, and diff
1861
            self.outf.write('\n')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1862
1863
1225 by Martin Pool
- branch now tracks ancestry - all merged revisions
1864
class cmd_ancestry(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
1865
    __doc__ = """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)
1866
1867
    _see_also = ['log', 'revision-history']
1733.2.2 by Michael Ellerman
Add optional location to ancestry and fix behaviour for checkouts.
1868
    takes_args = ['location?']
1869
1225 by Martin Pool
- branch now tracks ancestry - all merged revisions
1870
    hidden = True
1185.85.36 by John Arbash Meinel
Working on tests for revision-history, ancestry, and diff
1871
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1872
    @display_command
1733.2.2 by Michael Ellerman
Add optional location to ancestry and fix behaviour for checkouts.
1873
    def run(self, location="."):
1874
        try:
1875
            wt = WorkingTree.open_containing(location)[0]
1876
        except errors.NoWorkingTree:
1877
            b = Branch.open(location)
1878
            last_revision = b.last_revision()
1879
        else:
1880
            b = wt.branch
1881
            last_revision = wt.last_revision()
1882
5971.1.59 by Jonathan Riddell
revert mysterious unintended change to cmd_ancestry()
1883
        self.add_cleanup(b.repository.lock_read().unlock)
1884
        graph = b.repository.get_graph()
1885
        revisions = [revid for revid, parents in
1886
            graph.iter_ancestry([last_revision])]
1887
        for revision_id in reversed(revisions):
1888
            if _mod_revision.is_null(revision_id):
1889
                continue
1685.1.69 by Wouter van Heyst
merge bzr.dev 1740
1890
            self.outf.write(revision_id + '\n')
1225 by Martin Pool
- branch now tracks ancestry - all merged revisions
1891
1892
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1893
class cmd_init(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
1894
    __doc__ = """Make a directory into a versioned branch.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1895
1896
    Use this to create an empty branch, or before importing an
1897
    existing project.
1898
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1899
    If there is a repository in a parent directory of the location, then
1662.1.19 by Martin Pool
Better error message when initting existing tree
1900
    the history of the branch will be stored in the repository.  Otherwise
2374.1.2 by Ian Clatworthy
Improved after feedback from reviewers
1901
    init creates a standalone branch which carries its own history
1902
    in the .bzr directory.
1662.1.19 by Martin Pool
Better error message when initting existing tree
1903
1904
    If there is already a branch at the location but it has no working tree,
1905
    the tree can be populated with 'bzr checkout'.
1906
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
1907
    Recipe for importing a tree of files::
1908
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1909
        cd ~/project
1910
        bzr init
1185.12.93 by Aaron Bentley
Fixed obsolete help
1911
        bzr add .
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1912
        bzr status
3035.1.1 by John Arbash Meinel
Address bug #59302 and fix documentation that uses single quotes.
1913
        bzr commit -m "imported project"
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1914
    """
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
1915
2677.1.2 by Alexander Belchenko
bzr_man: see also topics as cross-reference links
1916
    _see_also = ['init-repository', 'branch', 'checkout']
1185.16.138 by Martin Pool
[patch] 'bzr init DIR' (John)
1917
    takes_args = ['location?']
1857.1.20 by Aaron Bentley
Strip out all the EnumOption stuff
1918
    takes_options = [
2524.1.1 by Aaron Bentley
Revert broken changes
1919
        Option('create-prefix',
1920
               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
1921
                    'if it does not already exist.'),
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
1922
         RegistryOption('format',
1923
                help='Specify a format for this branch. '
1924
                'See "help formats".',
3224.5.2 by Andrew Bennetts
Avoid importing bzrlib.bzrdir unnecessarily.
1925
                lazy_registry=('bzrlib.bzrdir', 'format_registry'),
6207.3.3 by jelmer at samba
Fix tests and the like.
1926
                converter=lambda name: controldir.format_registry.make_bzrdir(name),
2241.1.19 by mbp at sourcefrog
(merge) trunk
1927
                value_switches=True,
4634.39.39 by Ian Clatworthy
Fix ReST syntax errors in User Reference caused by options like --1.9 that ReST option lists don't permit
1928
                title="Branch format",
2241.1.19 by mbp at sourcefrog
(merge) trunk
1929
                ),
2230.3.42 by Aaron Bentley
add --append-revisions-only option to init
1930
         Option('append-revisions-only',
1931
                help='Never change revnos or the existing log.'
5448.6.4 by Matthew Gordon
Added --no-tree option to bzr init.
1932
                '  Append revisions to it only.'),
1933
         Option('no-tree',
1934
                'Create a branch without a working tree.')
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
1935
         ]
2524.1.1 by Aaron Bentley
Revert broken changes
1936
    def run(self, location=None, format=None, append_revisions_only=False,
5448.6.4 by Matthew Gordon
Added --no-tree option to bzr init.
1937
            create_prefix=False, no_tree=False):
1857.1.20 by Aaron Bentley
Strip out all the EnumOption stuff
1938
        if format is None:
6207.3.3 by jelmer at samba
Fix tests and the like.
1939
            format = controldir.format_registry.make_bzrdir('default')
1185.16.138 by Martin Pool
[patch] 'bzr init DIR' (John)
1940
        if location is None:
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
1941
            location = u'.'
1830.4.5 by Wouter van Heyst
cleanup
1942
1830.4.7 by Wouter van Heyst
review fixes, rename transport variable to to_transport
1943
        to_transport = transport.get_transport(location)
1830.4.5 by Wouter van Heyst
cleanup
1944
1945
        # The path has to exist to initialize a
1946
        # branch inside of it.
1947
        # Just using os.mkdir, since I don't
1948
        # believe that we want to create a bunch of
1949
        # locations if the user supplies an extended path
2524.1.1 by Aaron Bentley
Revert broken changes
1950
        try:
1951
            to_transport.ensure_base()
1952
        except errors.NoSuchFile:
1953
            if not create_prefix:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
1954
                raise errors.BzrCommandError(gettext("Parent directory of %s"
2524.1.1 by Aaron Bentley
Revert broken changes
1955
                    " does not exist."
1956
                    "\nYou may supply --create-prefix to create all"
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
1957
                    " leading parent directories.")
2524.1.1 by Aaron Bentley
Revert broken changes
1958
                    % location)
4294.2.1 by Robert Collins
Move directory checking for bzr push options into Branch.create_clone_on_transport.
1959
            to_transport.create_prefix()
2504.1.3 by Daniel Watkins
Implemented --create-prefix for 'init'.
1960
1654.1.4 by Robert Collins
Teach `bzr init` how to init at the root of a repository.
1961
        try:
6207.3.3 by jelmer at samba
Fix tests and the like.
1962
            a_bzrdir = controldir.ControlDir.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
1963
        except errors.NotBranchError:
1662.1.19 by Martin Pool
Better error message when initting existing tree
1964
            # really a NotBzrDir error...
6207.3.3 by jelmer at samba
Fix tests and the like.
1965
            create_branch = controldir.ControlDir.create_branch_convenience
5448.6.4 by Matthew Gordon
Added --no-tree option to bzr init.
1966
            if no_tree:
1967
                force_new_tree = False
1968
            else:
1969
                force_new_tree = None
2476.3.6 by Vincent Ladeuil
Fix the 'init connects multiple times' in a different way.
1970
            branch = create_branch(to_transport.base, format=format,
5448.6.4 by Matthew Gordon
Added --no-tree option to bzr init.
1971
                                   possible_transports=[to_transport],
1972
                                   force_new_tree=force_new_tree)
3697.5.4 by John Arbash Meinel
Merge vila's init[-repo] changes and add a NEWS entry.
1973
            a_bzrdir = branch.bzrdir
1654.1.4 by Robert Collins
Teach `bzr init` how to init at the root of a repository.
1974
        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
1975
            from bzrlib.transport.local import LocalTransport
3697.5.4 by John Arbash Meinel
Merge vila's init[-repo] changes and add a NEWS entry.
1976
            if a_bzrdir.has_branch():
1830.4.8 by Wouter van Heyst
clean up imports (and get if collapsing right)
1977
                if (isinstance(to_transport, LocalTransport)
3697.5.4 by John Arbash Meinel
Merge vila's init[-repo] changes and add a NEWS entry.
1978
                    and not a_bzrdir.has_workingtree()):
1830.4.1 by Wouter van Heyst
Allow bzr init to create remote branches
1979
                        raise errors.BranchExistsWithoutWorkingTree(location)
1980
                raise errors.AlreadyBranchError(location)
3697.5.4 by John Arbash Meinel
Merge vila's init[-repo] changes and add a NEWS entry.
1981
            branch = a_bzrdir.create_branch()
6083.2.3 by Jelmer Vernooij
Don't create working tree when there already is one.
1982
            if not no_tree and not a_bzrdir.has_workingtree():
5448.6.4 by Matthew Gordon
Added --no-tree option to bzr init.
1983
                a_bzrdir.create_workingtree()
2230.3.42 by Aaron Bentley
add --append-revisions-only option to init
1984
        if append_revisions_only:
1985
            try:
1986
                branch.set_append_revisions_only(True)
1987
            except errors.UpgradeRequired:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
1988
                raise errors.BzrCommandError(gettext('This branch format cannot be set'
1989
                    ' to append-revisions-only.  Try --default.'))
3535.9.1 by Marius Kruger
print info after init and init-repo
1990
        if not is_quiet():
3922.2.1 by Marius Kruger
make `bzr init` less verbose, and update tests
1991
            from bzrlib.info import describe_layout, describe_format
1992
            try:
1993
                tree = a_bzrdir.open_workingtree(recommend_upgrade=False)
1994
            except (errors.NoWorkingTree, errors.NotLocalUrl):
1995
                tree = None
1996
            repository = branch.repository
1997
            layout = describe_layout(repository, branch, tree).lower()
1998
            format = describe_format(a_bzrdir, repository, branch, tree)
6138.2.4 by Jonathan Riddell
use format strings where there are multiple substitutions to allow for translations
1999
            self.outf.write(gettext("Created a {0} (format: {1})\n").format(
2000
                  layout, format))
3922.2.1 by Marius Kruger
make `bzr init` less verbose, and update tests
2001
            if repository.is_shared():
2002
                #XXX: maybe this can be refactored into transport.path_or_url()
2003
                url = repository.bzrdir.root_transport.external_url()
2004
                try:
2005
                    url = urlutils.local_path_from_url(url)
2006
                except errors.InvalidURL:
2007
                    pass
6138.2.1 by Jonathan Riddell
add gettext to all the builtin commands outf usage
2008
                self.outf.write(gettext("Using shared repository: %s\n") % url)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2009
2010
1558.5.6 by Aaron Bentley
Renamed make-repo init-repo
2011
class cmd_init_repository(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
2012
    __doc__ = """Create a shared repository for branches to share storage space.
1658.1.6 by Martin Pool
init-repo shouldn't insist on creating a new directory (Malone #38331)
2013
2485.1.2 by James Westby
Update with comments from review, thanks to John and Aaron.
2014
    New branches created under the repository directory will store their
4849.3.1 by Neil Martinsen-Burrell
add more description about what shared repositories are good for
2015
    revisions in the repository, not in the branch directory.  For branches
2016
    with shared history, this reduces the amount of storage needed and 
2017
    speeds up the creation of new branches.
2485.1.2 by James Westby
Update with comments from review, thanks to John and Aaron.
2018
4849.3.1 by Neil Martinsen-Burrell
add more description about what shared repositories are good for
2019
    If the --no-trees option is given then the branches in the repository
2020
    will not have working trees by default.  They will still exist as 
2021
    directories on disk, but they will not have separate copies of the 
2022
    files at a certain revision.  This can be useful for repositories that
2023
    store branches which are interacted with through checkouts or remote
2024
    branches, such as on a server.
1658.1.6 by Martin Pool
init-repo shouldn't insist on creating a new directory (Malone #38331)
2025
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
2026
    :Examples:
4849.3.1 by Neil Martinsen-Burrell
add more description about what shared repositories are good for
2027
        Create a shared repository holding just branches::
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
2028
2029
            bzr init-repo --no-trees repo
2030
            bzr init repo/trunk
2031
2032
        Make a lightweight checkout elsewhere::
2033
2034
            bzr checkout --lightweight repo/trunk trunk-checkout
2035
            cd trunk-checkout
2036
            (add files here)
1658.1.6 by Martin Pool
init-repo shouldn't insist on creating a new directory (Malone #38331)
2037
    """
2353.2.1 by John Arbash Meinel
(Wouter van Heyst) switch 'bzr init-repo' to default to '--no-trees'
2038
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
2039
    _see_also = ['init', 'branch', 'checkout', 'repositories']
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
2040
    takes_args = ["location"]
2221.4.9 by Aaron Bentley
Zap trailing whitespace
2041
    takes_options = [RegistryOption('format',
2221.4.12 by Aaron Bentley
Add option grouping to RegistryOption and clean up format options
2042
                            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
2043
                                 ' "bzr help formats" for details.',
6207.3.3 by jelmer at samba
Fix tests and the like.
2044
                            lazy_registry=('bzrlib.controldir', 'format_registry'),
2045
                            converter=lambda name: controldir.format_registry.make_bzrdir(name),
2221.4.12 by Aaron Bentley
Add option grouping to RegistryOption and clean up format options
2046
                            value_switches=True, title='Repository format'),
2257.2.1 by Wouter van Heyst
Change the ui level default for init-repo to --trees.
2047
                     Option('no-trees',
2353.2.1 by John Arbash Meinel
(Wouter van Heyst) switch 'bzr init-repo' to default to '--no-trees'
2048
                             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
2049
                                  ' not having a working tree.'),
2353.2.1 by John Arbash Meinel
(Wouter van Heyst) switch 'bzr init-repo' to default to '--no-trees'
2050
                    ]
1558.5.6 by Aaron Bentley
Renamed make-repo init-repo
2051
    aliases = ["init-repo"]
2353.2.1 by John Arbash Meinel
(Wouter van Heyst) switch 'bzr init-repo' to default to '--no-trees'
2052
2257.2.2 by Wouter van Heyst
Actually test that `bzr init-repo --{no,}-trees` still works
2053
    def run(self, location, format=None, no_trees=False):
1857.1.20 by Aaron Bentley
Strip out all the EnumOption stuff
2054
        if format is None:
6207.3.3 by jelmer at samba
Fix tests and the like.
2055
            format = controldir.format_registry.make_bzrdir('default')
1857.1.20 by Aaron Bentley
Strip out all the EnumOption stuff
2056
2057
        if location is None:
2058
            location = '.'
2059
1830.4.7 by Wouter van Heyst
review fixes, rename transport variable to to_transport
2060
        to_transport = transport.get_transport(location)
2475.3.3 by John Arbash Meinel
Change calls to try/mkdir('.')/except FileExists to ensure_base()
2061
        to_transport.ensure_base()
1830.4.5 by Wouter van Heyst
cleanup
2062
1857.1.20 by Aaron Bentley
Strip out all the EnumOption stuff
2063
        newdir = format.initialize_on_transport(to_transport)
1558.5.2 by Aaron Bentley
Created *shared* repositories...
2064
        repo = newdir.create_repository(shared=True)
2257.2.2 by Wouter van Heyst
Actually test that `bzr init-repo --{no,}-trees` still works
2065
        repo.set_make_working_trees(not no_trees)
3535.9.1 by Marius Kruger
print info after init and init-repo
2066
        if not is_quiet():
2067
            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.
2068
            show_bzrdir_info(repo.bzrdir, verbose=0, outfile=self.outf)
1558.5.1 by Aaron Bentley
Added make-repository command
2069
2070
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2071
class cmd_diff(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
2072
    __doc__ = """Show differences in the working tree, between revisions or branches.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2073
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
2074
    If no arguments are given, all changes for the current tree are listed.
2075
    If files are given, only the changes in those files are listed.
2076
    Remote and multiple branches can be compared by using the --old and
2077
    --new options. If not provided, the default for both is derived from
2078
    the first argument, if any, or the current tree if no arguments are
2079
    given.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2080
1694.2.3 by Martin Pool
Add -p0, -p1 options for diff.
2081
    "bzr diff -p1" is equivalent to "bzr diff --prefix old/:new/", and
2082
    produces patches suitable for "patch -p1".
2083
5504.3.1 by Neil Martinsen-Burrell
give more information about revision ranges and the diff command
2084
    Note that when using the -r argument with a range of revisions, the
2085
    differences are computed between the two specified revisions.  That
2086
    is, the command does not show the changes introduced by the first 
2087
    revision in the range.  This differs from the interpretation of 
2088
    revision ranges used by "bzr log" which includes the first revision
2089
    in the range.
2090
2961.2.1 by Guillermo Gonzalez
* fix Bug #147938 (add exit values reference for cmd_diff help)
2091
    :Exit values:
2092
        1 - changed
2093
        2 - unrepresentable changes
2094
        3 - error
2095
        0 - no change
2096
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
2097
    :Examples:
2098
        Shows the difference in the working tree versus the last commit::
2099
2100
            bzr diff
2101
2102
        Difference between the working tree and revision 1::
2103
2104
            bzr diff -r1
2105
4816.2.1 by Ian Clatworthy
Better explanation of diff -c behaviour
2106
        Difference between revision 3 and revision 1::
2107
2108
            bzr diff -r1..3
2109
2110
        Difference between revision 3 and revision 1 for branch xxx::
2111
2112
            bzr diff -r1..3 xxx
2113
5504.3.1 by Neil Martinsen-Burrell
give more information about revision ranges and the diff command
2114
        The changes introduced by revision 2 (equivalent to -r1..2)::
2115
2116
            bzr diff -c2
2117
2118
        To see the changes introduced by revision X::
4816.2.1 by Ian Clatworthy
Better explanation of diff -c behaviour
2119
        
2120
            bzr diff -cX
2121
2122
        Note that in the case of a merge, the -c option shows the changes
2123
        compared to the left hand parent. To see the changes against
2124
        another parent, use::
2125
2126
            bzr diff -r<chosen_parent>..X
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
2127
5504.3.1 by Neil Martinsen-Burrell
give more information about revision ranges and the diff command
2128
        The changes between the current revision and the previous revision
2129
        (equivalent to -c-1 and -r-2..-1)
4798.2.1 by Neil Martinsen-Burrell
add example of -c usage to diff help
2130
5504.3.1 by Neil Martinsen-Burrell
give more information about revision ranges and the diff command
2131
            bzr diff -r-2..
4798.2.1 by Neil Martinsen-Burrell
add example of -c usage to diff help
2132
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
2133
        Show just the differences for file NEWS::
2134
2135
            bzr diff NEWS
2136
2137
        Show the differences in working tree xxx for file NEWS::
2138
2139
            bzr diff xxx/NEWS
2140
2141
        Show the differences from branch xxx to this working tree:
2142
2143
            bzr diff --old xxx
2144
2145
        Show the differences between two branches for file NEWS::
2146
3072.1.4 by Ian Clatworthy
Tweak help
2147
            bzr diff --old xxx --new yyy NEWS
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
2148
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
2149
        Same as 'bzr diff' but prefix paths with old/ and new/::
2150
2151
            bzr diff --prefix old/:new/
5349.1.4 by Matthäus G. Chajdas
Allow both --using and --diff-options.
2152
            
2153
        Show the differences using a custom diff program with options::
2154
        
2155
            bzr diff --using /usr/bin/diff --diff-options -wu
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2156
    """
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
2157
    _see_also = ['status']
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2158
    takes_args = ['file*']
2598.1.10 by Martin Pool
Clean up options that are registered globally and used once or not at all.
2159
    takes_options = [
2598.1.11 by Martin Pool
Insist that all options have a help string and fix those that don't.
2160
        Option('diff-options', type=str,
5349.1.4 by Matthäus G. Chajdas
Allow both --using and --diff-options.
2161
               help='Pass these options to the external diff program.'),
2193.3.1 by Martin Pool
Finish removal of global short-option table
2162
        Option('prefix', type=str,
2163
               short_name='p',
2852.1.1 by Vincent Ladeuil
Fix typo.
2164
               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
2165
                    'two values separated by a colon. (eg "old/:new/").'),
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
2166
        Option('old',
3118.1.2 by Ian Clatworthy
diff on branches without working trees (Ian Clatworthy, #6700)
2167
            help='Branch/tree to compare from.',
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
2168
            type=unicode,
2169
            ),
2170
        Option('new',
3118.1.2 by Ian Clatworthy
diff on branches without working trees (Ian Clatworthy, #6700)
2171
            help='Branch/tree to compare to.',
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
2172
            type=unicode,
2173
            ),
2598.1.11 by Martin Pool
Insist that all options have a help string and fix those that don't.
2174
        'revision',
2745.4.1 by Lukáš Lalinsky
New option -C/--change for diff and status to show changes in one revision. (#56299)
2175
        'change',
3123.6.2 by Aaron Bentley
Implement diff --using natively
2176
        Option('using',
2177
            help='Use this command to compare files.',
2178
            type=unicode,
2179
            ),
5131.1.1 by Jelmer Vernooij
Add --format option to 'bzr diff'.
2180
        RegistryOption('format',
5574.9.3 by Jelmer Vernooij
Add -F as alias for 'bzr diff -F format'
2181
            short_name='F',
5131.1.1 by Jelmer Vernooij
Add --format option to 'bzr diff'.
2182
            help='Diff format to use.',
2183
            lazy_registry=('bzrlib.diff', 'format_registry'),
5574.9.3 by Jelmer Vernooij
Add -F as alias for 'bzr diff -F format'
2184
            title='Diff format'),
2190.2.1 by Martin Pool
remove global registration of short options
2185
        ]
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2186
    aliases = ['di', 'dif']
1185.85.36 by John Arbash Meinel
Working on tests for revision-history, ancestry, and diff
2187
    encoding_type = 'exact'
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2188
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
2189
    @display_command
1684.1.6 by Martin Pool
(patch) --diff-prefix option (goffredo, alexander)
2190
    def run(self, revision=None, file_list=None, diff_options=None,
5131.1.1 by Jelmer Vernooij
Add --format option to 'bzr diff'.
2191
            prefix=None, old=None, new=None, using=None, format=None):
5147.3.3 by Andrew Bennetts
Add get_trees_and_branches_to_diff_locked, leave get_trees_and_branches_to_diff unchanged for qbzr.
2192
        from bzrlib.diff import (get_trees_and_branches_to_diff_locked,
5131.1.1 by Jelmer Vernooij
Add --format option to 'bzr diff'.
2193
            show_diff_trees)
1684.1.6 by Martin Pool
(patch) --diff-prefix option (goffredo, alexander)
2194
1694.2.3 by Martin Pool
Add -p0, -p1 options for diff.
2195
        if (prefix is None) or (prefix == '0'):
2196
            # diff -p0 format
1694.2.1 by Martin Pool
Remove 'a/', 'b/' default prefixes on diff output.
2197
            old_label = ''
2198
            new_label = ''
1694.2.3 by Martin Pool
Add -p0, -p1 options for diff.
2199
        elif prefix == '1':
2200
            old_label = 'old/'
2201
            new_label = 'new/'
2197.2.1 by Martin Pool
Refactor cmd_diff
2202
        elif ':' in prefix:
1694.2.3 by Martin Pool
Add -p0, -p1 options for diff.
2203
            old_label, new_label = prefix.split(":")
2197.2.1 by Martin Pool
Refactor cmd_diff
2204
        else:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
2205
            raise errors.BzrCommandError(gettext(
2325.1.2 by John Arbash Meinel
Add (eg "old/:new/") to errors to make it a little clearer.
2206
                '--prefix expects two values separated by a colon'
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
2207
                ' (eg "old/:new/")'))
2197.2.1 by Martin Pool
Refactor cmd_diff
2208
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.
2209
        if revision and len(revision) > 2:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
2210
            raise errors.BzrCommandError(gettext('bzr diff --revision takes exactly'
2211
                                         ' one or two revision specifiers'))
2325.1.2 by John Arbash Meinel
Add (eg "old/:new/") to errors to make it a little clearer.
2212
5131.1.2 by Jelmer Vernooij
Refuse both --using and --format to 'bzr diff'.
2213
        if using is not None and format is not None:
6123.11.17 by Martin von Gagern
Use the same translation template for all mutually exclusive command line options.
2214
            raise errors.BzrCommandError(gettext(
2215
                '{0} and {1} are mutually exclusive').format(
2216
                '--using', '--format'))
5131.1.2 by Jelmer Vernooij
Refuse both --using and --format to 'bzr diff'.
2217
4705.1.2 by Gary van der Merwe
Start on tests for get_trees_and_branches_to_diff.
2218
        (old_tree, new_tree,
2219
         old_branch, new_branch,
5147.3.3 by Andrew Bennetts
Add get_trees_and_branches_to_diff_locked, leave get_trees_and_branches_to_diff unchanged for qbzr.
2220
         specific_files, extra_trees) = get_trees_and_branches_to_diff_locked(
5147.3.1 by Andrew Bennetts
Avoid 6 branch/repo relocks in cmd_diff.
2221
            file_list, revision, old, new, self.add_cleanup, apply_view=True)
4797.57.3 by Alexander Belchenko
diff command: win32: passing user_encoding to show_diff_trees function so we can get proper encoding for non-ascii filenames (as GNU diff does).
2222
        # GNU diff on Windows uses ANSI encoding for filenames
4797.57.10 by Alexander Belchenko
path_encoding selection logic extracted as helper function
2223
        path_encoding = osutils.get_diff_header_encoding()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2224
        return show_diff_trees(old_tree, new_tree, sys.stdout,
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
2225
                               specific_files=specific_files,
2226
                               external_diff_options=diff_options,
2227
                               old_label=old_label, new_label=new_label,
4797.57.3 by Alexander Belchenko
diff command: win32: passing user_encoding to show_diff_trees function so we can get proper encoding for non-ascii filenames (as GNU diff does).
2228
                               extra_trees=extra_trees,
5258.1.1 by Alexander Belchenko
merge diff header work from my 2.1 branch
2229
                               path_encoding=path_encoding,
2230
                               using=using,
5131.1.1 by Jelmer Vernooij
Add --format option to 'bzr diff'.
2231
                               format_cls=format)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2232
2233
2234
class cmd_deleted(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
2235
    __doc__ = """List files deleted in the working tree.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2236
    """
1185.16.3 by Martin Pool
- remove all TODOs from bzr help messages
2237
    # TODO: Show files deleted since a previous revision, or
2238
    # between two revisions.
2239
    # TODO: Much more efficient way to do this: read in new
2240
    # directories with readdir, rather than stating each one.  Same
2241
    # level of effort but possibly much less IO.  (Or possibly not,
2242
    # if the directories are very large...)
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
2243
    _see_also = ['status', 'ls']
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
2244
    takes_options = ['directory', 'show-ids']
1185.85.49 by John Arbash Meinel
Updated cmd_deleted, including adding --show-ids option.
2245
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
2246
    @display_command
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
2247
    def run(self, show_ids=False, directory=u'.'):
2248
        tree = WorkingTree.open_containing(directory)[0]
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
2249
        self.add_cleanup(tree.lock_read().unlock)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
2250
        old = tree.basis_tree()
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
2251
        self.add_cleanup(old.lock_read().unlock)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
2252
        for path, ie in old.inventory.iter_entries():
2253
            if not tree.has_id(ie.file_id):
2254
                self.outf.write(path)
2255
                if show_ids:
2256
                    self.outf.write(' ')
2257
                    self.outf.write(ie.file_id)
2258
                self.outf.write('\n')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2259
2260
2261
class cmd_modified(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
2262
    __doc__ = """List files modified in working tree.
1551.10.13 by Aaron Bentley
Hide 'unknowns', document alterntatives to hidden commands
2263
    """
1551.10.14 by Aaron Bentley
Add some blank lines
2264
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2265
    hidden = True
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
2266
    _see_also = ['status', 'ls']
5193.3.7 by Parth Malwankar
merged in changes from trunk and resolved conflict in builtins.py
2267
    takes_options = ['directory', 'null']
1551.10.14 by Aaron Bentley
Add some blank lines
2268
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
2269
    @display_command
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
2270
    def run(self, null=False, directory=u'.'):
2271
        tree = WorkingTree.open_containing(directory)[0]
5588.3.1 by Andrew Bennetts
Fix -Drelock warnings in cmd_modified.
2272
        self.add_cleanup(tree.lock_read().unlock)
1852.10.3 by Robert Collins
Remove all uses of compare_trees and replace with Tree.changes_from throughout bzrlib.
2273
        td = tree.changes_from(tree.basis_tree())
5588.3.1 by Andrew Bennetts
Fix -Drelock warnings in cmd_modified.
2274
        self.cleanup_now()
1398 by Robert Collins
integrate in Gustavos x-bit patch
2275
        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
2276
            if null:
2277
                self.outf.write(path + '\0')
2278
            else:
2279
                self.outf.write(osutils.quotefn(path) + '\n')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2280
2281
2282
class cmd_added(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
2283
    __doc__ = """List files added in working tree.
1551.10.13 by Aaron Bentley
Hide 'unknowns', document alterntatives to hidden commands
2284
    """
1551.10.14 by Aaron Bentley
Add some blank lines
2285
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2286
    hidden = True
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
2287
    _see_also = ['status', 'ls']
5193.3.7 by Parth Malwankar
merged in changes from trunk and resolved conflict in builtins.py
2288
    takes_options = ['directory', 'null']
1551.10.14 by Aaron Bentley
Add some blank lines
2289
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
2290
    @display_command
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
2291
    def run(self, null=False, directory=u'.'):
2292
        wt = WorkingTree.open_containing(directory)[0]
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
2293
        self.add_cleanup(wt.lock_read().unlock)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
2294
        basis = wt.basis_tree()
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
2295
        self.add_cleanup(basis.lock_read().unlock)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
2296
        basis_inv = basis.inventory
2297
        inv = wt.inventory
2298
        for file_id in inv:
5967.7.1 by Martin Pool
Deprecate __contains__ on Tree and Inventory
2299
            if basis_inv.has_id(file_id):
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
2300
                continue
2301
            if inv.is_root(file_id) and len(basis_inv) == 0:
2302
                continue
2303
            path = inv.id2path(file_id)
5171.3.8 by Martin von Gagern
Fix error in bzr added --directory.
2304
            if not os.access(osutils.pathjoin(wt.basedir, path), os.F_OK):
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
2305
                continue
2306
            if null:
2307
                self.outf.write(path + '\0')
2308
            else:
2309
                self.outf.write(osutils.quotefn(path) + '\n')
1185.85.53 by John Arbash Meinel
Updated cmd_root
2310
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2311
2312
class cmd_root(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
2313
    __doc__ = """Show the tree root directory.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2314
2315
    The root is the nearest enclosing directory with a .bzr control
2316
    directory."""
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
2317
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2318
    takes_args = ['filename?']
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
2319
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2320
    def run(self, filename=None):
2321
        """Print the branch root."""
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
2322
        tree = WorkingTree.open_containing(filename)[0]
1685.1.80 by Wouter van Heyst
more code cleanup
2323
        self.outf.write(tree.basedir + '\n')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2324
2325
2466.9.1 by Kent Gibson
add bzr log --limit
2326
def _parse_limit(limitstring):
2327
    try:
2328
        return int(limitstring)
2329
    except ValueError:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
2330
        msg = gettext("The limit argument must be an integer.")
2466.9.1 by Kent Gibson
add bzr log --limit
2331
        raise errors.BzrCommandError(msg)
2332
2333
3970.1.1 by Ian Clatworthy
log -n/--levels (Ian Clatworthy)
2334
def _parse_levels(s):
3947.1.6 by Ian Clatworthy
log -n/--level-count N option
2335
    try:
2336
        return int(s)
2337
    except ValueError:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
2338
        msg = gettext("The levels argument must be an integer.")
3947.1.6 by Ian Clatworthy
log -n/--level-count N option
2339
        raise errors.BzrCommandError(msg)
2340
2341
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2342
class cmd_log(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
2343
    __doc__ = """Show historical log for a branch or subset of a branch.
3974.1.2 by Ian Clatworthy
enhanced log help
2344
2345
    log is bzr's default tool for exploring the history of a branch.
2346
    The branch to use is taken from the first parameter. If no parameters
2347
    are given, the branch containing the working directory is logged.
2348
    Here are some simple examples::
2349
2350
      bzr log                       log the current branch
2351
      bzr log foo.py                log a file in its branch
2352
      bzr log http://server/branch  log a branch on a server
2353
2354
    The filtering, ordering and information shown for each revision can
2355
    be controlled as explained below. By default, all revisions are
2356
    shown sorted (topologically) so that newer revisions appear before
2357
    older ones and descendants always appear before ancestors. If displayed,
2358
    merged revisions are shown indented under the revision in which they
2359
    were merged.
2360
2361
    :Output control:
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2362
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2363
      The log format controls how information about each revision is
2364
      displayed. The standard log formats are called ``long``, ``short``
2365
      and ``line``. The default is long. See ``bzr help log-formats``
2366
      for more details on log formats.
3974.1.2 by Ian Clatworthy
enhanced log help
2367
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2368
      The following options can be used to control what information is
2369
      displayed::
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2370
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2371
        -l N        display a maximum of N revisions
2372
        -n N        display N levels of revisions (0 for all, 1 for collapsed)
2373
        -v          display a status summary (delta) for each revision
2374
        -p          display a diff (patch) for each revision
2375
        --show-ids  display revision-ids (and file-ids), not just revnos
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2376
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2377
      Note that the default number of levels to display is a function of the
4206.1.1 by Ian Clatworthy
log mainline by default
2378
      log format. If the -n option is not used, the standard log formats show
2379
      just the top level (mainline).
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2380
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2381
      Status summaries are shown using status flags like A, M, etc. To see
2382
      the changes explained using words like ``added`` and ``modified``
2383
      instead, use the -vv option.
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2384
3974.1.2 by Ian Clatworthy
enhanced log help
2385
    :Ordering control:
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2386
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2387
      To display revisions from oldest to newest, use the --forward option.
2388
      In most cases, using this option will have little impact on the total
2389
      time taken to produce a log, though --forward does not incrementally
2390
      display revisions like --reverse does when it can.
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2391
3974.1.2 by Ian Clatworthy
enhanced log help
2392
    :Revision filtering:
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2393
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2394
      The -r option can be used to specify what revision or range of revisions
2395
      to filter against. The various forms are shown below::
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2396
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2397
        -rX      display revision X
2398
        -rX..    display revision X and later
2399
        -r..Y    display up to and including revision Y
2400
        -rX..Y   display from X to Y inclusive
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2401
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2402
      See ``bzr help revisionspec`` for details on how to specify X and Y.
2403
      Some common examples are given below::
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2404
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2405
        -r-1                show just the tip
2406
        -r-10..             show the last 10 mainline revisions
2407
        -rsubmit:..         show what's new on this branch
2408
        -rancestor:path..   show changes since the common ancestor of this
2409
                            branch and the one at location path
2410
        -rdate:yesterday..  show changes since yesterday
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2411
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2412
      When logging a range of revisions using -rX..Y, log starts at
2413
      revision Y and searches back in history through the primary
2414
      ("left-hand") parents until it finds X. When logging just the
2415
      top level (using -n1), an error is reported if X is not found
2416
      along the way. If multi-level logging is used (-n0), X may be
2417
      a nested merge revision and the log will be truncated accordingly.
2418
3974.1.2 by Ian Clatworthy
enhanced log help
2419
    :Path filtering:
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2420
4202.2.5 by Ian Clatworthy
apply review tweaks & update help
2421
      If parameters are given and the first one is not a branch, the log
2422
      will be filtered to show only those revisions that changed the
2423
      nominated files or directories.
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2424
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2425
      Filenames are interpreted within their historical context. To log a
2426
      deleted file, specify a revision range so that the file existed at
2427
      the end or start of the range.
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2428
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2429
      Historical context is also important when interpreting pathnames of
2430
      renamed files/directories. Consider the following example:
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2431
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2432
      * revision 1: add tutorial.txt
2433
      * revision 2: modify tutorial.txt
2434
      * revision 3: rename tutorial.txt to guide.txt; add tutorial.txt
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2435
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2436
      In this case:
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2437
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2438
      * ``bzr log guide.txt`` will log the file added in revision 1
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2439
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2440
      * ``bzr log tutorial.txt`` will log the new file added in revision 3
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2441
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2442
      * ``bzr log -r2 -p tutorial.txt`` will show the changes made to
2443
        the original file in revision 2.
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2444
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2445
      * ``bzr log -r2 -p guide.txt`` will display an error message as there
2446
        was no file called guide.txt in revision 2.
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2447
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2448
      Renames are always followed by log. By design, there is no need to
2449
      explicitly ask for this (and no way to stop logging a file back
2450
      until it was last renamed).
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2451
3974.1.2 by Ian Clatworthy
enhanced log help
2452
    :Other filtering:
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2453
5935.2.2 by Jacek Sieka
Improve help message and hide --message option
2454
      The --match option can be used for finding revisions that match a
2455
      regular expression in a commit message, committer, author or bug.
2456
      Specifying the option several times will match any of the supplied
2457
      expressions. --match-author, --match-bugs, --match-committer and
2458
      --match-message can be used to only match a specific field.
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2459
3974.1.2 by Ian Clatworthy
enhanced log help
2460
    :Tips & tricks:
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2461
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2462
      GUI tools and IDEs are often better at exploring history than command
4988.4.2 by Martin Pool
Change url to canonical.com or wiki, plus some doc improvements in passing
2463
      line tools: you may prefer qlog or viz from qbzr or bzr-gtk, the
2464
      bzr-explorer shell, or the Loggerhead web interface.  See the Plugin
2465
      Guide <http://doc.bazaar.canonical.com/plugins/en/> and
2466
      <http://wiki.bazaar.canonical.com/IDEIntegration>.  
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2467
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2468
      You may find it useful to add the aliases below to ``bazaar.conf``::
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2469
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2470
        [ALIASES]
4206.1.1 by Ian Clatworthy
log mainline by default
2471
        tip = log -r-1
4202.2.5 by Ian Clatworthy
apply review tweaks & update help
2472
        top = log -l10 --line
4206.1.1 by Ian Clatworthy
log mainline by default
2473
        show = log -v -p
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2474
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2475
      ``bzr tip`` will then show the latest revision while ``bzr top``
2476
      will show the last 10 mainline revisions. To see the details of a
2477
      particular revision X,  ``bzr show -rX``.
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2478
4206.1.1 by Ian Clatworthy
log mainline by default
2479
      If you are interested in looking deeper into a particular merge X,
2480
      use ``bzr log -n0 -rX``.
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2481
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2482
      ``bzr log -v`` on a branch with lots of history is currently
2483
      very slow. A fix for this issue is currently under development.
2484
      With or without that fix, it is recommended that a revision range
2485
      be given when using the -v option.
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2486
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2487
      bzr has a generic full-text matching plugin, bzr-search, that can be
2488
      used to find revisions matching user names, commit messages, etc.
2489
      Among other features, this plugin can find all revisions containing
2490
      a list of words but not others.
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2491
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2492
      When exploring non-mainline history on large projects with deep
2493
      history, the performance of log can be greatly improved by installing
4360.1.1 by Ian Clatworthy
(trivial) revnocache -> historycache in log help (Ian Clatworthy)
2494
      the historycache plugin. This plugin buffers historical information
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2495
      trading disk space for faster speed.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2496
    """
4202.2.1 by Ian Clatworthy
get directory logging working again
2497
    takes_args = ['file*']
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2498
    _see_also = ['log-formats', 'revisionspec']
2598.1.3 by Martin Pool
Option help improvements (thanks jamesw)
2499
    takes_options = [
2500
            Option('forward',
2501
                   help='Show from oldest to newest.'),
3755.1.1 by Vincent Ladeuil
Fix --verbose leaking into blackbox tests.
2502
            'timezone',
2768.1.5 by Ian Clatworthy
Wrap new std verbose option with new help instead of declaring a new one
2503
            custom_help('verbose',
2598.1.3 by Martin Pool
Option help improvements (thanks jamesw)
2504
                   help='Show files changed in each revision.'),
2505
            'show-ids',
2506
            'revision',
3734.1.1 by Vincent Ladeuil
Fix bug #248427 by adding a --change option to log.
2507
            Option('change',
2508
                   type=bzrlib.option._parse_revision_str,
2509
                   short_name='c',
2510
                   help='Show just the specified revision.'
2511
                   ' See also "help revisionspec".'),
2598.1.3 by Martin Pool
Option help improvements (thanks jamesw)
2512
            'log-format',
4081.3.9 by Martin von Gagern
Use proper registry for --authors option.
2513
            RegistryOption('authors',
4081.3.11 by Martin von Gagern
List alternatives for --authors option.
2514
                'What names to list as authors - first, all or committer.',
4081.3.8 by Martin von Gagern
Use convenience RegistryOption for --authors option to log command.
2515
                title='Authors',
4081.3.9 by Martin von Gagern
Use proper registry for --authors option.
2516
                lazy_registry=('bzrlib.log', 'author_list_registry'),
4081.3.8 by Martin von Gagern
Use convenience RegistryOption for --authors option to log command.
2517
            ),
3947.1.10 by Ian Clatworthy
review feedback from vila
2518
            Option('levels',
3947.1.5 by Ian Clatworthy
rename --merge-revisions to --include-merges
2519
                   short_name='n',
3947.1.6 by Ian Clatworthy
log -n/--level-count N option
2520
                   help='Number of levels to display - 0 for all, 1 for flat.',
2521
                   argname='N',
3970.1.1 by Ian Clatworthy
log -n/--levels (Ian Clatworthy)
2522
                   type=_parse_levels),
2598.1.3 by Martin Pool
Option help improvements (thanks jamesw)
2523
            Option('message',
2524
                   help='Show revisions whose message matches this '
2525
                        'regular expression.',
5935.2.2 by Jacek Sieka
Improve help message and hide --message option
2526
                   type=str,
2527
                   hidden=True),
2598.1.3 by Martin Pool
Option help improvements (thanks jamesw)
2528
            Option('limit',
3108.1.1 by Matt Nordhoff
bzr log: Add -l short name for the --limit argument.
2529
                   short_name='l',
2598.1.3 by Martin Pool
Option help improvements (thanks jamesw)
2530
                   help='Limit the output to the first N revisions.',
2531
                   argname='N',
2532
                   type=_parse_limit),
3943.5.1 by Ian Clatworthy
first cut at log --show-diff
2533
            Option('show-diff',
3943.5.5 by Ian Clatworthy
tweak option name as requested in bug report
2534
                   short_name='p',
2535
                   help='Show changes made in each revision as a patch.'),
6123.11.13 by Martin von Gagern
Rename --include-sidelines to --include-merged.
2536
            Option('include-merged',
4221.2.1 by Ian Clatworthy
--include-merges as an alias for --levels 0 in log
2537
                   help='Show merged revisions like --levels 0 does.'),
6123.11.1 by Martin von Gagern
Rename --include-merges option to --include-sidelines.
2538
            Option('include-merges', hidden=True,
6123.11.13 by Martin von Gagern
Rename --include-sidelines to --include-merged.
2539
                   help='Historical alias for --include-merged.'),
6123.11.4 by Martin von Gagern
Introduce an option "--omit-merges" for "bzr log".
2540
            Option('omit-merges',
2541
                   help='Do not report commits with more than one parent.'),
5097.1.12 by Vincent Ladeuil
Implement the --exclude-common-ancestry log option.
2542
            Option('exclude-common-ancestry',
2543
                   help='Display only the revisions that are not part'
6259.2.5 by Martin Packman
Add full stops to various option help text so test_option_grammar passes
2544
                   ' of both ancestries (require -rX..Y).'
5935.2.1 by Jacek Sieka
Change the meaning of the log -m option to match and make it match message, committer, authors and bugs. --match-message and friends can be used to make more specific matches.
2545
                   ),
5971.1.40 by Jonathan Riddell
add command line option
2546
            Option('signatures',
6259.2.5 by Martin Packman
Add full stops to various option help text so test_option_grammar passes
2547
                   help='Show digital signature validity.'),
5935.2.1 by Jacek Sieka
Change the meaning of the log -m option to match and make it match message, committer, authors and bugs. --match-message and friends can be used to make more specific matches.
2548
            ListOption('match',
2549
                short_name='m',
2550
                help='Show revisions whose properties match this '
2551
                'expression.',
2552
                type=str),
2553
            ListOption('match-message',
2554
                   help='Show revisions whose message matches this '
2555
                   'expression.',
2556
                type=str),
2557
            ListOption('match-committer',
2558
                   help='Show revisions whose committer matches this '
2559
                   'expression.',
2560
                type=str),
2561
            ListOption('match-author',
2562
                   help='Show revisions whose authors match this '
2563
                   'expression.',
2564
                type=str),
2565
            ListOption('match-bugs',
2566
                   help='Show revisions whose bugs match this '
2567
                   'expression.',
2568
                type=str)
2598.1.3 by Martin Pool
Option help improvements (thanks jamesw)
2569
            ]
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()
2570
    encoding_type = 'replace'
2571
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
2572
    @display_command
4202.2.1 by Ian Clatworthy
get directory logging working again
2573
    def run(self, file_list=None, timezone='original',
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2574
            verbose=False,
2575
            show_ids=False,
2576
            forward=False,
2577
            revision=None,
3734.1.1 by Vincent Ladeuil
Fix bug #248427 by adding a --change option to log.
2578
            change=None,
1553.2.1 by Erik Bågfors
Support for plugins to register log formatters and set default formatter
2579
            log_format=None,
3947.1.10 by Ian Clatworthy
review feedback from vila
2580
            levels=None,
2466.9.1 by Kent Gibson
add bzr log --limit
2581
            message=None,
3943.5.1 by Ian Clatworthy
first cut at log --show-diff
2582
            limit=None,
4221.2.1 by Ian Clatworthy
--include-merges as an alias for --levels 0 in log
2583
            show_diff=False,
6123.11.13 by Martin von Gagern
Rename --include-sidelines to --include-merged.
2584
            include_merged=None,
4081.3.15 by Gary van der Merwe
Merge bzr.dev.
2585
            authors=None,
5097.1.12 by Vincent Ladeuil
Implement the --exclude-common-ancestry log option.
2586
            exclude_common_ancestry=False,
5971.1.40 by Jonathan Riddell
add command line option
2587
            signatures=False,
5935.2.1 by Jacek Sieka
Change the meaning of the log -m option to match and make it match message, committer, authors and bugs. --match-message and friends can be used to make more specific matches.
2588
            match=None,
2589
            match_message=None,
2590
            match_committer=None,
2591
            match_author=None,
2592
            match_bugs=None,
6123.11.6 by Vincent Ladeuil
Add new paraneters add signature's ends, fix a test and a typo, check that no errors and no output is emitted when using assertLogRevnos.
2593
            omit_merges=False,
6123.11.10 by Martin von Gagern
Print deprecation warnings for all uses of include_merges.
2594
            include_merges=symbol_versioning.DEPRECATED_PARAMETER,
5097.1.12 by Vincent Ladeuil
Implement the --exclude-common-ancestry log option.
2595
            ):
4202.2.5 by Ian Clatworthy
apply review tweaks & update help
2596
        from bzrlib.log import (
2597
            Logger,
2598
            make_log_request_dict,
2599
            _get_info_for_log_files,
2600
            )
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2601
        direction = (forward and 'forward') or 'reverse'
6123.11.10 by Martin von Gagern
Print deprecation warnings for all uses of include_merges.
2602
        if symbol_versioning.deprecated_passed(include_merges):
2603
            ui.ui_factory.show_user_warning(
2604
                'deprecated_command_option',
2605
                deprecated_name='--include-merges',
6123.11.13 by Martin von Gagern
Rename --include-sidelines to --include-merged.
2606
                recommended_name='--include-merged',
6123.11.10 by Martin von Gagern
Print deprecation warnings for all uses of include_merges.
2607
                deprecated_in_version='2.5',
2608
                command=self.invoked_as)
6123.11.13 by Martin von Gagern
Rename --include-sidelines to --include-merged.
2609
            if include_merged is None:
2610
                include_merged = include_merges
6123.11.10 by Martin von Gagern
Print deprecation warnings for all uses of include_merges.
2611
            else:
6123.11.16 by Martin von Gagern
Use gettext for command errors about conflicting options.
2612
                raise errors.BzrCommandError(gettext(
6123.11.17 by Martin von Gagern
Use the same translation template for all mutually exclusive command line options.
2613
                    '{0} and {1} are mutually exclusive').format(
2614
                    '--include-merges', '--include-merged'))
6123.11.13 by Martin von Gagern
Rename --include-sidelines to --include-merged.
2615
        if include_merged is None:
2616
            include_merged = False
5097.1.12 by Vincent Ladeuil
Implement the --exclude-common-ancestry log option.
2617
        if (exclude_common_ancestry
2618
            and (revision is None or len(revision) != 2)):
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
2619
            raise errors.BzrCommandError(gettext(
2620
                '--exclude-common-ancestry requires -r with two revisions'))
6123.11.13 by Martin von Gagern
Rename --include-sidelines to --include-merged.
2621
        if include_merged:
4221.2.2 by Ian Clatworthy
jam feedback: make --levels and --include-merges mutually exclusive
2622
            if levels is None:
2623
                levels = 0
2624
            else:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
2625
                raise errors.BzrCommandError(gettext(
6123.11.17 by Martin von Gagern
Use the same translation template for all mutually exclusive command line options.
2626
                    '{0} and {1} are mutually exclusive').format(
2627
                    '--levels', '--include-merged'))
3734.1.1 by Vincent Ladeuil
Fix bug #248427 by adding a --change option to log.
2628
2629
        if change is not None:
2630
            if len(change) > 1:
2631
                raise errors.RangeInChangeOption()
2632
            if revision is not None:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
2633
                raise errors.BzrCommandError(gettext(
6123.11.17 by Martin von Gagern
Use the same translation template for all mutually exclusive command line options.
2634
                    '{0} and {1} are mutually exclusive').format(
2635
                    '--revision', '--change'))
3734.1.1 by Vincent Ladeuil
Fix bug #248427 by adding a --change option to log.
2636
            else:
2637
                revision = change
2638
4202.2.1 by Ian Clatworthy
get directory logging working again
2639
        file_ids = []
2640
        filter_by_dir = False
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
2641
        if file_list:
2642
            # find the file ids to log and check for directory filtering
2643
            b, file_info_list, rev1, rev2 = _get_info_for_log_files(
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
2644
                revision, file_list, self.add_cleanup)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
2645
            for relpath, file_id, kind in file_info_list:
2646
                if file_id is None:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
2647
                    raise errors.BzrCommandError(gettext(
2648
                        "Path unknown at end or start of revision range: %s") %
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
2649
                        relpath)
2650
                # If the relpath is the top of the tree, we log everything
2651
                if relpath == '':
2652
                    file_ids = []
2653
                    break
4202.2.1 by Ian Clatworthy
get directory logging working again
2654
                else:
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
2655
                    file_ids.append(file_id)
2656
                filter_by_dir = filter_by_dir or (
2657
                    kind in ['directory', 'tree-reference'])
2658
        else:
2659
            # log everything
2660
            # FIXME ? log the current subdir only RBC 20060203
2661
            if revision is not None \
2662
                    and len(revision) > 0 and revision[0].get_branch():
2663
                location = revision[0].get_branch()
2664
            else:
2665
                location = '.'
6207.3.3 by jelmer at samba
Fix tests and the like.
2666
            dir, relpath = controldir.ControlDir.open_containing(location)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
2667
            b = dir.open_branch()
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
2668
            self.add_cleanup(b.lock_read().unlock)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
2669
            rev1, rev2 = _get_revision_range(revision, b, self.name())
2670
5971.1.55 by Jonathan Riddell
add a config option to validate signatures
2671
        if b.get_config().validate_signatures_in_log():
2672
            signatures = True
2673
2674
        if signatures:
5971.1.60 by Jonathan Riddell
move checking for gpgme availability into gpg.py
2675
            if not gpg.GPGStrategy.verify_signatures_available():
2676
                raise errors.GpgmeNotInstalled(None)
5971.1.55 by Jonathan Riddell
add a config option to validate signatures
2677
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
2678
        # Decide on the type of delta & diff filtering to use
2679
        # TODO: add an --all-files option to make this configurable & consistent
2680
        if not verbose:
2681
            delta_type = None
2682
        else:
2683
            delta_type = 'full'
2684
        if not show_diff:
2685
            diff_type = None
2686
        elif file_ids:
2687
            diff_type = 'partial'
2688
        else:
2689
            diff_type = 'full'
2690
2691
        # Build the log formatter
2692
        if log_format is None:
2693
            log_format = log.log_formatter_registry.get_default(b)
2694
        # Make a non-encoding output to include the diffs - bug 328007
2695
        unencoded_output = ui.ui_factory.make_output_stream(encoding_type='exact')
2696
        lf = log_format(show_ids=show_ids, to_file=self.outf,
2697
                        to_exact_file=unencoded_output,
2698
                        show_timezone=timezone,
2699
                        delta_format=get_verbosity_level(),
2700
                        levels=levels,
4081.3.2 by Martin von Gagern
Provide --authors argument to log command.
2701
                        show_advice=levels is None,
4081.3.10 by Martin von Gagern
Renamed "authors" to "author_list_handler" in several places.
2702
                        author_list_handler=authors)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
2703
2704
        # Choose the algorithm for doing the logging. It's annoying
2705
        # having multiple code paths like this but necessary until
2706
        # the underlying repository format is faster at generating
2707
        # deltas or can provide everything we need from the indices.
2708
        # The default algorithm - match-using-deltas - works for
2709
        # multiple files and directories and is faster for small
2710
        # amounts of history (200 revisions say). However, it's too
2711
        # slow for logging a single file in a repository with deep
2712
        # history, i.e. > 10K revisions. In the spirit of "do no
2713
        # evil when adding features", we continue to use the
2714
        # original algorithm - per-file-graph - for the "single
2715
        # file that isn't a directory without showing a delta" case.
2716
        partial_history = revision and b.repository._format.supports_chks
2717
        match_using_deltas = (len(file_ids) != 1 or filter_by_dir
2718
            or delta_type or partial_history)
2719
5935.2.1 by Jacek Sieka
Change the meaning of the log -m option to match and make it match message, committer, authors and bugs. --match-message and friends can be used to make more specific matches.
2720
        match_dict = {}
2721
        if match:
2722
            match_dict[''] = match
2723
        if match_message:
2724
            match_dict['message'] = match_message
2725
        if match_committer:
2726
            match_dict['committer'] = match_committer
2727
        if match_author:
2728
            match_dict['author'] = match_author
2729
        if match_bugs:
2730
            match_dict['bugs'] = match_bugs
6162.1.1 by Vincent Ladeuil
Stop reloading all ancestry for each tag when searching tags in a revision range (still breaks if X>Y in -rX..Y)
2731
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
2732
        # Build the LogRequest and execute it
2733
        if len(file_ids) == 0:
2734
            file_ids = None
2735
        rqst = make_log_request_dict(
2736
            direction=direction, specific_fileids=file_ids,
2737
            start_revision=rev1, end_revision=rev2, limit=limit,
2738
            message_search=message, delta_type=delta_type,
5097.1.12 by Vincent Ladeuil
Implement the --exclude-common-ancestry log option.
2739
            diff_type=diff_type, _match_using_deltas=match_using_deltas,
5935.2.1 by Jacek Sieka
Change the meaning of the log -m option to match and make it match message, committer, authors and bugs. --match-message and friends can be used to make more specific matches.
2740
            exclude_common_ancestry=exclude_common_ancestry, match=match_dict,
6123.11.4 by Martin von Gagern
Introduce an option "--omit-merges" for "bzr log".
2741
            signature=signatures, omit_merges=omit_merges,
5097.1.12 by Vincent Ladeuil
Implement the --exclude-common-ancestry log option.
2742
            )
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
2743
        Logger(b, rqst).show(lf)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2744
3943.6.3 by Ian Clatworthy
search the start tree if the end tree doesn't have a file
2745
3904.2.4 by Marius Kruger
* rename _get2Revisions to _get_revision_range
2746
def _get_revision_range(revisionspec_list, branch, command_name):
2747
    """Take the input of a revision option and turn it into a revision range.
2748
2749
    It returns RevisionInfo objects which can be used to obtain the rev_id's
4202.2.1 by Ian Clatworthy
get directory logging working again
2750
    of the desired revisions. It does some user input validations.
3904.2.4 by Marius Kruger
* rename _get2Revisions to _get_revision_range
2751
    """
3904.2.1 by Marius Kruger
* factor out _get2Revisions from cmd_log to be able to reuse how revesions is determined by log.
2752
    if revisionspec_list is None:
2753
        rev1 = None
2754
        rev2 = None
2755
    elif len(revisionspec_list) == 1:
2756
        rev1 = rev2 = revisionspec_list[0].in_history(branch)
2757
    elif len(revisionspec_list) == 2:
3936.3.21 by Ian Clatworthy
make log -rX.. as fast as log -rX..-1
2758
        start_spec = revisionspec_list[0]
2759
        end_spec = revisionspec_list[1]
2760
        if end_spec.get_branch() != start_spec.get_branch():
3904.2.1 by Marius Kruger
* factor out _get2Revisions from cmd_log to be able to reuse how revesions is determined by log.
2761
            # b is taken from revision[0].get_branch(), and
2762
            # show_log will use its revision_history. Having
2763
            # different branches will lead to weird behaviors.
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
2764
            raise errors.BzrCommandError(gettext(
3904.2.4 by Marius Kruger
* rename _get2Revisions to _get_revision_range
2765
                "bzr %s doesn't accept two revisions in different"
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
2766
                " branches.") % command_name)
5092.1.2 by Vincent Ladeuil
Fix bug #519862.
2767
        if start_spec.spec is None:
2768
            # Avoid loading all the history.
5092.1.3 by Vincent Ladeuil
Tweak to fix failing test in the full test suite.
2769
            rev1 = RevisionInfo(branch, None, None)
5092.1.2 by Vincent Ladeuil
Fix bug #519862.
2770
        else:
2771
            rev1 = start_spec.in_history(branch)
3936.3.21 by Ian Clatworthy
make log -rX.. as fast as log -rX..-1
2772
        # Avoid loading all of history when we know a missing
2773
        # end of range means the last revision ...
3936.3.40 by Ian Clatworthy
review feedback from jam
2774
        if end_spec.spec is None:
3936.3.21 by Ian Clatworthy
make log -rX.. as fast as log -rX..-1
2775
            last_revno, last_revision_id = branch.last_revision_info()
2776
            rev2 = RevisionInfo(branch, last_revno, last_revision_id)
2777
        else:
2778
            rev2 = end_spec.in_history(branch)
3904.2.1 by Marius Kruger
* factor out _get2Revisions from cmd_log to be able to reuse how revesions is determined by log.
2779
    else:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
2780
        raise errors.BzrCommandError(gettext(
2781
            'bzr %s --revision takes one or two values.') % 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.
2782
    return rev1, rev2
1185.85.4 by John Arbash Meinel
currently broken, trying to fix things up.
2783
3921.3.4 by Marius Kruger
add support to filter on local and remote revisions
2784
2785
def _revision_range_to_revid_range(revision_range):
2786
    rev_id1 = None
2787
    rev_id2 = None
2788
    if revision_range[0] is not None:
2789
        rev_id1 = revision_range[0].rev_id
2790
    if revision_range[1] is not None:
2791
        rev_id2 = revision_range[1].rev_id
2792
    return rev_id1, rev_id2
2793
1857.1.20 by Aaron Bentley
Strip out all the EnumOption stuff
2794
def get_log_format(long=False, short=False, line=False, default='long'):
2795
    log_format = default
2796
    if long:
2797
        log_format = 'long'
2798
    if short:
2799
        log_format = 'short'
2800
    if line:
2801
        log_format = 'line'
2802
    return log_format
2803
2804
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2805
class cmd_touching_revisions(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
2806
    __doc__ = """Return revision-ids which affected a particular file.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2807
1685.1.80 by Wouter van Heyst
more code cleanup
2808
    A more user-friendly interface is "bzr log FILE".
2809
    """
2810
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2811
    hidden = True
2812
    takes_args = ["filename"]
1185.85.55 by John Arbash Meinel
Updated cmd_touching_revisions
2813
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
2814
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2815
    def run(self, filename):
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
2816
        tree, relpath = WorkingTree.open_containing(filename)
4634.90.3 by Andrew Bennetts
Fix other bugs revealed by clearing chk_map page cache during blackbox tests.
2817
        file_id = tree.path2id(relpath)
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
2818
        b = tree.branch
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
2819
        self.add_cleanup(b.lock_read().unlock)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
2820
        touching_revs = log.find_touching_revisions(b, file_id)
2821
        for revno, revision_id, what in touching_revs:
2822
            self.outf.write("%6d %s\n" % (revno, what))
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2823
2824
2825
class cmd_ls(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
2826
    __doc__ = """List files in a tree.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2827
    """
1551.9.24 by Aaron Bentley
Unhide ls, add kind flag
2828
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
2829
    _see_also = ['status', 'cat']
2215.3.1 by Aaron Bentley
Allow ls to take a PATH
2830
    takes_args = ['path?']
2598.1.2 by Martin Pool
Also check that option help ends in a period, and fix those that don't
2831
    takes_options = [
2832
            'verbose',
2833
            'revision',
4206.2.1 by Ian Clatworthy
ls should be non-recursive by default
2834
            Option('recursive', short_name='R',
2835
                   help='Recurse into subdirectories.'),
5193.3.3 by Parth Malwankar
removed -l for --from-root as that can be confusing as ls -l
2836
            Option('from-root',
2598.1.3 by Martin Pool
Option help improvements (thanks jamesw)
2837
                   help='Print paths relative to the root of the branch.'),
5193.3.1 by Parth Malwankar
added short options for ls.
2838
            Option('unknown', short_name='u',
2839
                help='Print unknown files.'),
3382.2.1 by Jerad Cramp
Fixed bug #165086. Command 'bzr ls' now accepts '-V' as an alias for '--versioned'.
2840
            Option('versioned', help='Print versioned files.',
2841
                   short_name='V'),
5193.3.1 by Parth Malwankar
added short options for ls.
2842
            Option('ignored', short_name='i',
2843
                help='Print ignored files.'),
2844
            Option('kind', short_name='k',
2598.1.12 by Martin Pool
Fix up --kind options
2845
                   help='List entries of a particular kind: file, directory, symlink.',
2846
                   type=unicode),
5193.3.4 by Parth Malwankar
--null is now a _standard_option
2847
            'null',
2598.1.2 by Martin Pool
Also check that option help ends in a period, and fix those that don't
2848
            'show-ids',
5171.3.3 by Martin von Gagern
Add --directory option to ls, cat and annotate.
2849
            'directory',
2598.1.2 by Martin Pool
Also check that option help ends in a period, and fix those that don't
2850
            ]
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
2851
    @display_command
2598.1.12 by Martin Pool
Fix up --kind options
2852
    def run(self, revision=None, verbose=False,
4206.2.1 by Ian Clatworthy
ls should be non-recursive by default
2853
            recursive=False, from_root=False,
1185.26.1 by John Arbash Meinel
Made ls work again, and take extra arguments.
2854
            unknown=False, versioned=False, ignored=False,
5171.3.3 by Martin von Gagern
Add --directory option to ls, cat and annotate.
2855
            null=False, kind=None, show_ids=False, path=None, directory=None):
1551.9.24 by Aaron Bentley
Unhide ls, add kind flag
2856
2857
        if kind and kind not in ('file', 'directory', 'symlink'):
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
2858
            raise errors.BzrCommandError(gettext('invalid kind specified'))
1185.26.1 by John Arbash Meinel
Made ls work again, and take extra arguments.
2859
2860
        if verbose and null:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
2861
            raise errors.BzrCommandError(gettext('Cannot set both --verbose and --null'))
1551.6.36 by Aaron Bentley
Revert --debris/--detritus changes
2862
        all = not (unknown or versioned or ignored)
1185.26.1 by John Arbash Meinel
Made ls work again, and take extra arguments.
2863
1551.6.36 by Aaron Bentley
Revert --debris/--detritus changes
2864
        selection = {'I':ignored, '?':unknown, 'V':versioned}
1185.26.1 by John Arbash Meinel
Made ls work again, and take extra arguments.
2865
2215.3.1 by Aaron Bentley
Allow ls to take a PATH
2866
        if path is None:
2867
            fs_path = '.'
2868
        else:
2869
            if from_root:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
2870
                raise errors.BzrCommandError(gettext('cannot specify both --from-root'
2871
                                             ' and PATH'))
2215.3.1 by Aaron Bentley
Allow ls to take a PATH
2872
            fs_path = path
5171.3.6 by Martin von Gagern
Fix --directory option to ls command.
2873
        tree, branch, relpath = \
5171.3.9 by Martin von Gagern
Rename function to _open_directory_or_containing_tree_or_branch.
2874
            _open_directory_or_containing_tree_or_branch(fs_path, directory)
4370.6.3 by Ian Clatworthy
minimise differences to trunk code
2875
2876
        # Calculate the prefix to use
2877
        prefix = None
1185.26.1 by John Arbash Meinel
Made ls work again, and take extra arguments.
2878
        if from_root:
4370.6.3 by Ian Clatworthy
minimise differences to trunk code
2879
            if relpath:
2880
                prefix = relpath + '/'
4832.1.1 by Benjamin Peterson
avoid getting extra slashes in the output when ls' argument ends with a slash
2881
        elif fs_path != '.' and not fs_path.endswith('/'):
4370.6.3 by Ian Clatworthy
minimise differences to trunk code
2882
            prefix = fs_path + '/'
4456.1.2 by Ian Clatworthy
fix tabs in builtins.py
2883
3655.3.1 by Lukáš Lalinský
Fix `bzr st -rbranch:PATH_TO_BRANCH`
2884
        if revision is not None or tree is None:
3732.1.1 by Ian Clatworthy
fix bzr st -rbranch:path-to-branch (Lukas Lalinsky)
2885
            tree = _get_one_revision_tree('ls', revision, branch=branch)
1551.6.36 by Aaron Bentley
Revert --debris/--detritus changes
2886
4032.4.5 by Eduardo Padoan
Check if the tree supports views only once when ls is called.
2887
        apply_view = False
4048.1.2 by Ian Clatworthy
fix broken test for ls -r
2888
        if isinstance(tree, WorkingTree) and tree.supports_views():
4032.4.2 by Eduardo Padoan
Make ls show only files on the current view.
2889
            view_files = tree.views.lookup_view()
2890
            if view_files:
4032.4.5 by Eduardo Padoan
Check if the tree supports views only once when ls is called.
2891
                apply_view = True
4032.4.2 by Eduardo Padoan
Make ls show only files on the current view.
2892
                view_str = views.view_display_str(view_files)
6138.2.2 by Jonathan Riddell
gettext builtin.py's note() usage
2893
                note(gettext("Ignoring files outside view. View is %s") % view_str)
4032.4.2 by Eduardo Padoan
Make ls show only files on the current view.
2894
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
2895
        self.add_cleanup(tree.lock_read().unlock)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
2896
        for fp, fc, fkind, fid, entry in tree.list_files(include_root=False,
2897
            from_dir=relpath, recursive=recursive):
2898
            # Apply additional masking
2899
            if not all and not selection[fc]:
2900
                continue
2901
            if kind is not None and fkind != kind:
2902
                continue
2903
            if apply_view:
2904
                try:
2905
                    if relpath:
2906
                        fullpath = osutils.pathjoin(relpath, fp)
2907
                    else:
2908
                        fullpath = fp
2909
                    views.check_path_in_view(tree, fullpath)
2910
                except errors.FileOutsideView:
2911
                    continue
4370.6.3 by Ian Clatworthy
minimise differences to trunk code
2912
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
2913
            # Output the entry
2914
            if prefix:
2915
                fp = osutils.pathjoin(prefix, fp)
2916
            kindch = entry.kind_character()
2917
            outstring = fp + kindch
2918
            ui.ui_factory.clear_term()
2919
            if verbose:
2920
                outstring = '%-8s %s' % (fc, outstring)
2921
                if show_ids and fid is not None:
2922
                    outstring = "%-50s %s" % (outstring, fid)
2923
                self.outf.write(outstring + '\n')
2924
            elif null:
2925
                self.outf.write(fp + '\0')
2926
                if show_ids:
2927
                    if fid is not None:
2928
                        self.outf.write(fid)
2929
                    self.outf.write('\0')
2930
                self.outf.flush()
2931
            else:
2932
                if show_ids:
2933
                    if fid is not None:
2934
                        my_id = fid
2935
                    else:
2936
                        my_id = ''
2937
                    self.outf.write('%-50s %s\n' % (outstring, my_id))
2938
                else:
4456.1.1 by Ian Clatworthy
(igc) fix ls DIR --from-root and improve ls performance
2939
                    self.outf.write(outstring + '\n')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2940
4370.6.3 by Ian Clatworthy
minimise differences to trunk code
2941
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2942
class cmd_unknowns(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
2943
    __doc__ = """List unknown files.
1551.10.13 by Aaron Bentley
Hide 'unknowns', document alterntatives to hidden commands
2944
    """
1551.10.14 by Aaron Bentley
Add some blank lines
2945
1551.10.13 by Aaron Bentley
Hide 'unknowns', document alterntatives to hidden commands
2946
    hidden = True
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
2947
    _see_also = ['ls']
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
2948
    takes_options = ['directory']
1551.10.14 by Aaron Bentley
Add some blank lines
2949
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
2950
    @display_command
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
2951
    def run(self, directory=u'.'):
2952
        for f in WorkingTree.open_containing(directory)[0].unknowns():
1773.4.2 by Martin Pool
Cleanup of imports; undeprecate all_revision_ids()
2953
            self.outf.write(osutils.quotefn(f) + '\n')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2954
2955
2956
class cmd_ignore(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
2957
    __doc__ = """Ignore specified files or patterns.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2958
3398.1.26 by Ian Clatworthy
jam feedback - make patterns a separate help topic
2959
    See ``bzr help patterns`` for details on the syntax of patterns.
2960
4800.2.2 by Patrick Regan
Reworded ignore to keep extra verbage down.
2961
    If a .bzrignore file does not exist, the ignore command
4800.2.1 by Patrick Regan
Added clarifying text about ignore command.
2962
    will create one and add the specified files or patterns to the newly
2963
    created file. The ignore command will also automatically add the 
4800.2.2 by Patrick Regan
Reworded ignore to keep extra verbage down.
2964
    .bzrignore file to be versioned. Creating a .bzrignore file without
4800.2.1 by Patrick Regan
Added clarifying text about ignore command.
2965
    the use of the ignore command will require an explicit add command.
2966
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2967
    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
2968
    After adding, editing or deleting that file either indirectly by
2969
    using this command or directly by using an editor, be sure to commit
2970
    it.
4948.5.7 by John Whitley
Terminology change: exclusion => exception.
2971
    
5168.3.3 by Parth Malwankar
Removed --old-default-rules flag.
2972
    Bazaar also supports a global ignore file ~/.bazaar/ignore. On Windows
2973
    the global ignore file can be found in the application data directory as
2974
    C:\\Documents and Settings\\<user>\\Application Data\\Bazaar\\2.0\\ignore.
5168.3.7 by Parth Malwankar
fixed doc.
2975
    Global ignores are not touched by this command. The global ignore file
5168.3.5 by Parth Malwankar
clarification on global ignores.
2976
    can be edited directly using an editor.
5168.3.3 by Parth Malwankar
Removed --old-default-rules flag.
2977
4948.5.7 by John Whitley
Terminology change: exclusion => exception.
2978
    Patterns prefixed with '!' are exceptions to ignore patterns and take
2979
    precedence over regular ignores.  Such exceptions are used to specify
2980
    files that should be versioned which would otherwise be ignored.
2981
    
2982
    Patterns prefixed with '!!' act as regular ignore patterns, but have
2983
    precedence over the '!' exception patterns.
2135.2.2 by Kent Gibson
Ignore pattern matcher (glob.py) patches:
2984
5504.1.1 by Neil Martinsen-Burrell
document the comment character in ignore files
2985
    :Notes: 
2986
        
2987
    * Ignore patterns containing shell wildcards must be quoted from
2988
      the shell on Unix.
2989
2990
    * Ignore patterns starting with "#" act as comments in the ignore file.
2991
      To ignore patterns that begin with that character, use the "RE:" prefix.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2992
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
2993
    :Examples:
2994
        Ignore the top level Makefile::
2995
2996
            bzr ignore ./Makefile
2997
4948.5.7 by John Whitley
Terminology change: exclusion => exception.
2998
        Ignore .class files in all directories...::
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
2999
3035.1.1 by John Arbash Meinel
Address bug #59302 and fix documentation that uses single quotes.
3000
            bzr ignore "*.class"
3001
4948.5.2 by John Whitley
NEWS and various documentation updates for ignore exclusions.
3002
        ...but do not ignore "special.class"::
3003
3004
            bzr ignore "!special.class"
3005
5504.1.1 by Neil Martinsen-Burrell
document the comment character in ignore files
3006
        Ignore files whose name begins with the "#" character::
3007
3008
            bzr ignore "RE:^#"
3009
3035.1.1 by John Arbash Meinel
Address bug #59302 and fix documentation that uses single quotes.
3010
        Ignore .o files under the lib directory::
3011
3012
            bzr ignore "lib/**/*.o"
3013
3014
        Ignore .o files under the lib directory::
3015
3016
            bzr ignore "RE:lib/.*\.o"
3257.1.1 by Adeodato Simó
Add an example of some bzrignore cool stuff with Python regexes.
3017
3018
        Ignore everything but the "debian" toplevel directory::
3019
3020
            bzr ignore "RE:(?!debian/).*"
4948.5.7 by John Whitley
Terminology change: exclusion => exception.
3021
        
3022
        Ignore everything except the "local" toplevel directory,
5749.2.2 by mbp at sourcefrog
Tweak ReST syntax to avoid formatting error
3023
        but always ignore autosave files ending in ~, even under local/::
4948.5.7 by John Whitley
Terminology change: exclusion => exception.
3024
        
3025
            bzr ignore "*"
3026
            bzr ignore "!./local"
3027
            bzr ignore "!!*~"
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3028
    """
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
3029
3398.1.26 by Ian Clatworthy
jam feedback - make patterns a separate help topic
3030
    _see_also = ['status', 'ignored', 'patterns']
2063.5.1 by wang
"bzr ignore" takes multiple arguments. Fixes bug 29488.
3031
    takes_args = ['name_pattern*']
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
3032
    takes_options = ['directory',
5168.3.1 by Parth Malwankar
bzr ignore now support --default-rules option
3033
        Option('default-rules',
5168.3.3 by Parth Malwankar
Removed --old-default-rules flag.
3034
               help='Display the default ignore rules that bzr uses.')
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
3035
        ]
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3036
5171.3.11 by Martin von Gagern
merge from trunk.
3037
    def run(self, name_pattern_list=None, default_rules=None,
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
3038
            directory=u'.'):
3528.2.1 by Jelmer Vernooij
Move functionality to add ignores to the ignore file into a separate function.
3039
        from bzrlib import ignores
5168.3.3 by Parth Malwankar
Removed --old-default-rules flag.
3040
        if default_rules is not None:
3041
            # dump the default rules and exit
3042
            for pattern in ignores.USER_DEFAULTS:
3043
                self.outf.write("%s\n" % pattern)
1765.1.1 by Robert Collins
Remove the default ignores list from bzr, lowering the minimum overhead in bzr add.
3044
            return
2077.1.2 by Kent Gibson
Strip trailing slashes from ignore patterns (#4559).
3045
        if not name_pattern_list:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
3046
            raise errors.BzrCommandError(gettext("ignore requires at least one "
3047
                "NAME_PATTERN or --default-rules."))
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3048
        name_pattern_list = [globbing.normalize_pattern(p)
2298.8.4 by Kent Gibson
Fix whitespace and alignment.
3049
                             for p in name_pattern_list]
5339.3.5 by Parth Malwankar
clean bad pattern handling code in cmd_ignore
3050
        bad_patterns = ''
6143.1.1 by Jonathan Riddell
use ngettext for plurals
3051
        bad_patterns_count = 0
5339.3.1 by Parth Malwankar
'bzr ignore' now fails on bad pattern.
3052
        for p in name_pattern_list:
3053
            if not globbing.Globster.is_pattern_valid(p):
6143.1.1 by Jonathan Riddell
use ngettext for plurals
3054
                bad_patterns_count += 1
5339.3.5 by Parth Malwankar
clean bad pattern handling code in cmd_ignore
3055
                bad_patterns += ('\n  %s' % p)
5339.3.1 by Parth Malwankar
'bzr ignore' now fails on bad pattern.
3056
        if bad_patterns:
6143.1.1 by Jonathan Riddell
use ngettext for plurals
3057
            msg = (ngettext('Invalid ignore pattern found. %s', 
3058
                            'Invalid ignore patterns found. %s',
3059
                            bad_patterns_count) % bad_patterns)
5339.3.5 by Parth Malwankar
clean bad pattern handling code in cmd_ignore
3060
            ui.ui_factory.show_error(msg)
5339.3.1 by Parth Malwankar
'bzr ignore' now fails on bad pattern.
3061
            raise errors.InvalidPattern('')
2077.1.2 by Kent Gibson
Strip trailing slashes from ignore patterns (#4559).
3062
        for name_pattern in name_pattern_list:
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3063
            if (name_pattern[0] == '/' or
2298.8.1 by Kent Gibson
Normalise ignore patterns to use '/' path separator.
3064
                (len(name_pattern) > 1 and name_pattern[1] == ':')):
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
3065
                raise errors.BzrCommandError(gettext(
3066
                    "NAME_PATTERN should not be an absolute path"))
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
3067
        tree, relpath = WorkingTree.open_containing(directory)
3528.2.1 by Jelmer Vernooij
Move functionality to add ignores to the ignore file into a separate function.
3068
        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.
3069
        ignored = globbing.Globster(name_pattern_list)
3070
        matches = []
5326.1.1 by Parth Malwankar
locking for cmd_ignore is now in add_cleanup.
3071
        self.add_cleanup(tree.lock_read().unlock)
2747.5.1 by Daniel Watkins
'ignore' now outputs a list of versioned files that match the given pattern.
3072
        for entry in tree.list_files():
3073
            id = entry[3]
3074
            if id is not None:
3075
                filename = entry[0]
3076
                if ignored.match(filename):
4988.8.3 by Ed Bayiates Home
More builtin command UIFactory updates
3077
                    matches.append(filename)
2747.5.1 by Daniel Watkins
'ignore' now outputs a list of versioned files that match the given pattern.
3078
        if len(matches) > 0:
6138.2.1 by Jonathan Riddell
add gettext to all the builtin commands outf usage
3079
            self.outf.write(gettext("Warning: the following files are version "
3080
                  "controlled and match your ignore pattern:\n%s"
4988.8.3 by Ed Bayiates Home
More builtin command UIFactory updates
3081
                  "\nThese files will continue to be version controlled"
6138.2.1 by Jonathan Riddell
add gettext to all the builtin commands outf usage
3082
                  " unless you 'bzr remove' them.\n") % ("\n".join(matches),))
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3083
3603.3.1 by Robert Collins
* The help for ``bzr ignored`` now sugests ``bzr ls --ignored`` for
3084
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3085
class cmd_ignored(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
3086
    __doc__ = """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
3087
3088
    List all the ignored files and the ignore pattern that caused the file to
3089
    be ignored.
3090
3091
    Alternatively, to list just the files::
3092
3093
        bzr ls --ignored
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
3094
    """
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3095
3123.2.1 by Lukáš Lalinský
Use self.outf instead of sys.stdout in cmd_ignored.
3096
    encoding_type = 'replace'
3603.3.1 by Robert Collins
* The help for ``bzr ignored`` now sugests ``bzr ls --ignored`` for
3097
    _see_also = ['ignore', 'ls']
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
3098
    takes_options = ['directory']
3123.2.1 by Lukáš Lalinský
Use self.outf instead of sys.stdout in cmd_ignored.
3099
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
3100
    @display_command
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
3101
    def run(self, directory=u'.'):
3102
        tree = WorkingTree.open_containing(directory)[0]
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
3103
        self.add_cleanup(tree.lock_read().unlock)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
3104
        for path, file_class, kind, file_id, entry in tree.list_files():
3105
            if file_class != 'I':
3106
                continue
3107
            ## XXX: Slightly inefficient since this was already calculated
3108
            pat = tree.is_ignored(path)
3109
            self.outf.write('%-50s %s\n' % (path, pat))
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3110
3111
3112
class cmd_lookup_revision(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
3113
    __doc__ = """Lookup the revision-id from a revision-number
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3114
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
3115
    :Examples:
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3116
        bzr lookup-revision 33
3117
    """
3118
    hidden = True
3119
    takes_args = ['revno']
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
3120
    takes_options = ['directory']
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3121
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
3122
    @display_command
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
3123
    def run(self, revno, directory=u'.'):
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3124
        try:
3125
            revno = int(revno)
3126
        except ValueError:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
3127
            raise errors.BzrCommandError(gettext("not a valid revision-number: %r")
4988.8.4 by Vincent Ladeuil
Fix lines too long, fix inverted assertions.
3128
                                         % revno)
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
3129
        revid = WorkingTree.open_containing(directory)[0].branch.get_rev_id(revno)
4988.8.4 by Vincent Ladeuil
Fix lines too long, fix inverted assertions.
3130
        self.outf.write("%s\n" % revid)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3131
3132
3133
class cmd_export(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
3134
    __doc__ = """Export current or past revision to a destination directory or archive.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3135
3136
    If no revision is specified this exports the last committed revision.
3137
3138
    Format may be an "exporter" name, such as tar, tgz, tbz2.  If none is
3139
    given, try to find the format with the extension. If no extension
3140
    is found exports to a directory (equivalent to --format=dir).
3141
2374.1.4 by Ian Clatworthy
Include feedback from mailing list.
3142
    If root is supplied, it will be used as the root directory inside
3143
    container formats (tar, zip, etc). If it is not supplied it will default
3144
    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
3145
2374.1.2 by Ian Clatworthy
Improved after feedback from reviewers
3146
    If branch is omitted then the branch containing the current working
3147
    directory will be used.
2099.1.1 by Daniel Silverstone
Add source branch support to export command
3148
2374.1.3 by Ian Clatworthy
Minor man page fixes for add, commit, export
3149
    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
3150
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
3151
      =================       =========================
3152
      Supported formats       Autodetected by extension
3153
      =================       =========================
2666.1.5 by Ian Clatworthy
Incorporate feedback from Alex B. & James W.
3154
         dir                         (none)
1185.31.11 by John Arbash Meinel
Merging Alexander's zip export patch
3155
         tar                          .tar
3156
         tbz2                    .tar.bz2, .tbz2
3157
         tgz                      .tar.gz, .tgz
3158
         zip                          .zip
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
3159
      =================       =========================
1185.31.11 by John Arbash Meinel
Merging Alexander's zip export patch
3160
    """
5724.1.1 by John Arbash Meinel
'bzr export' needs to use 'exact' encoding.
3161
    encoding = 'exact'
3613.2.1 by Robert Collins
Teach export how to export a subdirectory. (Robert Collins)
3162
    takes_args = ['dest', 'branch_or_subdir?']
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
3163
    takes_options = ['directory',
2598.1.10 by Martin Pool
Clean up options that are registered globally and used once or not at all.
3164
        Option('format',
3165
               help="Type of file to export to.",
3166
               type=unicode),
3167
        'revision',
3368.2.48 by Ian Clatworthy
apply first round of poolie's review feedback
3168
        Option('filters', help='Apply content filters to export the '
3169
                'convenient form.'),
2598.1.10 by Martin Pool
Clean up options that are registered globally and used once or not at all.
3170
        Option('root',
3171
               type=str,
3172
               help="Name of the root directory inside the exported file."),
5076.2.3 by Jelmer Vernooij
Review comments from Rob.
3173
        Option('per-file-timestamps',
3174
               help='Set modification time of files to that of the last '
3175
                    'revision in which it was changed.'),
6331.2.2 by Jelmer Vernooij
Add --uncommitted option to export.
3176
        Option('uncommitted',
3177
               help='Export the working tree contents rather than that of the '
3178
                    'last revision.'),
2598.1.10 by Martin Pool
Clean up options that are registered globally and used once or not at all.
3179
        ]
3613.2.1 by Robert Collins
Teach export how to export a subdirectory. (Robert Collins)
3180
    def run(self, dest, branch_or_subdir=None, revision=None, format=None,
6331.2.2 by Jelmer Vernooij
Add --uncommitted option to export.
3181
        root=None, filters=False, per_file_timestamps=False, uncommitted=False,
3182
        directory=u'.'):
1185.31.12 by John Arbash Meinel
Refactored the export code to make it easier to add new export formats.
3183
        from bzrlib.export import export
2099.1.1 by Daniel Silverstone
Add source branch support to export command
3184
3613.2.1 by Robert Collins
Teach export how to export a subdirectory. (Robert Collins)
3185
        if branch_or_subdir is None:
6331.2.2 by Jelmer Vernooij
Add --uncommitted option to export.
3186
            branch_or_subdir = directory
3187
3188
        (tree, b, subdir) = controldir.ControlDir.open_containing_tree_or_branch(
3189
            branch_or_subdir)
3190
        if tree is not None:
3191
            self.add_cleanup(tree.lock_read().unlock)
3192
3193
        if uncommitted:
3194
            if tree is None:
3195
                raise errors.BzrCommandError(
3196
                    gettext("--uncommitted requires a working tree"))
3197
            export_tree = tree
2099.1.1 by Daniel Silverstone
Add source branch support to export command
3198
        else:
6331.2.2 by Jelmer Vernooij
Add --uncommitted option to export.
3199
            export_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.
3200
        try:
6331.2.2 by Jelmer Vernooij
Add --uncommitted option to export.
3201
            export(export_tree, dest, format, root, subdir, filtered=filters,
5076.2.3 by Jelmer Vernooij
Review comments from Rob.
3202
                   per_file_timestamps=per_file_timestamps)
1185.31.12 by John Arbash Meinel
Refactored the export code to make it easier to add new export formats.
3203
        except errors.NoSuchExportFormat, e:
6331.2.2 by Jelmer Vernooij
Add --uncommitted option to export.
3204
            raise errors.BzrCommandError(
3205
                gettext('Unsupported export format: %s') % e.format)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3206
3207
3208
class cmd_cat(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
3209
    __doc__ = """Write the contents of a file as of a given revision to standard output.
2374.1.1 by Ian Clatworthy
Help and man page fixes
3210
3211
    If no revision is nominated, the last revision is used.
3212
2374.1.2 by Ian Clatworthy
Improved after feedback from reviewers
3213
    Note: Take care to redirect standard output when using this command on a
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3214
    binary file.
2374.1.1 by Ian Clatworthy
Help and man page fixes
3215
    """
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3216
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
3217
    _see_also = ['ls']
5171.3.3 by Martin von Gagern
Add --directory option to ls, cat and annotate.
3218
    takes_options = ['directory',
2598.1.10 by Martin Pool
Clean up options that are registered globally and used once or not at all.
3219
        Option('name-from-revision', help='The path name in the old tree.'),
3368.2.48 by Ian Clatworthy
apply first round of poolie's review feedback
3220
        Option('filters', help='Apply content filters to display the '
3221
                'convenience form.'),
2598.1.10 by Martin Pool
Clean up options that are registered globally and used once or not at all.
3222
        'revision',
3223
        ]
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3224
    takes_args = ['filename']
2178.4.4 by Alexander Belchenko
encoding_type = 'exact' force sys.stdout to be binary stream on win32
3225
    encoding_type = 'exact'
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3226
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
3227
    @display_command
3368.2.31 by Ian Clatworthy
add --filters option to cat command
3228
    def run(self, filename, revision=None, name_from_revision=False,
5171.3.3 by Martin von Gagern
Add --directory option to ls, cat and annotate.
3229
            filters=False, directory=None):
1185.50.9 by John Arbash Meinel
[bug 3632] Matthieu Moy- bzr cat should default to last revision
3230
        if revision is not None and len(revision) != 1:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
3231
            raise errors.BzrCommandError(gettext("bzr cat --revision takes exactly"
3232
                                         " one revision specifier"))
3063.4.1 by Lukáš Lalinský
Fix UnboundLocalError in cmd_cat.
3233
        tree, branch, relpath = \
5171.3.9 by Martin von Gagern
Rename function to _open_directory_or_containing_tree_or_branch.
3234
            _open_directory_or_containing_tree_or_branch(filename, directory)
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
3235
        self.add_cleanup(branch.lock_read().unlock)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
3236
        return self._run(tree, branch, relpath, filename, revision,
3237
                         name_from_revision, filters)
3010.1.17 by Robert Collins
Lock correctness and commit_group management for re-sign, in builtins.
3238
3368.2.31 by Ian Clatworthy
add --filters option to cat command
3239
    def _run(self, tree, b, relpath, filename, revision, name_from_revision,
3240
        filtered):
1907.4.5 by Matthieu Moy
Make bzr cat -r revno:N:foo consistant with bzr cat -r branch:foo.
3241
        if tree is None:
2158.1.1 by Wouter van Heyst
Fix #73500 mostly by catching a NotLocalUrl exception in cmd_cat.
3242
            tree = b.basis_tree()
3732.1.1 by Ian Clatworthy
fix bzr st -rbranch:path-to-branch (Lukas Lalinsky)
3243
        rev_tree = _get_one_revision_tree('cat', revision, branch=b)
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
3244
        self.add_cleanup(rev_tree.lock_read().unlock)
2073.2.1 by wang
``bzr cat`` can look up contents of removed or renamed files. If the
3245
3246
        old_file_id = rev_tree.path2id(relpath)
3655.3.1 by Lukáš Lalinský
Fix `bzr st -rbranch:PATH_TO_BRANCH`
3247
6006.3.3 by Martin Pool
add todo
3248
        # TODO: Split out this code to something that generically finds the
3249
        # best id for a path across one or more trees; it's like
3250
        # find_ids_across_trees but restricted to find just one. -- mbp
3251
        # 20110705.
2073.2.3 by wang
Change option name to --name-from-revision. Always make new tree the
3252
        if name_from_revision:
4112.1.1 by Vincent Ladeuil
Fallback to old revision id if the current one doesn't exist in
3253
            # Try in revision if requested
2073.2.1 by wang
``bzr cat`` can look up contents of removed or renamed files. If the
3254
            if old_file_id is None:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
3255
                raise errors.BzrCommandError(gettext(
6138.2.4 by Jonathan Riddell
use format strings where there are multiple substitutions to allow for translations
3256
                    "{0!r} is not present in revision {1}").format(
3655.3.1 by Lukáš Lalinský
Fix `bzr st -rbranch:PATH_TO_BRANCH`
3257
                        filename, rev_tree.get_revision_id()))
2073.2.1 by wang
``bzr cat`` can look up contents of removed or renamed files. If the
3258
            else:
6006.3.2 by Martin Pool
Change cmd_cat to use ContentFilterTree, and clean it up.
3259
                actual_file_id = old_file_id
2073.2.1 by wang
``bzr cat`` can look up contents of removed or renamed files. If the
3260
        else:
4112.1.1 by Vincent Ladeuil
Fallback to old revision id if the current one doesn't exist in
3261
            cur_file_id = tree.path2id(relpath)
6006.3.2 by Martin Pool
Change cmd_cat to use ContentFilterTree, and clean it up.
3262
            if cur_file_id is not None and rev_tree.has_id(cur_file_id):
3263
                actual_file_id = cur_file_id
3264
            elif old_file_id is not None:
3265
                actual_file_id = old_file_id
3266
            else:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
3267
                raise errors.BzrCommandError(gettext(
6138.2.4 by Jonathan Riddell
use format strings where there are multiple substitutions to allow for translations
3268
                    "{0!r} is not present in revision {1}").format(
4112.1.1 by Vincent Ladeuil
Fallback to old revision id if the current one doesn't exist in
3269
                        filename, rev_tree.get_revision_id()))
3368.2.31 by Ian Clatworthy
add --filters option to cat command
3270
        if filtered:
6006.3.2 by Martin Pool
Change cmd_cat to use ContentFilterTree, and clean it up.
3271
            from bzrlib.filter_tree import ContentFilterTree
3272
            filter_tree = ContentFilterTree(rev_tree,
3273
                rev_tree._content_filter_stack)
3274
            content = filter_tree.get_file_text(actual_file_id)
3368.2.31 by Ian Clatworthy
add --filters option to cat command
3275
        else:
6006.3.2 by Martin Pool
Change cmd_cat to use ContentFilterTree, and clean it up.
3276
            content = rev_tree.get_file_text(actual_file_id)
3277
        self.cleanup_now()
3278
        self.outf.write(content)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3279
3280
3281
class cmd_local_time_offset(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
3282
    __doc__ = """Show the offset in seconds from GMT to local time."""
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3283
    hidden = True
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
3284
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3285
    def run(self):
4988.8.3 by Ed Bayiates Home
More builtin command UIFactory updates
3286
        self.outf.write("%s\n" % osutils.local_time_offset())
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3287
3288
3289
3290
class cmd_commit(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
3291
    __doc__ = """Commit changes into a new revision.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3292
4351.1.1 by Ian Clatworthy
improve commit help
3293
    An explanatory message needs to be given for each commit. This is
3294
    often done by using the --message option (getting the message from the
3295
    command line) or by using the --file option (getting the message from
3296
    a file). If neither of these options is given, an editor is opened for
3297
    the user to enter the message. To see the changed files in the
3298
    boilerplate text loaded into the editor, use the --show-diff option.
3299
3300
    By default, the entire tree is committed and the person doing the
3301
    commit is assumed to be the author. These defaults can be overridden
3302
    as explained below.
3303
3304
    :Selective commits:
3305
3306
      If selected files are specified, only changes to those files are
3307
      committed.  If a directory is specified then the directory and
3308
      everything within it is committed.
3309
  
3310
      When excludes are given, they take precedence over selected files.
3311
      For example, to commit only changes within foo, but not changes
3312
      within foo/bar::
3313
  
3314
        bzr commit foo -x foo/bar
3315
  
3316
      A selective commit after a merge is not yet supported.
3317
3318
    :Custom authors:
3319
3320
      If the author of the change is not the same person as the committer,
3321
      you can specify the author's name using the --author option. The
3322
      name should be in the same format as a committer-id, e.g.
3323
      "John Doe <jdoe@example.com>". If there is more than one author of
3324
      the change you can specify the option multiple times, once for each
3325
      author.
3326
  
3327
    :Checks:
3328
3329
      A common mistake is to forget to add a new file or directory before
3330
      running the commit command. The --strict option checks for unknown
3331
      files and aborts the commit if any are found. More advanced pre-commit
3332
      checks can be implemented by defining hooks. See ``bzr help hooks``
3333
      for details.
3334
3335
    :Things to note:
3336
3337
      If you accidentially commit the wrong changes or make a spelling
3338
      mistake in the commit message say, you can use the uncommit command
3339
      to undo it. See ``bzr help uncommit`` for details.
3340
3341
      Hooks can also be configured to run after a commit. This allows you
3342
      to trigger updates to external systems like bug trackers. The --fixes
3343
      option can be used to record the association between a revision and
3344
      one or more bugs. See ``bzr help bugs`` for details.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3345
    """
1185.16.3 by Martin Pool
- remove all TODOs from bzr help messages
3346
4351.1.1 by Ian Clatworthy
improve commit help
3347
    _see_also = ['add', 'bugs', 'hooks', 'uncommit']
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3348
    takes_args = ['selected*']
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
3349
    takes_options = [
3602.1.1 by Robert Collins
Add support for -x or --exclude to bzr commit, fixing bug 3117. (Robert Collins)
3350
            ListOption('exclude', type=str, short_name='x',
3351
                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.
3352
            Option('message', type=unicode,
3353
                   short_name='m',
3354
                   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
3355
            'verbose',
3356
             Option('unchanged',
3357
                    help='Commit even if nothing has changed.'),
3358
             Option('file', type=str,
3359
                    short_name='F',
3360
                    argname='msgfile',
3361
                    help='Take commit message from this file.'),
3362
             Option('strict',
3363
                    help="Refuse to commit if there are unknown "
3364
                    "files in the working tree."),
4766.2.1 by Alexander Sack
add --commit-time Option to built-in 'commit' command (LP: #459276)
3365
             Option('commit-time', type=str,
4766.2.2 by Andrew Bennetts
Add tests, and capture timezone offset as well as timestamp.
3366
                    help="Manually set a commit time using commit date "
3367
                    "format, e.g. '2009-10-10 08:00:00 +0100'."),
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
3368
             ListOption('fixes', type=str,
3535.10.7 by James Westby
Make the --fixes option conform to the style guide check once more.
3369
                    help="Mark a bug as being fixed by this revision "
3535.10.9 by James Westby
Make the improved messages show up in the UI.
3370
                         "(see \"bzr help bugs\")."),
4056.2.1 by James Westby
Allow specifying multiple authors for a revision.
3371
             ListOption('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.
3372
                    help="Set the author's name, if it's different "
3373
                         "from the committer."),
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
3374
             Option('local',
3375
                    help="Perform a local commit in a bound "
3376
                         "branch.  Local commits are not pushed to "
3377
                         "the master branch until a normal commit "
3378
                         "is performed."
3379
                    ),
5193.1.1 by Parth Malwankar
added -p short option for 'commit --show-diff'
3380
             Option('show-diff', short_name='p',
4766.2.1 by Alexander Sack
add --commit-time Option to built-in 'commit' command (LP: #459276)
3381
                    help='When no message is supplied, show the diff along'
3382
                    ' with the status summary in the message editor.'),
5777.6.1 by Jelmer Vernooij
Add --lossy option to 'bzr commit'.
3383
             Option('lossy', 
3384
                    help='When committing to a foreign version control '
3385
                    'system do not push data that can not be natively '
3386
                    'represented.'),
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
3387
             ]
5741.3.7 by Martin Pool
Reinstate checkin alias for commit
3388
    aliases = ['ci', 'checkin']
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3389
4119.4.1 by Jonathan Lange
Extract bug fix encoding logic from commit.
3390
    def _iter_bug_fix_urls(self, fixes, branch):
6120.1.1 by Jelmer Vernooij
Support a default bug tracker.
3391
        default_bugtracker  = None
2376.4.7 by jml at canonical
- Add docstrings to tests.
3392
        # Configure the properties for bug fixing attributes.
3393
        for fixed_bug in fixes:
3394
            tokens = fixed_bug.split(':')
6120.1.1 by Jelmer Vernooij
Support a default bug tracker.
3395
            if len(tokens) == 1:
3396
                if default_bugtracker is None:
3397
                    branch_config = branch.get_config()
3398
                    default_bugtracker = branch_config.get_user_option(
6120.1.2 by Jelmer Vernooij
Doc doc doc.
3399
                        "bugtracker")
6120.1.1 by Jelmer Vernooij
Support a default bug tracker.
3400
                if default_bugtracker is None:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
3401
                    raise errors.BzrCommandError(gettext(
6120.1.1 by Jelmer Vernooij
Support a default bug tracker.
3402
                        "No tracker specified for bug %s. Use the form "
3403
                        "'tracker:id' or specify a default bug tracker "
6120.1.2 by Jelmer Vernooij
Doc doc doc.
3404
                        "using the `bugtracker` option.\nSee "
6120.1.1 by Jelmer Vernooij
Support a default bug tracker.
3405
                        "\"bzr help bugs\" for more information on this "
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
3406
                        "feature. Commit refused.") % fixed_bug)
6120.1.1 by Jelmer Vernooij
Support a default bug tracker.
3407
                tag = default_bugtracker
3408
                bug_id = tokens[0]
3409
            elif len(tokens) != 2:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
3410
                raise errors.BzrCommandError(gettext(
3535.10.3 by James Westby
Talk about "trackers" rather than "tags" as it may be less confusing.
3411
                    "Invalid bug %s. Must be in the form of 'tracker:id'. "
3535.10.9 by James Westby
Make the improved messages show up in the UI.
3412
                    "See \"bzr help bugs\" for more information on this "
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
3413
                    "feature.\nCommit refused.") % fixed_bug)
6120.1.1 by Jelmer Vernooij
Support a default bug tracker.
3414
            else:
3415
                tag, bug_id = tokens
2376.4.7 by jml at canonical
- Add docstrings to tests.
3416
            try:
4119.4.1 by Jonathan Lange
Extract bug fix encoding logic from commit.
3417
                yield bugtracker.get_bug_url(tag, branch, bug_id)
2376.4.26 by Jonathan Lange
Tests for MalformedBugIdentifier and new error UnknownBugTrackerAbbreviation.
3418
            except errors.UnknownBugTrackerAbbreviation:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
3419
                raise errors.BzrCommandError(gettext(
3420
                    'Unrecognized bug %s. Commit refused.') % fixed_bug)
3535.10.9 by James Westby
Make the improved messages show up in the UI.
3421
            except errors.MalformedBugIdentifier, e:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
3422
                raise errors.BzrCommandError(gettext(
3423
                    "%s\nCommit refused.") % (str(e),))
2376.4.7 by jml at canonical
- Add docstrings to tests.
3424
2768.1.5 by Ian Clatworthy
Wrap new std verbose option with new help instead of declaring a new one
3425
    def run(self, message=None, file=None, verbose=False, selected_list=None,
2817.4.4 by Vincent Ladeuil
Redo the lost modification.
3426
            unchanged=False, strict=False, local=False, fixes=None,
5777.6.1 by Jelmer Vernooij
Add --lossy option to 'bzr commit'.
3427
            author=None, show_diff=False, exclude=None, commit_time=None,
3428
            lossy=False):
2598.6.30 by ghigo
- Updated the identation on the basis of Aaron suggestions
3429
        from bzrlib.errors import (
3430
            PointlessCommit,
3431
            ConflictsInTree,
3432
            StrictCommitFailed
3433
        )
3434
        from bzrlib.msgeditor import (
3435
            edit_commit_message_encoded,
3642.2.1 by Jelmer Vernooij
Add simple commit message template hook.
3436
            generate_commit_message_template,
5912.4.1 by Jonathan Riddell
Add commit message hook
3437
            make_commit_message_template_encoded,
5912.4.6 by Jonathan Riddell
add comma at end of list
3438
            set_commit_message,
2598.6.30 by ghigo
- Updated the identation on the basis of Aaron suggestions
3439
        )
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3440
4766.2.2 by Andrew Bennetts
Add tests, and capture timezone offset as well as timestamp.
3441
        commit_stamp = offset = None
4766.2.1 by Alexander Sack
add --commit-time Option to built-in 'commit' command (LP: #459276)
3442
        if commit_time is not None:
4766.2.2 by Andrew Bennetts
Add tests, and capture timezone offset as well as timestamp.
3443
            try:
4766.2.1 by Alexander Sack
add --commit-time Option to built-in 'commit' command (LP: #459276)
3444
                commit_stamp, offset = timestamp.parse_patch_date(commit_time)
4766.2.2 by Andrew Bennetts
Add tests, and capture timezone offset as well as timestamp.
3445
            except ValueError, e:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
3446
                raise errors.BzrCommandError(gettext(
3447
                    "Could not parse --commit-time: " + str(e)))
4766.2.1 by Alexander Sack
add --commit-time Option to built-in 'commit' command (LP: #459276)
3448
2376.4.2 by jml at canonical
More sophisticated error handling for --fixes option
3449
        properties = {}
3450
5346.4.5 by Martin Pool
Deprecate and avoid internal_tree_files and tree_files.
3451
        tree, selected_list = WorkingTree.open_containing_paths(selected_list)
1704.2.11 by Martin Pool
Handle 'bzr commit DIR' when dir contains pending merges.
3452
        if selected_list == ['']:
3453
            # workaround - commit of root of tree should be exactly the same
3454
            # as just default commit in that tree, and succeed even though
3455
            # selected-file merge commit is not done yet
3456
            selected_list = []
3457
2817.4.4 by Vincent Ladeuil
Redo the lost modification.
3458
        if fixes is None:
3459
            fixes = []
4119.4.1 by Jonathan Lange
Extract bug fix encoding logic from commit.
3460
        bug_property = bugtracker.encode_fixes_bug_urls(
3461
            self._iter_bug_fix_urls(fixes, tree.branch))
2453.2.1 by Martin Pool
Don't set the bugs property unless bugs are actually set
3462
        if bug_property:
3463
            properties['bugs'] = bug_property
2376.4.7 by jml at canonical
- Add docstrings to tests.
3464
1587.1.8 by Robert Collins
Local commits on unbound branches fail.
3465
        if local and not tree.branch.get_bound_location():
3466
            raise errors.LocalRequiresBoundBranch()
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3467
4795.5.1 by Gioele Barabucci
Ask for confirmation if the commit message is a file name
3468
        if message is not None:
4795.5.15 by Vincent Ladeuil
Fix PQM failures for LC_ALL=C for bug #73073 fix (commit warns for file-name-like messages).
3469
            try:
4878.1.1 by Vincent Ladeuil
Fix babune failures when LC_ALL=C for bug #73073 fix using lexists not exists
3470
                file_exists = osutils.lexists(message)
4795.5.15 by Vincent Ladeuil
Fix PQM failures for LC_ALL=C for bug #73073 fix (commit warns for file-name-like messages).
3471
            except UnicodeError:
3472
                # The commit message contains unicode characters that can't be
3473
                # represented in the filesystem encoding, so that can't be a
3474
                # file.
3475
                file_exists = False
3476
            if file_exists:
3477
                warning_msg = (
3478
                    'The commit message is a file name: "%(f)s".\n'
3479
                    '(use --file "%(f)s" to take commit message from that file)'
3480
                    % { 'f': message })
4795.5.13 by Gioele Barabucci
Do not check for interactivity
3481
                ui.ui_factory.show_warning(warning_msg)
5137.1.1 by Robert Collins
* ``bzr commit`` will prompt before using a commit message that was
3482
            if '\r' in message:
3483
                message = message.replace('\r\n', '\n')
3484
                message = message.replace('\r', '\n')
3485
            if file:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
3486
                raise errors.BzrCommandError(gettext(
3487
                    "please specify either --message or --file"))
4795.5.1 by Gioele Barabucci
Ask for confirmation if the commit message is a file name
3488
2149.1.4 by Aaron Bentley
Add additional test that callback is called with a Commit instance
3489
        def get_message(commit_obj):
2149.1.2 by Aaron Bentley
Defer getting the commit message until the revision is almost-committed
3490
            """Callback to get commit message"""
5137.1.1 by Robert Collins
* ``bzr commit`` will prompt before using a commit message that was
3491
            if file:
5340.7.1 by Martin
Rather than using codecs.open with potentially invalid flags when getting a commit message, just decode the bytes after reading
3492
                f = open(file)
4708.2.3 by Martin
Merge bzr.dev to unite with similar changes already made
3493
                try:
5340.7.1 by Martin
Rather than using codecs.open with potentially invalid flags when getting a commit message, just decode the bytes after reading
3494
                    my_message = f.read().decode(osutils.get_user_encoding())
4708.2.3 by Martin
Merge bzr.dev to unite with similar changes already made
3495
                finally:
3496
                    f.close()
5137.1.1 by Robert Collins
* ``bzr commit`` will prompt before using a commit message that was
3497
            elif message is not None:
3498
                my_message = message
3499
            else:
3500
                # No message supplied: make one up.
3501
                # text is the status of the tree
3502
                text = make_commit_message_template_encoded(tree,
2598.6.30 by ghigo
- Updated the identation on the basis of Aaron suggestions
3503
                        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.
3504
                        output_encoding=osutils.get_user_encoding())
5086.6.1 by Robert Collins
Minor commit tidyup in preparation for hooking around revprops.
3505
                # start_message is the template generated from hooks
5137.1.1 by Robert Collins
* ``bzr commit`` will prompt before using a commit message that was
3506
                # XXX: Warning - looks like hooks return unicode,
3507
                # make_commit_message_template_encoded returns user encoding.
3508
                # We probably want to be using edit_commit_message instead to
3509
                # avoid this.
5912.4.1 by Jonathan Riddell
Add commit message hook
3510
                my_message = set_commit_message(commit_obj)
3511
                if my_message is None:
3512
                    start_message = generate_commit_message_template(commit_obj)
3513
                    my_message = edit_commit_message_encoded(text,
3514
                        start_message=start_message)
2149.1.2 by Aaron Bentley
Defer getting the commit message until the revision is almost-committed
3515
                if my_message is None:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
3516
                    raise errors.BzrCommandError(gettext("please specify a commit"
3517
                        " message with either --message or --file"))
6064.1.1 by Jelmer Vernooij
Allow committing with an explicit empty commit message.
3518
                if my_message == "":
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
3519
                    raise errors.BzrCommandError(gettext("Empty commit message specified."
6064.1.3 by Jelmer Vernooij
Merge bzr.dev.
3520
                            " Please specify a commit message with either"
3521
                            " --message or --file or leave a blank message"
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
3522
                            " with --message \"\"."))
2149.1.2 by Aaron Bentley
Defer getting the commit message until the revision is almost-committed
3523
            return my_message
2376.4.2 by jml at canonical
More sophisticated error handling for --fixes option
3524
4570.4.3 by Robert Collins
Fix a couple of small bugs in the patch - use specific files with record_iter_changs, and the CLI shouldn't generate a filter of [] for commit.
3525
        # The API permits a commit with a filter of [] to mean 'select nothing'
3526
        # but the command line should not do that.
3527
        if not selected_list:
3528
            selected_list = None
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3529
        try:
2149.1.2 by Aaron Bentley
Defer getting the commit message until the revision is almost-committed
3530
            tree.commit(message_callback=get_message,
3531
                        specific_files=selected_list,
1607.1.5 by Robert Collins
Make commit verbose mode work!.
3532
                        allow_pointless=unchanged, strict=strict, local=local,
2789.2.1 by Ian Clatworthy
Make commit less verbose by default
3533
                        reporter=None, verbose=verbose, revprops=properties,
4766.2.1 by Alexander Sack
add --commit-time Option to built-in 'commit' command (LP: #459276)
3534
                        authors=author, timestamp=commit_stamp,
4766.2.2 by Andrew Bennetts
Add tests, and capture timezone offset as well as timestamp.
3535
                        timezone=offset,
5777.6.1 by Jelmer Vernooij
Add --lossy option to 'bzr commit'.
3536
                        exclude=tree.safe_relpath_files(exclude),
3537
                        lossy=lossy)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3538
        except PointlessCommit:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
3539
            raise errors.BzrCommandError(gettext("No changes to commit."
5765.1.2 by John Arbash Meinel
Rewrap the text, it was missing a space anyway.
3540
                " Please 'bzr add' the files you want to commit, or use"
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
3541
                " --unchanged to force an empty commit."))
1185.14.10 by Aaron Bentley
Commit aborts with conflicts in the tree.
3542
        except ConflictsInTree:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
3543
            raise errors.BzrCommandError(gettext('Conflicts detected in working '
1551.9.5 by Aaron Bentley
Revert broken save-commit-message code
3544
                'tree.  Use "bzr conflicts" to list, "bzr resolve FILE" to'
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
3545
                ' resolve.'))
1185.16.65 by mbp at sourcefrog
- new commit --strict option
3546
        except StrictCommitFailed:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
3547
            raise errors.BzrCommandError(gettext("Commit refused because there are"
3548
                              " 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
3549
        except errors.BoundBranchOutOfDate, e:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
3550
            e.extra_help = (gettext("\n"
5066.1.1 by Gary van der Merwe
Make it possible to detect a BoundBranchOutOfDate from commit.
3551
                'To commit to master branch, run update and then commit.\n'
3552
                'You can also pass --local to commit to continue working '
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
3553
                'disconnected.'))
5066.1.1 by Gary van der Merwe
Make it possible to detect a BoundBranchOutOfDate from commit.
3554
            raise
2111.1.1 by Martin Pool
Fix #32054, save message if commit fails.
3555
3556
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3557
class cmd_check(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
3558
    __doc__ = """Validate working tree structure, branch consistency and repository history.
3015.3.25 by Daniel Watkins
Updated help.
3559
3560
    This command checks various invariants about branch and repository storage
3561
    to detect data corruption or bzr bugs.
3562
3563
    The working tree and branch checks will only give output if a problem is
3564
    detected. The output fields of the repository check are:
2745.6.8 by Aaron Bentley
Clean up text
3565
4070.11.7 by Martin Pool
Correction to rest syntax for cmd_check
3566
    revisions
3567
        This is just the number of revisions checked.  It doesn't
3568
        indicate a problem.
3569
3570
    versionedfiles
3571
        This is just the number of versionedfiles checked.  It
3572
        doesn't indicate a problem.
3573
3574
    unreferenced ancestors
3575
        Texts that are ancestors of other texts, but
3576
        are not properly referenced by the revision ancestry.  This is a
3577
        subtle problem that Bazaar can work around.
3578
3579
    unique file texts
3580
        This is the total number of unique file contents
3581
        seen in the checked revisions.  It does not indicate a problem.
3582
3583
    repeated file texts
3584
        This is the total number of repeated texts seen
3585
        in the checked revisions.  Texts can be repeated when their file
3586
        entries are modified, but the file contents are not.  It does not
3587
        indicate a problem.
3015.4.14 by Daniel Watkins
Updated check help to explain what happens when no options are given.
3588
3015.4.19 by Daniel Watkins
Improved check docs.
3589
    If no restrictions are specified, all Bazaar data that is found at the given
3590
    location will be checked.
3591
3592
    :Examples:
3593
3594
        Check the tree and branch at 'foo'::
3595
3596
            bzr check --tree --branch foo
3597
3598
        Check only the repository at 'bar'::
3599
3600
            bzr check --repo bar
3601
3602
        Check everything at 'baz'::
3603
3604
            bzr check baz
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3605
    """
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
3606
3607
    _see_also = ['reconcile']
3015.3.2 by Daniel Watkins
Check.check now takes a path rather than a branch.
3608
    takes_args = ['path?']
3015.4.2 by Daniel Watkins
Made UI changes to include CLI options.
3609
    takes_options = ['verbose',
3610
                     Option('branch', help="Check the branch related to the"
3611
                                           " current directory."),
3612
                     Option('repo', help="Check the repository related to the"
3613
                                         " current directory."),
3614
                     Option('tree', help="Check the working tree related to"
3615
                                         " the current directory.")]
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3616
3015.4.5 by Daniel Watkins
Each option selects only the specific thing to be checked.
3617
    def run(self, path=None, verbose=False, branch=False, repo=False,
3618
            tree=False):
3015.3.22 by Daniel Watkins
Changed 'check' to 'check_dwim'.
3619
        from bzrlib.check import check_dwim
3015.3.2 by Daniel Watkins
Check.check now takes a path rather than a branch.
3620
        if path is None:
3621
            path = '.'
3015.4.7 by Daniel Watkins
Vanilla 'bzr check' checks all items.
3622
        if not branch and not repo and not tree:
3623
            branch = repo = tree = True
3015.4.2 by Daniel Watkins
Made UI changes to include CLI options.
3624
        check_dwim(path, verbose, do_branch=branch, do_repo=repo, do_tree=tree)
1534.5.16 by Robert Collins
Review feedback.
3625
3626
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3627
class cmd_upgrade(Command):
4360.10.22 by Matthew Fuller
Merge up through 2.2.0.
3628
    __doc__ = """Upgrade a repository, branch or working tree to a newer format.
4360.10.15 by Ian Clatworthy
enhance the upgrade help and add a NEWS item
3629
4360.10.19 by Ian Clatworthy
Take --pack out of the UI and improve help (feedback from lifeless and poolie)
3630
    When the default format has changed after a major new release of
3631
    Bazaar, you may be informed during certain operations that you
3632
    should upgrade. Upgrading to a newer format may improve performance
3633
    or make new features available. It may however limit interoperability
3634
    with older repositories or with older versions of Bazaar.
4360.10.15 by Ian Clatworthy
enhance the upgrade help and add a NEWS item
3635
4360.10.19 by Ian Clatworthy
Take --pack out of the UI and improve help (feedback from lifeless and poolie)
3636
    If you wish to upgrade to a particular format rather than the
3637
    current default, that can be specified using the --format option.
3638
    As a consequence, you can use the upgrade command this way to
3639
    "downgrade" to an earlier format, though some conversions are
3640
    a one way process (e.g. changing from the 1.x default to the
3641
    2.x default) so downgrading is not always possible.
4360.10.15 by Ian Clatworthy
enhance the upgrade help and add a NEWS item
3642
4360.10.42 by Matthew Fuller
Correct backup dir name.
3643
    A backup.bzr.~#~ directory is created at the start of the conversion
4360.10.43 by Matthew Fuller
Rewrap paragraph.
3644
    process (where # is a number). By default, this is left there on
3645
    completion. If the conversion fails, delete the new .bzr directory
3646
    and rename this one back in its place. Use the --clean option to ask
3647
    for the backup.bzr directory to be removed on successful conversion.
3648
    Alternatively, you can delete it by hand if everything looks good
3649
    afterwards.
4360.10.15 by Ian Clatworthy
enhance the upgrade help and add a NEWS item
3650
4360.10.19 by Ian Clatworthy
Take --pack out of the UI and improve help (feedback from lifeless and poolie)
3651
    If the location given is a shared repository, dependent branches
3652
    are also converted provided the repository converts successfully.
3653
    If the conversion of a branch fails, remaining branches are still
3654
    tried.
4360.10.15 by Ian Clatworthy
enhance the upgrade help and add a NEWS item
3655
4360.10.45 by Vincent Ladeuil
Stop mentioning 2.0 in the upgrade guide, all documented steps are valid for all bzr versions.
3656
    For more information on upgrades, see the Bazaar Upgrade Guide,
4360.10.37 by Vincent Ladeuil
Fix reference to bazaar-vcs.org.
3657
    http://doc.bazaar.canonical.com/latest/en/upgrade-guide/.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3658
    """
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
3659
4360.10.19 by Ian Clatworthy
Take --pack out of the UI and improve help (feedback from lifeless and poolie)
3660
    _see_also = ['check', 'reconcile', 'formats']
4360.10.9 by Ian Clatworthy
limit ui to upgrading a single location for now
3661
    takes_args = ['url?']
1857.1.20 by Aaron Bentley
Strip out all the EnumOption stuff
3662
    takes_options = [
4360.10.2 by Ian Clatworthy
drop stacked vs unstacked logic; support multiple URLs
3663
        RegistryOption('format',
3664
            help='Upgrade to a specific format.  See "bzr help'
3665
                 ' formats" for details.',
6207.3.3 by jelmer at samba
Fix tests and the like.
3666
            lazy_registry=('bzrlib.controldir', 'format_registry'),
3667
            converter=lambda name: controldir.format_registry.make_bzrdir(name),
4360.10.2 by Ian Clatworthy
drop stacked vs unstacked logic; support multiple URLs
3668
            value_switches=True, title='Branch format'),
3669
        Option('clean',
3670
            help='Remove the backup.bzr directory if successful.'),
4360.10.4 by Ian Clatworthy
support multiple urls, --pack and --dry-run
3671
        Option('dry-run',
3672
            help="Show what would be done, but don't actually do anything."),
4360.10.2 by Ian Clatworthy
drop stacked vs unstacked logic; support multiple URLs
3673
    ]
1857.1.20 by Aaron Bentley
Strip out all the EnumOption stuff
3674
4360.10.19 by Ian Clatworthy
Take --pack out of the UI and improve help (feedback from lifeless and poolie)
3675
    def run(self, url='.', format=None, clean=False, dry_run=False):
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3676
        from bzrlib.upgrade import upgrade
4360.10.19 by Ian Clatworthy
Take --pack out of the UI and improve help (feedback from lifeless and poolie)
3677
        exceptions = upgrade(url, format, clean_up=clean, dry_run=dry_run)
4360.10.2 by Ian Clatworthy
drop stacked vs unstacked logic; support multiple URLs
3678
        if exceptions:
3679
            if len(exceptions) == 1:
4360.10.44 by Matthew Fuller
Make comment clearer about what's being compatible.
3680
                # Compatibility with historical behavior
4360.10.2 by Ian Clatworthy
drop stacked vs unstacked logic; support multiple URLs
3681
                raise exceptions[0]
3682
            else:
3683
                return 3
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3684
3685
3686
class cmd_whoami(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
3687
    __doc__ = """Show or set bzr user id.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3688
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
3689
    :Examples:
3690
        Show the email of the current user::
3691
3692
            bzr whoami --email
3693
3694
        Set the current user::
3695
3035.1.1 by John Arbash Meinel
Address bug #59302 and fix documentation that uses single quotes.
3696
            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
3697
    """
5171.3.15 by Martin von Gagern
Add --directory option to whoami.
3698
    takes_options = [ 'directory',
3699
                      Option('email',
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
3700
                             help='Display email address only.'),
1816.2.2 by Robey Pointer
fix 'whoami' to use encodings and allow setting the global or branch identity
3701
                      Option('branch',
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
3702
                             help='Set identity for the current branch instead of '
3703
                                  'globally.'),
1816.2.2 by Robey Pointer
fix 'whoami' to use encodings and allow setting the global or branch identity
3704
                    ]
3705
    takes_args = ['name?']
3706
    encoding_type = 'replace'
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3707
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
3708
    @display_command
5171.3.15 by Martin von Gagern
Add --directory option to whoami.
3709
    def run(self, email=False, branch=False, name=None, directory=None):
1816.2.2 by Robey Pointer
fix 'whoami' to use encodings and allow setting the global or branch identity
3710
        if name is None:
5171.3.15 by Martin von Gagern
Add --directory option to whoami.
3711
            if directory is None:
3712
                # use branch if we're inside one; otherwise global config
3713
                try:
6351.3.4 by Jelmer Vernooij
Convert whoami to config stack.
3714
                    c = Branch.open_containing(u'.')[0].get_config_stack()
5171.3.15 by Martin von Gagern
Add --directory option to whoami.
3715
                except errors.NotBranchError:
6351.3.4 by Jelmer Vernooij
Convert whoami to config stack.
3716
                    c = _mod_config.GlobalStack()
5171.3.15 by Martin von Gagern
Add --directory option to whoami.
3717
            else:
6351.3.4 by Jelmer Vernooij
Convert whoami to config stack.
3718
                c = Branch.open(directory).get_config_stack()
3719
            identity = c.get('email')
1816.2.4 by Robey Pointer
flesh out 'whoami' docs a little, and don't display the identity after setting it
3720
            if email:
6351.3.4 by Jelmer Vernooij
Convert whoami to config stack.
3721
                self.outf.write(_mod_config.extract_email_address(identity)
3722
                                + '\n')
1816.2.2 by Robey Pointer
fix 'whoami' to use encodings and allow setting the global or branch identity
3723
            else:
6351.3.4 by Jelmer Vernooij
Convert whoami to config stack.
3724
                self.outf.write(identity + '\n')
1816.2.4 by Robey Pointer
flesh out 'whoami' docs a little, and don't display the identity after setting it
3725
            return
1816.2.2 by Robey Pointer
fix 'whoami' to use encodings and allow setting the global or branch identity
3726
5616.3.1 by Jelmer Vernooij
Print error if both --email and a new identity were specified.
3727
        if email:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
3728
            raise errors.BzrCommandError(gettext("--email can only be used to display existing "
3729
                                         "identity"))
5616.3.1 by Jelmer Vernooij
Print error if both --email and a new identity were specified.
3730
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
3731
        # display a warning if an email address isn't included in the given name.
3732
        try:
5345.5.9 by Vincent Ladeuil
Implements 'bzr lock --config <file>'.
3733
            _mod_config.extract_email_address(name)
2055.2.2 by John Arbash Meinel
Switch extract_email_address() to use a more specific exception
3734
        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
3735
            warning('"%s" does not seem to contain an email address.  '
3736
                    'This is allowed, but not recommended.', name)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3737
1816.2.4 by Robey Pointer
flesh out 'whoami' docs a little, and don't display the identity after setting it
3738
        # use global config unless --branch given
3739
        if branch:
5171.3.15 by Martin von Gagern
Add --directory option to whoami.
3740
            if directory is None:
6351.3.4 by Jelmer Vernooij
Convert whoami to config stack.
3741
                c = Branch.open_containing(u'.')[0].get_config_stack()
5171.3.15 by Martin von Gagern
Add --directory option to whoami.
3742
            else:
6351.3.4 by Jelmer Vernooij
Convert whoami to config stack.
3743
                c = Branch.open(directory).get_config_stack()
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3744
        else:
6351.3.4 by Jelmer Vernooij
Convert whoami to config stack.
3745
            c = _mod_config.GlobalStack()
3746
        c.set('email', name)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3747
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.
3748
1185.35.14 by Aaron Bentley
Implemented nick command
3749
class cmd_nick(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
3750
    __doc__ = """Print or set the branch nickname.
3565.6.16 by Marius Kruger
update nick command description to mention how it works for bound branches,
3751
3752
    If unset, the tree root directory name is used as the nickname.
3753
    To print the current nickname, execute with no argument.
3754
3755
    Bound branches use the nickname of its master branch unless it is set
3756
    locally.
1185.35.14 by Aaron Bentley
Implemented nick command
3757
    """
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
3758
3759
    _see_also = ['info']
1185.35.14 by Aaron Bentley
Implemented nick command
3760
    takes_args = ['nickname?']
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
3761
    takes_options = ['directory']
3762
    def run(self, nickname=None, directory=u'.'):
3763
        branch = Branch.open_containing(directory)[0]
1185.35.14 by Aaron Bentley
Implemented nick command
3764
        if nickname is None:
3765
            self.printme(branch)
3766
        else:
3767
            branch.nick = nickname
3768
3769
    @display_command
3770
    def printme(self, branch):
4988.8.4 by Vincent Ladeuil
Fix lines too long, fix inverted assertions.
3771
        self.outf.write('%s\n' % branch.nick)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3772
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.
3773
2900.3.2 by Tim Penhey
A working alias command.
3774
class cmd_alias(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
3775
    __doc__ = """Set/unset and display aliases.
2900.3.2 by Tim Penhey
A working alias command.
3776
3777
    :Examples:
3778
        Show the current aliases::
3779
3780
            bzr alias
3781
3782
        Show the alias specified for 'll'::
3783
3784
            bzr alias ll
3785
3786
        Set an alias for 'll'::
3787
2900.3.10 by Tim Penhey
Show examples, and change text to use double rather than single quotes.
3788
            bzr alias ll="log --line -r-10..-1"
2900.3.2 by Tim Penhey
A working alias command.
3789
2900.3.4 by Tim Penhey
Removed the unalais separate command.
3790
        To remove an alias for 'll'::
3791
3792
            bzr alias --remove ll
3793
2900.3.2 by Tim Penhey
A working alias command.
3794
    """
3795
    takes_args = ['name?']
2900.3.4 by Tim Penhey
Removed the unalais separate command.
3796
    takes_options = [
3797
        Option('remove', help='Remove the alias.'),
3798
        ]
2900.3.2 by Tim Penhey
A working alias command.
3799
2900.3.4 by Tim Penhey
Removed the unalais separate command.
3800
    def run(self, name=None, remove=False):
3801
        if remove:
3802
            self.remove_alias(name)
3803
        elif name is None:
2900.3.2 by Tim Penhey
A working alias command.
3804
            self.print_aliases()
3805
        else:
3806
            equal_pos = name.find('=')
3807
            if equal_pos == -1:
3808
                self.print_alias(name)
3809
            else:
3810
                self.set_alias(name[:equal_pos], name[equal_pos+1:])
3811
2900.3.4 by Tim Penhey
Removed the unalais separate command.
3812
    def remove_alias(self, alias_name):
3813
        if alias_name is None:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
3814
            raise errors.BzrCommandError(gettext(
3815
                'bzr alias --remove expects an alias to remove.'))
2900.3.4 by Tim Penhey
Removed the unalais separate command.
3816
        # If alias is not found, print something like:
3817
        # unalias: foo: not found
5345.5.9 by Vincent Ladeuil
Implements 'bzr lock --config <file>'.
3818
        c = _mod_config.GlobalConfig()
2900.3.8 by Tim Penhey
Use the exception text for unalias not found.
3819
        c.unset_alias(alias_name)
2900.3.4 by Tim Penhey
Removed the unalais separate command.
3820
3821
    @display_command
2900.3.2 by Tim Penhey
A working alias command.
3822
    def print_aliases(self):
3823
        """Print out the defined aliases in a similar format to bash."""
5345.5.9 by Vincent Ladeuil
Implements 'bzr lock --config <file>'.
3824
        aliases = _mod_config.GlobalConfig().get_aliases()
2900.3.7 by Tim Penhey
Updates from Aaron's review.
3825
        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.
3826
            self.outf.write('bzr alias %s="%s"\n' % (key, value))
2900.3.2 by Tim Penhey
A working alias command.
3827
3828
    @display_command
3829
    def print_alias(self, alias_name):
3830
        from bzrlib.commands import get_alias
3831
        alias = get_alias(alias_name)
3832
        if alias is None:
2900.3.7 by Tim Penhey
Updates from Aaron's review.
3833
            self.outf.write("bzr alias: %s: not found\n" % alias_name)
2900.3.2 by Tim Penhey
A working alias command.
3834
        else:
2900.3.7 by Tim Penhey
Updates from Aaron's review.
3835
            self.outf.write(
2900.3.11 by Tim Penhey
Fixed the output in the tests.
3836
                'bzr alias %s="%s"\n' % (alias_name, ' '.join(alias)))
2900.3.2 by Tim Penhey
A working alias command.
3837
2900.3.12 by Tim Penhey
Final review comments.
3838
    def set_alias(self, alias_name, alias_command):
2900.3.2 by Tim Penhey
A working alias command.
3839
        """Save the alias in the global config."""
5345.5.9 by Vincent Ladeuil
Implements 'bzr lock --config <file>'.
3840
        c = _mod_config.GlobalConfig()
2900.3.12 by Tim Penhey
Final review comments.
3841
        c.set_alias(alias_name, alias_command)
2900.3.2 by Tim Penhey
A working alias command.
3842
3843
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3844
class cmd_selftest(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
3845
    __doc__ = """Run internal test suite.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3846
2213.2.1 by Martin Pool
Add selftest --first flag
3847
    If arguments are given, they are regular expressions that say which tests
3848
    should run.  Tests matching any expression are run, and other tests are
3849
    not run.
3850
3851
    Alternatively if --first is given, matching tests are run first and then
3852
    all other tests are run.  This is useful if you have been working in a
3853
    particular area, but want to make sure nothing else was broken.
1552 by Martin Pool
Improved help text for bzr selftest
3854
2394.2.2 by Ian Clatworthy
Add --randomize and update help
3855
    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
3856
    excluded, regardless of whether they match --first or not.
2394.2.2 by Ian Clatworthy
Add --randomize and update help
3857
3858
    To help catch accidential dependencies between tests, the --randomize
3859
    option is useful. In most cases, the argument used is the word 'now'.
3860
    Note that the seed used for the random number generator is displayed
3861
    when this option is used. The seed can be explicitly passed as the
3862
    argument to this option if required. This enables reproduction of the
3863
    actual ordering used if and when an order sensitive problem is encountered.
3864
3865
    If --list-only is given, the tests that would be run are listed. This is
3866
    useful when combined with --first, --exclude and/or --randomize to
3867
    understand their impact. The test harness reports "Listed nn tests in ..."
3868
    instead of "Ran nn tests in ..." when list mode is enabled.
3869
1552 by Martin Pool
Improved help text for bzr selftest
3870
    If the global option '--no-plugins' is given, plugins are not loaded
3871
    before running the selftests.  This has two effects: features provided or
3872
    modified by plugins will not be tested, and tests provided by plugins will
3873
    not be run.
3874
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3875
    Tests that need working space on disk use a common temporary directory,
2598.4.1 by Martin Pool
Remove obsolete --clean-output, --keep-output, --numbered-dirs selftest options (thanks Alexander)
3876
    typically inside $TMPDIR or /tmp.
3877
4685.1.2 by Robert Collins
Document BZR_TEST_PDB in cmd_selftest's help.
3878
    If you set BZR_TEST_PDB=1 when running selftest, failing tests will drop
3879
    into a pdb postmortem session.
3880
5418.2.4 by Martin Pool
Mention --coverage in selftest help
3881
    The --coverage=DIRNAME global option produces a report with covered code
3882
    indicated.
3883
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
3884
    :Examples:
3885
        Run only tests relating to 'ignore'::
3886
3887
            bzr selftest ignore
3888
3889
        Disable plugins and list tests as they're run::
3890
3891
            bzr --no-plugins selftest -v
1185.16.58 by mbp at sourcefrog
- run all selftests by default
3892
    """
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.
3893
    # NB: this is used from the class without creating an instance, which is
3894
    # why it does not have a self parameter.
3895
    def get_transport_type(typestring):
3896
        """Parse and return a transport specifier."""
3897
        if typestring == "sftp":
4797.11.2 by Vincent Ladeuil
Stop requiring testtools for sftp use.
3898
            from bzrlib.tests import stub_sftp
3899
            return stub_sftp.SFTPAbsoluteServer
5904.1.1 by Martin Pool
Pyflakes-driven cleanups
3900
        elif typestring == "memory":
5017.3.36 by Vincent Ladeuil
-s bb.test_selftest passing
3901
            from bzrlib.tests import test_server
5017.3.45 by Vincent Ladeuil
Move MemoryServer back into bzrlib.transport.memory as it's needed as soon as a MemoryTransport is used. Add a NEWS entry.
3902
            return memory.MemoryServer
5904.1.1 by Martin Pool
Pyflakes-driven cleanups
3903
        elif typestring == "fakenfs":
5017.3.36 by Vincent Ladeuil
-s bb.test_selftest passing
3904
            from bzrlib.tests import test_server
3905
            return test_server.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.
3906
        msg = "No known transport type %s. Supported types are: sftp\n" %\
3907
            (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
3908
        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.
3909
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3910
    hidden = True
1185.1.57 by Robert Collins
nuke --pattern to selftest, replace with regexp.search calls.
3911
    takes_args = ['testspecs*']
1552 by Martin Pool
Improved help text for bzr selftest
3912
    takes_options = ['verbose',
2418.2.2 by Martin Pool
Add -1 option to selftest
3913
                     Option('one',
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
3914
                             help='Stop when one test fails.',
2418.2.2 by Martin Pool
Add -1 option to selftest
3915
                             short_name='1',
3916
                             ),
2333.1.1 by Dmitry Vasiliev
Fixed typo and removed some trailing whitespaces
3917
                     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.
3918
                            help='Use a different transport by default '
3919
                                 'throughout the test suite.',
3920
                            type=get_transport_type),
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
3921
                     Option('benchmark',
5050.10.1 by Martin Pool
Remove bzr selftest --benchmark
3922
                            help='Run the benchmarks rather than selftests.',
3923
                            hidden=True),
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
3924
                     Option('lsprof-timed',
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
3925
                            help='Generate lsprof output for benchmarked'
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
3926
                                 ' sections of code.'),
4641.3.3 by Robert Collins
Enable --lsprof-tests on bzr selftest.
3927
                     Option('lsprof-tests',
3928
                            help='Generate lsprof output for each test.'),
2213.2.1 by Martin Pool
Add selftest --first flag
3929
                     Option('first',
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
3930
                            help='Run all tests, but run specified tests first.',
2418.2.1 by Martin Pool
Add -f alias for selftest --first
3931
                            short_name='f',
2321.2.1 by Alexander Belchenko
`bzr selftest --numbered-dirs` use numbered dirs for TestCaseInTempDir
3932
                            ),
2394.2.1 by Ian Clatworthy
--list and --exclude first cut
3933
                     Option('list-only',
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
3934
                            help='List the tests instead of running them.'),
4205.3.2 by Robert Collins
Create fork and reinvoke parallel testing support.
3935
                     RegistryOption('parallel',
4205.3.5 by Robert Collins
Missing . on the parallel option.
3936
                        help="Run the test suite in parallel.",
4205.3.2 by Robert Collins
Create fork and reinvoke parallel testing support.
3937
                        lazy_registry=('bzrlib.tests', 'parallel_registry'),
3938
                        value_switches=False,
3939
                        ),
2394.2.2 by Ian Clatworthy
Add --randomize and update help
3940
                     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
3941
                            help='Randomize the order of tests using the given'
3942
                                 ' seed or "now" for the current time.'),
5924.1.2 by Vincent Ladeuil
Support multiple selftest --exclude options
3943
                     ListOption('exclude', type=str, argname="PATTERN",
3944
                                short_name='x',
3945
                                help='Exclude tests that match this regular'
3946
                                ' expression.'),
4165.1.1 by Robert Collins
Add builtin subunit support.
3947
                     Option('subunit',
3948
                        help='Output test progress via subunit.'),
2658.3.3 by Daniel Watkins
Added UI support for bzr selftest --strict.
3949
                     Option('strict', help='Fail on missing dependencies or '
3950
                            'known failures.'),
3193.1.8 by Vincent Ladeuil
Add '--load-list' option to selftest.
3951
                     Option('load-list', type=str, argname='TESTLISTFILE',
3952
                            help='Load a test id list from a text file.'),
3390.1.1 by Andrew Bennetts
Add --debugflags/-E option to selftest.
3953
                     ListOption('debugflag', type=str, short_name='E',
3954
                                help='Turn on a selftest debug flag.'),
3649.6.4 by Vincent Ladeuil
selftest --starting-with now accepts multiple values.
3955
                     ListOption('starting-with', type=str, argname='TESTID',
3956
                                param_name='starting_with', short_name='s',
3957
                                help=
3958
                                'Load only the tests starting with TESTID.'),
6015.31.1 by John Arbash Meinel
Bug #837293, make 'bzr selftest' disable fsync/fdatasync while running.
3959
                     Option('sync',
3960
                            help="By default we disable fsync and fdatasync"
3961
                                 " while running the test suite.")
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
3962
                     ]
2204.3.4 by Alexander Belchenko
Command 'selftest' use 'replace' encoding_type to prevent sudden traceback
3963
    encoding_type = 'replace'
1185.16.58 by mbp at sourcefrog
- run all selftests by default
3964
4000.2.3 by Robert Collins
Allow extra options to bzrlib.tests.selftest from plugins.
3965
    def __init__(self):
3966
        Command.__init__(self)
3967
        self.additional_selftest_args = {}
3968
2805.1.1 by Ian Clatworthy
Fix selftest --benchmark so verbose by default again
3969
    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)
3970
            transport=None, benchmark=None,
5050.10.3 by Martin Pool
Delete obsolete selftest --cache-dir option
3971
            lsprof_timed=None,
2598.4.1 by Martin Pool
Remove obsolete --clean-output, --keep-output, --numbered-dirs selftest options (thanks Alexander)
3972
            first=False, list_only=False,
3198.1.1 by Vincent Ladeuil
Add --load-list option to selftest
3973
            randomize=None, exclude=None, strict=False,
4205.3.2 by Robert Collins
Create fork and reinvoke parallel testing support.
3974
            load_list=None, debugflag=None, starting_with=None, subunit=False,
6015.31.1 by John Arbash Meinel
Bug #837293, make 'bzr selftest' disable fsync/fdatasync while running.
3975
            parallel=None, lsprof_tests=False,
3976
            sync=False):
5247.1.15 by Vincent Ladeuil
Merge cleanup into first-try resolving conflicts
3977
        from bzrlib import tests
3427.5.3 by John Arbash Meinel
Update the activate_deprecation_warnings so it can be skipped if there is already an error set.
3978
2095.4.1 by Martin Pool
Better progress bars during tests
3979
        if testspecs_list is not None:
3980
            pattern = '|'.join(testspecs_list)
3981
        else:
3982
            pattern = ".*"
4165.1.1 by Robert Collins
Add builtin subunit support.
3983
        if subunit:
4165.1.2 by Robert Collins
Make a clear error when attempting to use subunit and it is not available.
3984
            try:
3985
                from bzrlib.tests import SubUnitBzrRunner
3986
            except ImportError:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
3987
                raise errors.BzrCommandError(gettext("subunit not available. subunit "
3988
                    "needs to be installed to use --subunit."))
4165.1.1 by Robert Collins
Add builtin subunit support.
3989
            self.additional_selftest_args['runner_class'] = SubUnitBzrRunner
5229.1.8 by Vincent Ladeuil
Subunit stream handling.
3990
            # On Windows, disable automatic conversion of '\n' to '\r\n' in
3991
            # stdout, which would corrupt the subunit stream. 
5229.2.2 by Vincent Ladeuil
More robust stream checking for subunit on windows
3992
            # FIXME: This has been fixed in subunit trunk (>0.0.5) so the
3993
            # following code can be deleted when it's sufficiently deployed
3994
            # -- vila/mgz 20100514
3995
            if (sys.platform == "win32"
3996
                and getattr(sys.stdout, 'fileno', None) is not None):
5229.1.8 by Vincent Ladeuil
Subunit stream handling.
3997
                import msvcrt
3998
                msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
4205.3.2 by Robert Collins
Create fork and reinvoke parallel testing support.
3999
        if parallel:
4000
            self.additional_selftest_args.setdefault(
4001
                'suite_decorators', []).append(parallel)
2095.4.1 by Martin Pool
Better progress bars during tests
4002
        if benchmark:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
4003
            raise errors.BzrCommandError(gettext(
5050.10.1 by Martin Pool
Remove bzr selftest --benchmark
4004
                "--benchmark is no longer supported from bzr 2.2; "
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
4005
                "use bzr-usertest instead"))
5050.10.1 by Martin Pool
Remove bzr selftest --benchmark
4006
        test_suite_factory = None
5924.1.2 by Vincent Ladeuil
Support multiple selftest --exclude options
4007
        if not exclude:
4008
            exclude_pattern = None
4009
        else:
4010
            exclude_pattern = '(' + '|'.join(exclude) + ')'
6015.31.1 by John Arbash Meinel
Bug #837293, make 'bzr selftest' disable fsync/fdatasync while running.
4011
        if not sync:
4012
            self._disable_fsync()
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
4013
        selftest_kwargs = {"verbose": verbose,
4014
                          "pattern": pattern,
4015
                          "stop_on_failure": one,
4016
                          "transport": transport,
4017
                          "test_suite_factory": test_suite_factory,
4018
                          "lsprof_timed": lsprof_timed,
4019
                          "lsprof_tests": lsprof_tests,
4020
                          "matching_tests_first": first,
4021
                          "list_only": list_only,
4022
                          "random_seed": randomize,
5924.1.2 by Vincent Ladeuil
Support multiple selftest --exclude options
4023
                          "exclude_pattern": exclude_pattern,
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
4024
                          "strict": strict,
4025
                          "load_list": load_list,
4026
                          "debug_flags": debugflag,
4027
                          "starting_with": starting_with
4028
                          }
4029
        selftest_kwargs.update(self.additional_selftest_args)
5393.2.1 by Vincent Ladeuil
Fix bug #625686 by removing the warning filter added by selftest.
4030
4031
        # Make deprecation warnings visible, unless -Werror is set
4032
        cleanup = symbol_versioning.activate_deprecation_warnings(
4033
            override=False)
4034
        try:
5398.1.1 by Vincent Ladeuil
Cleanup warnings.filters after running selftest
4035
            result = tests.selftest(**selftest_kwargs)
5393.2.1 by Vincent Ladeuil
Fix bug #625686 by removing the warning filter added by selftest.
4036
        finally:
4037
            cleanup()
2095.4.1 by Martin Pool
Better progress bars during tests
4038
        return int(not result)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4039
6015.31.1 by John Arbash Meinel
Bug #837293, make 'bzr selftest' disable fsync/fdatasync while running.
4040
    def _disable_fsync(self):
4041
        """Change the 'os' functionality to not synchronize."""
4042
        self._orig_fsync = getattr(os, 'fsync', None)
4043
        if self._orig_fsync is not None:
4044
            os.fsync = lambda filedes: None
4045
        self._orig_fdatasync = getattr(os, 'fdatasync', None)
4046
        if self._orig_fdatasync is not None:
4047
            os.fdatasync = lambda filedes: None
4048
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4049
4050
class cmd_version(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
4051
    __doc__ = """Show version of bzr."""
1871.1.1 by Robert Collins
Relocate bzrlib selftest external output tests to bzrlib/tests/blackbox/test_selftest.py.
4052
2785.1.2 by bialix at ukr
bugfix for #131100
4053
    encoding_type = 'replace'
3346.2.1 by Martin Pool
Add version --short option
4054
    takes_options = [
4055
        Option("short", help="Print just the version number."),
4056
        ]
2785.1.2 by bialix at ukr
bugfix for #131100
4057
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
4058
    @display_command
3346.2.1 by Martin Pool
Add version --short option
4059
    def run(self, short=False):
1819.1.8 by Martin Pool
Improved reporting of bzrlib revision_id
4060
        from bzrlib.version import show_version
3346.2.1 by Martin Pool
Add version --short option
4061
        if short:
3346.2.7 by Martin Pool
Commands should use self.outf not print
4062
            self.outf.write(bzrlib.version_string + '\n')
3346.2.1 by Martin Pool
Add version --short option
4063
        else:
4064
            show_version(to_file=self.outf)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4065
1871.1.1 by Robert Collins
Relocate bzrlib selftest external output tests to bzrlib/tests/blackbox/test_selftest.py.
4066
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4067
class cmd_rocks(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
4068
    __doc__ = """Statement of optimism."""
1871.1.1 by Robert Collins
Relocate bzrlib selftest external output tests to bzrlib/tests/blackbox/test_selftest.py.
4069
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4070
    hidden = True
1871.1.1 by Robert Collins
Relocate bzrlib selftest external output tests to bzrlib/tests/blackbox/test_selftest.py.
4071
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
4072
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4073
    def run(self):
6138.2.1 by Jonathan Riddell
add gettext to all the builtin commands outf usage
4074
        self.outf.write(gettext("It sure does!\n"))
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4075
4076
4077
class cmd_find_merge_base(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
4078
    __doc__ = """Find and print a base revision for merging two branches."""
1185.16.3 by Martin Pool
- remove all TODOs from bzr help messages
4079
    # TODO: Options to specify revisions on either side, as if
4080
    #       merging only part of the history.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4081
    takes_args = ['branch', 'other']
4082
    hidden = True
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
4083
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
4084
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4085
    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.
4086
        from bzrlib.revision import ensure_null
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
4087
1442.1.64 by Robert Collins
Branch.open_containing now returns a tuple (Branch, relative-path).
4088
        branch1 = Branch.open_containing(branch)[0]
4089
        branch2 = Branch.open_containing(other)[0]
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
4090
        self.add_cleanup(branch1.lock_read().unlock)
4091
        self.add_cleanup(branch2.lock_read().unlock)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
4092
        last1 = ensure_null(branch1.last_revision())
4093
        last2 = ensure_null(branch2.last_revision())
4094
4095
        graph = branch1.repository.get_graph(branch2.repository)
4096
        base_rev_id = graph.find_unique_lca(last1, last2)
4097
6138.2.1 by Jonathan Riddell
add gettext to all the builtin commands outf usage
4098
        self.outf.write(gettext('merge base is revision %s\n') % base_rev_id)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4099
4100
4101
class cmd_merge(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
4102
    __doc__ = """Perform a three-way merge.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
4103
3277.1.1 by Peter Schuller
Document the relationship between bzr send and bzr merge. In
4104
    The source of the merge can be specified either in the form of a branch,
4105
    or in the form of a path to a file containing a merge directive generated
4106
    with bzr send. If neither is specified, the default is the upstream branch
5887.2.1 by Jonathan Riddell
give an error when trying to merge a non existent file
4107
    or the branch most recently merged using --remember.  The source of the
4108
    merge may also be specified in the form of a path to a file in another
4109
    branch:  in this case, only the modifications to that file are merged into
4110
    the current working tree.
3277.1.1 by Peter Schuller
Document the relationship between bzr send and bzr merge. In
4111
5537.3.1 by Eric Siegerman
Clarify the description of --revision, and an example.
4112
    When merging from a branch, by default bzr will try to merge in all new
4113
    work from the other branch, automatically determining an appropriate base
4114
    revision.  If this fails, you may need to give an explicit base.
4115
5537.3.4 by Eric Siegerman
Fix capitalization of "bzr", per review. Grammar fix: change "cherrypicking" to "a cherrypick".
4116
    To pick a different ending revision, pass "--revision OTHER".  bzr will
5537.3.1 by Eric Siegerman
Clarify the description of --revision, and an example.
4117
    try to merge in all new work up to and including revision OTHER.
4118
4119
    If you specify two values, "--revision BASE..OTHER", only revisions BASE
4120
    through OTHER, excluding BASE but including OTHER, will be merged.  If this
4121
    causes some revisions to be skipped, i.e. if the destination branch does
5537.3.3 by Eric Siegerman
Fix an off-by-one error in the description of "--revision BASE..OTHER".
4122
    not already contain revision BASE, such a merge is commonly referred to as
5877.3.1 by Matt Giuca
help merge: Added a few sentences explaining the different semantics of cherrypick merges.
4123
    a "cherrypick". Unlike a normal merge, Bazaar does not currently track
4124
    cherrypicks. The changes look like a normal commit, and the history of the
4125
    changes from the other branch is not stored in the commit.
3277.1.3 by Peter Schuller
Identify by name the "cherrypicking" mode of operation of 'bzr merge'.
4126
5537.3.2 by Eric Siegerman
Drive-by clarification.
4127
    Revision numbers are always relative to the source branch.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
4128
1551.2.18 by Aaron Bentley
Updated docs to clarify conflict handling
4129
    Merge will do its best to combine the changes in two branches, but there
4130
    are some kinds of problems only a human can fix.  When it encounters those,
4131
    it will mark a conflict.  A conflict means that you need to fix something,
4132
    before you should commit.
4133
1551.2.19 by Aaron Bentley
Added See Conflicts to merge help
4134
    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
4135
5861.1.2 by Vincent Ladeuil
Use positive forms where possible, fix the command help and the user guide.
4136
    If there is no default branch set, the first merge will set it (use
6105.2.4 by Martin von Gagern
Drive-by typo correction in command docstrings.
4137
    --no-remember to avoid setting it). After that, you can omit the branch
5861.1.3 by Vincent Ladeuil
Fix the docs for push/pull/send regarding --no-remember.
4138
    to use the default.  To change the default, use --remember. The value will
4139
    only be saved if the remote location can be accessed.
1614.2.2 by Olaf Conradi
Merge command:
4140
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
4141
    The results of the merge are placed into the destination working
4142
    directory, where they can be reviewed (with bzr diff), tested, and then
4143
    committed to record the result of the merge.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
4144
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4145
    merge refuses to run if there are any uncommitted changes, unless
5939.2.1 by Neil Martinsen-Burrell
better document the effect of merge --force
4146
    --force is given.  If --force is given, then the changes from the source 
5939.2.2 by Neil Martinsen-Burrell
language recommendation from Eli Zaretskii
4147
    will be merged with the current working tree, including any uncommitted
4148
    changes in the tree.  The --force option can also be used to create a
4149
    merge revision which has more than two parents.
4955.3.2 by Vincent Ladeuil
Tweak the spacing.
4150
4151
    If one would like to merge changes from the working tree of the other
4152
    branch without merging any committed revisions, the --uncommitted option
4153
    can be given.
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
4154
4526.6.15 by Aaron Bentley
Update command help
4155
    To select only some changes to merge, use "merge -i", which will prompt
4156
    you to apply each diff hunk and file change, similar to "shelve".
4157
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
4158
    :Examples:
5537.3.1 by Eric Siegerman
Clarify the description of --revision, and an example.
4159
        To merge all new revisions from bzr.dev::
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
4160
4161
            bzr merge ../bzr.dev
4162
4163
        To merge changes up to and including revision 82 from bzr.dev::
4164
4165
            bzr merge -r 82 ../bzr.dev
4166
4167
        To merge the changes introduced by 82, without previous changes::
4168
4169
            bzr merge -r 81..82 ../bzr.dev
3277.1.1 by Peter Schuller
Document the relationship between bzr send and bzr merge. In
4170
4816.1.1 by Ian Clatworthy
Trivial formatting fix to merge help
4171
        To apply a merge directive contained in /tmp/merge::
3277.1.1 by Peter Schuller
Document the relationship between bzr send and bzr merge. In
4172
4173
            bzr merge /tmp/merge
4971.3.2 by Neil Martinsen-Burrell
reformat examples with less reST
4174
4175
        To create a merge revision with three parents from two branches
4971.3.3 by Vincent Ladeuil
Tweak NEWS entry order and some cleanup.
4176
        feature1a and feature1b:
4971.3.2 by Neil Martinsen-Burrell
reformat examples with less reST
4177
4178
            bzr merge ../feature1a
4179
            bzr merge ../feature1b --force
4180
            bzr commit -m 'revision with three parents'
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4181
    """
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
4182
3008.1.25 by Aaron Bentley
Set encoding exact on cmd_merge
4183
    encoding_type = 'exact'
4095.2.1 by Neil Martinsen-Burrell
Better help for bzr send
4184
    _see_also = ['update', 'remerge', 'status-flags', 'send']
3277.1.4 by Peter Schuller
As per further feedback, use LOCATION instead of MERGE_OR_MERGE_DIRECTIVE.
4185
    takes_args = ['location?']
2598.1.10 by Martin Pool
Clean up options that are registered globally and used once or not at all.
4186
    takes_options = [
2839.5.1 by Alexander Belchenko
add -c option to merge command
4187
        'change',
2598.1.10 by Martin Pool
Clean up options that are registered globally and used once or not at all.
4188
        'revision',
4189
        Option('force',
4190
               help='Merge even if the destination tree has uncommitted changes.'),
4191
        'merge-type',
4192
        'reprocess',
4193
        'remember',
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
4194
        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
4195
               "conflicts."),
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
4196
        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
4197
               ' from a working copy, instead of branch changes.'),
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
4198
        Option('pull', help='If the destination is already'
4199
                ' 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
4200
                ' source rather than merging.  When this happens,'
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
4201
                ' you do not need to commit the result.'),
5171.3.1 by Martin von Gagern
Turn --directory and -d into a global option.
4202
        custom_help('directory',
2598.1.10 by Martin Pool
Clean up options that are registered globally and used once or not at all.
4203
               help='Branch to merge into, '
5171.3.1 by Martin von Gagern
Turn --directory and -d into a global option.
4204
                    'rather than the one containing the working directory.'),
4526.6.3 by Aaron Bentley
Implement interactive merging.
4205
        Option('preview', help='Instead of merging, show a diff of the'
4206
               ' merge.'),
4207
        Option('interactive', help='Select changes interactively.',
5321.1.74 by Gordon Tyler
Reverted some more command-related stuff that I missed earlier.
4208
            short_name='i')
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
4209
    ]
1551.6.22 by Aaron Bentley
Improved help for remerge and merge
4210
3277.1.4 by Peter Schuller
As per further feedback, use LOCATION instead of MERGE_OR_MERGE_DIRECTIVE.
4211
    def run(self, location=None, revision=None, force=False,
5861.1.1 by Vincent Ladeuil
Don't set submit_branch if it's not yet set when merging.
4212
            merge_type=None, show_base=False, reprocess=None, remember=None,
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
4213
            uncommitted=False, pull=False,
4214
            directory=None,
3008.1.24 by Aaron Bentley
Add merge --preview to show diff
4215
            preview=False,
4526.6.3 by Aaron Bentley
Implement interactive merging.
4216
            interactive=False,
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
4217
            ):
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4218
        if merge_type is None:
1996.3.5 by John Arbash Meinel
Cleanup, deprecated, and get the tests passing again.
4219
            merge_type = _mod_merge.Merge3Merger
1614.2.2 by Olaf Conradi
Merge command:
4220
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
4221
        if directory is None: directory = u'.'
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
4222
        possible_transports = []
4223
        merger = None
4224
        allow_pending = True
4225
        verified = 'inapplicable'
5863.5.1 by Jonathan Riddell
add an error message when merging into empty branch
4226
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
4227
        tree = WorkingTree.open_containing(directory)[0]
5863.5.1 by Jonathan Riddell
add an error message when merging into empty branch
4228
        if tree.branch.revno() == 0:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
4229
            raise errors.BzrCommandError(gettext('Merging into empty branches not currently supported, '
4230
                                         'https://bugs.launchpad.net/bzr/+bug/308562'))
4037.2.1 by Roberto Aguilar
Check for umcommitted changes.
4231
4037.2.2 by Roberto Aguilar
Updating uncommitted changes check.
4232
        try:
4233
            basis_tree = tree.revision_tree(tree.last_revision())
4234
        except errors.NoSuchRevision:
4235
            basis_tree = tree.basis_tree()
4672.3.2 by Vincent Ladeuil
Don't allow merge on top of pending merges without --force.
4236
4237
        # die as quickly as possible if there are uncommitted changes
4104.8.1 by Robert Collins
Cherrypick the fix for merge --force onto 1.13.1
4238
        if not force:
4721.3.2 by Vincent Ladeuil
Simplify mutable_tree.has_changes() and update call sites.
4239
            if tree.has_changes():
4104.8.1 by Robert Collins
Cherrypick the fix for merge --force onto 1.13.1
4240
                raise errors.UncommittedChanges(tree)
4037.2.1 by Roberto Aguilar
Check for umcommitted changes.
4241
3586.1.31 by Ian Clatworthy
view filtering for pull, update & merge
4242
        view_info = _get_view_info_for_change_reporter(tree)
1551.10.25 by Aaron Bentley
Make ChangeReporter private
4243
        change_reporter = delta._ChangeReporter(
3586.1.31 by Ian Clatworthy
view filtering for pull, update & merge
4244
            unversioned_filter=tree.is_ignored, view_info=view_info)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
4245
        pb = ui.ui_factory.nested_progress_bar()
4246
        self.add_cleanup(pb.finished)
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
4247
        self.add_cleanup(tree.lock_write().unlock)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
4248
        if location is not None:
4249
            try:
4250
                mergeable = bundle.read_mergeable_from_url(location,
4251
                    possible_transports=possible_transports)
4252
            except errors.NotABundle:
4253
                mergeable = None
4254
            else:
4255
                if uncommitted:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
4256
                    raise errors.BzrCommandError(gettext('Cannot use --uncommitted'
4257
                        ' with bundles or merge directives.'))
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
4258
4259
                if revision is not None:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
4260
                    raise errors.BzrCommandError(gettext(
4261
                        'Cannot use -r with merge directives or bundles'))
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
4262
                merger, verified = _mod_merge.Merger.from_mergeable(tree,
4961.2.11 by Martin Pool
Pull out pbs and ProgressPhases stored in object state; just use them in single functions
4263
                   mergeable, None)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
4264
4265
        if merger is None and uncommitted:
4266
            if revision is not None and len(revision) > 0:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
4267
                raise errors.BzrCommandError(gettext('Cannot use --uncommitted and'
4268
                    ' --revision at the same time.'))
4961.2.11 by Martin Pool
Pull out pbs and ProgressPhases stored in object state; just use them in single functions
4269
            merger = self.get_merger_from_uncommitted(tree, location, None)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
4270
            allow_pending = False
4271
4272
        if merger is None:
4273
            merger, allow_pending = self._get_merger_from_branch(tree,
4961.2.11 by Martin Pool
Pull out pbs and ProgressPhases stored in object state; just use them in single functions
4274
                location, revision, remember, possible_transports, None)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
4275
4276
        merger.merge_type = merge_type
4277
        merger.reprocess = reprocess
4278
        merger.show_base = show_base
4279
        self.sanity_check_merger(merger)
4280
        if (merger.base_rev_id == merger.other_rev_id and
4281
            merger.other_rev_id is not None):
5887.3.1 by Vincent Ladeuil
Simplify code and fix the test.
4282
            # check if location is a nonexistent file (and not a branch) to
4283
            # disambiguate the 'Nothing to do'
4284
            if merger.interesting_files:
4285
                if not merger.other_tree.has_filename(
4286
                    merger.interesting_files[0]):
6138.2.2 by Jonathan Riddell
gettext builtin.py's note() usage
4287
                    note(gettext("merger: ") + str(merger))
5887.2.3 by Jonathan Riddell
PathsDoNotExist a better error to throw
4288
                    raise errors.PathsDoNotExist([location])
6138.2.2 by Jonathan Riddell
gettext builtin.py's note() usage
4289
            note(gettext('Nothing to do.'))
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
4290
            return 0
4797.86.1 by John Arbash Meinel
Fix bug #760152, 'bzr merge --pull --preview' should just be 'bzr merge --preview'
4291
        if pull and not preview:
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
4292
            if merger.interesting_files is not None:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
4293
                raise errors.BzrCommandError(gettext('Cannot pull individual files'))
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
4294
            if (merger.base_rev_id == tree.last_revision()):
4295
                result = tree.pull(merger.other_branch, False,
4296
                                   merger.other_rev_id)
4297
                result.report(self.outf)
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
4298
                return 0
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
4299
        if merger.this_basis is None:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
4300
            raise errors.BzrCommandError(gettext(
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
4301
                "This branch has no commits."
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
4302
                " (perhaps you would prefer 'bzr pull')"))
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
4303
        if preview:
5321.1.68 by Gordon Tyler
Removed mergetools command and integrations into merge and remerge commands, in preparation for splitting them off into a separate branch.
4304
            return self._do_preview(merger)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
4305
        elif interactive:
5321.1.68 by Gordon Tyler
Removed mergetools command and integrations into merge and remerge commands, in preparation for splitting them off into a separate branch.
4306
            return self._do_interactive(merger)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
4307
        else:
5321.1.68 by Gordon Tyler
Removed mergetools command and integrations into merge and remerge commands, in preparation for splitting them off into a separate branch.
4308
            return self._do_merge(merger, change_reporter, allow_pending,
4309
                                  verified)
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
4310
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
4311
    def _get_preview(self, merger):
3008.1.24 by Aaron Bentley
Add merge --preview to show diff
4312
        tree_merger = merger.make_merger()
4313
        tt = tree_merger.make_preview_transform()
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
4314
        self.add_cleanup(tt.finalize)
4526.6.3 by Aaron Bentley
Implement interactive merging.
4315
        result_tree = tt.get_preview_tree()
4526.6.8 by Aaron Bentley
Remove unused tt parameter.
4316
        return result_tree
4526.6.3 by Aaron Bentley
Implement interactive merging.
4317
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
4318
    def _do_preview(self, merger):
4526.6.3 by Aaron Bentley
Implement interactive merging.
4319
        from bzrlib.diff import show_diff_trees
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
4320
        result_tree = self._get_preview(merger)
4797.57.10 by Alexander Belchenko
path_encoding selection logic extracted as helper function
4321
        path_encoding = osutils.get_diff_header_encoding()
4526.6.3 by Aaron Bentley
Implement interactive merging.
4322
        show_diff_trees(merger.this_tree, result_tree, self.outf,
4797.57.7 by Alexander Belchenko
merge --preview: encode diff headers in mbcs on windows.
4323
                        old_label='', new_label='',
4324
                        path_encoding=path_encoding)
3008.1.24 by Aaron Bentley
Add merge --preview to show diff
4325
4326
    def _do_merge(self, merger, change_reporter, allow_pending, verified):
4327
        merger.change_reporter = change_reporter
4328
        conflict_count = merger.do_merge()
4329
        if allow_pending:
4330
            merger.set_pending()
4331
        if verified == 'failed':
4332
            warning('Preview patch does not match changes')
4333
        if conflict_count != 0:
4334
            return 1
4335
        else:
4336
            return 0
4337
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
4338
    def _do_interactive(self, merger):
4526.6.13 by Aaron Bentley
Add docstring to do_interactive.
4339
        """Perform an interactive merge.
4340
4341
        This works by generating a preview tree of the merge, then using
4342
        Shelver to selectively remove the differences between the working tree
4343
        and the preview tree.
4344
        """
4526.6.4 by Aaron Bentley
Remove changes_destroyed message.
4345
        from bzrlib import shelf_ui
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
4346
        result_tree = self._get_preview(merger)
4526.6.14 by Aaron Bentley
Use default DiffWriter.
4347
        writer = bzrlib.option.diff_writer_registry.get()
4526.6.4 by Aaron Bentley
Remove changes_destroyed message.
4348
        shelver = shelf_ui.Shelver(merger.this_tree, result_tree, destroy=True,
4526.6.14 by Aaron Bentley
Use default DiffWriter.
4349
                                   reporter=shelf_ui.ApplyReporter(),
4350
                                   diff_writer=writer(sys.stdout))
4832.2.1 by Aaron Bentley
Ensure merge -i doesn't leave branch write_locked.
4351
        try:
4352
            shelver.run()
4353
        finally:
4354
            shelver.finalize()
4526.6.3 by Aaron Bentley
Implement interactive merging.
4355
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
4356
    def sanity_check_merger(self, merger):
4357
        if (merger.show_base and
4358
            not merger.merge_type is _mod_merge.Merge3Merger):
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
4359
            raise errors.BzrCommandError(gettext("Show-base is not supported for this"
4360
                                         " 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.
4361
        if merger.reprocess is None:
4362
            if merger.show_base:
4363
                merger.reprocess = False
4364
            else:
4365
                # Use reprocess if the merger supports it
4366
                merger.reprocess = merger.merge_type.supports_reprocess
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
4367
        if merger.reprocess and not merger.merge_type.supports_reprocess:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
4368
            raise errors.BzrCommandError(gettext("Conflict reduction is not supported"
4369
                                         " for merge type %s.") %
2665.2.1 by Michael Hudson
test and fix for a NameError in merge --weave --show-base
4370
                                         merger.merge_type)
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
4371
        if merger.reprocess and merger.show_base:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
4372
            raise errors.BzrCommandError(gettext("Cannot do conflict reduction and"
4373
                                         " show base."))
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
4374
1551.15.75 by Aaron Bentley
_merger_from_branch -> _get_merger_from_branch
4375
    def _get_merger_from_branch(self, tree, location, revision, remember,
4376
                                possible_transports, pb):
4377
        """Produce a merger from a location, assuming it refers to a branch."""
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
4378
        from bzrlib.tag import _merge_tags_if_possible
4379
        # find the branch locations
1551.20.2 by Aaron Bentley
Merge prefers submit branch, but falls back to parent branch
4380
        other_loc, user_location = self._select_branch_location(tree, location,
1551.15.74 by Aaron Bentley
Textual updates from review
4381
            revision, -1)
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
4382
        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
4383
            base_loc, _unused = self._select_branch_location(tree,
4384
                location, revision, 0)
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
4385
        else:
4386
            base_loc = other_loc
4387
        # Open the branches
4388
        other_branch, other_path = Branch.open_containing(other_loc,
4389
            possible_transports)
4390
        if base_loc == other_loc:
4391
            base_branch = other_branch
4392
        else:
4393
            base_branch, base_path = Branch.open_containing(base_loc,
1551.15.66 by Aaron Bentley
Improve behavior with revision ids
4394
                possible_transports)
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
4395
        # Find the revision ids
4435.1.4 by Aaron Bentley
Fix tabs.
4396
        other_revision_id = None
4397
        base_revision_id = None
4398
        if revision is not None:
4399
            if len(revision) >= 1:
4400
                other_revision_id = revision[-1].as_revision_id(other_branch)
4401
            if len(revision) == 2:
4402
                base_revision_id = revision[0].as_revision_id(base_branch)
4435.1.1 by Aaron Bentley
Correctly fall back to basis when no second revision specified.
4403
        if other_revision_id is None:
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
4404
            other_revision_id = _mod_revision.ensure_null(
4405
                other_branch.last_revision())
5861.1.1 by Vincent Ladeuil
Don't set submit_branch if it's not yet set when merging.
4406
        # Remember where we merge from. We need to remember if:
4407
        # - user specify a location (and we don't merge from the parent
4408
        #   branch)
4409
        # - user ask to remember or there is no previous location set to merge
4410
        #   from and user didn't ask to *not* remember
4411
        if (user_location is not None
4412
            and ((remember
4413
                  or (remember is None
4414
                      and tree.branch.get_submit_branch() is None)))):
1551.20.2 by Aaron Bentley
Merge prefers submit branch, but falls back to parent branch
4415
            tree.branch.set_submit_branch(other_branch.base)
5050.53.4 by Andrew Bennetts
Don't propagate tags to the master branch during cmd_merge.
4416
        # Merge tags (but don't set them in the master branch yet, the user
4417
        # might revert this merge).  Commit will propagate them.
4418
        _merge_tags_if_possible(other_branch, tree.branch, ignore_master=True)
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
4419
        merger = _mod_merge.Merger.from_revision_ids(pb, tree,
4420
            other_revision_id, base_revision_id, other_branch, base_branch)
4421
        if other_path != '':
4422
            allow_pending = False
4423
            merger.interesting_files = [other_path]
1645.1.1 by Aaron Bentley
Implement single-file merge
4424
        else:
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
4425
            allow_pending = True
4426
        return merger, allow_pending
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4427
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
4428
    def get_merger_from_uncommitted(self, tree, location, pb):
4465.1.1 by Aaron Bentley
Refactor cmd_merge to allow supplying other forms of uncommitted changes.
4429
        """Get a merger for uncommitted changes.
4430
4431
        :param tree: The tree the merger should apply to.
4432
        :param location: The location containing uncommitted changes.
4433
        :param pb: The progress bar to use for showing progress.
4434
        """
4435
        location = self._select_branch_location(tree, location)[0]
4436
        other_tree, other_path = WorkingTree.open_containing(location)
4437
        merger = _mod_merge.Merger.from_uncommitted(tree, other_tree, pb)
4438
        if other_path != '':
4439
            merger.interesting_files = [other_path]
4440
        return merger
4441
1551.20.2 by Aaron Bentley
Merge prefers submit branch, but falls back to parent branch
4442
    def _select_branch_location(self, tree, user_location, revision=None,
1551.15.74 by Aaron Bentley
Textual updates from review
4443
                                index=None):
4444
        """Select a branch location, according to possible inputs.
4445
4446
        If provided, branches from ``revision`` are preferred.  (Both
4447
        ``revision`` and ``index`` must be supplied.)
4448
4449
        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
4450
        ``submit`` or ``parent`` location is used, and a note is printed.
1551.15.74 by Aaron Bentley
Textual updates from review
4451
4452
        :param tree: The working tree to select a branch for merging into
4453
        :param location: The location entered by the user
4454
        :param revision: The revision parameter to the command
4455
        :param index: The index to use for the revision parameter.  Negative
4456
            indices are permitted.
1551.20.2 by Aaron Bentley
Merge prefers submit branch, but falls back to parent branch
4457
        :return: (selected_location, user_location).  The default location
4458
            will be the user-entered location.
1551.15.74 by Aaron Bentley
Textual updates from review
4459
        """
1551.15.66 by Aaron Bentley
Improve behavior with revision ids
4460
        if (revision is not None and index is not None
4461
            and revision[index] is not None):
4462
            branch = revision[index].get_branch()
4463
            if branch is not None:
1551.20.2 by Aaron Bentley
Merge prefers submit branch, but falls back to parent branch
4464
                return branch, branch
4465
        if user_location is None:
4466
            location = self._get_remembered(tree, 'Merging from')
4467
        else:
4468
            location = user_location
4469
        return location, user_location
1551.15.66 by Aaron Bentley
Improve behavior with revision ids
4470
1551.20.2 by Aaron Bentley
Merge prefers submit branch, but falls back to parent branch
4471
    def _get_remembered(self, tree, verb_string):
1685.1.59 by Martin Pool
[broken] Fix up & refactor display of remembered urls to unescape properly
4472
        """Use tree.branch's parent if none was supplied.
4473
4474
        Report if the remembered location was used.
4475
        """
1551.20.2 by Aaron Bentley
Merge prefers submit branch, but falls back to parent branch
4476
        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.
4477
        stored_location_type = "submit"
1551.20.2 by Aaron Bentley
Merge prefers submit branch, but falls back to parent branch
4478
        if stored_location is None:
4479
            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.
4480
            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
4481
        mutter("%s", stored_location)
1685.1.59 by Martin Pool
[broken] Fix up & refactor display of remembered urls to unescape properly
4482
        if stored_location is None:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
4483
            raise errors.BzrCommandError(gettext("No location specified or remembered"))
3249.1.1 by Ian Clatworthy
fix merge redirection when using a remembered location
4484
        display_url = urlutils.unescape_for_display(stored_location, 'utf-8')
6138.2.4 by Jonathan Riddell
use format strings where there are multiple substitutions to allow for translations
4485
        note(gettext("{0} remembered {1} location {2}").format(verb_string,
4486
                stored_location_type, display_url))
1685.1.59 by Martin Pool
[broken] Fix up & refactor display of remembered urls to unescape properly
4487
        return stored_location
4488
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4489
1185.35.4 by Aaron Bentley
Implemented remerge
4490
class cmd_remerge(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
4491
    __doc__ = """Redo a merge.
1551.6.22 by Aaron Bentley
Improved help for remerge and merge
4492
4493
    Use this if you want to try a different merge technique while resolving
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
4494
    conflicts.  Some merge techniques are better than others, and remerge
1551.6.22 by Aaron Bentley
Improved help for remerge and merge
4495
    lets you try different ones on different files.
4496
4497
    The options for remerge have the same meaning and defaults as the ones for
4498
    merge.  The difference is that remerge can (only) be run when there is a
4499
    pending merge, and it lets you specify particular files.
4500
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
4501
    :Examples:
1551.6.22 by Aaron Bentley
Improved help for remerge and merge
4502
        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
4503
        conflict regions, in addition to the usual THIS and OTHER texts::
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
4504
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
4505
            bzr remerge --show-base
1551.6.22 by Aaron Bentley
Improved help for remerge and merge
4506
4507
        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
4508
        additional processing to reduce the size of conflict regions::
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
4509
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
4510
            bzr remerge --merge-type weave --reprocess foobar
2374.1.1 by Ian Clatworthy
Help and man page fixes
4511
    """
1185.35.4 by Aaron Bentley
Implemented remerge
4512
    takes_args = ['file*']
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
4513
    takes_options = [
5321.1.74 by Gordon Tyler
Reverted some more command-related stuff that I missed earlier.
4514
            'merge-type',
4515
            'reprocess',
4516
            Option('show-base',
5321.1.75 by Gordon Tyler
Reverted more command-related stuff and my own idiocy.
4517
                   help="Show base revision text in conflicts."),
4518
            ]
1551.6.22 by Aaron Bentley
Improved help for remerge and merge
4519
1185.35.4 by Aaron Bentley
Implemented remerge
4520
    def run(self, file_list=None, merge_type=None, show_base=False,
5321.1.68 by Gordon Tyler
Removed mergetools command and integrations into merge and remerge commands, in preparation for splitting them off into a separate branch.
4521
            reprocess=False):
5127.1.2 by Martin Pool
Lazy-load conflict commands
4522
        from bzrlib.conflicts import restore
1185.35.4 by Aaron Bentley
Implemented remerge
4523
        if merge_type is None:
1996.3.5 by John Arbash Meinel
Cleanup, deprecated, and get the tests passing again.
4524
            merge_type = _mod_merge.Merge3Merger
5346.4.5 by Martin Pool
Deprecate and avoid internal_tree_files and tree_files.
4525
        tree, file_list = WorkingTree.open_containing_paths(file_list)
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
4526
        self.add_cleanup(tree.lock_write().unlock)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
4527
        parents = tree.get_parent_ids()
4528
        if len(parents) != 2:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
4529
            raise errors.BzrCommandError(gettext("Sorry, remerge only works after normal"
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
4530
                                         " merges.  Not cherrypicking or"
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
4531
                                         " multi-merges."))
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
4532
        repository = tree.branch.repository
4533
        interesting_ids = None
4534
        new_conflicts = []
4535
        conflicts = tree.conflicts()
4536
        if file_list is not None:
4537
            interesting_ids = set()
4538
            for filename in file_list:
4539
                file_id = tree.path2id(filename)
4540
                if file_id is None:
4541
                    raise errors.NotVersionedError(filename)
4542
                interesting_ids.add(file_id)
4543
                if tree.kind(file_id) != "directory":
4544
                    continue
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
4545
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
4546
                for name, ie in tree.inventory.iter_entries(file_id):
4547
                    interesting_ids.add(ie.file_id)
4548
            new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
4549
        else:
4550
            # Remerge only supports resolving contents conflicts
4551
            allowed_conflicts = ('text conflict', 'contents conflict')
4552
            restore_files = [c.path for c in conflicts
4553
                             if c.typestring in allowed_conflicts]
4554
        _mod_merge.transform_tree(tree, tree.basis_tree(), interesting_ids)
4555
        tree.set_conflicts(ConflictList(new_conflicts))
4556
        if file_list is not None:
4557
            restore_files = file_list
4558
        for filename in restore_files:
1551.15.47 by Aaron Bentley
Fix remerge --weave
4559
            try:
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
4560
                restore(tree.abspath(filename))
4561
            except errors.NotConflicted:
4562
                pass
4563
        # Disable pending merges, because the file texts we are remerging
4564
        # have not had those merges performed.  If we use the wrong parents
4565
        # list, we imply that the working tree text has seen and rejected
4566
        # all the changes from the other tree, when in fact those changes
4567
        # have not yet been seen.
4568
        tree.set_parent_ids(parents[:1])
4569
        try:
4961.2.13 by Martin Pool
Further progress bar string-pulling
4570
            merger = _mod_merge.Merger.from_revision_ids(None, tree, parents[1])
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
4571
            merger.interesting_ids = interesting_ids
4572
            merger.merge_type = merge_type
4573
            merger.show_base = show_base
4574
            merger.reprocess = reprocess
4575
            conflicts = merger.do_merge()
1185.35.4 by Aaron Bentley
Implemented remerge
4576
        finally:
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
4577
            tree.set_parent_ids(parents)
1185.35.4 by Aaron Bentley
Implemented remerge
4578
        if conflicts > 0:
4579
            return 1
4580
        else:
4581
            return 0
4582
2023.1.1 by ghigo
add topics help
4583
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4584
class cmd_revert(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
4585
    __doc__ = """Revert files to a previous revision.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4586
1551.8.27 by Aaron Bentley
Update docs again
4587
    Giving a list of files will revert only those files.  Otherwise, all files
4588
    will be reverted.  If the revision is not specified with '--revision', the
4589
    last committed revision is used.
1551.8.26 by Aaron Bentley
Update revert help text
4590
4591
    To remove only some changes, without reverting to a prior version, use
5561.1.2 by Andrew Bennetts
Fix double dash, highlight the significant '.' param.
4592
    merge instead.  For example, "merge . -r -2..-3" (don't forget the ".")
4593
    will remove the changes introduced by the second last commit (-2), without
4594
    affecting the changes introduced by the last commit (-1).  To remove
4595
    certain changes on a hunk-by-hunk basis, see the shelve command.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
4596
1551.8.26 by Aaron Bentley
Update revert help text
4597
    By default, any files that have been manually changed will be backed up
4598
    first.  (Files changed only by merge are not backed up.)  Backup files have
1551.8.27 by Aaron Bentley
Update docs again
4599
    '.~#~' appended to their name, where # is a number.
4600
4601
    When you provide files, you can use their current pathname or the pathname
4602
    from the target revision.  So you can use revert to "undelete" a file by
4603
    name.  If you name a directory, all the contents of that directory will be
4604
    reverted.
2614.1.1 by Martin Pool
Doc for revert, #87548
4605
4825.1.1 by Robert Collins
Merge documentation fixes from Neil Martinsen-Burrell.
4606
    If you have newly added files since the target revision, they will be
4798.1.1 by Neil Martinsen-Burrell
change revert documentation to be clearer about when it removes files
4607
    removed.  If the files to be removed have been changed, backups will be
4608
    created as above.  Directories containing unknown files will not be
4609
    deleted.
2911.2.1 by Martin Pool
Better help for revert
4610
4955.2.1 by Neil Martinsen-Burrell
improve revert documentations discussion of pending merges
4611
    The working tree contains a list of revisions that have been merged but
4612
    not yet committed. These revisions will be included as additional parents
4613
    of the next commit.  Normally, using revert clears that list as well as
4614
    reverting the files.  If any files are specified, revert leaves the list
4615
    of uncommitted merges alone and reverts only the files.  Use ``bzr revert
4616
    .`` in the tree root to revert all files but keep the recorded merges,
4617
    and ``bzr revert --forget-merges`` to clear the pending merge list without
2911.2.1 by Martin Pool
Better help for revert
4618
    reverting any files.
4798.6.1 by Neil Martinsen-Burrell
document the use of revert --forget-merges to condense merges to a single revision
4619
4955.2.1 by Neil Martinsen-Burrell
improve revert documentations discussion of pending merges
4620
    Using "bzr revert --forget-merges", it is possible to apply all of the
4621
    changes from a branch in a single revision.  To do this, perform the merge
4622
    as desired.  Then doing revert with the "--forget-merges" option will keep
4623
    the content of the tree as it was, but it will clear the list of pending
4624
    merges.  The next commit will then contain all of the changes that are
4625
    present in the other branch, but without any other parent revisions.
4626
    Because this technique forgets where these changes originated, it may
4627
    cause additional conflicts on later merges involving the same source and
4798.6.3 by Neil Martinsen-Burrell
Add discussion of conflicts
4628
    target branches.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4629
    """
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
4630
5561.1.1 by Andrew Bennetts
Tweak 'revert' help based on IRC feedback: make clear the meanings of -2 & -1, use '-r' rather than '--revision' in example, update text for shelve being built in, and add 'merge' and 'shelve' to the see also list.
4631
    _see_also = ['cat', 'export', 'merge', 'shelve']
2598.1.6 by Martin Pool
Add help for --no-backup
4632
    takes_options = [
2851.2.1 by Martin Pool
Add revert --forget-merges
4633
        'revision',
4634
        Option('no-backup', "Do not save backups of reverted files."),
4635
        Option('forget-merges',
4636
               'Remove pending merge marker, without changing any files.'),
4637
        ]
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4638
    takes_args = ['file*']
4639
2851.2.1 by Martin Pool
Add revert --forget-merges
4640
    def run(self, revision=None, no_backup=False, file_list=None,
4641
            forget_merges=None):
5346.4.5 by Martin Pool
Deprecate and avoid internal_tree_files and tree_files.
4642
        tree, file_list = WorkingTree.open_containing_paths(file_list)
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
4643
        self.add_cleanup(tree.lock_tree_write().unlock)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
4644
        if forget_merges:
4645
            tree.set_parent_ids(tree.get_parent_ids()[:1])
4646
        else:
4647
            self._revert_tree_to_revision(tree, revision, file_list, no_backup)
2851.2.1 by Martin Pool
Add revert --forget-merges
4648
4649
    @staticmethod
4650
    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)
4651
        rev_tree = _get_one_revision_tree('revert', revision, tree=tree)
4961.2.11 by Martin Pool
Pull out pbs and ProgressPhases stored in object state; just use them in single functions
4652
        tree.revert(file_list, rev_tree, not no_backup, None,
4653
            report_changes=True)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4654
4655
4656
class cmd_assert_fail(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
4657
    __doc__ = """Test reporting of assertion failures"""
2090.2.1 by Martin Pool
Fix some code which relies on assertions and breaks under python -O
4658
    # intended just for use in testing
4659
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4660
    hidden = True
2090.2.1 by Martin Pool
Fix some code which relies on assertions and breaks under python -O
4661
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4662
    def run(self):
2090.2.1 by Martin Pool
Fix some code which relies on assertions and breaks under python -O
4663
        raise AssertionError("always fails")
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4664
4665
4666
class cmd_help(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
4667
    __doc__ = """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)
4668
    """
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4669
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
4670
    _see_also = ['topics']
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
4671
    takes_options = [
4672
            Option('long', 'Show help on all commands.'),
4673
            ]
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4674
    takes_args = ['topic?']
1616.1.15 by Martin Pool
Handle 'bzr ?', etc.
4675
    aliases = ['?', '--help', '-?', '-h']
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
4676
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
4677
    @display_command
3984.4.5 by Ian Clatworthy
help xxx is full help; xxx -h is concise help
4678
    def run(self, topic=None, long=False):
2023.1.1 by ghigo
add topics help
4679
        import bzrlib.help
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4680
        if topic is None and long:
4681
            topic = "commands"
3984.4.5 by Ian Clatworthy
help xxx is full help; xxx -h is concise help
4682
        bzrlib.help.help(topic)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4683
4684
4685
class cmd_shell_complete(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
4686
    __doc__ = """Show appropriate completions for context.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4687
2023.1.1 by ghigo
add topics help
4688
    For a list of all available commands, say 'bzr shell-complete'.
4689
    """
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4690
    takes_args = ['context?']
4691
    aliases = ['s-c']
4692
    hidden = True
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
4693
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
4694
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4695
    def run(self, context=None):
4696
        import shellcomplete
4697
        shellcomplete.shellcomplete(context)
4698
4699
4700
class cmd_missing(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
4701
    __doc__ = """Show unmerged/unpulled revisions between two branches.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
4702
2023.1.1 by ghigo
add topics help
4703
    OTHER_BRANCH may be local or remote.
3921.3.12 by Marius Kruger
add missing examples and NEWS
4704
4156.1.1 by Vincent Ladeuil
Trivial spelling correction to "bzr missing" documentation
4705
    To filter on a range of revisions, you can use the command -r begin..end
3921.3.13 by Marius Kruger
update missing documentation and blackbox test to better reflect `-r 3` behaviour.
4706
    -r revision requests a specific revision, -r ..end or -r begin.. are
4707
    also valid.
4849.2.1 by Neil Martinsen-Burrell
document the return values of bzr missing
4708
            
4849.2.2 by Neil Martinsen-Burrell
better markup
4709
    :Exit values:
4849.2.1 by Neil Martinsen-Burrell
document the return values of bzr missing
4710
        1 - some missing revisions
4711
        0 - no missing revisions
3921.3.13 by Marius Kruger
update missing documentation and blackbox test to better reflect `-r 3` behaviour.
4712
3921.3.12 by Marius Kruger
add missing examples and NEWS
4713
    :Examples:
4714
4715
        Determine the missing revisions between this and the branch at the
4716
        remembered pull location::
4717
4718
            bzr missing
4719
4720
        Determine the missing revisions between this and another branch::
4721
4722
            bzr missing http://server/branch
4723
4724
        Determine the missing revisions up to a specific revision on the other
4725
        branch::
4726
4727
            bzr missing -r ..-10
4728
4729
        Determine the missing revisions up to a specific revision on this
4730
        branch::
4731
4732
            bzr missing --my-revision ..-10
2023.1.1 by ghigo
add topics help
4733
    """
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
4734
4735
    _see_also = ['merge', 'pull']
1185.54.1 by Aaron Bentley
Import Kinnison's plugin
4736
    takes_args = ['other_branch?']
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
4737
    takes_options = [
5171.3.13 by Martin von Gagern
Add --directory option to 7 more commands.
4738
        'directory',
3921.3.6 by Marius Kruger
* fix some indentation anomalies in cmd_missing
4739
        Option('reverse', 'Reverse the order of revisions.'),
4740
        Option('mine-only',
4741
               'Display changes in the local branch only.'),
4742
        Option('this' , 'Same as --mine-only.'),
4743
        Option('theirs-only',
4744
               'Display changes in the remote branch only.'),
4745
        Option('other', 'Same as --theirs-only.'),
4746
        'log-format',
4747
        'show-ids',
4748
        'verbose',
4749
        custom_help('revision',
3921.3.11 by Marius Kruger
swap options as per review:
4750
             help='Filter on other branch revisions (inclusive). '
3921.3.6 by Marius Kruger
* fix some indentation anomalies in cmd_missing
4751
                'See "help revisionspec" for details.'),
3921.3.11 by Marius Kruger
swap options as per review:
4752
        Option('my-revision',
3921.3.6 by Marius Kruger
* fix some indentation anomalies in cmd_missing
4753
            type=_parse_revision_str,
3921.3.11 by Marius Kruger
swap options as per review:
4754
            help='Filter on local branch revisions (inclusive). '
3921.3.6 by Marius Kruger
* fix some indentation anomalies in cmd_missing
4755
                'See "help revisionspec" for details.'),
6123.11.13 by Martin von Gagern
Rename --include-sidelines to --include-merged.
4756
        Option('include-merged',
4221.1.1 by Vincent Ladeuil
Clarify 'missing --include-merges' help.
4757
               'Show all revisions in addition to the mainline ones.'),
6123.11.1 by Martin von Gagern
Rename --include-merges option to --include-sidelines.
4758
        Option('include-merges', hidden=True,
6123.11.13 by Martin von Gagern
Rename --include-sidelines to --include-merged.
4759
               help='Historical alias for --include-merged.'),
3921.3.6 by Marius Kruger
* fix some indentation anomalies in cmd_missing
4760
        ]
1816.1.2 by Alexander Belchenko
fix non-ascii messages handling in 'missing' command
4761
    encoding_type = 'replace'
1185.54.1 by Aaron Bentley
Import Kinnison's plugin
4762
1816.1.2 by Alexander Belchenko
fix non-ascii messages handling in 'missing' command
4763
    @display_command
1185.54.1 by Aaron Bentley
Import Kinnison's plugin
4764
    def run(self, other_branch=None, reverse=False, mine_only=False,
3677.1.1 by Vincent Ladeuil
Begin fixing bug #233817.
4765
            theirs_only=False,
4766
            log_format=None, long=False, short=False, line=False,
4767
            show_ids=False, verbose=False, this=False, other=False,
6123.11.13 by Martin von Gagern
Rename --include-sidelines to --include-merged.
4768
            include_merged=None, revision=None, my_revision=None,
6123.11.10 by Martin von Gagern
Print deprecation warnings for all uses of include_merges.
4769
            directory=u'.',
4770
            include_merges=symbol_versioning.DEPRECATED_PARAMETER):
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.
4771
        from bzrlib.missing import find_unmerged, iter_log_revisions
3778.5.1 by Martin Pool
missing -q is quieter (#284748)
4772
        def message(s):
4773
            if not is_quiet():
4774
                self.outf.write(s)
2528.1.1 by Martin Pool
Better option names for missing (elliot)
4775
6123.11.10 by Martin von Gagern
Print deprecation warnings for all uses of include_merges.
4776
        if symbol_versioning.deprecated_passed(include_merges):
4777
            ui.ui_factory.show_user_warning(
4778
                'deprecated_command_option',
4779
                deprecated_name='--include-merges',
6123.11.13 by Martin von Gagern
Rename --include-sidelines to --include-merged.
4780
                recommended_name='--include-merged',
6123.11.10 by Martin von Gagern
Print deprecation warnings for all uses of include_merges.
4781
                deprecated_in_version='2.5',
4782
                command=self.invoked_as)
6123.11.13 by Martin von Gagern
Rename --include-sidelines to --include-merged.
4783
            if include_merged is None:
4784
                include_merged = include_merges
6123.11.10 by Martin von Gagern
Print deprecation warnings for all uses of include_merges.
4785
            else:
6123.11.16 by Martin von Gagern
Use gettext for command errors about conflicting options.
4786
                raise errors.BzrCommandError(gettext(
6123.11.17 by Martin von Gagern
Use the same translation template for all mutually exclusive command line options.
4787
                    '{0} and {1} are mutually exclusive').format(
4788
                    '--include-merges', '--include-merged'))
6123.11.13 by Martin von Gagern
Rename --include-sidelines to --include-merged.
4789
        if include_merged is None:
4790
            include_merged = False
2528.1.1 by Martin Pool
Better option names for missing (elliot)
4791
        if this:
3427.3.3 by John Arbash Meinel
Revert cmd_missing to use the original function, only now supply restrict
4792
            mine_only = this
2528.1.1 by Martin Pool
Better option names for missing (elliot)
4793
        if other:
3427.3.3 by John Arbash Meinel
Revert cmd_missing to use the original function, only now supply restrict
4794
            theirs_only = other
4795
        # TODO: We should probably check that we don't have mine-only and
4796
        #       theirs-only set, but it gets complicated because we also have
4797
        #       this and other which could be used.
4798
        restrict = 'all'
4799
        if mine_only:
4800
            restrict = 'local'
4801
        elif theirs_only:
4802
            restrict = 'remote'
2528.1.1 by Martin Pool
Better option names for missing (elliot)
4803
5171.3.13 by Martin von Gagern
Add --directory option to 7 more commands.
4804
        local_branch = Branch.open_containing(directory)[0]
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
4805
        self.add_cleanup(local_branch.lock_read().unlock)
5144.1.1 by Andrew Bennetts
Read-lock local_branch and remote_branch in cmd_missing as soon as they are opened. Makes 'bzr missing' clean w.r.t. -Drelock.
4806
1185.54.16 by Aaron Bentley
fixed location handling to match old missing
4807
        parent = local_branch.get_parent()
1185.54.1 by Aaron Bentley
Import Kinnison's plugin
4808
        if other_branch is None:
1185.54.16 by Aaron Bentley
fixed location handling to match old missing
4809
            other_branch = parent
4810
            if other_branch is None:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
4811
                raise errors.BzrCommandError(gettext("No peer location known"
4812
                                             " or specified."))
2193.4.1 by Alexander Belchenko
'bzr missing' without specifying location show remembered location unescaped
4813
            display_url = urlutils.unescape_for_display(parent,
4814
                                                        self.outf.encoding)
6138.2.1 by Jonathan Riddell
add gettext to all the builtin commands outf usage
4815
            message(gettext("Using saved parent location: {0}\n").format(
4816
                    display_url))
2193.4.1 by Alexander Belchenko
'bzr missing' without specifying location show remembered location unescaped
4817
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
4818
        remote_branch = Branch.open(other_branch)
1551.2.46 by abentley
Made bzr missing . work on win32
4819
        if remote_branch.base == local_branch.base:
4820
            remote_branch = local_branch
5144.1.1 by Andrew Bennetts
Read-lock local_branch and remote_branch in cmd_missing as soon as they are opened. Makes 'bzr missing' clean w.r.t. -Drelock.
4821
        else:
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
4822
            self.add_cleanup(remote_branch.lock_read().unlock)
3921.3.4 by Marius Kruger
add support to filter on local and remote revisions
4823
4824
        local_revid_range = _revision_range_to_revid_range(
3921.3.11 by Marius Kruger
swap options as per review:
4825
            _get_revision_range(my_revision, local_branch,
3921.3.9 by Marius Kruger
* add some blackbox tests and another whitebox test
4826
                self.name()))
3921.3.4 by Marius Kruger
add support to filter on local and remote revisions
4827
4828
        remote_revid_range = _revision_range_to_revid_range(
3921.3.11 by Marius Kruger
swap options as per review:
4829
            _get_revision_range(revision,
3921.3.9 by Marius Kruger
* add some blackbox tests and another whitebox test
4830
                remote_branch, self.name()))
3921.3.4 by Marius Kruger
add support to filter on local and remote revisions
4831
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
4832
        local_extra, remote_extra = find_unmerged(
4833
            local_branch, remote_branch, restrict,
4834
            backward=not reverse,
6123.11.13 by Martin von Gagern
Rename --include-sidelines to --include-merged.
4835
            include_merged=include_merged,
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
4836
            local_revid_range=local_revid_range,
4837
            remote_revid_range=remote_revid_range)
4838
4839
        if log_format is None:
4840
            registry = log.log_formatter_registry
4841
            log_format = registry.get_default(local_branch)
4842
        lf = log_format(to_file=self.outf,
4843
                        show_ids=show_ids,
4844
                        show_timezone='original')
4845
4846
        status_code = 0
4847
        if local_extra and not theirs_only:
6143.1.1 by Jonathan Riddell
use ngettext for plurals
4848
            message(ngettext("You have %d extra revision:\n",
4849
                             "You have %d extra revisions:\n", 
4850
                             len(local_extra)) %
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
4851
                len(local_extra))
4852
            for revision in iter_log_revisions(local_extra,
4853
                                local_branch.repository,
4854
                                verbose):
4855
                lf.log_revision(revision)
4856
            printed_local = True
4857
            status_code = 1
4858
        else:
4859
            printed_local = False
4860
4861
        if remote_extra and not mine_only:
4862
            if printed_local is True:
4863
                message("\n\n\n")
6143.1.1 by Jonathan Riddell
use ngettext for plurals
4864
            message(ngettext("You are missing %d revision:\n",
4865
                             "You are missing %d revisions:\n",
4866
                             len(remote_extra)) %
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
4867
                len(remote_extra))
4868
            for revision in iter_log_revisions(remote_extra,
4869
                                remote_branch.repository,
4870
                                verbose):
4871
                lf.log_revision(revision)
4872
            status_code = 1
4873
4874
        if mine_only and not local_extra:
4875
            # We checked local, and found nothing extra
6138.2.1 by Jonathan Riddell
add gettext to all the builtin commands outf usage
4876
            message(gettext('This branch has no new revisions.\n'))
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
4877
        elif theirs_only and not remote_extra:
4878
            # We checked remote, and found nothing extra
6138.2.1 by Jonathan Riddell
add gettext to all the builtin commands outf usage
4879
            message(gettext('Other branch has no new revisions.\n'))
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
4880
        elif not (mine_only or theirs_only or local_extra or
4881
                  remote_extra):
4882
            # We checked both branches, and neither one had extra
4883
            # revisions
6138.2.1 by Jonathan Riddell
add gettext to all the builtin commands outf usage
4884
            message(gettext("Branches are up to date.\n"))
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
4885
        self.cleanup_now()
1666.1.5 by Robert Collins
Merge bound branch test performance improvements.
4886
        if not status_code and parent is None and other_branch is not None:
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
4887
            self.add_cleanup(local_branch.lock_write().unlock)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
4888
            # handle race conditions - a parent might be set while we run.
4889
            if local_branch.get_parent() is None:
4890
                local_branch.set_parent(remote_branch.base)
1666.1.5 by Robert Collins
Merge bound branch test performance improvements.
4891
        return status_code
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4892
4893
2604.2.1 by Robert Collins
(robertc) Introduce a pack command.
4894
class cmd_pack(Command):
5131.2.3 by Martin
Merge bzr.dev to resolve conflicts
4895
    __doc__ = """Compress the data within a repository.
5108.1.1 by Parth Malwankar
initial support for 'pack --clean-obsolete-packs'. tested only manually.
4896
5108.1.6 by Parth Malwankar
fixed typo.
4897
    This operation compresses the data within a bazaar repository. As
5108.1.1 by Parth Malwankar
initial support for 'pack --clean-obsolete-packs'. tested only manually.
4898
    bazaar supports automatic packing of repository, this operation is
4899
    normally not required to be done manually.
4900
5108.1.5 by Parth Malwankar
updated docstring for pack command with better warning.
4901
    During the pack operation, bazaar takes a backup of existing repository
4902
    data, i.e. pack files. This backup is eventually removed by bazaar
5108.1.1 by Parth Malwankar
initial support for 'pack --clean-obsolete-packs'. tested only manually.
4903
    automatically when it is safe to do so. To save disk space by removing
4904
    the backed up pack files, the --clean-obsolete-packs option may be
4905
    used.
4906
5108.1.5 by Parth Malwankar
updated docstring for pack command with better warning.
4907
    Warning: If you use --clean-obsolete-packs and your machine crashes
4908
    during or immediately after repacking, you may be left with a state
4909
    where the deletion has been written to disk but the new packs have not
4910
    been. In this case the repository may be unusable.
5108.1.1 by Parth Malwankar
initial support for 'pack --clean-obsolete-packs'. tested only manually.
4911
    """
2604.2.1 by Robert Collins
(robertc) Introduce a pack command.
4912
4913
    _see_also = ['repositories']
4914
    takes_args = ['branch_or_repo?']
5108.1.1 by Parth Malwankar
initial support for 'pack --clean-obsolete-packs'. tested only manually.
4915
    takes_options = [
4916
        Option('clean-obsolete-packs', 'Delete obsolete packs to save disk space.'),
4917
        ]
2604.2.1 by Robert Collins
(robertc) Introduce a pack command.
4918
5108.1.1 by Parth Malwankar
initial support for 'pack --clean-obsolete-packs'. tested only manually.
4919
    def run(self, branch_or_repo='.', clean_obsolete_packs=False):
6207.3.3 by jelmer at samba
Fix tests and the like.
4920
        dir = controldir.ControlDir.open_containing(branch_or_repo)[0]
2604.2.1 by Robert Collins
(robertc) Introduce a pack command.
4921
        try:
4922
            branch = dir.open_branch()
4923
            repository = branch.repository
4924
        except errors.NotBranchError:
4925
            repository = dir.open_repository()
5108.1.1 by Parth Malwankar
initial support for 'pack --clean-obsolete-packs'. tested only manually.
4926
        repository.pack(clean_obsolete_packs=clean_obsolete_packs)
2604.2.1 by Robert Collins
(robertc) Introduce a pack command.
4927
4928
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4929
class cmd_plugins(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
4930
    __doc__ = """List the installed plugins.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
4931
3193.2.3 by Alexander Belchenko
another formatting variant suggested by John Meinel.
4932
    This command displays the list of installed plugins including
4933
    version of plugin and a short description of each.
4934
4935
    --verbose shows the path where each plugin is located.
2617.3.1 by Ian Clatworthy
Make the plugins command public with better help
4936
4937
    A plugin is an external component for Bazaar that extends the
4938
    revision control system, by adding or replacing code in Bazaar.
4939
    Plugins can do a variety of things, including overriding commands,
4940
    adding new commands, providing additional network transports and
4941
    customizing log output.
4942
4988.4.2 by Martin Pool
Change url to canonical.com or wiki, plus some doc improvements in passing
4943
    See the Bazaar Plugin Guide <http://doc.bazaar.canonical.com/plugins/en/>
4944
    for further information on plugins including where to find them and how to
4945
    install them. Instructions are also provided there on how to write new
4946
    plugins using the Python programming language.
2617.3.1 by Ian Clatworthy
Make the plugins command public with better help
4947
    """
3193.2.3 by Alexander Belchenko
another formatting variant suggested by John Meinel.
4948
    takes_options = ['verbose']
2629.1.1 by Ian Clatworthy
(Ian Clatworthy) Tweak the 'make plugins public' change following feedback from lifeless
4949
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
4950
    @display_command
3193.2.3 by Alexander Belchenko
another formatting variant suggested by John Meinel.
4951
    def run(self, verbose=False):
5616.7.5 by Martin Pool
Factor out describe_loaded_plugins
4952
        from bzrlib import plugin
5863.3.4 by Martin
Add comment suggested by poolie in review
4953
        # Don't give writelines a generator as some codecs don't like that
5863.3.3 by Martin
Use list() instead as suggested by jam in review
4954
        self.outf.writelines(
4955
            list(plugin.describe_plugins(show_paths=verbose)))
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4956
4957
1185.16.24 by Martin Pool
- add and test 'testament' builtin command
4958
class cmd_testament(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
4959
    __doc__ = """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
4960
    takes_options = [
4961
            'revision',
4962
            Option('long', help='Produce long-format testament.'),
4963
            Option('strict',
4964
                   help='Produce a strict-format testament.')]
1185.16.24 by Martin Pool
- add and test 'testament' builtin command
4965
    takes_args = ['branch?']
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
4966
    @display_command
1551.7.1 by Aaron Bentley
Implement --strict at commandline, fix up strict format
4967
    def run(self, branch=u'.', revision=None, long=False, strict=False):
4968
        from bzrlib.testament import Testament, StrictTestament
4969
        if strict is True:
4970
            testament_class = StrictTestament
4971
        else:
4972
            testament_class = Testament
3530.2.1 by John Arbash Meinel
'bzr testament' should just open the branch
4973
        if branch == '.':
4974
            b = Branch.open_containing(branch)[0]
4975
        else:
4976
            b = Branch.open(branch)
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
4977
        self.add_cleanup(b.lock_read().unlock)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
4978
        if revision is None:
4979
            rev_id = b.last_revision()
4980
        else:
4981
            rev_id = revision[0].as_revision_id(b)
4982
        t = testament_class.from_revision(b.repository, rev_id)
4983
        if long:
4984
            sys.stdout.writelines(t.as_text_lines())
4985
        else:
4986
            sys.stdout.write(t.as_short_text())
1185.16.32 by Martin Pool
- add a basic annotate built-in command
4987
4988
4989
class cmd_annotate(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
4990
    __doc__ = """Show the origin of each line in a file.
1185.16.32 by Martin Pool
- add a basic annotate built-in command
4991
1185.16.53 by Martin Pool
- annotate improvements from Goffreddo, with extra bug fixes and tests
4992
    This prints out the given file with an annotation on the left side
4993
    indicating which revision, author and date introduced the change.
4994
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
4995
    If the origin is the same for a run of consecutive lines, it is
1185.16.53 by Martin Pool
- annotate improvements from Goffreddo, with extra bug fixes and tests
4996
    shown only at the top, unless the --all option is given.
1185.16.32 by Martin Pool
- add a basic annotate built-in command
4997
    """
4998
    # TODO: annotate directories; showing when each file was last changed
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
4999
    # TODO: if the working copy is modified, show annotations on that
1185.16.53 by Martin Pool
- annotate improvements from Goffreddo, with extra bug fixes and tests
5000
    #       with new uncommitted lines marked
1733.2.8 by Michael Ellerman
Add CVS compatible aliases for checkout and annotate, from fullermd.
5001
    aliases = ['ann', 'blame', 'praise']
1185.16.32 by Martin Pool
- add a basic annotate built-in command
5002
    takes_args = ['filename']
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
5003
    takes_options = [Option('all', help='Show annotations on all lines.'),
5004
                     Option('long', help='Show commit date in annotations.'),
2182.3.1 by John Arbash Meinel
Annotate now shows dotted revnos instead of plain revnos.
5005
                     'revision',
5006
                     'show-ids',
5171.3.3 by Martin von Gagern
Add --directory option to ls, cat and annotate.
5007
                     'directory',
1185.16.53 by Martin Pool
- annotate improvements from Goffreddo, with extra bug fixes and tests
5008
                     ]
2593.1.1 by Adeodato Simó
Improve annotate to prevent unicode exceptions in certain situations.
5009
    encoding_type = 'exact'
1185.16.32 by Martin Pool
- add a basic annotate built-in command
5010
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
5011
    @display_command
2182.3.1 by John Arbash Meinel
Annotate now shows dotted revnos instead of plain revnos.
5012
    def run(self, filename, all=False, long=False, revision=None,
5171.3.3 by Martin von Gagern
Add --directory option to ls, cat and annotate.
5013
            show_ids=False, directory=None):
5815.3.1 by Jelmer Vernooij
Add annotate_file_revision_tree.
5014
        from bzrlib.annotate import (
5015
            annotate_file_tree,
5016
            )
3146.2.1 by Lukáš Lalinský
Don't require a working tree in cmd_annotate.
5017
        wt, branch, relpath = \
5171.3.9 by Martin von Gagern
Rename function to _open_directory_or_containing_tree_or_branch.
5018
            _open_directory_or_containing_tree_or_branch(filename, directory)
3146.2.1 by Lukáš Lalinský
Don't require a working tree in cmd_annotate.
5019
        if wt is not None:
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
5020
            self.add_cleanup(wt.lock_read().unlock)
3146.2.1 by Lukáš Lalinský
Don't require a working tree in cmd_annotate.
5021
        else:
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
5022
            self.add_cleanup(branch.lock_read().unlock)
4900.1.2 by Andrew Bennetts
Use Command.add_cleanup to fix ObjectNotLocked bug in cmd_annotate.
5023
        tree = _get_one_revision_tree('annotate', revision, branch=branch)
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
5024
        self.add_cleanup(tree.lock_read().unlock)
5638.2.1 by Andrew King
Fix 537442 - cannot annotate deleted file
5025
        if wt is not None and revision is None:
4900.1.2 by Andrew Bennetts
Use Command.add_cleanup to fix ObjectNotLocked bug in cmd_annotate.
5026
            file_id = wt.path2id(relpath)
5027
        else:
5028
            file_id = tree.path2id(relpath)
5029
        if file_id is None:
5030
            raise errors.NotVersionedError(filename)
5031
        if wt is not None and revision is None:
5032
            # If there is a tree and we're not annotating historical
5033
            # versions, annotate the working tree's content.
5034
            annotate_file_tree(wt, file_id, self.outf, long, all,
5035
                show_ids=show_ids)
5036
        else:
5815.3.14 by Jelmer Vernooij
Kill annotate_file_revision_tree() in favor annotate_file_tree().
5037
            annotate_file_tree(tree, file_id, self.outf, long, all,
5815.3.1 by Jelmer Vernooij
Add annotate_file_revision_tree.
5038
                show_ids=show_ids, branch=branch)
1185.16.33 by Martin Pool
- move 'conflict' and 'resolved' from shipped plugin to regular builtins
5039
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
5040
5041
class cmd_re_sign(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
5042
    __doc__ = """Create a digital signature for an existing revision."""
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
5043
    # TODO be able to replace existing ones.
5044
5045
    hidden = True # is this right ?
1185.78.1 by John Arbash Meinel
Updating bzr re-sign to allow multiple arguments, and updating tests
5046
    takes_args = ['revision_id*']
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
5047
    takes_options = ['directory', 'revision']
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
5048
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
5049
    def run(self, revision_id_list=None, revision=None, directory=u'.'):
1185.78.1 by John Arbash Meinel
Updating bzr re-sign to allow multiple arguments, and updating tests
5050
        if revision_id_list is not None and revision is not None:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
5051
            raise errors.BzrCommandError(gettext('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
5052
        if revision_id_list is None and revision is None:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
5053
            raise errors.BzrCommandError(gettext('You must supply either --revision or a revision_id'))
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
5054
        b = WorkingTree.open_containing(directory)[0].branch
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
5055
        self.add_cleanup(b.lock_write().unlock)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
5056
        return self._run(b, revision_id_list, revision)
3010.1.17 by Robert Collins
Lock correctness and commit_group management for re-sign, in builtins.
5057
5058
    def _run(self, b, revision_id_list, revision):
5059
        import bzrlib.gpg as gpg
6351.3.2 by Jelmer Vernooij
Convert some gpg options to config stacks.
5060
        gpg_strategy = gpg.GPGStrategy(b.get_config_stack())
1185.78.1 by John Arbash Meinel
Updating bzr re-sign to allow multiple arguments, and updating tests
5061
        if revision_id_list is not None:
3010.1.17 by Robert Collins
Lock correctness and commit_group management for re-sign, in builtins.
5062
            b.repository.start_write_group()
5063
            try:
5064
                for revision_id in revision_id_list:
5065
                    b.repository.sign_revision(revision_id, gpg_strategy)
5066
            except:
5067
                b.repository.abort_write_group()
5068
                raise
5069
            else:
5070
                b.repository.commit_write_group()
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
5071
        elif revision is not None:
1483 by Robert Collins
BUGFIX: re-sign should accept ranges
5072
            if len(revision) == 1:
5073
                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.
5074
                b.repository.start_write_group()
5075
                try:
5076
                    b.repository.sign_revision(rev_id, gpg_strategy)
5077
                except:
5078
                    b.repository.abort_write_group()
5079
                    raise
5080
                else:
5081
                    b.repository.commit_write_group()
1483 by Robert Collins
BUGFIX: re-sign should accept ranges
5082
            elif len(revision) == 2:
5083
                # are they both on rh- if so we can walk between them
5084
                # might be nice to have a range helper for arbitrary
5085
                # revision paths. hmm.
5086
                from_revno, from_revid = revision[0].in_history(b)
5087
                to_revno, to_revid = revision[1].in_history(b)
5088
                if to_revid is None:
5089
                    to_revno = b.revno()
5090
                if from_revno is None or to_revno is None:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
5091
                    raise errors.BzrCommandError(gettext('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.
5092
                b.repository.start_write_group()
5093
                try:
5094
                    for revno in range(from_revno, to_revno + 1):
5095
                        b.repository.sign_revision(b.get_rev_id(revno),
5096
                                                   gpg_strategy)
5097
                except:
5098
                    b.repository.abort_write_group()
5099
                    raise
5100
                else:
5101
                    b.repository.commit_write_group()
1483 by Robert Collins
BUGFIX: re-sign should accept ranges
5102
            else:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
5103
                raise errors.BzrCommandError(gettext('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.
5104
1505.1.22 by John Arbash Meinel
Some small cleanup and discussion in preparation for modifying commit, pull, and merge
5105
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
5106
class cmd_bind(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
5107
    __doc__ = """Convert the current branch into a checkout of the supplied branch.
5185.1.1 by John C Barstow
Document what happens when no location is supplied to bzr bind
5108
    If no branch is supplied, rebind to the last bound location.
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
5109
2270.1.2 by John Arbash Meinel
Tweak the help text for bind/unbind according to Robert's suggestions.
5110
    Once converted into a checkout, commits must succeed on the master branch
5111
    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.
5112
3565.6.16 by Marius Kruger
update nick command description to mention how it works for bound branches,
5113
    Bound branches use the nickname of its master branch unless it is set
4775.1.1 by Martin Pool
Remove several 'the the' typos
5114
    locally, in which case binding will update the local nickname to be
3565.6.15 by Marius Kruger
update bind and switch command descriptions to state what will happen to nicknames.
5115
    that of the master.
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
5116
    """
5117
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
5118
    _see_also = ['checkouts', 'unbind']
2230.3.31 by Aaron Bentley
Implement re-binding previously-bound branches
5119
    takes_args = ['location?']
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
5120
    takes_options = ['directory']
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
5121
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
5122
    def run(self, location=None, directory=u'.'):
5123
        b, relpath = Branch.open_containing(directory)
2230.3.31 by Aaron Bentley
Implement re-binding previously-bound branches
5124
        if location is None:
5125
            try:
5126
                location = b.get_old_bound_location()
5127
            except errors.UpgradeRequired:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
5128
                raise errors.BzrCommandError(gettext('No location supplied.  '
5129
                    'This format does not remember old locations.'))
2230.3.31 by Aaron Bentley
Implement re-binding previously-bound branches
5130
            else:
5131
                if location is None:
4988.7.1 by Neil Martinsen-Burrell
better error message for bzr bind on and already bound branch
5132
                    if b.get_bound_location() is not None:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
5133
                        raise errors.BzrCommandError(gettext('Branch is already bound'))
4988.7.1 by Neil Martinsen-Burrell
better error message for bzr bind on and already bound branch
5134
                    else:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
5135
                        raise errors.BzrCommandError(gettext('No location supplied '
5136
                            'and no previous location known'))
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
5137
        b_other = Branch.open(location)
1505.1.3 by John Arbash Meinel
(broken) Adding more tests, and some functionality
5138
        try:
5139
            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
5140
        except errors.DivergedBranches:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
5141
            raise errors.BzrCommandError(gettext('These branches have diverged.'
5142
                                         ' Try merging, and then bind again.'))
3565.6.11 by Marius Kruger
Bind now updates explicit nicks
5143
        if b.get_config().has_explicit_nickname():
5144
            b.nick = b_other.nick
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
5145
1505.1.22 by John Arbash Meinel
Some small cleanup and discussion in preparation for modifying commit, pull, and merge
5146
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
5147
class cmd_unbind(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
5148
    __doc__ = """Convert the current checkout into a regular branch.
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
5149
2270.1.2 by John Arbash Meinel
Tweak the help text for bind/unbind according to Robert's suggestions.
5150
    After unbinding, the local branch is considered independent and subsequent
5151
    commits will be local only.
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
5152
    """
5153
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
5154
    _see_also = ['checkouts', 'bind']
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
5155
    takes_args = []
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
5156
    takes_options = ['directory']
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
5157
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
5158
    def run(self, directory=u'.'):
5159
        b, relpath = Branch.open_containing(directory)
1505.1.22 by John Arbash Meinel
Some small cleanup and discussion in preparation for modifying commit, pull, and merge
5160
        if not b.unbind():
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
5161
            raise errors.BzrCommandError(gettext('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
5162
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
5163
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
5164
class cmd_uncommit(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
5165
    __doc__ = """Remove the last committed revision.
1185.31.24 by John Arbash Meinel
[merge] Added the uncommit plugin
5166
5167
    --verbose will print out what is being removed.
5168
    --dry-run will go through all the motions, but not actually
5169
    remove anything.
2747.2.1 by Daniel Watkins
Modified the help message of 'uncommit'.
5170
5171
    If --revision is specified, uncommit revisions to leave the branch at the
5172
    specified revision.  For example, "bzr uncommit -r 15" will leave the
5173
    branch at revision 15.
5174
1551.19.39 by Aaron Bentley
Update 'uncommit' docs
5175
    Uncommit leaves the working tree ready for a new commit.  The only change
5176
    it may make is to restore any pending merges that were present before
5177
    the commit.
1553.5.34 by Martin Pool
Stub lock-breaking command
5178
    """
1185.62.11 by John Arbash Meinel
Added TODO for bzr uncommit to remove unreferenced information.
5179
1553.5.34 by Martin Pool
Stub lock-breaking command
5180
    # TODO: jam 20060108 Add an option to allow uncommit to remove
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
5181
    # unreferenced information in 'branch-as-repository' branches.
1553.5.34 by Martin Pool
Stub lock-breaking command
5182
    # TODO: jam 20060108 Add the ability for uncommit to remove unreferenced
5183
    # information in shared branches as well.
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
5184
    _see_also = ['commit']
1185.62.10 by John Arbash Meinel
Removed --all from bzr uncommit, it was broken anyway.
5185
    takes_options = ['verbose', 'revision',
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
5186
                    Option('dry-run', help='Don\'t actually make changes.'),
3280.4.1 by John Arbash Meinel
Add uncommit --local.
5187
                    Option('force', help='Say yes to all questions.'),
6091.1.2 by Jelmer Vernooij
Add --keep-tags option to 'bzr uncommit'.
5188
                    Option('keep-tags',
5189
                           help='Keep tags that point to removed revisions.'),
3280.4.1 by John Arbash Meinel
Add uncommit --local.
5190
                    Option('local',
5191
                           help="Only remove the commits from the local branch"
5192
                                " when in a checkout."
5193
                           ),
5194
                    ]
1185.31.24 by John Arbash Meinel
[merge] Added the uncommit plugin
5195
    takes_args = ['location?']
5196
    aliases = []
3101.1.1 by Aaron Bentley
Uncommit doesn't throw when it encounters un-encodable characters
5197
    encoding_type = 'replace'
1185.31.24 by John Arbash Meinel
[merge] Added the uncommit plugin
5198
6091.1.6 by Jelmer Vernooij
Add keywords at the end.
5199
    def run(self, location=None, dry_run=False, verbose=False,
5200
            revision=None, force=False, local=False, keep_tags=False):
1185.31.24 by John Arbash Meinel
[merge] Added the uncommit plugin
5201
        if location is None:
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
5202
            location = u'.'
6207.3.3 by jelmer at samba
Fix tests and the like.
5203
        control, relpath = controldir.ControlDir.open_containing(location)
1558.1.12 by Aaron Bentley
Got uncommit working properly with checkouts
5204
        try:
5205
            tree = control.open_workingtree()
1558.9.1 by Aaron Bentley
Fix uncommit to handle bound branches, and to do locking
5206
            b = tree.branch
1558.1.12 by Aaron Bentley
Got uncommit working properly with checkouts
5207
        except (errors.NoWorkingTree, errors.NotLocalUrl):
5208
            tree = None
1558.9.1 by Aaron Bentley
Fix uncommit to handle bound branches, and to do locking
5209
            b = control.open_branch()
1185.31.24 by John Arbash Meinel
[merge] Added the uncommit plugin
5210
3065.2.2 by John Arbash Meinel
During bzr uncommit, lock the working tree if it is available.
5211
        if tree is not None:
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
5212
            self.add_cleanup(tree.lock_write().unlock)
3065.2.2 by John Arbash Meinel
During bzr uncommit, lock the working tree if it is available.
5213
        else:
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
5214
            self.add_cleanup(b.lock_write().unlock)
6091.1.2 by Jelmer Vernooij
Add --keep-tags option to 'bzr uncommit'.
5215
        return self._run(b, tree, dry_run, verbose, revision, force,
6091.1.6 by Jelmer Vernooij
Add keywords at the end.
5216
                         local, keep_tags)
3065.2.1 by Lukáš Lalinský
Add a global branch write lock to cmd_uncommit and avoid unnecessary Branch.revno calls.
5217
6091.1.6 by Jelmer Vernooij
Add keywords at the end.
5218
    def _run(self, b, tree, dry_run, verbose, revision, force, local,
5219
             keep_tags):
3065.2.1 by Lukáš Lalinský
Add a global branch write lock to cmd_uncommit and avoid unnecessary Branch.revno calls.
5220
        from bzrlib.log import log_formatter, show_log
5221
        from bzrlib.uncommit import uncommit
5222
5223
        last_revno, last_rev_id = b.last_revision_info()
5224
1850.3.2 by John Arbash Meinel
Change uncommit -r 10 so that it uncommits *to* 10, rather than removing 10
5225
        rev_id = None
1185.31.24 by John Arbash Meinel
[merge] Added the uncommit plugin
5226
        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.
5227
            revno = last_revno
5228
            rev_id = last_rev_id
1185.31.24 by John Arbash Meinel
[merge] Added the uncommit plugin
5229
        else:
1850.3.2 by John Arbash Meinel
Change uncommit -r 10 so that it uncommits *to* 10, rather than removing 10
5230
            # 'bzr uncommit -r 10' actually means uncommit
5231
            # so that the final tree is at revno 10.
5232
            # but bzrlib.uncommit.uncommit() actually uncommits
5233
            # the revisions that are supplied.
5234
            # 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.
5235
            revno = revision[0].in_history(b).revno + 1
5236
            if revno <= last_revno:
5237
                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
5238
2948.2.2 by John Arbash Meinel
Re-introduce the None check in case someone asks to uncommit *to* the last revision
5239
        if rev_id is None or _mod_revision.is_null(rev_id):
6138.2.1 by Jonathan Riddell
add gettext to all the builtin commands outf usage
5240
            self.outf.write(gettext('No revisions to uncommit.\n'))
1850.3.2 by John Arbash Meinel
Change uncommit -r 10 so that it uncommits *to* 10, rather than removing 10
5241
            return 1
5242
5243
        lf = log_formatter('short',
4988.8.3 by Ed Bayiates Home
More builtin command UIFactory updates
5244
                           to_file=self.outf,
3629.1.2 by John Arbash Meinel
Change to just display the command to restore the tip,
5245
                           show_timezone='original')
1850.3.2 by John Arbash Meinel
Change uncommit -r 10 so that it uncommits *to* 10, rather than removing 10
5246
5247
        show_log(b,
5248
                 lf,
5249
                 verbose=False,
5250
                 direction='forward',
5251
                 start_revision=revno,
3065.2.1 by Lukáš Lalinský
Add a global branch write lock to cmd_uncommit and avoid unnecessary Branch.revno calls.
5252
                 end_revision=last_revno)
1185.31.24 by John Arbash Meinel
[merge] Added the uncommit plugin
5253
5254
        if dry_run:
6138.2.1 by Jonathan Riddell
add gettext to all the builtin commands outf usage
5255
            self.outf.write(gettext('Dry-run, pretending to remove'
5256
                            ' the above revisions.\n'))
1185.31.24 by John Arbash Meinel
[merge] Added the uncommit plugin
5257
        else:
6138.2.1 by Jonathan Riddell
add gettext to all the builtin commands outf usage
5258
            self.outf.write(gettext('The above revision(s) will be removed.\n'))
4988.8.1 by Ed Bayiates
Updated builtins.py cmd_uncommit to use UIFactory
5259
5260
        if not force:
5416.1.6 by Martin Pool
Change 'uncommit' command to use confirm_action not get_boolean
5261
            if not ui.ui_factory.confirm_action(
6138.2.1 by Jonathan Riddell
add gettext to all the builtin commands outf usage
5262
                    gettext(u'Uncommit these revisions'),
5416.1.6 by Martin Pool
Change 'uncommit' command to use confirm_action not get_boolean
5263
                    'bzrlib.builtins.uncommit',
5264
                    {}):
6138.2.1 by Jonathan Riddell
add gettext to all the builtin commands outf usage
5265
                self.outf.write(gettext('Canceled\n'))
4988.8.1 by Ed Bayiates
Updated builtins.py cmd_uncommit to use UIFactory
5266
                return 0
1185.31.24 by John Arbash Meinel
[merge] Added the uncommit plugin
5267
3629.1.1 by John Arbash Meinel
Change 'bzr uncommit' to display the revision ids and log them.
5268
        mutter('Uncommitting from {%s} to {%s}',
5269
               last_rev_id, rev_id)
1558.1.12 by Aaron Bentley
Got uncommit working properly with checkouts
5270
        uncommit(b, tree=tree, dry_run=dry_run, verbose=verbose,
6091.1.2 by Jelmer Vernooij
Add --keep-tags option to 'bzr uncommit'.
5271
                 revno=revno, local=local, keep_tags=keep_tags)
6138.2.1 by Jonathan Riddell
add gettext to all the builtin commands outf usage
5272
        self.outf.write(gettext('You can restore the old tip by running:\n'
5273
             '  bzr pull . -r revid:%s\n') % last_rev_id)
1185.31.24 by John Arbash Meinel
[merge] Added the uncommit plugin
5274
5275
1553.5.34 by Martin Pool
Stub lock-breaking command
5276
class cmd_break_lock(Command):
5345.5.9 by Vincent Ladeuil
Implements 'bzr lock --config <file>'.
5277
    __doc__ = """Break a dead lock.
5278
5279
    This command breaks a lock on a repository, branch, working directory or
5280
    config file.
1553.5.34 by Martin Pool
Stub lock-breaking command
5281
1553.5.35 by Martin Pool
Start break-lock --show
5282
    CAUTION: Locks should only be broken when you are sure that the process
1553.5.34 by Martin Pool
Stub lock-breaking command
5283
    holding the lock has been stopped.
1687.1.12 by Robert Collins
Hook in the full break-lock ui.
5284
4960.2.3 by Martin Pool
Better break-lock help
5285
    You can get information on what locks are open via the 'bzr info
5286
    [location]' command.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
5287
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
5288
    :Examples:
1687.1.12 by Robert Collins
Hook in the full break-lock ui.
5289
        bzr break-lock
4960.2.3 by Martin Pool
Better break-lock help
5290
        bzr break-lock bzr+ssh://example.com/bzr/foo
5345.5.9 by Vincent Ladeuil
Implements 'bzr lock --config <file>'.
5291
        bzr break-lock --conf ~/.bazaar
1553.5.34 by Martin Pool
Stub lock-breaking command
5292
    """
5345.5.9 by Vincent Ladeuil
Implements 'bzr lock --config <file>'.
5293
1687.1.12 by Robert Collins
Hook in the full break-lock ui.
5294
    takes_args = ['location?']
5345.5.9 by Vincent Ladeuil
Implements 'bzr lock --config <file>'.
5295
    takes_options = [
5296
        Option('config',
5297
               help='LOCATION is the directory where the config lock is.'),
5416.2.1 by Martin Pool
Add 'break-lock --force'
5298
        Option('force',
5299
            help='Do not ask for confirmation before breaking the lock.'),
5345.5.9 by Vincent Ladeuil
Implements 'bzr lock --config <file>'.
5300
        ]
1687.1.12 by Robert Collins
Hook in the full break-lock ui.
5301
5416.2.1 by Martin Pool
Add 'break-lock --force'
5302
    def run(self, location=None, config=False, force=False):
1687.1.12 by Robert Collins
Hook in the full break-lock ui.
5303
        if location is None:
5304
            location = u'.'
5416.2.1 by Martin Pool
Add 'break-lock --force'
5305
        if force:
5306
            ui.ui_factory = ui.ConfirmationUserInterfacePolicy(ui.ui_factory,
5307
                None,
5308
                {'bzrlib.lockdir.break': True})
5345.5.9 by Vincent Ladeuil
Implements 'bzr lock --config <file>'.
5309
        if config:
5310
            conf = _mod_config.LockableConfig(file_name=location)
5311
            conf.break_lock()
5312
        else:
6207.3.3 by jelmer at samba
Fix tests and the like.
5313
            control, relpath = controldir.ControlDir.open_containing(location)
5345.5.9 by Vincent Ladeuil
Implements 'bzr lock --config <file>'.
5314
            try:
5315
                control.break_lock()
5316
            except NotImplementedError:
5317
                pass
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
5318
1553.5.35 by Martin Pool
Start break-lock --show
5319
1910.17.2 by Andrew Bennetts
Add start_bzr_subprocess and stop_bzr_subprocess to allow test code to continue
5320
class cmd_wait_until_signalled(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
5321
    __doc__ = """Test helper for test_start_and_stop_bzr_subprocess_send_signal.
1910.17.2 by Andrew Bennetts
Add start_bzr_subprocess and stop_bzr_subprocess to allow test code to continue
5322
5323
    This just prints a line to signal when it is ready, then blocks on stdin.
5324
    """
5325
5326
    hidden = True
5327
5328
    def run(self):
1910.17.6 by Andrew Bennetts
Use sys.stdout consistently, rather than mixed with print.
5329
        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
5330
        sys.stdout.flush()
5331
        sys.stdin.readline()
5332
1553.5.35 by Martin Pool
Start break-lock --show
5333
1910.19.1 by Andrew Bennetts
Support bzr:// urls to work with the new RPC-based transport which will be used
5334
class cmd_serve(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
5335
    __doc__ = """Run the bzr server."""
2020.1.1 by Robert Collins
Add readonly support to the smart server, enabled by default via `bzr server`.
5336
5337
    aliases = ['server']
5338
1910.19.1 by Andrew Bennetts
Support bzr:// urls to work with the new RPC-based transport which will be used
5339
    takes_options = [
5340
        Option('inet',
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
5341
               help='Serve on stdin/out for use from inetd or sshd.'),
4822.1.1 by Robert Collins
Be more clean in the help for bzr serve about the --allow-writes option.
5342
        RegistryOption('protocol',
5343
               help="Protocol to serve.",
4370.4.6 by Jelmer Vernooij
Move server protocol registry to bzrlib.transport.
5344
               lazy_registry=('bzrlib.transport', 'transport_server_registry'),
4370.4.1 by Jelmer Vernooij
Add registry for 'bzr serve' protocols.
5345
               value_switches=True),
1910.19.1 by Andrew Bennetts
Support bzr:// urls to work with the new RPC-based transport which will be used
5346
        Option('port',
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
5347
               help='Listen for connections on nominated port of the form '
5348
                    '[hostname:]portnumber.  Passing 0 as the port number will '
4370.4.1 by Jelmer Vernooij
Add registry for 'bzr serve' protocols.
5349
                    'result in a dynamically allocated port.  The default port '
5350
                    'depends on the protocol.',
1910.19.7 by Andrew Bennetts
Allow specifying the host/interface to bzr serve, and use the new test
5351
               type=str),
5171.3.1 by Martin von Gagern
Turn --directory and -d into a global option.
5352
        custom_help('directory',
5353
               help='Serve contents of this directory.'),
2020.1.1 by Robert Collins
Add readonly support to the smart server, enabled by default via `bzr server`.
5354
        Option('allow-writes',
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
5355
               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`.
5356
                    '--allow-writes enables write access to the contents of '
4822.1.1 by Robert Collins
Be more clean in the help for bzr serve about the --allow-writes option.
5357
                    'the served directory and below.  Note that ``bzr serve`` '
5358
                    'does not perform authentication, so unless some form of '
5359
                    'external authentication is arranged supplying this '
5360
                    'option leads to global uncontrolled write access to your '
5361
                    'file system.'
2020.1.1 by Robert Collins
Add readonly support to the smart server, enabled by default via `bzr server`.
5362
                ),
6133.4.29 by John Arbash Meinel
Expose --client-timeout to the command line, pass it through the layers.
5363
        Option('client-timeout', type=float,
5364
               help='Override the default idle client timeout (5min).'),
1910.19.1 by Andrew Bennetts
Support bzr:// urls to work with the new RPC-based transport which will be used
5365
        ]
5366
3955.1.4 by Jonathan Lange
Docstrings and extraction of method to get the smart server.
5367
    def get_host_and_port(self, port):
5368
        """Return the host and port to run the smart server on.
5369
4370.4.3 by Jelmer Vernooij
Move host/port parsing to early in bzr-serve.
5370
        If 'port' is None, None will be returned for the host and port.
3955.1.4 by Jonathan Lange
Docstrings and extraction of method to get the smart server.
5371
5372
        If 'port' has a colon in it, the string before the colon will be
5373
        interpreted as the host.
5374
5375
        :param port: A string of the port to run the server on.
5376
        :return: A tuple of (host, port), where 'host' is a host name or IP,
5377
            and port is an integer TCP/IP port.
5378
        """
4370.4.3 by Jelmer Vernooij
Move host/port parsing to early in bzr-serve.
5379
        host = None
4370.4.7 by Jelmer Vernooij
Review feedback from Ian.
5380
        if port is not None:
3955.1.2 by Jonathan Lange
Extract the port-getting logic. Use note() rather than print()
5381
            if ':' in port:
5382
                host, port = port.split(':')
5383
            port = int(port)
5384
        return host, port
5385
4370.4.1 by Jelmer Vernooij
Add registry for 'bzr serve' protocols.
5386
    def run(self, port=None, inet=False, directory=None, allow_writes=False,
6133.4.29 by John Arbash Meinel
Expose --client-timeout to the command line, pass it through the layers.
5387
            protocol=None, client_timeout=None):
5273.1.7 by Vincent Ladeuil
No more use of the get_transport imported *symbol*, all uses are through
5388
        from bzrlib import transport
4370.4.1 by Jelmer Vernooij
Add registry for 'bzr serve' protocols.
5389
        if directory is None:
5390
            directory = os.getcwd()
5391
        if protocol is None:
5273.1.7 by Vincent Ladeuil
No more use of the get_transport imported *symbol*, all uses are through
5392
            protocol = transport.transport_server_registry.get()
4370.4.3 by Jelmer Vernooij
Move host/port parsing to early in bzr-serve.
5393
        host, port = self.get_host_and_port(port)
6236.1.1 by Jelmer Vernooij
bzr serve can now serve remote URLs and things behind directory services.
5394
        url = transport.location_to_url(directory)
4370.4.4 by Jelmer Vernooij
Move more bzr smart server-specific stuff into a single function.
5395
        if not allow_writes:
5396
            url = 'readonly+' + url
6236.1.1 by Jelmer Vernooij
bzr serve can now serve remote URLs and things behind directory services.
5397
        t = transport.get_transport_from_url(url)
6133.4.29 by John Arbash Meinel
Expose --client-timeout to the command line, pass it through the layers.
5398
        try:
5399
            protocol(t, host, port, inet, client_timeout)
6133.4.30 by John Arbash Meinel
Give a warning if we have to invoke the compatibility code.
5400
        except TypeError, e:
6133.4.31 by John Arbash Meinel
Turn it into a DeprecationWarning.
5401
            # We use symbol_versioning.deprecated_in just so that people
5402
            # grepping can find it here.
5403
            # symbol_versioning.deprecated_in((2, 5, 0))
5404
            symbol_versioning.warn(
5405
                'Got TypeError(%s)\ntrying to call protocol: %s.%s\n'
5406
                'Most likely it needs to be updated to support a'
5407
                ' "timeout" parameter (added in bzr 2.5.0)'
5408
                % (e, protocol.__module__, protocol),
5409
                DeprecationWarning)
6133.4.29 by John Arbash Meinel
Expose --client-timeout to the command line, pass it through the layers.
5410
            protocol(t, host, port, inet)
4370.4.1 by Jelmer Vernooij
Add registry for 'bzr serve' protocols.
5411
3955.1.2 by Jonathan Lange
Extract the port-getting logic. Use note() rather than print()
5412
1731.2.7 by Aaron Bentley
Add join command
5413
class cmd_join(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
5414
    __doc__ = """Combine a tree into its containing tree.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
5415
4251.1.2 by Aaron Bentley
Hide the --reference option.
5416
    This command requires the target tree to be in a rich-root format.
2338.3.1 by Aaron Bentley
Hide nested-tree commands and improve their docs
5417
5418
    The TREE argument should be an independent tree, inside another tree, but
5419
    not part of it.  (Such trees can be produced by "bzr split", but also by
5420
    running "bzr branch" with the target inside a tree.)
5421
5432.1.1 by John C Barstow
Correct spelling of 'independent'
5422
    The result is a combined tree, with the subtree no longer an independent
2338.3.1 by Aaron Bentley
Hide nested-tree commands and improve their docs
5423
    part.  This is marked as a merge of the subtree into the containing tree,
5424
    and all history is preserved.
1731.2.7 by Aaron Bentley
Add join command
5425
    """
5426
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
5427
    _see_also = ['split']
1731.2.7 by Aaron Bentley
Add join command
5428
    takes_args = ['tree']
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
5429
    takes_options = [
4251.1.2 by Aaron Bentley
Hide the --reference option.
5430
            Option('reference', help='Join by reference.', hidden=True),
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
5431
            ]
1731.2.7 by Aaron Bentley
Add join command
5432
2100.3.11 by Aaron Bentley
Add join --reference support
5433
    def run(self, tree, reference=False):
1731.2.7 by Aaron Bentley
Add join command
5434
        sub_tree = WorkingTree.open(tree)
5435
        parent_dir = osutils.dirname(sub_tree.basedir)
5436
        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
5437
        repo = containing_tree.branch.repository
5438
        if not repo.supports_rich_root():
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
5439
            raise errors.BzrCommandError(gettext(
2255.2.235 by Martin Pool
Add blackbox test that join gives clean error when the repository doesn't support rich roots
5440
                "Can't join trees because %s doesn't support rich root data.\n"
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
5441
                "You can use bzr upgrade on the repository.")
2255.2.235 by Martin Pool
Add blackbox test that join gives clean error when the repository doesn't support rich roots
5442
                % (repo,))
2100.3.11 by Aaron Bentley
Add join --reference support
5443
        if reference:
2255.2.219 by Martin Pool
fix unbound local error in cmd_join
5444
            try:
2100.3.11 by Aaron Bentley
Add join --reference support
5445
                containing_tree.add_reference(sub_tree)
2255.2.219 by Martin Pool
fix unbound local error in cmd_join
5446
            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
5447
                # XXX: Would be better to just raise a nicely printable
5448
                # exception from the real origin.  Also below.  mbp 20070306
6138.2.4 by Jonathan Riddell
use format strings where there are multiple substitutions to allow for translations
5449
                raise errors.BzrCommandError(
5450
                       gettext("Cannot join {0}.  {1}").format(tree, e.reason))
2100.3.11 by Aaron Bentley
Add join --reference support
5451
        else:
5452
            try:
5453
                containing_tree.subsume(sub_tree)
5454
            except errors.BadSubsumeSource, e:
6138.2.4 by Jonathan Riddell
use format strings where there are multiple substitutions to allow for translations
5455
                raise errors.BzrCommandError(
5456
                       gettext("Cannot join {0}.  {1}").format(tree, e.reason))
1553.5.35 by Martin Pool
Start break-lock --show
5457
1731.2.22 by Aaron Bentley
Initial work on split command
5458
5459
class cmd_split(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
5460
    __doc__ = """Split a subdirectory of a tree into a separate tree.
2338.3.1 by Aaron Bentley
Hide nested-tree commands and improve their docs
5461
3113.6.2 by Aaron Bentley
Un-hide split command, add NEWS
5462
    This command will produce a target tree in a format that supports
5463
    rich roots, like 'rich-root' or 'rich-root-pack'.  These formats cannot be
5464
    converted into earlier formats like 'dirstate-tags'.
2338.3.1 by Aaron Bentley
Hide nested-tree commands and improve their docs
5465
5466
    The TREE argument should be a subdirectory of a working tree.  That
5467
    subdirectory will be converted into an independent tree, with its own
5468
    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
5469
    """
5470
4251.1.4 by Aaron Bentley
Uncomment split's 'See also:join'
5471
    _see_also = ['join']
1731.2.22 by Aaron Bentley
Initial work on split command
5472
    takes_args = ['tree']
5473
5474
    def run(self, tree):
5475
        containing_tree, subdir = WorkingTree.open_containing(tree)
5476
        sub_id = containing_tree.path2id(subdir)
5477
        if sub_id is None:
5478
            raise errors.NotVersionedError(subdir)
1731.2.23 by Aaron Bentley
Throw user-friendly error splitting in shared repo with wrong format
5479
        try:
5480
            containing_tree.extract(sub_id)
5481
        except errors.RootNotRich:
4416.6.1 by Neil Martinsen-Burrell
Fix #220067 adding more specificity to the error message when split fails
5482
            raise errors.RichRootUpgradeRequired(containing_tree.branch.base)
1731.2.22 by Aaron Bentley
Initial work on split command
5483
5484
1551.12.8 by Aaron Bentley
Add merge-directive command
5485
class cmd_merge_directive(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
5486
    __doc__ = """Generate a merge directive for auto-merge tools.
1551.12.32 by Aaron Bentley
Improve merge directive help
5487
5488
    A directive requests a merge to be performed, and also provides all the
5489
    information necessary to do so.  This means it must either include a
5490
    revision bundle, or the location of a branch containing the desired
5491
    revision.
5492
5493
    A submit branch (the location to merge into) must be supplied the first
5494
    time the command is issued.  After it has been supplied once, it will
5495
    be remembered as the default.
5496
5497
    A public branch is optional if a revision bundle is supplied, but required
5498
    if --diff or --plain is specified.  It will be remembered as the default
5499
    after the first use.
5500
    """
1551.12.20 by Aaron Bentley
Pull directive registry into command class
5501
1551.12.14 by Aaron Bentley
Get merge-directive command basically working
5502
    takes_args = ['submit_branch?', 'public_branch?']
5503
2520.5.4 by Aaron Bentley
Replace 'bundle-revisions' with 'submit' command
5504
    hidden = True
5505
2681.1.4 by Aaron Bentley
Fix reference to told submit command
5506
    _see_also = ['send']
2520.4.121 by Aaron Bentley
Polish up submit command
5507
1551.12.43 by Aaron Bentley
Misc changes from review
5508
    takes_options = [
5171.3.13 by Martin von Gagern
Add --directory option to 7 more commands.
5509
        'directory',
1551.12.43 by Aaron Bentley
Misc changes from review
5510
        RegistryOption.from_kwargs('patch-type',
2681.1.7 by Aaron Bentley
Fix option grammar
5511
            '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
5512
            title='Patch type',
5513
            value_switches=True,
5514
            enum_switch=False,
5515
            bundle='Bazaar revision bundle (default).',
5516
            diff='Normal unified diff.',
5517
            plain='No patch, just directive.'),
5518
        Option('sign', help='GPG-sign the directive.'), 'revision',
1551.12.26 by Aaron Bentley
Get email working, with optional message
5519
        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
5520
            help='Instead of printing the directive, email to this address.'),
1551.12.27 by Aaron Bentley
support custom message everywhere
5521
        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
5522
            help='Message to use when committing this merge.')
1551.12.27 by Aaron Bentley
support custom message everywhere
5523
        ]
1551.12.14 by Aaron Bentley
Get merge-directive command basically working
5524
2530.2.1 by Adeodato Simó
Add encoding_type = 'exact' to cmd_merge_directive. (LP #120591)
5525
    encoding_type = 'exact'
5526
1551.12.16 by Aaron Bentley
Enable signing merge directives
5527
    def run(self, submit_branch=None, public_branch=None, patch_type='bundle',
5171.3.13 by Martin von Gagern
Add --directory option to 7 more commands.
5528
            sign=False, revision=None, mail_to=None, message=None,
5529
            directory=u'.'):
2490.2.28 by Aaron Bentley
Fix handling of null revision
5530
        from bzrlib.revision import ensure_null, NULL_REVISION
2520.5.4 by Aaron Bentley
Replace 'bundle-revisions' with 'submit' command
5531
        include_patch, include_bundle = {
5532
            'plain': (False, False),
5533
            'diff': (True, False),
5534
            'bundle': (True, True),
5535
            }[patch_type]
5171.3.13 by Martin von Gagern
Add --directory option to 7 more commands.
5536
        branch = Branch.open(directory)
1551.12.44 by Aaron Bentley
Add (set|get)_public_branch
5537
        stored_submit_branch = branch.get_submit_branch()
1551.12.14 by Aaron Bentley
Get merge-directive command basically working
5538
        if submit_branch is None:
1551.12.44 by Aaron Bentley
Add (set|get)_public_branch
5539
            submit_branch = stored_submit_branch
1551.12.14 by Aaron Bentley
Get merge-directive command basically working
5540
        else:
1551.12.44 by Aaron Bentley
Add (set|get)_public_branch
5541
            if stored_submit_branch is None:
1551.12.14 by Aaron Bentley
Get merge-directive command basically working
5542
                branch.set_submit_branch(submit_branch)
5543
        if submit_branch is None:
5544
            submit_branch = branch.get_parent()
5545
        if submit_branch is None:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
5546
            raise errors.BzrCommandError(gettext('No submit branch specified or known'))
1551.12.44 by Aaron Bentley
Add (set|get)_public_branch
5547
5548
        stored_public_branch = branch.get_public_branch()
1551.12.14 by Aaron Bentley
Get merge-directive command basically working
5549
        if public_branch is None:
1551.12.44 by Aaron Bentley
Add (set|get)_public_branch
5550
            public_branch = stored_public_branch
5551
        elif stored_public_branch is None:
5552
            branch.set_public_branch(public_branch)
2520.5.4 by Aaron Bentley
Replace 'bundle-revisions' with 'submit' command
5553
        if not include_bundle and public_branch is None:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
5554
            raise errors.BzrCommandError(gettext('No public branch specified or'
5555
                                         ' known'))
2520.4.112 by Aaron Bentley
Make cherry-pick merge directives possible
5556
        base_revision_id = None
1551.12.17 by Aaron Bentley
add revision selection to mergedirective
5557
        if revision is not None:
2520.4.112 by Aaron Bentley
Make cherry-pick merge directives possible
5558
            if len(revision) > 2:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
5559
                raise errors.BzrCommandError(gettext('bzr merge-directive takes '
5560
                    '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()
5561
            revision_id = revision[-1].as_revision_id(branch)
2520.4.112 by Aaron Bentley
Make cherry-pick merge directives possible
5562
            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()
5563
                base_revision_id = revision[0].as_revision_id(branch)
1551.12.17 by Aaron Bentley
add revision selection to mergedirective
5564
        else:
5565
            revision_id = branch.last_revision()
2490.2.28 by Aaron Bentley
Fix handling of null revision
5566
        revision_id = ensure_null(revision_id)
5567
        if revision_id == NULL_REVISION:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
5568
            raise errors.BzrCommandError(gettext('No revisions to bundle.'))
2520.4.73 by Aaron Bentley
Implement new merge directive format
5569
        directive = merge_directive.MergeDirective2.from_objects(
1551.12.17 by Aaron Bentley
add revision selection to mergedirective
5570
            branch.repository, revision_id, time.time(),
1551.12.8 by Aaron Bentley
Add merge-directive command
5571
            osutils.local_time_offset(), submit_branch,
2520.5.4 by Aaron Bentley
Replace 'bundle-revisions' with 'submit' command
5572
            public_branch=public_branch, include_patch=include_patch,
5573
            include_bundle=include_bundle, message=message,
5574
            base_revision_id=base_revision_id)
1551.12.26 by Aaron Bentley
Get email working, with optional message
5575
        if mail_to is None:
5576
            if sign:
5577
                self.outf.write(directive.to_signed(branch))
5578
            else:
5579
                self.outf.writelines(directive.to_lines())
1551.12.16 by Aaron Bentley
Enable signing merge directives
5580
        else:
1551.12.26 by Aaron Bentley
Get email working, with optional message
5581
            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.
5582
            s = SMTPConnection(branch.get_config())
5583
            s.send_email(message)
1551.12.8 by Aaron Bentley
Add merge-directive command
5584
1551.12.14 by Aaron Bentley
Get merge-directive command basically working
5585
4367.1.3 by Jelmer Vernooij
Move cmd_{send,bundle_revisions} back to bzrlib.builtins per Ians request.
5586
class cmd_send(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
5587
    __doc__ = """Mail or create a merge-directive for submitting changes.
4367.1.3 by Jelmer Vernooij
Move cmd_{send,bundle_revisions} back to bzrlib.builtins per Ians request.
5588
5589
    A merge directive provides many things needed for requesting merges:
5590
5591
    * A machine-readable description of the merge to perform
5592
5593
    * An optional patch that is a preview of the changes requested
5594
5595
    * An optional bundle of revision data, so that the changes can be applied
5596
      directly from the merge directive, without retrieving data from a
5597
      branch.
5598
4949.2.1 by Martin Pool
Better help for cmd_send
5599
    `bzr send` creates a compact data set that, when applied using bzr
5600
    merge, has the same effect as merging from the source branch.  
5601
    
5602
    By default the merge directive is self-contained and can be applied to any
5603
    branch containing submit_branch in its ancestory without needing access to
5604
    the source branch.
5605
    
5606
    If --no-bundle is specified, then Bazaar doesn't send the contents of the
5607
    revisions, but only a structured request to merge from the
5608
    public_location.  In that case the public_branch is needed and it must be
5609
    up-to-date and accessible to the recipient.  The public_branch is always
5610
    included if known, so that people can check it later.
5611
5612
    The submit branch defaults to the parent of the source branch, but can be
5613
    overridden.  Both submit branch and public branch will be remembered in
5614
    branch.conf the first time they are used for a particular branch.  The
5615
    source branch defaults to that containing the working directory, but can
5616
    be changed using --from.
5617
5861.1.3 by Vincent Ladeuil
Fix the docs for push/pull/send regarding --no-remember.
5618
    Both the submit branch and the public branch follow the usual behavior with
5619
    respect to --remember: If there is no default location set, the first send
6105.2.4 by Martin von Gagern
Drive-by typo correction in command docstrings.
5620
    will set it (use --no-remember to avoid setting it). After that, you can
5861.1.3 by Vincent Ladeuil
Fix the docs for push/pull/send regarding --no-remember.
5621
    omit the location to use the default.  To change the default, use
5622
    --remember. The value will only be saved if the location can be accessed.
5623
4949.2.1 by Martin Pool
Better help for cmd_send
5624
    In order to calculate those changes, bzr must analyse the submit branch.
5625
    Therefore it is most efficient for the submit branch to be a local mirror.
5626
    If a public location is known for the submit_branch, that location is used
5627
    in the merge directive.
5628
5629
    The default behaviour is to send the merge directive by mail, unless -o is
5630
    given, in which case it is sent to a file.
4367.1.3 by Jelmer Vernooij
Move cmd_{send,bundle_revisions} back to bzrlib.builtins per Ians request.
5631
5632
    Mail is sent using your preferred mail program.  This should be transparent
5278.1.2 by Martin Pool
Don't say 'Linux' except when specifically talking about the kernel
5633
    on Windows (it uses MAPI).  On Unix, it requires the xdg-email utility.
4367.1.3 by Jelmer Vernooij
Move cmd_{send,bundle_revisions} back to bzrlib.builtins per Ians request.
5634
    If the preferred client can't be found (or used), your editor will be used.
5635
5636
    To use a specific mail program, set the mail_client configuration option.
5637
    (For Thunderbird 1.5, this works around some bugs.)  Supported values for
4715.3.1 by Brian de Alwis
Introduce new mailer to support MacOS X's Mail.app
5638
    specific clients are "claws", "evolution", "kmail", "mail.app" (MacOS X's
5639
    Mail.app), "mutt", and "thunderbird"; generic options are "default",
5640
    "editor", "emacsclient", "mapi", and "xdg-email".  Plugins may also add
5641
    supported clients.
4367.1.3 by Jelmer Vernooij
Move cmd_{send,bundle_revisions} back to bzrlib.builtins per Ians request.
5642
5643
    If mail is being sent, a to address is required.  This can be supplied
5644
    either on the commandline, by setting the submit_to configuration
5645
    option in the branch itself or the child_submit_to configuration option
5646
    in the submit branch.
5647
5648
    Two formats are currently supported: "4" uses revision bundle format 4 and
5649
    merge directive format 2.  It is significantly faster and smaller than
5650
    older formats.  It is compatible with Bazaar 0.19 and later.  It is the
5651
    default.  "0.9" uses revision bundle format 0.9 and merge directive
5652
    format 1.  It is compatible with Bazaar 0.12 - 0.18.
5653
5654
    The merge directives created by bzr send may be applied using bzr merge or
5655
    bzr pull by specifying a file containing a merge directive as the location.
4949.2.1 by Martin Pool
Better help for cmd_send
5656
5657
    bzr send makes extensive use of public locations to map local locations into
5658
    URLs that can be used by other people.  See `bzr help configuration` to
5659
    set them, and use `bzr info` to display them.
4367.1.3 by Jelmer Vernooij
Move cmd_{send,bundle_revisions} back to bzrlib.builtins per Ians request.
5660
    """
5661
5662
    encoding_type = 'exact'
5663
5664
    _see_also = ['merge', 'pull']
5665
5666
    takes_args = ['submit_branch?', 'public_branch?']
5667
5668
    takes_options = [
5669
        Option('no-bundle',
5670
               help='Do not include a bundle in the merge directive.'),
5671
        Option('no-patch', help='Do not include a preview patch in the merge'
5672
               ' directive.'),
5673
        Option('remember',
5674
               help='Remember submit and public branch.'),
5675
        Option('from',
5676
               help='Branch to generate the submission from, '
5677
               'rather than the one containing the working directory.',
5678
               short_name='f',
5679
               type=unicode),
5680
        Option('output', short_name='o',
5086.3.3 by Jelmer Vernooij
Allow merge directives to output multiple patch files.
5681
               help='Write merge directive to this file or directory; '
4367.1.3 by Jelmer Vernooij
Move cmd_{send,bundle_revisions} back to bzrlib.builtins per Ians request.
5682
                    'use - for stdout.',
5683
               type=unicode),
4464.3.4 by Vincent Ladeuil
Fix bug #206577 by adding a --strict option to send.
5684
        Option('strict',
5685
               help='Refuse to send if there are uncommitted changes in'
4464.3.11 by Vincent Ladeuil
Add a check for tree/branch sync and tweak help.
5686
               ' the working tree, --no-strict disables the check.'),
4367.1.3 by Jelmer Vernooij
Move cmd_{send,bundle_revisions} back to bzrlib.builtins per Ians request.
5687
        Option('mail-to', help='Mail the request to this address.',
5688
               type=unicode),
5689
        'revision',
5690
        'message',
5691
        Option('body', help='Body for the email.', type=unicode),
5692
        RegistryOption('format',
4464.3.4 by Vincent Ladeuil
Fix bug #206577 by adding a --strict option to send.
5693
                       help='Use the specified output format.',
5694
                       lazy_registry=('bzrlib.send', 'format_registry')),
4367.1.3 by Jelmer Vernooij
Move cmd_{send,bundle_revisions} back to bzrlib.builtins per Ians request.
5695
        ]
5696
5697
    def run(self, submit_branch=None, public_branch=None, no_bundle=False,
5861.1.4 by Vincent Ladeuil
Fix send --no-remember when no location is set.
5698
            no_patch=False, revision=None, remember=None, output=None,
4464.3.4 by Vincent Ladeuil
Fix bug #206577 by adding a --strict option to send.
5699
            format=None, mail_to=None, message=None, body=None,
5700
            strict=None, **kwargs):
4367.1.3 by Jelmer Vernooij
Move cmd_{send,bundle_revisions} back to bzrlib.builtins per Ians request.
5701
        from bzrlib.send import send
5702
        return send(submit_branch, revision, public_branch, remember,
4464.3.4 by Vincent Ladeuil
Fix bug #206577 by adding a --strict option to send.
5703
                    format, no_bundle, no_patch, output,
5704
                    kwargs.get('from', '.'), mail_to, message, body,
5705
                    self.outf,
5706
                    strict=strict)
4367.1.3 by Jelmer Vernooij
Move cmd_{send,bundle_revisions} back to bzrlib.builtins per Ians request.
5707
5708
4367.1.6 by Jelmer Vernooij
Fix bundle revisions.
5709
class cmd_bundle_revisions(cmd_send):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
5710
    __doc__ = """Create a merge-directive for submitting changes.
4367.1.3 by Jelmer Vernooij
Move cmd_{send,bundle_revisions} back to bzrlib.builtins per Ians request.
5711
5712
    A merge directive provides many things needed for requesting merges:
5713
5714
    * A machine-readable description of the merge to perform
5715
5716
    * An optional patch that is a preview of the changes requested
5717
5718
    * An optional bundle of revision data, so that the changes can be applied
5719
      directly from the merge directive, without retrieving data from a
5720
      branch.
5721
5722
    If --no-bundle is specified, then public_branch is needed (and must be
5723
    up-to-date), so that the receiver can perform the merge using the
5724
    public_branch.  The public_branch is always included if known, so that
5725
    people can check it later.
5726
5727
    The submit branch defaults to the parent, but can be overridden.  Both
5728
    submit branch and public branch will be remembered if supplied.
5729
5730
    If a public_branch is known for the submit_branch, that public submit
5731
    branch is used in the merge instructions.  This means that a local mirror
5732
    can be used as your actual submit branch, once you have set public_branch
5733
    for that mirror.
5734
5735
    Two formats are currently supported: "4" uses revision bundle format 4 and
5736
    merge directive format 2.  It is significantly faster and smaller than
5737
    older formats.  It is compatible with Bazaar 0.19 and later.  It is the
5738
    default.  "0.9" uses revision bundle format 0.9 and merge directive
5739
    format 1.  It is compatible with Bazaar 0.12 - 0.18.
5740
    """
5741
5742
    takes_options = [
5743
        Option('no-bundle',
5744
               help='Do not include a bundle in the merge directive.'),
5745
        Option('no-patch', help='Do not include a preview patch in the merge'
5746
               ' directive.'),
5747
        Option('remember',
5748
               help='Remember submit and public branch.'),
5749
        Option('from',
5750
               help='Branch to generate the submission from, '
5751
               'rather than the one containing the working directory.',
5752
               short_name='f',
5753
               type=unicode),
5754
        Option('output', short_name='o', help='Write directive to this file.',
5755
               type=unicode),
4464.3.6 by Vincent Ladeuil
bundle-revisions should support --strict too.
5756
        Option('strict',
4464.3.11 by Vincent Ladeuil
Add a check for tree/branch sync and tweak help.
5757
               help='Refuse to bundle revisions if there are uncommitted'
5758
               ' changes in the working tree, --no-strict disables the check.'),
4367.1.3 by Jelmer Vernooij
Move cmd_{send,bundle_revisions} back to bzrlib.builtins per Ians request.
5759
        'revision',
5760
        RegistryOption('format',
5761
                       help='Use the specified output format.',
5762
                       lazy_registry=('bzrlib.send', 'format_registry')),
5763
        ]
5764
    aliases = ['bundle']
5765
5766
    _see_also = ['send', 'merge']
5767
5768
    hidden = True
5769
5770
    def run(self, submit_branch=None, public_branch=None, no_bundle=False,
5771
            no_patch=False, revision=None, remember=False, output=None,
4464.3.6 by Vincent Ladeuil
bundle-revisions should support --strict too.
5772
            format=None, strict=None, **kwargs):
4367.1.3 by Jelmer Vernooij
Move cmd_{send,bundle_revisions} back to bzrlib.builtins per Ians request.
5773
        if output is None:
5774
            output = '-'
5775
        from bzrlib.send import send
5776
        return send(submit_branch, revision, public_branch, remember,
5777
                         format, no_bundle, no_patch, output,
5778
                         kwargs.get('from', '.'), None, None, None,
4464.3.6 by Vincent Ladeuil
bundle-revisions should support --strict too.
5779
                         self.outf, strict=strict)
4367.1.3 by Jelmer Vernooij
Move cmd_{send,bundle_revisions} back to bzrlib.builtins per Ians request.
5780
5781
2220.2.2 by Martin Pool
Add tag command and basic implementation
5782
class cmd_tag(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
5783
    __doc__ = """Create, remove or modify a tag naming a revision.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
5784
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
5785
    Tags give human-meaningful names to revisions.  Commands that take a -r
5786
    (--revision) option can be given -rtag:X, where X is any previously
5787
    created tag.
5788
2220.2.41 by Martin Pool
Fix tag help (fullermd)
5789
    Tags are stored in the branch.  Tags are copied from one branch to another
5790
    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.
5791
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
5792
    It is an error to give a tag name that already exists unless you pass
2220.2.42 by Martin Pool
Tag command refuses to replace existing tags unless you force it.
5793
    --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
5794
3566.2.2 by Benjamin Peterson
fix markup
5795
    To rename a tag (change the name but keep it on the same revsion), run ``bzr
5796
    tag new-name -r tag:old-name`` and then ``bzr tag --delete oldname``.
5086.4.9 by Jelmer Vernooij
Update documentation.
5797
5798
    If no tag name is specified it will be determined through the 
5799
    'automatic_tag_name' hook. This can e.g. be used to automatically tag
5800
    upstream releases by reading configure.ac. See ``bzr help hooks`` for
5801
    details.
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
5802
    """
2220.2.2 by Martin Pool
Add tag command and basic implementation
5803
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
5804
    _see_also = ['commit', 'tags']
5086.4.2 by Jelmer Vernooij
Tag names can now be determined automatically by hooks if they are
5805
    takes_args = ['tag_name?']
2220.2.2 by Martin Pool
Add tag command and basic implementation
5806
    takes_options = [
2220.2.21 by Martin Pool
Add tag --delete command and implementation
5807
        Option('delete',
2220.2.42 by Martin Pool
Tag command refuses to replace existing tags unless you force it.
5808
            help='Delete this tag rather than placing it.',
5809
            ),
5171.3.1 by Martin von Gagern
Turn --directory and -d into a global option.
5810
        custom_help('directory',
5811
            help='Branch in which to place the tag.'),
2220.2.42 by Martin Pool
Tag command refuses to replace existing tags unless you force it.
5812
        Option('force',
2598.1.2 by Martin Pool
Also check that option help ends in a period, and fix those that don't
5813
            help='Replace existing tags.',
2220.2.21 by Martin Pool
Add tag --delete command and implementation
5814
            ),
2220.2.6 by Martin Pool
Add tag -r option
5815
        'revision',
2220.2.2 by Martin Pool
Add tag command and basic implementation
5816
        ]
5817
5086.4.2 by Jelmer Vernooij
Tag names can now be determined automatically by hooks if they are
5818
    def run(self, tag_name=None,
2220.2.42 by Martin Pool
Tag command refuses to replace existing tags unless you force it.
5819
            delete=None,
5820
            directory='.',
5821
            force=None,
2220.2.21 by Martin Pool
Add tag --delete command and implementation
5822
            revision=None,
2220.2.42 by Martin Pool
Tag command refuses to replace existing tags unless you force it.
5823
            ):
2220.2.2 by Martin Pool
Add tag command and basic implementation
5824
        branch, relpath = Branch.open_containing(directory)
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
5825
        self.add_cleanup(branch.lock_write().unlock)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
5826
        if delete:
5086.4.2 by Jelmer Vernooij
Tag names can now be determined automatically by hooks if they are
5827
            if tag_name is None:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
5828
                raise errors.BzrCommandError(gettext("No tag specified to delete."))
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
5829
            branch.tags.delete_tag(tag_name)
6138.2.2 by Jonathan Riddell
gettext builtin.py's note() usage
5830
            note(gettext('Deleted tag %s.') % tag_name)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
5831
        else:
5832
            if revision:
5833
                if len(revision) != 1:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
5834
                    raise errors.BzrCommandError(gettext(
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
5835
                        "Tags can only be placed on a single revision, "
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
5836
                        "not on a range"))
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
5837
                revision_id = revision[0].as_revision_id(branch)
2220.2.21 by Martin Pool
Add tag --delete command and implementation
5838
            else:
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
5839
                revision_id = branch.last_revision()
5086.4.2 by Jelmer Vernooij
Tag names can now be determined automatically by hooks if they are
5840
            if tag_name is None:
5086.4.7 by Jelmer Vernooij
Put automatic_tag_name on Branch.
5841
                tag_name = branch.automatic_tag_name(revision_id)
5086.4.2 by Jelmer Vernooij
Tag names can now be determined automatically by hooks if they are
5842
                if tag_name is None:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
5843
                    raise errors.BzrCommandError(gettext(
5844
                        "Please specify a tag name."))
6111.2.1 by Jelmer Vernooij
``bzr tag`` no longer errors if a tag already exists but refers to the
5845
            try:
5846
                existing_target = branch.tags.lookup_tag(tag_name)
5847
            except errors.NoSuchTag:
5848
                existing_target = None
5849
            if not force and existing_target not in (None, revision_id):
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
5850
                raise errors.TagAlreadyExists(tag_name)
6111.2.1 by Jelmer Vernooij
``bzr tag`` no longer errors if a tag already exists but refers to the
5851
            if existing_target == revision_id:
6138.2.2 by Jonathan Riddell
gettext builtin.py's note() usage
5852
                note(gettext('Tag %s already exists for that revision.') % tag_name)
6111.2.1 by Jelmer Vernooij
``bzr tag`` no longer errors if a tag already exists but refers to the
5853
            else:
6123.4.7 by Jelmer Vernooij
Remove unnecessary handling of GhostTagsNotSupported.
5854
                branch.tags.set_tag(tag_name, revision_id)
6123.5.1 by Jelmer Vernooij
Mention when a tag has been updated vs created.
5855
                if existing_target is None:
6138.2.2 by Jonathan Riddell
gettext builtin.py's note() usage
5856
                    note(gettext('Created tag %s.') % tag_name)
6123.5.1 by Jelmer Vernooij
Mention when a tag has been updated vs created.
5857
                else:
6138.2.2 by Jonathan Riddell
gettext builtin.py's note() usage
5858
                    note(gettext('Updated tag %s.') % tag_name)
2220.2.2 by Martin Pool
Add tag command and basic implementation
5859
5860
2220.2.24 by Martin Pool
Add tags command
5861
class cmd_tags(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
5862
    __doc__ = """List tags.
2220.2.24 by Martin Pool
Add tags command
5863
3007.1.1 by Adeodato Simó
Small fix to tags' help.
5864
    This command shows a table of tag names and the revisions they reference.
2220.2.24 by Martin Pool
Add tags command
5865
    """
5866
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
5867
    _see_also = ['tag']
2220.2.24 by Martin Pool
Add tags command
5868
    takes_options = [
5171.3.1 by Martin von Gagern
Turn --directory and -d into a global option.
5869
        custom_help('directory',
5870
            help='Branch whose tags should be displayed.'),
5582.2.1 by Jelmer Vernooij
support extending --sort argument to 'bzr tags'.
5871
        RegistryOption('sort',
2805.8.6 by Adeodato Simó
Don't sort by revno; only by time if --sort=time is passed.
5872
            'Sort tags by different criteria.', title='Sorting',
5582.2.1 by Jelmer Vernooij
support extending --sort argument to 'bzr tags'.
5873
            lazy_registry=('bzrlib.tag', 'tag_sort_methods')
2805.8.6 by Adeodato Simó
Don't sort by revno; only by time if --sort=time is passed.
5874
            ),
2805.8.3 by Adeodato Simó
Show dotted revnos, and revids only with --show-ids.
5875
        '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.
5876
        'revision',
2220.2.24 by Martin Pool
Add tags command
5877
    ]
5878
5879
    @display_command
5582.2.1 by Jelmer Vernooij
support extending --sort argument to 'bzr tags'.
5880
    def run(self, directory='.', sort=None, show_ids=False, revision=None):
5881
        from bzrlib.tag import tag_sort_methods
2220.2.24 by Martin Pool
Add tags command
5882
        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.
5883
2805.8.6 by Adeodato Simó
Don't sort by revno; only by time if --sort=time is passed.
5884
        tags = branch.tags.get_tag_dict().items()
3553.1.1 by Robert Collins
Do not scan history for tags when none are present.
5885
        if not tags:
5886
            return
3904.2.1 by Marius Kruger
* factor out _get2Revisions from cmd_log to be able to reuse how revesions is determined by log.
5887
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
5888
        self.add_cleanup(branch.lock_read().unlock)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
5889
        if revision:
6162.1.3 by Vincent Ladeuil
Add a separate method to determines the tags for the reivision range.
5890
            # Restrict to the specified range
5891
            tags = self._tags_for_range(branch, revision)
5582.2.1 by Jelmer Vernooij
support extending --sort argument to 'bzr tags'.
5892
        if sort is None:
5893
            sort = tag_sort_methods.get()
5894
        sort(branch, tags)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
5895
        if not show_ids:
5896
            # [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
5897
            for index, (tag, revid) in enumerate(tags):
5898
                try:
5899
                    revno = branch.revision_id_to_dotted_revno(revid)
5900
                    if isinstance(revno, tuple):
5901
                        revno = '.'.join(map(str, revno))
6162.1.1 by Vincent Ladeuil
Stop reloading all ancestry for each tag when searching tags in a revision range (still breaks if X>Y in -rX..Y)
5902
                except (errors.NoSuchRevision,
6165.3.1 by Jelmer Vernooij
Support running 'bzr tags' against remote repositories without revision graph access.
5903
                        errors.GhostRevisionsHaveNoRevno,
5904
                        errors.UnsupportedOperation):
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
5905
                    # Bad tag data/merges can lead to tagged revisions
5906
                    # which are not in this branch. Fail gracefully ...
5907
                    revno = '?'
5908
                tags[index] = (tag, revno)
5909
        self.cleanup_now()
2805.8.6 by Adeodato Simó
Don't sort by revno; only by time if --sort=time is passed.
5910
        for tag, revspec in tags:
5911
            self.outf.write('%-20s %s\n' % (tag, revspec))
2220.2.24 by Martin Pool
Add tags command
5912
6162.1.3 by Vincent Ladeuil
Add a separate method to determines the tags for the reivision range.
5913
    def _tags_for_range(self, branch, revision):
5914
        range_valid = True
5915
        rev1, rev2 = _get_revision_range(revision, branch, self.name())
5916
        revid1, revid2 = rev1.rev_id, rev2.rev_id
5917
        # _get_revision_range will always set revid2 if it's not specified.
5918
        # If revid1 is None, it means we want to start from the branch
5919
        # origin which is always a valid ancestor. If revid1 == revid2, the
5920
        # ancestry check is useless.
5921
        if revid1 and revid1 != revid2:
5922
            # FIXME: We really want to use the same graph than
5923
            # branch.iter_merge_sorted_revisions below, but this is not
5924
            # easily available -- vila 2011-09-23
5925
            if branch.repository.get_graph().is_ancestor(revid2, revid1):
5926
                # We don't want to output anything in this case...
5927
                return []
5928
        # only show revisions between revid1 and revid2 (inclusive)
5929
        tagged_revids = branch.tags.get_reverse_tag_dict()
5930
        found = []
5931
        for r in branch.iter_merge_sorted_revisions(
5932
            start_revision_id=revid2, stop_revision_id=revid1,
5933
            stop_rule='include'):
5934
            revid_tags = tagged_revids.get(r[0], None)
5935
            if revid_tags:
5936
                found.extend([(tag, r[0]) for tag in revid_tags])
5937
        return found
5938
2220.2.24 by Martin Pool
Add tags command
5939
2796.2.5 by Aaron Bentley
Implement reconfigure command
5940
class cmd_reconfigure(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
5941
    __doc__ = """Reconfigure the type of a bzr directory.
2796.2.15 by Aaron Bentley
More updates from review
5942
5943
    A target configuration must be specified.
5944
5945
    For checkouts, the bind-to location will be auto-detected if not specified.
5946
    The order of preference is
5947
    1. For a lightweight checkout, the current bound location.
5948
    2. For branches that used to be checkouts, the previously-bound location.
5949
    3. The push location.
5950
    4. The parent location.
5951
    If none of these is available, --bind-to must be specified.
5952
    """
2796.2.5 by Aaron Bentley
Implement reconfigure command
5953
3535.4.1 by Marius Kruger
Update reconfigure help to say exactly what it wil do.
5954
    _see_also = ['branches', 'checkouts', 'standalone-trees', 'working-trees']
2796.2.5 by Aaron Bentley
Implement reconfigure command
5955
    takes_args = ['location?']
3983.3.11 by Vincent Ladeuil
Fix indentation as per Aaron's review and then some.
5956
    takes_options = [
5957
        RegistryOption.from_kwargs(
6123.8.2 by Martin von Gagern
Make the various aspects of reconfigure independent from one another.
5958
            'tree_type',
5959
            title='Tree type',
5960
            help='The relation between branch and tree.',
3983.3.11 by Vincent Ladeuil
Fix indentation as per Aaron's review and then some.
5961
            value_switches=True, enum_switch=False,
5962
            branch='Reconfigure to be an unbound branch with no working tree.',
5963
            tree='Reconfigure to be an unbound branch with a working tree.',
5964
            checkout='Reconfigure to be a bound branch with a working tree.',
5965
            lightweight_checkout='Reconfigure to be a lightweight'
5966
                ' checkout (with no local history).',
6123.8.2 by Martin von Gagern
Make the various aspects of reconfigure independent from one another.
5967
            ),
5968
        RegistryOption.from_kwargs(
5969
            'repository_type',
5970
            title='Repository type',
5971
            help='Location fo the repository.',
5972
            value_switches=True, enum_switch=False,
3983.3.11 by Vincent Ladeuil
Fix indentation as per Aaron's review and then some.
5973
            standalone='Reconfigure to be a standalone branch '
5974
                '(i.e. stop using shared repository).',
5975
            use_shared='Reconfigure to use a shared repository.',
6123.8.2 by Martin von Gagern
Make the various aspects of reconfigure independent from one another.
5976
            ),
5977
        RegistryOption.from_kwargs(
5978
            'repository_trees',
5979
            title='Trees in Repository',
5980
            help='Whether new branches in the repository have trees.',
5981
            value_switches=True, enum_switch=False,
3983.3.11 by Vincent Ladeuil
Fix indentation as per Aaron's review and then some.
5982
            with_trees='Reconfigure repository to create '
5983
                'working trees on branches by default.',
5984
            with_no_trees='Reconfigure repository to not create '
5985
                'working trees on branches by default.'
5986
            ),
5987
        Option('bind-to', help='Branch to bind checkout to.', type=str),
5988
        Option('force',
4509.3.1 by Martin Pool
Initial failing test for 'reconfigure --stacked-on'
5989
            help='Perform reconfiguration even if local changes'
5990
            ' will be lost.'),
5991
        Option('stacked-on',
4509.3.3 by Martin Pool
Add reconfigure --unstacked command
5992
            help='Reconfigure a branch to be stacked on another branch.',
4509.3.1 by Martin Pool
Initial failing test for 'reconfigure --stacked-on'
5993
            type=unicode,
5994
            ),
4509.3.3 by Martin Pool
Add reconfigure --unstacked command
5995
        Option('unstacked',
5996
            help='Reconfigure a branch to be unstacked.  This '
4509.3.34 by Martin Pool
Fix typo
5997
                'may require copying substantial data into it.',
4509.3.3 by Martin Pool
Add reconfigure --unstacked command
5998
            ),
3983.3.11 by Vincent Ladeuil
Fix indentation as per Aaron's review and then some.
5999
        ]
2796.2.5 by Aaron Bentley
Implement reconfigure command
6000
6123.8.2 by Martin von Gagern
Make the various aspects of reconfigure independent from one another.
6001
    def run(self, location=None, bind_to=None, force=False,
6002
            tree_type=None, repository_type=None, repository_trees=None,
6003
            stacked_on=None, unstacked=None):
6207.3.3 by jelmer at samba
Fix tests and the like.
6004
        directory = controldir.ControlDir.open(location)
4509.3.35 by Martin Pool
Ban reconfigure --stacked-on foo --unstacked
6005
        if stacked_on and unstacked:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
6006
            raise errors.BzrCommandError(gettext("Can't use both --stacked-on and --unstacked"))
4509.3.35 by Martin Pool
Ban reconfigure --stacked-on foo --unstacked
6007
        elif stacked_on is not None:
4509.3.38 by Martin Pool
Move reconfigure --stacked-on core code into reconfigure.py
6008
            reconfigure.ReconfigureStackedOn().apply(directory, stacked_on)
4509.3.3 by Martin Pool
Add reconfigure --unstacked command
6009
        elif unstacked:
4509.3.39 by Martin Pool
Move reconfigure --unstacked to reconfigure.py
6010
            reconfigure.ReconfigureUnstacked().apply(directory)
4509.3.1 by Martin Pool
Initial failing test for 'reconfigure --stacked-on'
6011
        # At the moment you can use --stacked-on and a different
6012
        # reconfiguration shape at the same time; there seems no good reason
6013
        # to ban it.
6123.8.2 by Martin von Gagern
Make the various aspects of reconfigure independent from one another.
6014
        if (tree_type is None and
6015
            repository_type is None and
6016
            repository_trees is None):
4509.3.3 by Martin Pool
Add reconfigure --unstacked command
6017
            if stacked_on or unstacked:
4509.3.1 by Martin Pool
Initial failing test for 'reconfigure --stacked-on'
6018
                return
6019
            else:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
6020
                raise errors.BzrCommandError(gettext('No target configuration '
6021
                    'specified'))
6123.8.2 by Martin von Gagern
Make the various aspects of reconfigure independent from one another.
6022
        reconfiguration = None
6023
        if tree_type == 'branch':
2796.2.5 by Aaron Bentley
Implement reconfigure command
6024
            reconfiguration = reconfigure.Reconfigure.to_branch(directory)
6123.8.2 by Martin von Gagern
Make the various aspects of reconfigure independent from one another.
6025
        elif tree_type == 'tree':
2796.2.5 by Aaron Bentley
Implement reconfigure command
6026
            reconfiguration = reconfigure.Reconfigure.to_tree(directory)
6123.8.2 by Martin von Gagern
Make the various aspects of reconfigure independent from one another.
6027
        elif tree_type == 'checkout':
3983.3.11 by Vincent Ladeuil
Fix indentation as per Aaron's review and then some.
6028
            reconfiguration = reconfigure.Reconfigure.to_checkout(
6029
                directory, bind_to)
6123.8.2 by Martin von Gagern
Make the various aspects of reconfigure independent from one another.
6030
        elif tree_type == 'lightweight-checkout':
2796.2.19 by Aaron Bentley
Support reconfigure --lightweight-checkout
6031
            reconfiguration = reconfigure.Reconfigure.to_lightweight_checkout(
6032
                directory, bind_to)
6123.8.2 by Martin von Gagern
Make the various aspects of reconfigure independent from one another.
6033
        if reconfiguration:
6034
            reconfiguration.apply(force)
6035
            reconfiguration = None
6036
        if repository_type == 'use-shared':
3311.2.6 by Aaron Bentley
rename 'sharing' to 'use-shared'
6037
            reconfiguration = reconfigure.Reconfigure.to_use_shared(directory)
6123.8.2 by Martin von Gagern
Make the various aspects of reconfigure independent from one another.
6038
        elif repository_type == 'standalone':
3311.2.5 by Aaron Bentley
Implement reconfigure --standalone and --sharing
6039
            reconfiguration = reconfigure.Reconfigure.to_standalone(directory)
6123.8.2 by Martin von Gagern
Make the various aspects of reconfigure independent from one another.
6040
        if reconfiguration:
6041
            reconfiguration.apply(force)
6042
            reconfiguration = None
6043
        if repository_trees == 'with-trees':
3921.4.3 by Matthew Fuller
Add --with-trees and --with-no-trees to the 'reconfigure' command.
6044
            reconfiguration = reconfigure.Reconfigure.set_repository_trees(
6045
                directory, True)
6123.8.2 by Martin von Gagern
Make the various aspects of reconfigure independent from one another.
6046
        elif repository_trees == 'with-no-trees':
3921.4.3 by Matthew Fuller
Add --with-trees and --with-no-trees to the 'reconfigure' command.
6047
            reconfiguration = reconfigure.Reconfigure.set_repository_trees(
6048
                directory, False)
6123.8.2 by Martin von Gagern
Make the various aspects of reconfigure independent from one another.
6049
        if reconfiguration:
6050
            reconfiguration.apply(force)
6051
            reconfiguration = None
2796.2.5 by Aaron Bentley
Implement reconfigure command
6052
6053
2999.1.1 by Ian Clatworthy
migrate switch command into the core - was in BzrTools
6054
class cmd_switch(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
6055
    __doc__ = """Set the branch of a checkout and update.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
6056
3078.2.2 by Ian Clatworthy
get switch tests passing on heavyweight checkouts
6057
    For lightweight checkouts, this changes the branch being referenced.
6058
    For heavyweight checkouts, this checks that there are no local commits
6059
    versus the current bound branch, then it makes the local branch a mirror
6060
    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.
6061
3078.2.2 by Ian Clatworthy
get switch tests passing on heavyweight checkouts
6062
    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.
6063
    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
6064
6065
    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
6066
6067
    The path to the branch to switch to can be specified relative to the parent
6068
    directory of the current branch. For example, if you are currently in a
6069
    checkout of /path/to/branch, specifying 'newbranch' will find a branch at
6070
    /path/to/newbranch.
3565.6.15 by Marius Kruger
update bind and switch command descriptions to state what will happen to nicknames.
6071
3565.6.16 by Marius Kruger
update nick command description to mention how it works for bound branches,
6072
    Bound branches use the nickname of its master branch unless it is set
4775.1.1 by Martin Pool
Remove several 'the the' typos
6073
    locally, in which case switching will update the local nickname to be
3565.6.15 by Marius Kruger
update bind and switch command descriptions to state what will happen to nicknames.
6074
    that of the master.
3078.2.2 by Ian Clatworthy
get switch tests passing on heavyweight checkouts
6075
    """
2999.1.1 by Ian Clatworthy
migrate switch command into the core - was in BzrTools
6076
3984.5.11 by Daniel Watkins
Allow only a revision to be passed to switch.
6077
    takes_args = ['to_location?']
5171.3.13 by Martin von Gagern
Add --directory option to 7 more commands.
6078
    takes_options = ['directory',
6079
                     Option('force',
3984.5.5 by Daniel Watkins
bzr switch now takes a revision option.
6080
                        help='Switch even if local commits will be lost.'),
3984.5.19 by Andrew Bennetts
Merge lp:bzr, resolving conflicts.
6081
                     'revision',
4520.1.1 by John Arbash Meinel
'bzr switch -b' can now be used to create the branch while you switch to it.
6082
                     Option('create-branch', short_name='b',
6083
                        help='Create the target branch from this one before'
6084
                             ' switching to it.'),
3984.5.19 by Andrew Bennetts
Merge lp:bzr, resolving conflicts.
6085
                    ]
2999.1.1 by Ian Clatworthy
migrate switch command into the core - was in BzrTools
6086
3984.5.19 by Andrew Bennetts
Merge lp:bzr, resolving conflicts.
6087
    def run(self, to_location=None, force=False, create_branch=False,
5171.3.13 by Martin von Gagern
Add --directory option to 7 more commands.
6088
            revision=None, directory=u'.'):
2999.1.2 by Ian Clatworthy
incorporate review feedback including basic blackbox tests
6089
        from bzrlib import switch
5171.3.13 by Martin von Gagern
Add --directory option to 7 more commands.
6090
        tree_location = directory
3984.5.18 by Daniel Watkins
cmd_switch now uses _get_one_revision.
6091
        revision = _get_one_revision('switch', revision)
6207.3.3 by jelmer at samba
Fix tests and the like.
6092
        control_dir = controldir.ControlDir.open_containing(tree_location)[0]
3984.5.11 by Daniel Watkins
Allow only a revision to be passed to switch.
6093
        if to_location is None:
6094
            if revision is None:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
6095
                raise errors.BzrCommandError(gettext('You must supply either a'
6096
                                             ' revision or a location'))
5171.3.13 by Martin von Gagern
Add --directory option to 7 more commands.
6097
            to_location = tree_location
4354.2.1 by Aaron Bentley
Improve switch --force with lightweight checkouts.
6098
        try:
6099
            branch = control_dir.open_branch()
6100
            had_explicit_nick = branch.get_config().has_explicit_nickname()
6101
        except errors.NotBranchError:
4520.1.1 by John Arbash Meinel
'bzr switch -b' can now be used to create the branch while you switch to it.
6102
            branch = None
4354.2.1 by Aaron Bentley
Improve switch --force with lightweight checkouts.
6103
            had_explicit_nick = False
4520.1.1 by John Arbash Meinel
'bzr switch -b' can now be used to create the branch while you switch to it.
6104
        if create_branch:
6105
            if branch is None:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
6106
                raise errors.BzrCommandError(gettext('cannot create branch without'
6107
                                             ' source branch'))
4879.2.1 by Neil Martinsen-Burrell
switch should use directory services when creating a branch
6108
            to_location = directory_service.directories.dereference(
6109
                              to_location)
4520.1.1 by John Arbash Meinel
'bzr switch -b' can now be used to create the branch while you switch to it.
6110
            if '/' not in to_location and '\\' not in to_location:
6111
                # This path is meant to be relative to the existing branch
6112
                this_url = self._get_branch_location(control_dir)
5268.8.12 by Jelmer Vernooij
support creating new colocated branches from 'bzr switch -b'.
6113
                # Perhaps the target control dir supports colocated branches?
6114
                try:
6115
                    root = controldir.ControlDir.open(this_url,
6116
                        possible_transports=[control_dir.user_transport])
6117
                except errors.NotBranchError:
6118
                    colocated = False
6119
                else:
6120
                    colocated = root._format.colocated_branches
6121
                if colocated:
6122
                    to_location = urlutils.join_segment_parameters(this_url,
5268.8.17 by Jelmer Vernooij
Support switching to new unicode colocated branch.
6123
                        {"branch": urlutils.escape(to_location)})
5268.8.12 by Jelmer Vernooij
support creating new colocated branches from 'bzr switch -b'.
6124
                else:
5268.8.15 by Jelmer Vernooij
Fix switching to unicode branch names.
6125
                    to_location = urlutils.join(
6126
                        this_url, '..', urlutils.escape(to_location))
4520.1.1 by John Arbash Meinel
'bzr switch -b' can now be used to create the branch while you switch to it.
6127
            to_branch = branch.bzrdir.sprout(to_location,
6128
                                 possible_transports=[branch.bzrdir.root_transport],
6129
                                 source_branch=branch).open_branch()
6130
        else:
5268.8.1 by Jelmer Vernooij
Support colocated branches in "bzr switch".
6131
            # Perhaps it's a colocated branch?
4520.1.1 by John Arbash Meinel
'bzr switch -b' can now be used to create the branch while you switch to it.
6132
            try:
5268.8.1 by Jelmer Vernooij
Support colocated branches in "bzr switch".
6133
                to_branch = control_dir.open_branch(to_location)
6134
            except (errors.NotBranchError, errors.NoColocatedBranchSupport):
6135
                try:
6136
                    to_branch = Branch.open(to_location)
6137
                except errors.NotBranchError:
6138
                    this_url = self._get_branch_location(control_dir)
6139
                    to_branch = Branch.open(
5268.8.15 by Jelmer Vernooij
Fix switching to unicode branch names.
6140
                        urlutils.join(
6141
                            this_url, '..', urlutils.escape(to_location)))
3984.5.13 by Daniel Watkins
Changed switch and cmd_switch to reflect change back.
6142
        if revision is not None:
3984.5.18 by Daniel Watkins
cmd_switch now uses _get_one_revision.
6143
            revision = revision.as_revision_id(to_branch)
3984.5.19 by Andrew Bennetts
Merge lp:bzr, resolving conflicts.
6144
        switch.switch(control_dir, to_branch, force, revision_id=revision)
4354.2.1 by Aaron Bentley
Improve switch --force with lightweight checkouts.
6145
        if had_explicit_nick:
3565.6.7 by Marius Kruger
* checkouts now use master nick when no explicit nick is set.
6146
            branch = control_dir.open_branch() #get the new branch!
6147
            branch.nick = to_branch.nick
6138.2.2 by Jonathan Riddell
gettext builtin.py's note() usage
6148
        note(gettext('Switched to branch: %s'),
2999.1.1 by Ian Clatworthy
migrate switch command into the core - was in BzrTools
6149
            urlutils.unescape_for_display(to_branch.base, 'utf-8'))
6150
4354.2.1 by Aaron Bentley
Improve switch --force with lightweight checkouts.
6151
    def _get_branch_location(self, control_dir):
6152
        """Return location of branch for this control dir."""
6153
        try:
6154
            this_branch = control_dir.open_branch()
6155
            # This may be a heavy checkout, where we want the master branch
4354.2.2 by Aaron Bentley
Enable switch --force for lightweight checkouts after moves.
6156
            master_location = this_branch.get_bound_location()
6157
            if master_location is not None:
6158
                return master_location
4354.2.1 by Aaron Bentley
Improve switch --force with lightweight checkouts.
6159
            # If not, use a local sibling
6160
            return this_branch.base
6161
        except errors.NotBranchError:
6162
            format = control_dir.find_branch_format()
6163
            if getattr(format, 'get_reference', None) is not None:
6164
                return format.get_reference(control_dir)
6165
            else:
6166
                return control_dir.root_transport.base
6167
2999.1.1 by Ian Clatworthy
migrate switch command into the core - was in BzrTools
6168
3586.1.9 by Ian Clatworthy
first cut at view command
6169
class cmd_view(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
6170
    __doc__ = """Manage filtered views.
3586.1.33 by Ian Clatworthy
cleanup trailing whitespace
6171
3586.1.9 by Ian Clatworthy
first cut at view command
6172
    Views provide a mask over the tree so that users can focus on
6173
    a subset of a tree when doing their work. After creating a view,
6174
    commands that support a list of files - status, diff, commit, etc -
6175
    effectively have that list of files implicitly given each time.
6176
    An explicit list of files can still be given but those files
6177
    must be within the current view.
6178
6179
    In most cases, a view has a short life-span: it is created to make
6180
    a selected change and is deleted once that change is committed.
6181
    At other times, you may wish to create one or more named views
3586.1.14 by Ian Clatworthy
added --all option to the view command
6182
    and switch between them.
3586.1.33 by Ian Clatworthy
cleanup trailing whitespace
6183
3586.1.9 by Ian Clatworthy
first cut at view command
6184
    To disable the current view without deleting it, you can switch to
6185
    the pseudo view called ``off``. This can be useful when you need
6186
    to see the whole tree for an operation or two (e.g. merge) but
6187
    want to switch back to your view after that.
6188
6189
    :Examples:
3586.1.14 by Ian Clatworthy
added --all option to the view command
6190
      To define the current view::
3586.1.9 by Ian Clatworthy
first cut at view command
6191
6192
        bzr view file1 dir1 ...
6193
6194
      To list the current view::
6195
6196
        bzr view
6197
6198
      To delete the current view::
6199
6200
        bzr view --delete
6201
6202
      To disable the current view without deleting it::
6203
6204
        bzr view --switch off
6205
3586.1.14 by Ian Clatworthy
added --all option to the view command
6206
      To define a named view and switch to it::
3586.1.9 by Ian Clatworthy
first cut at view command
6207
6208
        bzr view --name view-name file1 dir1 ...
6209
6210
      To list a named view::
6211
6212
        bzr view --name view-name
6213
6214
      To delete a named view::
6215
6216
        bzr view --name view-name --delete
6217
6218
      To switch to a named view::
6219
6220
        bzr view --switch view-name
3586.1.14 by Ian Clatworthy
added --all option to the view command
6221
6222
      To list all views defined::
6223
6224
        bzr view --all
6225
6226
      To delete all views::
6227
6228
        bzr view --delete --all
3586.1.9 by Ian Clatworthy
first cut at view command
6229
    """
6230
3586.1.14 by Ian Clatworthy
added --all option to the view command
6231
    _see_also = []
3586.1.9 by Ian Clatworthy
first cut at view command
6232
    takes_args = ['file*']
6233
    takes_options = [
3586.1.14 by Ian Clatworthy
added --all option to the view command
6234
        Option('all',
6235
            help='Apply list or delete action to all views.',
6236
            ),
3586.1.9 by Ian Clatworthy
first cut at view command
6237
        Option('delete',
6238
            help='Delete the view.',
6239
            ),
6240
        Option('name',
3586.1.14 by Ian Clatworthy
added --all option to the view command
6241
            help='Name of the view to define, list or delete.',
3586.1.9 by Ian Clatworthy
first cut at view command
6242
            type=unicode,
6243
            ),
6244
        Option('switch',
6245
            help='Name of the view to switch to.',
6246
            type=unicode,
6247
            ),
6248
        ]
6249
6250
    def run(self, file_list,
3586.1.14 by Ian Clatworthy
added --all option to the view command
6251
            all=False,
3586.1.9 by Ian Clatworthy
first cut at view command
6252
            delete=False,
6253
            name=None,
6254
            switch=None,
6255
            ):
5346.4.5 by Martin Pool
Deprecate and avoid internal_tree_files and tree_files.
6256
        tree, file_list = WorkingTree.open_containing_paths(file_list,
6257
            apply_view=False)
3586.1.9 by Ian Clatworthy
first cut at view command
6258
        current_view, view_dict = tree.views.get_view_info()
6259
        if name is None:
6260
            name = current_view
6261
        if delete:
6262
            if file_list:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
6263
                raise errors.BzrCommandError(gettext(
6264
                    "Both --delete and a file list specified"))
3586.1.9 by Ian Clatworthy
first cut at view command
6265
            elif switch:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
6266
                raise errors.BzrCommandError(gettext(
6267
                    "Both --delete and --switch specified"))
3586.1.14 by Ian Clatworthy
added --all option to the view command
6268
            elif all:
6269
                tree.views.set_view_info(None, {})
6138.2.1 by Jonathan Riddell
add gettext to all the builtin commands outf usage
6270
                self.outf.write(gettext("Deleted all views.\n"))
3586.1.9 by Ian Clatworthy
first cut at view command
6271
            elif name is None:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
6272
                raise errors.BzrCommandError(gettext("No current view to delete"))
3586.1.9 by Ian Clatworthy
first cut at view command
6273
            else:
6274
                tree.views.delete_view(name)
6138.2.1 by Jonathan Riddell
add gettext to all the builtin commands outf usage
6275
                self.outf.write(gettext("Deleted '%s' view.\n") % name)
3586.1.9 by Ian Clatworthy
first cut at view command
6276
        elif switch:
6277
            if file_list:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
6278
                raise errors.BzrCommandError(gettext(
6279
                    "Both --switch and a file list specified"))
3586.1.14 by Ian Clatworthy
added --all option to the view command
6280
            elif all:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
6281
                raise errors.BzrCommandError(gettext(
6282
                    "Both --switch and --all specified"))
3586.1.9 by Ian Clatworthy
first cut at view command
6283
            elif switch == 'off':
6284
                if current_view is None:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
6285
                    raise errors.BzrCommandError(gettext("No current view to disable"))
3586.1.9 by Ian Clatworthy
first cut at view command
6286
                tree.views.set_view_info(None, view_dict)
6138.2.1 by Jonathan Riddell
add gettext to all the builtin commands outf usage
6287
                self.outf.write(gettext("Disabled '%s' view.\n") % (current_view))
3586.1.9 by Ian Clatworthy
first cut at view command
6288
            else:
6289
                tree.views.set_view_info(switch, view_dict)
3586.1.20 by Ian Clatworthy
centralise formatting of view file lists
6290
                view_str = views.view_display_str(tree.views.lookup_view())
6138.2.4 by Jonathan Riddell
use format strings where there are multiple substitutions to allow for translations
6291
                self.outf.write(gettext("Using '{0}' view: {1}\n").format(switch, view_str))
3586.1.14 by Ian Clatworthy
added --all option to the view command
6292
        elif all:
6293
            if view_dict:
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
6294
                self.outf.write(gettext('Views defined:\n'))
3586.1.14 by Ian Clatworthy
added --all option to the view command
6295
                for view in sorted(view_dict):
6296
                    if view == current_view:
6297
                        active = "=>"
6298
                    else:
6299
                        active = "  "
3586.1.20 by Ian Clatworthy
centralise formatting of view file lists
6300
                    view_str = views.view_display_str(view_dict[view])
6301
                    self.outf.write('%s %-20s %s\n' % (active, view, view_str))
3586.1.14 by Ian Clatworthy
added --all option to the view command
6302
            else:
6138.2.1 by Jonathan Riddell
add gettext to all the builtin commands outf usage
6303
                self.outf.write(gettext('No views defined.\n'))
3586.1.9 by Ian Clatworthy
first cut at view command
6304
        elif file_list:
6305
            if name is None:
6306
                # No name given and no current view set
6307
                name = 'my'
6308
            elif name == 'off':
6138.2.3 by Jonathan Riddell
gettext() on builtin.py's error messages
6309
                raise errors.BzrCommandError(gettext(
6310
                    "Cannot change the 'off' pseudo view"))
3586.1.9 by Ian Clatworthy
first cut at view command
6311
            tree.views.set_view(name, sorted(file_list))
3586.1.20 by Ian Clatworthy
centralise formatting of view file lists
6312
            view_str = views.view_display_str(tree.views.lookup_view())
6138.2.4 by Jonathan Riddell
use format strings where there are multiple substitutions to allow for translations
6313
            self.outf.write(gettext("Using '{0}' view: {1}\n").format(name, view_str))
3586.1.9 by Ian Clatworthy
first cut at view command
6314
        else:
6315
            # list the files
3586.1.13 by Ian Clatworthy
fix list of a known view when no current view set
6316
            if name is None:
6317
                # No name given and no current view set
6138.2.1 by Jonathan Riddell
add gettext to all the builtin commands outf usage
6318
                self.outf.write(gettext('No current view.\n'))
3586.1.9 by Ian Clatworthy
first cut at view command
6319
            else:
3586.1.20 by Ian Clatworthy
centralise formatting of view file lists
6320
                view_str = views.view_display_str(tree.views.lookup_view(name))
6138.2.4 by Jonathan Riddell
use format strings where there are multiple substitutions to allow for translations
6321
                self.outf.write(gettext("'{0}' view is: {1}\n").format(name, view_str))
3586.1.9 by Ian Clatworthy
first cut at view command
6322
6323
3254.2.1 by Daniel Watkins
Added cmd_hooks.
6324
class cmd_hooks(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
6325
    __doc__ = """Show hooks."""
3254.2.1 by Daniel Watkins
Added cmd_hooks.
6326
3254.2.9 by Daniel Watkins
Made cmd_hooks hidden.
6327
    hidden = True
3254.2.1 by Daniel Watkins
Added cmd_hooks.
6328
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
6329
    def run(self):
6330
        for hook_key in sorted(hooks.known_hooks.keys()):
6331
            some_hooks = hooks.known_hooks_key_to_object(hook_key)
6332
            self.outf.write("%s:\n" % type(some_hooks).__name__)
6333
            for hook_name, hook_point in sorted(some_hooks.items()):
6334
                self.outf.write("  %s:\n" % (hook_name,))
6335
                found_hooks = list(hook_point)
6336
                if found_hooks:
6337
                    for hook in found_hooks:
6338
                        self.outf.write("    %s\n" %
6339
                                        (some_hooks.get_hook_name(hook),))
6340
                else:
6138.2.1 by Jonathan Riddell
add gettext to all the builtin commands outf usage
6341
                    self.outf.write(gettext("    <no hooks installed>\n"))
3254.2.1 by Daniel Watkins
Added cmd_hooks.
6342
6343
4991.1.3 by Jelmer Vernooij
Name command remove-branch, rmbranch as alias.
6344
class cmd_remove_branch(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
6345
    __doc__ = """Remove a branch.
4991.1.1 by Jelmer Vernooij
Add rmbranch command.
6346
4991.1.5 by Jelmer Vernooij
Add example for rmbranch, explain a bit better what the command does.
6347
    This will remove the branch from the specified location but 
4991.1.6 by Jelmer Vernooij
Docstring tweaks from Ians review.
6348
    will keep any working tree or repository in place.
4991.1.5 by Jelmer Vernooij
Add example for rmbranch, explain a bit better what the command does.
6349
6350
    :Examples:
6351
4991.1.6 by Jelmer Vernooij
Docstring tweaks from Ians review.
6352
      Remove the branch at repo/trunk::
4991.1.5 by Jelmer Vernooij
Add example for rmbranch, explain a bit better what the command does.
6353
6354
        bzr remove-branch repo/trunk
6355
4991.1.1 by Jelmer Vernooij
Add rmbranch command.
6356
    """
6357
6358
    takes_args = ["location?"]
6359
4991.1.3 by Jelmer Vernooij
Name command remove-branch, rmbranch as alias.
6360
    aliases = ["rmbranch"]
6361
4991.1.1 by Jelmer Vernooij
Add rmbranch command.
6362
    def run(self, location=None):
6363
        if location is None:
6364
            location = "."
6365
        branch = Branch.open_containing(location)[0]
6366
        branch.bzrdir.destroy_branch()
5521.1.1 by Vincent Ladeuil
Handle --directory when paths are also provided to shelve and restore.
6367
4991.1.1 by Jelmer Vernooij
Add rmbranch command.
6368
0.16.80 by Aaron Bentley
Rename shelve2/unshelve2 to shelve/unshelve
6369
class cmd_shelve(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
6370
    __doc__ = """Temporarily set aside some changes from the current tree.
0.16.74 by Aaron Bentley
Merge with shelf-manager
6371
6372
    Shelve allows you to temporarily put changes you've made "on the shelf",
6373
    ie. out of the way, until a later time when you can bring them back from
3990.2.6 by Daniel Watkins
Improved shelve documentation, as per #327421.
6374
    the shelf with the 'unshelve' command.  The changes are stored alongside
6375
    your working tree, and so they aren't propagated along with your branch nor
6376
    will they survive its deletion.
0.16.74 by Aaron Bentley
Merge with shelf-manager
6377
0.16.113 by Aaron Bentley
Change ls-shelf to shelve --list
6378
    If shelve --list is specified, previously-shelved changes are listed.
6379
0.16.74 by Aaron Bentley
Merge with shelf-manager
6380
    Shelve is intended to help separate several sets of changes that have
6381
    been inappropriately mingled.  If you just want to get rid of all changes
6382
    and you don't need to restore them later, use revert.  If you want to
6383
    shelve all text changes at once, use shelve --all.
6384
6385
    If filenames are specified, only the changes to those files will be
6386
    shelved. Other files will be left untouched.
6387
6388
    If a revision is specified, changes since that revision will be shelved.
6389
6390
    You can put multiple items on the shelf, and by default, 'unshelve' will
6391
    restore the most recently shelved changes.
5504.2.1 by Neil Martinsen-Burrell
add documentation of the ability to edit changes when shelving
6392
6393
    For complicated changes, it is possible to edit the changes in a separate
6394
    editor program to decide what the file remaining in the working copy
6395
    should look like.  To do this, add the configuration option
6396
6397
        change_editor = PROGRAM @new_path @old_path
6398
6399
    where @new_path is replaced with the path of the new version of the 
6400
    file and @old_path is replaced with the path of the old version of 
6401
    the file.  The PROGRAM should save the new file with the desired 
6402
    contents of the file in the working tree.
6403
        
0.16.74 by Aaron Bentley
Merge with shelf-manager
6404
    """
6405
6406
    takes_args = ['file*']
6407
6408
    takes_options = [
5171.3.13 by Martin von Gagern
Add --directory option to 7 more commands.
6409
        'directory',
0.16.74 by Aaron Bentley
Merge with shelf-manager
6410
        'revision',
6411
        Option('all', help='Shelve all changes.'),
6412
        'message',
0.16.108 by Aaron Bentley
Shelf supports multiple diff writers.
6413
        RegistryOption('writer', 'Method to use for writing diffs.',
6414
                       bzrlib.option.diff_writer_registry,
0.16.113 by Aaron Bentley
Change ls-shelf to shelve --list
6415
                       value_switches=True, enum_switch=False),
6416
0.16.119 by Aaron Bentley
Fix option help style.
6417
        Option('list', help='List shelved changes.'),
4100.3.1 by Aaron Bentley
Implement shelve --destroy
6418
        Option('destroy',
6419
               help='Destroy removed changes instead of shelving them.'),
0.16.74 by Aaron Bentley
Merge with shelf-manager
6420
    ]
5504.2.1 by Neil Martinsen-Burrell
add documentation of the ability to edit changes when shelving
6421
    _see_also = ['unshelve', 'configuration']
0.16.74 by Aaron Bentley
Merge with shelf-manager
6422
0.16.108 by Aaron Bentley
Shelf supports multiple diff writers.
6423
    def run(self, revision=None, all=False, file_list=None, message=None,
5521.1.1 by Vincent Ladeuil
Handle --directory when paths are also provided to shelve and restore.
6424
            writer=None, list=False, destroy=False, directory=None):
0.16.113 by Aaron Bentley
Change ls-shelf to shelve --list
6425
        if list:
5521.1.1 by Vincent Ladeuil
Handle --directory when paths are also provided to shelve and restore.
6426
            return self.run_for_list(directory=directory)
0.16.74 by Aaron Bentley
Merge with shelf-manager
6427
        from bzrlib.shelf_ui import Shelver
0.16.108 by Aaron Bentley
Shelf supports multiple diff writers.
6428
        if writer is None:
6429
            writer = bzrlib.option.diff_writer_registry.get()
0.16.103 by Aaron Bentley
raise UserAbort instead of doing sys.exit
6430
        try:
4603.1.7 by Aaron Bentley
Allow configuring change editor.
6431
            shelver = Shelver.from_args(writer(sys.stdout), revision, all,
5171.3.13 by Martin von Gagern
Add --directory option to 7 more commands.
6432
                file_list, message, destroy=destroy, directory=directory)
4603.1.7 by Aaron Bentley
Allow configuring change editor.
6433
            try:
6434
                shelver.run()
6435
            finally:
4603.1.11 by Aaron Bentley
Implement shelver.finalize
6436
                shelver.finalize()
0.16.103 by Aaron Bentley
raise UserAbort instead of doing sys.exit
6437
        except errors.UserAbort:
6438
            return 0
0.16.74 by Aaron Bentley
Merge with shelf-manager
6439
5521.1.1 by Vincent Ladeuil
Handle --directory when paths are also provided to shelve and restore.
6440
    def run_for_list(self, directory=None):
6441
        if directory is None:
6442
            directory = u'.'
6443
        tree = WorkingTree.open_containing(directory)[0]
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
6444
        self.add_cleanup(tree.lock_read().unlock)
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
6445
        manager = tree.get_shelf_manager()
5418.4.6 by Parth Malwankar
used active_shelves instead of creating a new function for listing shelves
6446
        shelves = manager.active_shelves()
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
6447
        if len(shelves) == 0:
6138.2.2 by Jonathan Riddell
gettext builtin.py's note() usage
6448
            note(gettext('No shelved changes.'))
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
6449
            return 0
5418.4.6 by Parth Malwankar
used active_shelves instead of creating a new function for listing shelves
6450
        for shelf_id in reversed(shelves):
6451
            message = manager.get_metadata(shelf_id).get('message')
6452
            if message is None:
6453
                message = '<no message>'
4900.1.3 by Andrew Bennetts
Replace lots of try/finally blocks in builtins.py with add_cleanup. Reduces line count by 80, and removes lots of indentation levels too.
6454
            self.outf.write('%3d: %s\n' % (shelf_id, message))
6455
        return 1
0.16.113 by Aaron Bentley
Change ls-shelf to shelve --list
6456
0.16.74 by Aaron Bentley
Merge with shelf-manager
6457
0.16.80 by Aaron Bentley
Rename shelve2/unshelve2 to shelve/unshelve
6458
class cmd_unshelve(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
6459
    __doc__ = """Restore shelved changes.
0.16.74 by Aaron Bentley
Merge with shelf-manager
6460
6461
    By default, the most recently shelved changes are restored. However if you
3990.2.5 by Daniel Watkins
Improve unshelve documentation, as per #327425.
6462
    specify a shelf by id those changes will be restored instead.  This works
6463
    best when the changes don't depend on each other.
0.16.74 by Aaron Bentley
Merge with shelf-manager
6464
    """
6465
6466
    takes_args = ['shelf_id?']
6467
    takes_options = [
5171.3.13 by Martin von Gagern
Add --directory option to 7 more commands.
6468
        'directory',
0.16.74 by Aaron Bentley
Merge with shelf-manager
6469
        RegistryOption.from_kwargs(
6470
            'action', help="The action to perform.",
6471
            enum_switch=False, value_switches=True,
6472
            apply="Apply changes and remove from the shelf.",
4902.1.2 by Guilherme Salgado
First round of the new approach, using a new action (--preview) on the unshelve command
6473
            dry_run="Show changes, but do not apply or remove them.",
6474
            preview="Instead of unshelving the changes, show the diff that "
6475
                    "would result from unshelving.",
4889.1.3 by Martin Pool
New option unshelve --keep
6476
            delete_only="Delete changes without applying them.",
6477
            keep="Apply changes but don't delete them.",
0.16.74 by Aaron Bentley
Merge with shelf-manager
6478
        )
6479
    ]
0.16.117 by Aaron Bentley
Remove references to ls-shelf
6480
    _see_also = ['shelve']
0.16.74 by Aaron Bentley
Merge with shelf-manager
6481
5171.3.13 by Martin von Gagern
Add --directory option to 7 more commands.
6482
    def run(self, shelf_id=None, action='apply', directory=u'.'):
0.16.74 by Aaron Bentley
Merge with shelf-manager
6483
        from bzrlib.shelf_ui import Unshelver
5171.3.13 by Martin von Gagern
Add --directory option to 7 more commands.
6484
        unshelver = Unshelver.from_args(shelf_id, action, directory=directory)
4595.13.2 by Alexander Belchenko
[cherrypick revno 4650 from bzr.dev] Fix shelve on windows. (Robert Collins, #305006)
6485
        try:
6486
            unshelver.run()
6487
        finally:
6488
            unshelver.tree.unlock()
0.16.74 by Aaron Bentley
Merge with shelf-manager
6489
6490
4020.1.1 by Jelmer Vernooij
Import clean-tree from bzrtools.
6491
class cmd_clean_tree(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
6492
    __doc__ = """Remove unwanted files from working tree.
4020.1.1 by Jelmer Vernooij
Import clean-tree from bzrtools.
6493
6494
    By default, only unknown files, not ignored files, are deleted.  Versioned
6495
    files are never deleted.
6496
6497
    Another class is 'detritus', which includes files emitted by bzr during
6498
    normal operations and selftests.  (The value of these files decreases with
6499
    time.)
6500
6501
    If no options are specified, unknown files are deleted.  Otherwise, option
6502
    flags are respected, and may be combined.
6503
6504
    To check what clean-tree will do, use --dry-run.
6505
    """
5171.3.4 by Martin von Gagern
Add --directory option to clean-tree.
6506
    takes_options = ['directory',
6507
                     Option('ignored', help='Delete all ignored files.'),
5666.1.1 by Jelmer Vernooij
Clarify that 'bzr clean-tree --detritus' cleans up revert backups too.
6508
                     Option('detritus', help='Delete conflict files, merge and revert'
4020.1.1 by Jelmer Vernooij
Import clean-tree from bzrtools.
6509
                            ' backups, and failed selftest dirs.'),
6510
                     Option('unknown',
6511
                            help='Delete files unknown to bzr (default).'),
6512
                     Option('dry-run', help='Show files to delete instead of'
6513
                            ' deleting them.'),
6514
                     Option('force', help='Do not prompt before deleting.')]
6515
    def run(self, unknown=False, ignored=False, detritus=False, dry_run=False,
5171.3.4 by Martin von Gagern
Add --directory option to clean-tree.
6516
            force=False, directory=u'.'):
4020.1.1 by Jelmer Vernooij
Import clean-tree from bzrtools.
6517
        from bzrlib.clean_tree import clean_tree
6518
        if not (unknown or ignored or detritus):
6519
            unknown = True
6520
        if dry_run:
6521
            force = True
5171.3.4 by Martin von Gagern
Add --directory option to clean-tree.
6522
        clean_tree(directory, unknown=unknown, ignored=ignored,
6523
                   detritus=detritus, dry_run=dry_run, no_prompt=force)
4020.1.1 by Jelmer Vernooij
Import clean-tree from bzrtools.
6524
6525
4273.1.19 by Aaron Bentley
Implement reference command
6526
class cmd_reference(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
6527
    __doc__ = """list, view and set branch locations for nested trees.
4273.1.19 by Aaron Bentley
Implement reference command
6528
6529
    If no arguments are provided, lists the branch locations for nested trees.
6530
    If one argument is provided, display the branch location for that tree.
6531
    If two arguments are provided, set the branch location for that tree.
6532
    """
6533
6534
    hidden = True
6535
6536
    takes_args = ['path?', 'location?']
6537
6538
    def run(self, path=None, location=None):
6539
        branchdir = '.'
6540
        if path is not None:
6541
            branchdir = path
6542
        tree, branch, relpath =(
6207.3.3 by jelmer at samba
Fix tests and the like.
6543
            controldir.ControlDir.open_containing_tree_or_branch(branchdir))
4273.1.19 by Aaron Bentley
Implement reference command
6544
        if path is not None:
6545
            path = relpath
6546
        if tree is None:
6547
            tree = branch.basis_tree()
6548
        if path is None:
6549
            info = branch._get_all_reference_info().iteritems()
6550
            self._display_reference_info(tree, branch, info)
6551
        else:
6552
            file_id = tree.path2id(path)
6553
            if file_id is None:
6554
                raise errors.NotVersionedError(path)
6555
            if location is None:
6556
                info = [(file_id, branch.get_reference_info(file_id))]
6557
                self._display_reference_info(tree, branch, info)
6558
            else:
6559
                branch.set_reference_info(file_id, path, location)
6560
6561
    def _display_reference_info(self, tree, branch, info):
6562
        ref_list = []
6563
        for file_id, (path, location) in info:
6564
            try:
6565
                path = tree.id2path(file_id)
6566
            except errors.NoSuchId:
6567
                pass
6568
            ref_list.append((path, location))
6569
        for path, location in sorted(ref_list):
6570
            self.outf.write('%s %s\n' % (path, location))
6571
6572
5830.2.12 by INADA Naoki
Make "export-pot" hidden command.
6573
class cmd_export_pot(Command):
6574
    __doc__ = """Export command helps and error messages in po format."""
6575
6576
    hidden = True
6162.4.5 by Jonathan Riddell
change export-pot --plugins option to --plugin which takes a plugin name rather than command name
6577
    takes_options = [Option('plugin', 
6578
                            help='Export help text from named command '\
6579
                                 '(defaults to all built in commands).',
6351.2.1 by Martin Packman
Add export-pot --include-duplicates option for permitting multiple entries with the same msgid
6580
                            type=str),
6581
                     Option('include-duplicates',
6582
                            help='Output multiple copies of the same msgid '
6583
                                 'string if it appears more than once.'),
6584
                            ]
5830.2.12 by INADA Naoki
Make "export-pot" hidden command.
6585
6351.2.1 by Martin Packman
Add export-pot --include-duplicates option for permitting multiple entries with the same msgid
6586
    def run(self, plugin=None, include_duplicates=False):
5830.2.12 by INADA Naoki
Make "export-pot" hidden command.
6587
        from bzrlib.export_pot import export_pot
6351.2.1 by Martin Packman
Add export-pot --include-duplicates option for permitting multiple entries with the same msgid
6588
        export_pot(self.outf, plugin, include_duplicates)
5830.2.12 by INADA Naoki
Make "export-pot" hidden command.
6589
6590
5127.1.1 by Martin Pool
version-info is lazily loaded
6591
def _register_lazy_builtins():
6592
    # register lazy builtins from other modules; called at startup and should
6593
    # be only called once.
6594
    for (name, aliases, module_name) in [
6595
        ('cmd_bundle_info', [], 'bzrlib.bundle.commands'),
5447.4.16 by Vincent Ladeuil
Use config_id instead of id as suggested by poolie.
6596
        ('cmd_config', [], 'bzrlib.config'),
5127.1.3 by Martin Pool
lazy-load dpush
6597
        ('cmd_dpush', [], 'bzrlib.foreign'),
5321.1.74 by Gordon Tyler
Reverted some more command-related stuff that I missed earlier.
6598
        ('cmd_version_info', [], 'bzrlib.cmd_version_info'),
5127.1.2 by Martin Pool
Lazy-load conflict commands
6599
        ('cmd_resolve', ['resolved'], 'bzrlib.conflicts'),
5321.1.74 by Gordon Tyler
Reverted some more command-related stuff that I missed earlier.
6600
        ('cmd_conflicts', [], 'bzrlib.conflicts'),
5971.1.37 by Jonathan Riddell
renamed file 'bzrlib/sign_my_commits.py' => 'bzrlib/commit_signature_commands.py'
6601
        ('cmd_sign_my_commits', [], 'bzrlib.commit_signature_commands'),
5971.1.64 by Jonathan Riddell
no short form for verify-signatures
6602
        ('cmd_verify_signatures', [],
5971.1.52 by Jonathan Riddell
change command name to verify-signatures
6603
                                        'bzrlib.commit_signature_commands'),
5510.1.2 by Martin von Gagern
Avoid test-script command depending on testtools.
6604
        ('cmd_test_script', [], 'bzrlib.cmd_test_script'),
5127.1.1 by Martin Pool
version-info is lazily loaded
6605
        ]:
6606
        builtin_command_registry.register_lazy(name, aliases, module_name)